]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - cmdgen.c
Support loading public-key-only files in Unix PuTTYgen.
[PuTTY.git] / cmdgen.c
1 /*
2  * cmdgen.c - command-line form of PuTTYgen
3  */
4
5 #define PUTTY_DO_GLOBALS
6
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <ctype.h>
10 #include <limits.h>
11 #include <assert.h>
12 #include <time.h>
13
14 #include "putty.h"
15 #include "ssh.h"
16
17 #ifdef TEST_CMDGEN
18 /*
19  * This section overrides some definitions below for test purposes.
20  * When compiled with -DTEST_CMDGEN:
21  * 
22  *  - Calls to get_random_data() are replaced with the diagnostic
23  *    function below (I #define the name so that I can still link
24  *    with the original set of modules without symbol clash), in
25  *    order to avoid depleting the test system's /dev/random
26  *    unnecessarily.
27  * 
28  *  - Calls to console_get_userpass_input() are replaced with the
29  *    diagnostic function below, so that I can run tests in an
30  *    automated manner and provide their interactive passphrase
31  *    inputs.
32  * 
33  *  - main() is renamed to cmdgen_main(); at the bottom of the file
34  *    I define another main() which calls the former repeatedly to
35  *    run tests.
36  */
37 #define get_random_data get_random_data_diagnostic
38 char *get_random_data(int len)
39 {
40     char *buf = snewn(len, char);
41     memset(buf, 'x', len);
42     return buf;
43 }
44 #define console_get_userpass_input console_get_userpass_input_diagnostic
45 int nprompts, promptsgot;
46 const char *prompts[3];
47 int console_get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
48 {
49     size_t i;
50     int ret = 1;
51     for (i = 0; i < p->n_prompts; i++) {
52         if (promptsgot < nprompts) {
53             assert(strlen(prompts[promptsgot]) < p->prompts[i]->result_len);
54             strcpy(p->prompts[i]->result, prompts[promptsgot++]);
55         } else {
56             promptsgot++;           /* track number of requests anyway */
57             ret = 0;
58         }
59     }
60     return ret;
61 }
62 #define main cmdgen_main
63 #endif
64
65 struct progress {
66     int phase, current;
67 };
68
69 static void progress_update(void *param, int action, int phase, int iprogress)
70 {
71     struct progress *p = (struct progress *)param;
72     if (action != PROGFN_PROGRESS)
73         return;
74     if (phase > p->phase) {
75         if (p->phase >= 0)
76             fputc('\n', stderr);
77         p->phase = phase;
78         if (iprogress >= 0)
79             p->current = iprogress - 1;
80         else
81             p->current = iprogress;
82     }
83     while (p->current < iprogress) {
84         fputc('+', stdout);
85         p->current++;
86     }
87     fflush(stdout);
88 }
89
90 static void no_progress(void *param, int action, int phase, int iprogress)
91 {
92 }
93
94 void modalfatalbox(char *p, ...)
95 {
96     va_list ap;
97     fprintf(stderr, "FATAL ERROR: ");
98     va_start(ap, p);
99     vfprintf(stderr, p, ap);
100     va_end(ap);
101     fputc('\n', stderr);
102     cleanup_exit(1);
103 }
104
105 void nonfatal(char *p, ...)
106 {
107     va_list ap;
108     fprintf(stderr, "ERROR: ");
109     va_start(ap, p);
110     vfprintf(stderr, p, ap);
111     va_end(ap);
112     fputc('\n', stderr);
113 }
114
115 /*
116  * Stubs to let everything else link sensibly.
117  */
118 void log_eventlog(void *handle, const char *event)
119 {
120 }
121 char *x_get_default(const char *key)
122 {
123     return NULL;
124 }
125 void sk_cleanup(void)
126 {
127 }
128
129 void showversion(void)
130 {
131     printf("puttygen: %s\n", ver);
132 }
133
134 void usage(int standalone)
135 {
136     fprintf(stderr,
137             "Usage: puttygen ( keyfile | -t type [ -b bits ] )\n"
138             "                [ -C comment ] [ -P ] [ -q ]\n"
139             "                [ -o output-keyfile ] [ -O type | -l | -L"
140             " | -p ]\n");
141     if (standalone)
142         fprintf(stderr,
143                 "Use \"puttygen --help\" for more detail.\n");
144 }
145
146 void help(void)
147 {
148     /*
149      * Help message is an extended version of the usage message. So
150      * start with that, plus a version heading.
151      */
152     showversion();
153     usage(FALSE);
154     fprintf(stderr,
155             "  -t    specify key type when generating (rsa, dsa, rsa1)\n"
156             "  -b    specify number of bits when generating key\n"
157             "  -C    change or specify key comment\n"
158             "  -P    change key passphrase\n"
159             "  -q    quiet: do not display progress bar\n"
160             "  -O    specify output type:\n"
161             "           private             output PuTTY private key format\n"
162             "           private-openssh     export OpenSSH private key\n"
163             "           private-openssh-new export OpenSSH private key "
164                                              "(force new file format)\n"
165             "           private-sshcom      export ssh.com private key\n"
166             "           public              RFC 4716 / ssh.com public key\n"
167             "           public-openssh      OpenSSH public key\n"
168             "           fingerprint         output the key fingerprint\n"
169             "  -o    specify output file\n"
170             "  -l    equivalent to `-O fingerprint'\n"
171             "  -L    equivalent to `-O public-openssh'\n"
172             "  -p    equivalent to `-O public'\n"
173             );
174 }
175
176 static int save_ssh2_pubkey(char *filename, char *comment,
177                             void *v_pub_blob, int pub_len)
178 {
179     unsigned char *pub_blob = (unsigned char *)v_pub_blob;
180     char *p;
181     int i, column;
182     FILE *fp;
183
184     if (filename) {
185         fp = fopen(filename, "wb");
186         if (!fp)
187             return 0;
188     } else
189         fp = stdout;
190
191     fprintf(fp, "---- BEGIN SSH2 PUBLIC KEY ----\n");
192
193     if (comment) {
194         fprintf(fp, "Comment: \"");
195         for (p = comment; *p; p++) {
196             if (*p == '\\' || *p == '\"')
197                 fputc('\\', fp);
198             fputc(*p, fp);
199         }
200         fprintf(fp, "\"\n");
201     }
202
203     i = 0;
204     column = 0;
205     while (i < pub_len) {
206         char buf[5];
207         int n = (pub_len - i < 3 ? pub_len - i : 3);
208         base64_encode_atom(pub_blob + i, n, buf);
209         i += n;
210         buf[4] = '\0';
211         fputs(buf, fp);
212         if (++column >= 16) {
213             fputc('\n', fp);
214             column = 0;
215         }
216     }
217     if (column > 0)
218         fputc('\n', fp);
219     
220     fprintf(fp, "---- END SSH2 PUBLIC KEY ----\n");
221     if (filename)
222         fclose(fp);
223     return 1;
224 }
225
226 static int move(char *from, char *to)
227 {
228     int ret;
229
230     ret = rename(from, to);
231     if (ret) {
232         /*
233          * This OS may require us to remove the original file first.
234          */
235         remove(to);
236         ret = rename(from, to);
237     }
238     if (ret) {
239         perror("puttygen: cannot move new file on to old one");
240         return FALSE;
241     }
242     return TRUE;
243 }
244
245 static char *blobfp(char *alg, int bits, unsigned char *blob, int bloblen)
246 {
247     char buffer[128];
248     unsigned char digest[16];
249     struct MD5Context md5c;
250     int i;
251
252     MD5Init(&md5c);
253     MD5Update(&md5c, blob, bloblen);
254     MD5Final(digest, &md5c);
255
256     sprintf(buffer, "%s ", alg);
257     if (bits > 0)
258         sprintf(buffer + strlen(buffer), "%d ", bits);
259     for (i = 0; i < 16; i++)
260         sprintf(buffer + strlen(buffer), "%s%02x", i ? ":" : "",
261                 digest[i]);
262
263     return dupstr(buffer);
264 }
265
266 int main(int argc, char **argv)
267 {
268     char *infile = NULL;
269     Filename *infilename = NULL, *outfilename = NULL;
270     enum { NOKEYGEN, RSA1, RSA2, DSA, ECDSA, ED25519 } keytype = NOKEYGEN;
271     char *outfile = NULL, *outfiletmp = NULL;
272     enum { PRIVATE, PUBLIC, PUBLICO, FP, OPENSSH_AUTO,
273            OPENSSH_NEW, SSHCOM } outtype = PRIVATE;
274     int bits = -1;
275     char *comment = NULL, *origcomment = NULL;
276     int change_passphrase = FALSE;
277     int errs = FALSE, nogo = FALSE;
278     int intype = SSH_KEYTYPE_UNOPENABLE;
279     int sshver = 0;
280     struct ssh2_userkey *ssh2key = NULL;
281     struct RSAKey *ssh1key = NULL;
282     unsigned char *ssh2blob = NULL;
283     char *ssh2alg = NULL;
284     const struct ssh_signkey *ssh2algf = NULL;
285     int ssh2bloblen;
286     char *passphrase = NULL;
287     int load_encrypted;
288     progfn_t progressfn = is_interactive() ? progress_update : no_progress;
289
290     /* ------------------------------------------------------------------
291      * Parse the command line to figure out what we've been asked to do.
292      */
293
294     /*
295      * If run with no arguments at all, print the usage message and
296      * return success.
297      */
298     if (argc <= 1) {
299         usage(TRUE);
300         return 0;
301     }
302
303     /*
304      * Parse command line arguments.
305      */
306     while (--argc) {
307         char *p = *++argv;
308         if (*p == '-') {
309             /*
310              * An option.
311              */
312             while (p && *++p) {
313                 char c = *p;
314                 switch (c) {
315                   case '-':
316                     /*
317                      * Long option.
318                      */
319                     {
320                         char *opt, *val;
321                         opt = p++;     /* opt will have _one_ leading - */
322                         while (*p && *p != '=')
323                             p++;               /* find end of option */
324                         if (*p == '=') {
325                             *p++ = '\0';
326                             val = p;
327                         } else
328                             val = NULL;
329
330                         if (!strcmp(opt, "-help")) {
331                             if (val) {
332                                 errs = TRUE;
333                                 fprintf(stderr, "puttygen: option `-%s'"
334                                         " expects no argument\n", opt);
335                             } else {
336                                 help();
337                                 nogo = TRUE;
338                             }
339                         } else if (!strcmp(opt, "-version")) {
340                             if (val) {
341                                 errs = TRUE;
342                                 fprintf(stderr, "puttygen: option `-%s'"
343                                         " expects no argument\n", opt);
344                             } else {
345                                 showversion();
346                                 nogo = TRUE;
347                             }
348                         } else if (!strcmp(opt, "-pgpfp")) {
349                             if (val) {
350                                 errs = TRUE;
351                                 fprintf(stderr, "puttygen: option `-%s'"
352                                         " expects no argument\n", opt);
353                             } else {
354                                 /* support --pgpfp for consistency */
355                                 pgp_fingerprints();
356                                 nogo = TRUE;
357                             }
358                         }
359                         /*
360                          * For long options requiring an argument, add
361                          * code along the lines of
362                          * 
363                          * else if (!strcmp(opt, "-output")) {
364                          *     if (!val) {
365                          *         errs = TRUE;
366                          *         fprintf(stderr, "puttygen: option `-%s'"
367                          *                 " expects an argument\n", opt);
368                          *     } else
369                          *         ofile = val;
370                          * }
371                          */
372                         else {
373                             errs = TRUE;
374                             fprintf(stderr,
375                                     "puttygen: no such option `-%s'\n", opt);
376                         }
377                     }
378                     p = NULL;
379                     break;
380                   case 'h':
381                   case 'V':
382                   case 'P':
383                   case 'l':
384                   case 'L':
385                   case 'p':
386                   case 'q':
387                     /*
388                      * Option requiring no parameter.
389                      */
390                     switch (c) {
391                       case 'h':
392                         help();
393                         nogo = TRUE;
394                         break;
395                       case 'V':
396                         showversion();
397                         nogo = TRUE;
398                         break;
399                       case 'P':
400                         change_passphrase = TRUE;
401                         break;
402                       case 'l':
403                         outtype = FP;
404                         break;
405                       case 'L':
406                         outtype = PUBLICO;
407                         break;
408                       case 'p':
409                         outtype = PUBLIC;
410                         break;
411                       case 'q':
412                         progressfn = no_progress;
413                         break;
414                     }
415                     break;
416                   case 't':
417                   case 'b':
418                   case 'C':
419                   case 'O':
420                   case 'o':
421                     /*
422                      * Option requiring parameter.
423                      */
424                     p++;
425                     if (!*p && argc > 1)
426                         --argc, p = *++argv;
427                     else if (!*p) {
428                         fprintf(stderr, "puttygen: option `-%c' expects a"
429                                 " parameter\n", c);
430                         errs = TRUE;
431                     }
432                     /*
433                      * Now c is the option and p is the parameter.
434                      */
435                     switch (c) {
436                       case 't':
437                         if (!strcmp(p, "rsa") || !strcmp(p, "rsa2"))
438                             keytype = RSA2, sshver = 2;
439                         else if (!strcmp(p, "rsa1"))
440                             keytype = RSA1, sshver = 1;
441                         else if (!strcmp(p, "dsa") || !strcmp(p, "dss"))
442                             keytype = DSA, sshver = 2;
443                         else if (!strcmp(p, "ecdsa"))
444                             keytype = ECDSA, sshver = 2;
445                         else if (!strcmp(p, "ed25519"))
446                             keytype = ED25519, sshver = 2;
447                         else {
448                             fprintf(stderr,
449                                     "puttygen: unknown key type `%s'\n", p);
450                             errs = TRUE;
451                         }
452                         break;
453                       case 'b':
454                         bits = atoi(p);
455                         break;
456                       case 'C':
457                         comment = p;
458                         break;
459                       case 'O':
460                         if (!strcmp(p, "public"))
461                             outtype = PUBLIC;
462                         else if (!strcmp(p, "public-openssh"))
463                             outtype = PUBLICO;
464                         else if (!strcmp(p, "private"))
465                             outtype = PRIVATE;
466                         else if (!strcmp(p, "fingerprint"))
467                             outtype = FP;
468                         else if (!strcmp(p, "private-openssh"))
469                             outtype = OPENSSH_AUTO, sshver = 2;
470                         else if (!strcmp(p, "private-openssh-new"))
471                             outtype = OPENSSH_NEW, sshver = 2;
472                         else if (!strcmp(p, "private-sshcom"))
473                             outtype = SSHCOM, sshver = 2;
474                         else {
475                             fprintf(stderr,
476                                     "puttygen: unknown output type `%s'\n", p);
477                             errs = TRUE;
478                         }
479                         break;
480                       case 'o':
481                         outfile = p;
482                         break;
483                     }
484                     p = NULL;          /* prevent continued processing */
485                     break;
486                   default:
487                     /*
488                      * Unrecognised option.
489                      */
490                     errs = TRUE;
491                     fprintf(stderr, "puttygen: no such option `-%c'\n", c);
492                     break;
493                 }
494             }
495         } else {
496             /*
497              * A non-option argument.
498              */
499             if (!infile)
500                 infile = p;
501             else {
502                 errs = TRUE;
503                 fprintf(stderr, "puttygen: cannot handle more than one"
504                         " input file\n");
505             }
506         }
507     }
508
509     if (bits == -1) {
510         /*
511          * No explicit key size was specified. Default varies
512          * depending on key type.
513          */
514         switch (keytype) {
515           case ECDSA:
516             bits = 384;
517             break;
518           case ED25519:
519             bits = 256;
520             break;
521           default:
522             bits = 2048;
523             break;
524         }
525     }
526
527     if (keytype == ECDSA && (bits != 256 && bits != 384 && bits != 521)) {
528         fprintf(stderr, "puttygen: invalid bits for ECDSA, choose 256, 384 or 521\n");
529         errs = TRUE;
530     }
531
532     if (keytype == ED25519 && (bits != 256)) {
533         fprintf(stderr, "puttygen: invalid bits for ED25519, choose 256\n");
534         errs = TRUE;
535     }
536
537     if (errs)
538         return 1;
539
540     if (nogo)
541         return 0;
542
543     /*
544      * If run with at least one argument _but_ not the required
545      * ones, print the usage message and return failure.
546      */
547     if (!infile && keytype == NOKEYGEN) {
548         usage(TRUE);
549         return 1;
550     }
551
552     /* ------------------------------------------------------------------
553      * Figure out further details of exactly what we're going to do.
554      */
555
556     /*
557      * Bomb out if we've been asked to both load and generate a
558      * key.
559      */
560     if (keytype != NOKEYGEN && infile) {
561         fprintf(stderr, "puttygen: cannot both load and generate a key\n");
562         return 1;
563     }
564
565     /* 
566      * We must save the private part when generating a new key.
567      */
568     if (keytype != NOKEYGEN &&
569         (outtype != PRIVATE && outtype != OPENSSH_AUTO &&
570          outtype != OPENSSH_NEW && outtype != SSHCOM)) {
571         fprintf(stderr, "puttygen: this would generate a new key but "
572                 "discard the private part\n");
573         return 1;
574     }
575
576     /*
577      * Analyse the type of the input file, in case this affects our
578      * course of action.
579      */
580     if (infile) {
581         infilename = filename_from_str(infile);
582
583         intype = key_type(infilename);
584
585         switch (intype) {
586           case SSH_KEYTYPE_UNOPENABLE:
587           case SSH_KEYTYPE_UNKNOWN:
588             fprintf(stderr, "puttygen: unable to load file `%s': %s\n",
589                     infile, key_type_to_str(intype));
590             return 1;
591
592           case SSH_KEYTYPE_SSH1:
593           case SSH_KEYTYPE_SSH1_PUBLIC:
594             if (sshver == 2) {
595                 fprintf(stderr, "puttygen: conversion from SSH-1 to SSH-2 keys"
596                         " not supported\n");
597                 return 1;
598             }
599             sshver = 1;
600             break;
601
602           case SSH_KEYTYPE_SSH2:
603           case SSH_KEYTYPE_SSH2_PUBLIC_RFC4716:
604           case SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH:
605           case SSH_KEYTYPE_OPENSSH_PEM:
606           case SSH_KEYTYPE_OPENSSH_NEW:
607           case SSH_KEYTYPE_SSHCOM:
608             if (sshver == 1) {
609                 fprintf(stderr, "puttygen: conversion from SSH-2 to SSH-1 keys"
610                         " not supported\n");
611                 return 1;
612             }
613             sshver = 2;
614             break;
615
616           case SSH_KEYTYPE_OPENSSH_AUTO:
617           default:
618             assert(0 && "Should never see these types on an input file");
619         }
620     }
621
622     /*
623      * Determine the default output file, if none is provided.
624      * 
625      * This will usually be equal to stdout, except that if the
626      * input and output file formats are the same then the default
627      * output is to overwrite the input.
628      * 
629      * Also in this code, we bomb out if the input and output file
630      * formats are the same and no other action is performed.
631      */
632     if ((intype == SSH_KEYTYPE_SSH1 && outtype == PRIVATE) ||
633         (intype == SSH_KEYTYPE_SSH2 && outtype == PRIVATE) ||
634         (intype == SSH_KEYTYPE_OPENSSH_PEM && outtype == OPENSSH_AUTO) ||
635         (intype == SSH_KEYTYPE_OPENSSH_NEW && outtype == OPENSSH_NEW) ||
636         (intype == SSH_KEYTYPE_SSHCOM && outtype == SSHCOM)) {
637         if (!outfile) {
638             outfile = infile;
639             outfiletmp = dupcat(outfile, ".tmp", NULL);
640         }
641
642         if (!change_passphrase && !comment) {
643             fprintf(stderr, "puttygen: this command would perform no useful"
644                     " action\n");
645             return 1;
646         }
647     } else {
648         if (!outfile) {
649             /*
650              * Bomb out rather than automatically choosing to write
651              * a private key file to stdout.
652              */
653             if (outtype == PRIVATE || outtype == OPENSSH_AUTO ||
654                 outtype == OPENSSH_NEW || outtype == SSHCOM) {
655                 fprintf(stderr, "puttygen: need to specify an output file\n");
656                 return 1;
657             }
658         }
659     }
660
661     /*
662      * Figure out whether we need to load the encrypted part of the
663      * key. This will be the case if either (a) we need to write
664      * out a private key format, or (b) the entire input key file
665      * is encrypted.
666      */
667     if (outtype == PRIVATE || outtype == OPENSSH_AUTO ||
668         outtype == OPENSSH_NEW || outtype == SSHCOM ||
669         intype == SSH_KEYTYPE_OPENSSH_PEM ||
670         intype == SSH_KEYTYPE_OPENSSH_NEW ||
671         intype == SSH_KEYTYPE_SSHCOM)
672         load_encrypted = TRUE;
673     else
674         load_encrypted = FALSE;
675
676     if (load_encrypted && (intype == SSH_KEYTYPE_SSH1_PUBLIC ||
677                            intype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
678                            intype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH)) {
679         fprintf(stderr, "puttygen: cannot perform this action on a "
680                 "public-key-only input file\n");
681         return 1;
682     }
683
684     /* ------------------------------------------------------------------
685      * Now we're ready to actually do some stuff.
686      */
687
688     /*
689      * Either load or generate a key.
690      */
691     if (keytype != NOKEYGEN) {
692         char *entropy;
693         char default_comment[80];
694         struct tm tm;
695         struct progress prog;
696
697         prog.phase = -1;
698         prog.current = -1;
699
700         tm = ltime();
701         if (keytype == DSA)
702             strftime(default_comment, 30, "dsa-key-%Y%m%d", &tm);
703         else if (keytype == ECDSA)
704             strftime(default_comment, 30, "ecdsa-key-%Y%m%d", &tm);
705         else if (keytype == ED25519)
706             strftime(default_comment, 30, "ed25519-key-%Y%m%d", &tm);
707         else
708             strftime(default_comment, 30, "rsa-key-%Y%m%d", &tm);
709
710         random_ref();
711         entropy = get_random_data(bits / 8);
712         if (!entropy) {
713             fprintf(stderr, "puttygen: failed to collect entropy, "
714                     "could not generate key\n");
715             return 1;
716         }
717         random_add_heavynoise(entropy, bits / 8);
718         smemclr(entropy, bits/8);
719         sfree(entropy);
720
721         if (keytype == DSA) {
722             struct dss_key *dsskey = snew(struct dss_key);
723             dsa_generate(dsskey, bits, progressfn, &prog);
724             ssh2key = snew(struct ssh2_userkey);
725             ssh2key->data = dsskey;
726             ssh2key->alg = &ssh_dss;
727             ssh1key = NULL;
728         } else if (keytype == ECDSA) {
729             struct ec_key *ec = snew(struct ec_key);
730             ec_generate(ec, bits, progressfn, &prog);
731             ssh2key = snew(struct ssh2_userkey);
732             ssh2key->data = ec;
733             if (bits == 256) {
734                 ssh2key->alg = &ssh_ecdsa_nistp256;
735             } else if (bits == 384) {
736                 ssh2key->alg = &ssh_ecdsa_nistp384;
737             } else {
738                 ssh2key->alg = &ssh_ecdsa_nistp521;
739             }
740             ssh1key = NULL;
741         } else if (keytype == ED25519) {
742             struct ec_key *ec = snew(struct ec_key);
743             ec_edgenerate(ec, bits, progressfn, &prog);
744             ssh2key = snew(struct ssh2_userkey);
745             ssh2key->data = ec;
746             ssh2key->alg = &ssh_ecdsa_ed25519;
747             ssh1key = NULL;
748         } else {
749             struct RSAKey *rsakey = snew(struct RSAKey);
750             rsa_generate(rsakey, bits, progressfn, &prog);
751             rsakey->comment = NULL;
752             if (keytype == RSA1) {
753                 ssh1key = rsakey;
754             } else {
755                 ssh2key = snew(struct ssh2_userkey);
756                 ssh2key->data = rsakey;
757                 ssh2key->alg = &ssh_rsa;
758             }
759         }
760         progressfn(&prog, PROGFN_PROGRESS, INT_MAX, -1);
761
762         if (ssh2key)
763             ssh2key->comment = dupstr(default_comment);
764         if (ssh1key)
765             ssh1key->comment = dupstr(default_comment);
766
767     } else {
768         const char *error = NULL;
769         int encrypted;
770
771         assert(infile != NULL);
772
773         /*
774          * Find out whether the input key is encrypted.
775          */
776         if (intype == SSH_KEYTYPE_SSH1)
777             encrypted = rsakey_encrypted(infilename, &origcomment);
778         else if (intype == SSH_KEYTYPE_SSH2)
779             encrypted = ssh2_userkey_encrypted(infilename, &origcomment);
780         else
781             encrypted = import_encrypted(infilename, intype, &origcomment);
782
783         /*
784          * If so, ask for a passphrase.
785          */
786         if (encrypted && load_encrypted) {
787             prompts_t *p = new_prompts(NULL);
788             int ret;
789             p->to_server = FALSE;
790             p->name = dupstr("SSH key passphrase");
791             add_prompt(p, dupstr("Enter passphrase to load key: "), FALSE);
792             ret = console_get_userpass_input(p, NULL, 0);
793             assert(ret >= 0);
794             if (!ret) {
795                 free_prompts(p);
796                 perror("puttygen: unable to read passphrase");
797                 return 1;
798             } else {
799                 passphrase = dupstr(p->prompts[0]->result);
800                 free_prompts(p);
801             }
802         } else {
803             passphrase = NULL;
804         }
805
806         switch (intype) {
807             int ret;
808
809           case SSH_KEYTYPE_SSH1:
810           case SSH_KEYTYPE_SSH1_PUBLIC:
811             ssh1key = snew(struct RSAKey);
812             if (!load_encrypted) {
813                 void *vblob;
814                 unsigned char *blob;
815                 int n, l, bloblen;
816
817                 ret = rsakey_pubblob(infilename, &vblob, &bloblen,
818                                      &origcomment, &error);
819                 blob = (unsigned char *)vblob;
820
821                 n = 4;                 /* skip modulus bits */
822                 
823                 l = ssh1_read_bignum(blob + n, bloblen - n,
824                                      &ssh1key->exponent);
825                 if (l < 0) {
826                     error = "SSH-1 public key blob was too short";
827                 } else {
828                     n += l;
829                     l = ssh1_read_bignum(blob + n, bloblen - n,
830                                          &ssh1key->modulus);
831                     if (l < 0) {
832                         error = "SSH-1 public key blob was too short";
833                     } else
834                         n += l;
835                 }
836                 ssh1key->comment = dupstr(origcomment);
837                 ssh1key->private_exponent = NULL;
838                 ssh1key->p = NULL;
839                 ssh1key->q = NULL;
840                 ssh1key->iqmp = NULL;
841             } else {
842                 ret = loadrsakey(infilename, ssh1key, passphrase, &error);
843             }
844             if (ret > 0)
845                 error = NULL;
846             else if (!error)
847                 error = "unknown error";
848             break;
849
850           case SSH_KEYTYPE_SSH2:
851           case SSH_KEYTYPE_SSH2_PUBLIC_RFC4716:
852           case SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH:
853             if (!load_encrypted) {
854                 ssh2blob = ssh2_userkey_loadpub(infilename, &ssh2alg,
855                                                 &ssh2bloblen, &origcomment,
856                                                 &error);
857                 if (ssh2blob) {
858                     ssh2algf = find_pubkey_alg(ssh2alg);
859                     if (ssh2algf)
860                         bits = ssh2algf->pubkey_bits(ssh2blob, ssh2bloblen);
861                     else
862                         bits = -1;
863                 }
864             } else {
865                 ssh2key = ssh2_load_userkey(infilename, passphrase, &error);
866             }
867             if ((ssh2key && ssh2key != SSH2_WRONG_PASSPHRASE) || ssh2blob)
868                 error = NULL;
869             else if (!error) {
870                 if (ssh2key == SSH2_WRONG_PASSPHRASE)
871                     error = "wrong passphrase";
872                 else
873                     error = "unknown error";
874             }
875             break;
876
877           case SSH_KEYTYPE_OPENSSH_PEM:
878           case SSH_KEYTYPE_OPENSSH_NEW:
879           case SSH_KEYTYPE_SSHCOM:
880             ssh2key = import_ssh2(infilename, intype, passphrase, &error);
881             if (ssh2key) {
882                 if (ssh2key != SSH2_WRONG_PASSPHRASE)
883                     error = NULL;
884                 else
885                     error = "wrong passphrase";
886             } else if (!error)
887                 error = "unknown error";
888             break;
889
890           default:
891             assert(0);
892         }
893
894         if (error) {
895             fprintf(stderr, "puttygen: error loading `%s': %s\n",
896                     infile, error);
897             return 1;
898         }
899     }
900
901     /*
902      * Change the comment if asked to.
903      */
904     if (comment) {
905         if (sshver == 1) {
906             assert(ssh1key);
907             sfree(ssh1key->comment);
908             ssh1key->comment = dupstr(comment);
909         } else {
910             assert(ssh2key);
911             sfree(ssh2key->comment);
912             ssh2key->comment = dupstr(comment);
913         }
914     }
915
916     /*
917      * Prompt for a new passphrase if we have been asked to, or if
918      * we have just generated a key.
919      */
920     if (change_passphrase || keytype != NOKEYGEN) {
921         prompts_t *p = new_prompts(NULL);
922         int ret;
923
924         p->to_server = FALSE;
925         p->name = dupstr("New SSH key passphrase");
926         add_prompt(p, dupstr("Enter passphrase to save key: "), FALSE);
927         add_prompt(p, dupstr("Re-enter passphrase to verify: "), FALSE);
928         ret = console_get_userpass_input(p, NULL, 0);
929         assert(ret >= 0);
930         if (!ret) {
931             free_prompts(p);
932             perror("puttygen: unable to read new passphrase");
933             return 1;
934         } else {
935             if (strcmp(p->prompts[0]->result, p->prompts[1]->result)) {
936                 free_prompts(p);
937                 fprintf(stderr, "puttygen: passphrases do not match\n");
938                 return 1;
939             }
940             if (passphrase) {
941                 smemclr(passphrase, strlen(passphrase));
942                 sfree(passphrase);
943             }
944             passphrase = dupstr(p->prompts[0]->result);
945             free_prompts(p);
946             if (!*passphrase) {
947                 sfree(passphrase);
948                 passphrase = NULL;
949             }
950         }
951     }
952
953     /*
954      * Write output.
955      * 
956      * (In the case where outfile and outfiletmp are both NULL,
957      * there is no semantic reason to initialise outfilename at
958      * all; but we have to write _something_ to it or some compiler
959      * will probably complain that it might be used uninitialised.)
960      */
961     if (outfiletmp)
962         outfilename = filename_from_str(outfiletmp);
963     else
964         outfilename = filename_from_str(outfile ? outfile : "");
965
966     switch (outtype) {
967         int ret, real_outtype;
968
969       case PRIVATE:
970         if (sshver == 1) {
971             assert(ssh1key);
972             ret = saversakey(outfilename, ssh1key, passphrase);
973             if (!ret) {
974                 fprintf(stderr, "puttygen: unable to save SSH-1 private key\n");
975                 return 1;
976             }
977         } else {
978             assert(ssh2key);
979             ret = ssh2_save_userkey(outfilename, ssh2key, passphrase);
980             if (!ret) {
981                 fprintf(stderr, "puttygen: unable to save SSH-2 private key\n");
982                 return 1;
983             }
984         }
985         if (outfiletmp) {
986             if (!move(outfiletmp, outfile))
987                 return 1;              /* rename failed */
988         }
989         break;
990
991       case PUBLIC:
992       case PUBLICO:
993         if (sshver == 1) {
994             FILE *fp;
995             char *dec1, *dec2;
996
997             assert(ssh1key);
998
999             if (outfile)
1000                 fp = f_open(outfilename, "w", FALSE);
1001             else
1002                 fp = stdout;
1003             dec1 = bignum_decimal(ssh1key->exponent);
1004             dec2 = bignum_decimal(ssh1key->modulus);
1005             fprintf(fp, "%d %s %s %s\n", bignum_bitcount(ssh1key->modulus),
1006                     dec1, dec2, ssh1key->comment);
1007             sfree(dec1);
1008             sfree(dec2);
1009             if (outfile)
1010                 fclose(fp);
1011         } else if (outtype == PUBLIC) {
1012             if (!ssh2blob) {
1013                 assert(ssh2key);
1014                 ssh2blob = ssh2key->alg->public_blob(ssh2key->data,
1015                                                      &ssh2bloblen);
1016             }
1017             save_ssh2_pubkey(outfile, ssh2key ? ssh2key->comment : origcomment,
1018                              ssh2blob, ssh2bloblen);
1019         } else if (outtype == PUBLICO) {
1020             char *buffer, *p;
1021             int i;
1022             FILE *fp;
1023
1024             if (!ssh2blob) {
1025                 assert(ssh2key);
1026                 ssh2blob = ssh2key->alg->public_blob(ssh2key->data,
1027                                                      &ssh2bloblen);
1028             }
1029             if (!ssh2alg) {
1030                 assert(ssh2key);
1031                 ssh2alg = ssh2key->alg->name;
1032             }
1033             if (ssh2key)
1034                 comment = ssh2key->comment;
1035             else
1036                 comment = origcomment;
1037
1038             buffer = snewn(strlen(ssh2alg) +
1039                            4 * ((ssh2bloblen+2) / 3) +
1040                            strlen(comment) + 3, char);
1041             strcpy(buffer, ssh2alg);
1042             p = buffer + strlen(buffer);
1043             *p++ = ' ';
1044             i = 0;
1045             while (i < ssh2bloblen) {
1046                 int n = (ssh2bloblen - i < 3 ? ssh2bloblen - i : 3);
1047                 base64_encode_atom(ssh2blob + i, n, p);
1048                 i += n;
1049                 p += 4;
1050             }
1051             if (*comment) {
1052                 *p++ = ' ';
1053                 strcpy(p, comment);
1054             } else
1055                 *p++ = '\0';
1056
1057             if (outfile)
1058                 fp = f_open(outfilename, "w", FALSE);
1059             else
1060                 fp = stdout;
1061             fprintf(fp, "%s\n", buffer);
1062             if (outfile)
1063                 fclose(fp);
1064
1065             sfree(buffer);
1066         }
1067         break;
1068
1069       case FP:
1070         {
1071             FILE *fp;
1072             char *fingerprint;
1073
1074             if (sshver == 1) {
1075                 assert(ssh1key);
1076                 fingerprint = snewn(128, char);
1077                 rsa_fingerprint(fingerprint, 128, ssh1key);
1078             } else {
1079                 if (ssh2key) {
1080                     fingerprint = ssh2key->alg->fingerprint(ssh2key->data);
1081                 } else {
1082                     assert(ssh2blob);
1083                     fingerprint = blobfp(ssh2alg, bits, ssh2blob, ssh2bloblen);
1084                 }
1085             }
1086
1087             if (outfile)
1088                 fp = f_open(outfilename, "w", FALSE);
1089             else
1090                 fp = stdout;
1091             fprintf(fp, "%s\n", fingerprint);
1092             if (outfile)
1093                 fclose(fp);
1094
1095             sfree(fingerprint);
1096         }
1097         break;
1098         
1099       case OPENSSH_AUTO:
1100       case OPENSSH_NEW:
1101       case SSHCOM:
1102         assert(sshver == 2);
1103         assert(ssh2key);
1104         random_ref(); /* both foreign key types require randomness,
1105                        * for IV or padding */
1106         switch (outtype) {
1107           case OPENSSH_AUTO:
1108             real_outtype = SSH_KEYTYPE_OPENSSH_AUTO;
1109             break;
1110           case OPENSSH_NEW:
1111             real_outtype = SSH_KEYTYPE_OPENSSH_NEW;
1112             break;
1113           case SSHCOM:
1114             real_outtype = SSH_KEYTYPE_SSHCOM;
1115             break;
1116           default:
1117             assert(0 && "control flow goof");
1118         }
1119         ret = export_ssh2(outfilename, real_outtype, ssh2key, passphrase);
1120         if (!ret) {
1121             fprintf(stderr, "puttygen: unable to export key\n");
1122             return 1;
1123         }
1124         if (outfiletmp) {
1125             if (!move(outfiletmp, outfile))
1126                 return 1;              /* rename failed */
1127         }
1128         break;
1129     }
1130
1131     if (passphrase) {
1132         smemclr(passphrase, strlen(passphrase));
1133         sfree(passphrase);
1134     }
1135
1136     if (ssh1key)
1137         freersakey(ssh1key);
1138     if (ssh2key) {
1139         ssh2key->alg->freekey(ssh2key->data);
1140         sfree(ssh2key);
1141     }
1142
1143     return 0;
1144 }
1145
1146 #ifdef TEST_CMDGEN
1147
1148 #undef main
1149
1150 #include <stdarg.h>
1151
1152 int passes, fails;
1153
1154 void setup_passphrases(char *first, ...)
1155 {
1156     va_list ap;
1157     char *next;
1158
1159     nprompts = 0;
1160     if (first) {
1161         prompts[nprompts++] = first;
1162         va_start(ap, first);
1163         while ((next = va_arg(ap, char *)) != NULL) {
1164             assert(nprompts < lenof(prompts));
1165             prompts[nprompts++] = next;
1166         }
1167         va_end(ap);
1168     }
1169 }
1170
1171 void test(int retval, ...)
1172 {
1173     va_list ap;
1174     int i, argc, ret;
1175     char **argv;
1176
1177     argc = 0;
1178     va_start(ap, retval);
1179     while (va_arg(ap, char *) != NULL)
1180         argc++;
1181     va_end(ap);
1182
1183     argv = snewn(argc+1, char *);
1184     va_start(ap, retval);
1185     for (i = 0; i <= argc; i++)
1186         argv[i] = va_arg(ap, char *);
1187     va_end(ap);
1188
1189     promptsgot = 0;
1190     ret = cmdgen_main(argc, argv);
1191
1192     if (ret != retval) {
1193         printf("FAILED retval (exp %d got %d):", retval, ret);
1194         for (i = 0; i < argc; i++)
1195             printf(" %s", argv[i]);
1196         printf("\n");
1197         fails++;
1198     } else if (promptsgot != nprompts) {
1199         printf("FAILED nprompts (exp %d got %d):", nprompts, promptsgot);
1200         for (i = 0; i < argc; i++)
1201             printf(" %s", argv[i]);
1202         printf("\n");
1203         fails++;
1204     } else {
1205         passes++;
1206     }
1207 }
1208
1209 void filecmp(char *file1, char *file2, char *fmt, ...)
1210 {
1211     /*
1212      * Ideally I should do file comparison myself, to maximise the
1213      * portability of this test suite once this application begins
1214      * running on non-Unix platforms. For the moment, though,
1215      * calling Unix diff is perfectly adequate.
1216      */
1217     char *buf;
1218     int ret;
1219
1220     buf = dupprintf("diff -q '%s' '%s'", file1, file2);
1221     ret = system(buf);
1222     sfree(buf);
1223
1224     if (ret) {
1225         va_list ap;
1226
1227         printf("FAILED diff (ret=%d): ", ret);
1228
1229         va_start(ap, fmt);
1230         vprintf(fmt, ap);
1231         va_end(ap);
1232
1233         printf("\n");
1234
1235         fails++;
1236     } else
1237         passes++;
1238 }
1239
1240 char *cleanup_fp(char *s)
1241 {
1242     char *p;
1243
1244     if (!strncmp(s, "ssh-", 4)) {
1245         s += strcspn(s, " \n\t");
1246         s += strspn(s, " \n\t");
1247     }
1248
1249     p = s;
1250     s += strcspn(s, " \n\t");
1251     s += strspn(s, " \n\t");
1252     s += strcspn(s, " \n\t");
1253
1254     return dupprintf("%.*s", s - p, p);
1255 }
1256
1257 char *get_fp(char *filename)
1258 {
1259     FILE *fp;
1260     char buf[256], *ret;
1261
1262     fp = fopen(filename, "r");
1263     if (!fp)
1264         return NULL;
1265     ret = fgets(buf, sizeof(buf), fp);
1266     fclose(fp);
1267     if (!ret)
1268         return NULL;
1269     return cleanup_fp(buf);
1270 }
1271
1272 void check_fp(char *filename, char *fp, char *fmt, ...)
1273 {
1274     char *newfp;
1275
1276     if (!fp)
1277         return;
1278
1279     newfp = get_fp(filename);
1280
1281     if (!strcmp(fp, newfp)) {
1282         passes++;
1283     } else {
1284         va_list ap;
1285
1286         printf("FAILED check_fp ['%s' != '%s']: ", newfp, fp);
1287
1288         va_start(ap, fmt);
1289         vprintf(fmt, ap);
1290         va_end(ap);
1291
1292         printf("\n");
1293
1294         fails++;
1295     }
1296
1297     sfree(newfp);
1298 }
1299
1300 int main(int argc, char **argv)
1301 {
1302     int i;
1303     static char *const keytypes[] = { "rsa1", "dsa", "rsa" };
1304
1305     /*
1306      * Even when this thing is compiled for automatic test mode,
1307      * it's helpful to be able to invoke it with command-line
1308      * options for _manual_ tests.
1309      */
1310     if (argc > 1)
1311         return cmdgen_main(argc, argv);
1312
1313     passes = fails = 0;
1314
1315     for (i = 0; i < lenof(keytypes); i++) {
1316         char filename[128], osfilename[128], scfilename[128];
1317         char pubfilename[128], tmpfilename1[128], tmpfilename2[128];
1318         char *fp;
1319
1320         sprintf(filename, "test-%s.ppk", keytypes[i]);
1321         sprintf(pubfilename, "test-%s.pub", keytypes[i]);
1322         sprintf(osfilename, "test-%s.os", keytypes[i]);
1323         sprintf(scfilename, "test-%s.sc", keytypes[i]);
1324         sprintf(tmpfilename1, "test-%s.tmp1", keytypes[i]);
1325         sprintf(tmpfilename2, "test-%s.tmp2", keytypes[i]);
1326
1327         /*
1328          * Create an encrypted key.
1329          */
1330         setup_passphrases("sponge", "sponge", NULL);
1331         test(0, "puttygen", "-t", keytypes[i], "-o", filename, NULL);
1332
1333         /*
1334          * List the public key in OpenSSH format.
1335          */
1336         setup_passphrases(NULL);
1337         test(0, "puttygen", "-L", filename, "-o", pubfilename, NULL);
1338         {
1339             char cmdbuf[256];
1340             fp = NULL;
1341             sprintf(cmdbuf, "ssh-keygen -l -f '%s' > '%s'",
1342                     pubfilename, tmpfilename1);
1343             if (system(cmdbuf) ||
1344                 (fp = get_fp(tmpfilename1)) == NULL) {
1345                 printf("UNABLE to test fingerprint matching against OpenSSH");
1346             }
1347         }
1348
1349         /*
1350          * List the public key in IETF/ssh.com format.
1351          */
1352         setup_passphrases(NULL);
1353         test(0, "puttygen", "-p", filename, NULL);
1354
1355         /*
1356          * List the fingerprint of the key.
1357          */
1358         setup_passphrases(NULL);
1359         test(0, "puttygen", "-l", filename, "-o", tmpfilename1, NULL);
1360         if (!fp) {
1361             /*
1362              * If we can't test fingerprints against OpenSSH, we
1363              * can at the very least test equality of all the
1364              * fingerprints we generate of this key throughout
1365              * testing.
1366              */
1367             fp = get_fp(tmpfilename1);
1368         } else {
1369             check_fp(tmpfilename1, fp, "%s initial fp", keytypes[i]);
1370         }
1371
1372         /*
1373          * Change the comment of the key; this _does_ require a
1374          * passphrase owing to the tamperproofing.
1375          * 
1376          * NOTE: In SSH-1, this only requires a passphrase because
1377          * of inadequacies of the loading and saving mechanisms. In
1378          * _principle_, it should be perfectly possible to modify
1379          * the comment on an SSH-1 key without requiring a
1380          * passphrase; the only reason I can't do it is because my
1381          * loading and saving mechanisms don't include a method of
1382          * loading all the key data without also trying to decrypt
1383          * the private section.
1384          * 
1385          * I don't consider this to be a problem worth solving,
1386          * because (a) to fix it would probably end up bloating
1387          * PuTTY proper, and (b) SSH-1 is on the way out anyway so
1388          * it shouldn't be highly significant. If it seriously
1389          * bothers anyone then perhaps I _might_ be persuadable.
1390          */
1391         setup_passphrases("sponge", NULL);
1392         test(0, "puttygen", "-C", "new-comment", filename, NULL);
1393
1394         /*
1395          * Change the passphrase to nothing.
1396          */
1397         setup_passphrases("sponge", "", "", NULL);
1398         test(0, "puttygen", "-P", filename, NULL);
1399
1400         /*
1401          * Change the comment of the key again; this time we expect no
1402          * passphrase to be required.
1403          */
1404         setup_passphrases(NULL);
1405         test(0, "puttygen", "-C", "new-comment-2", filename, NULL);
1406
1407         /*
1408          * Export the private key into OpenSSH format; no passphrase
1409          * should be required since the key is currently unencrypted.
1410          * For RSA1 keys, this should give an error.
1411          */
1412         setup_passphrases(NULL);
1413         test((i==0), "puttygen", "-O", "private-openssh", "-o", osfilename,
1414              filename, NULL);
1415
1416         if (i) {
1417             /*
1418              * List the fingerprint of the OpenSSH-formatted key.
1419              */
1420             setup_passphrases(NULL);
1421             test(0, "puttygen", "-l", osfilename, "-o", tmpfilename1, NULL);
1422             check_fp(tmpfilename1, fp, "%s openssh clear fp", keytypes[i]);
1423
1424             /*
1425              * List the public half of the OpenSSH-formatted key in
1426              * OpenSSH format.
1427              */
1428             setup_passphrases(NULL);
1429             test(0, "puttygen", "-L", osfilename, NULL);
1430
1431             /*
1432              * List the public half of the OpenSSH-formatted key in
1433              * IETF/ssh.com format.
1434              */
1435             setup_passphrases(NULL);
1436             test(0, "puttygen", "-p", osfilename, NULL);
1437         }
1438
1439         /*
1440          * Export the private key into ssh.com format; no passphrase
1441          * should be required since the key is currently unencrypted.
1442          * For RSA1 keys, this should give an error.
1443          */
1444         setup_passphrases(NULL);
1445         test((i==0), "puttygen", "-O", "private-sshcom", "-o", scfilename,
1446              filename, NULL);
1447
1448         if (i) {
1449             /*
1450              * List the fingerprint of the ssh.com-formatted key.
1451              */
1452             setup_passphrases(NULL);
1453             test(0, "puttygen", "-l", scfilename, "-o", tmpfilename1, NULL);
1454             check_fp(tmpfilename1, fp, "%s ssh.com clear fp", keytypes[i]);
1455
1456             /*
1457              * List the public half of the ssh.com-formatted key in
1458              * OpenSSH format.
1459              */
1460             setup_passphrases(NULL);
1461             test(0, "puttygen", "-L", scfilename, NULL);
1462
1463             /*
1464              * List the public half of the ssh.com-formatted key in
1465              * IETF/ssh.com format.
1466              */
1467             setup_passphrases(NULL);
1468             test(0, "puttygen", "-p", scfilename, NULL);
1469         }
1470
1471         if (i) {
1472             /*
1473              * Convert from OpenSSH into ssh.com.
1474              */
1475             setup_passphrases(NULL);
1476             test(0, "puttygen", osfilename, "-o", tmpfilename1,
1477                  "-O", "private-sshcom", NULL);
1478
1479             /*
1480              * Convert from ssh.com back into a PuTTY key,
1481              * supplying the same comment as we had before we
1482              * started to ensure the comparison works.
1483              */
1484             setup_passphrases(NULL);
1485             test(0, "puttygen", tmpfilename1, "-C", "new-comment-2",
1486                  "-o", tmpfilename2, NULL);
1487
1488             /*
1489              * See if the PuTTY key thus generated is the same as
1490              * the original.
1491              */
1492             filecmp(filename, tmpfilename2,
1493                     "p->o->s->p clear %s", keytypes[i]);
1494
1495             /*
1496              * Convert from ssh.com to OpenSSH.
1497              */
1498             setup_passphrases(NULL);
1499             test(0, "puttygen", scfilename, "-o", tmpfilename1,
1500                  "-O", "private-openssh", NULL);
1501
1502             /*
1503              * Convert from OpenSSH back into a PuTTY key,
1504              * supplying the same comment as we had before we
1505              * started to ensure the comparison works.
1506              */
1507             setup_passphrases(NULL);
1508             test(0, "puttygen", tmpfilename1, "-C", "new-comment-2",
1509                  "-o", tmpfilename2, NULL);
1510
1511             /*
1512              * See if the PuTTY key thus generated is the same as
1513              * the original.
1514              */
1515             filecmp(filename, tmpfilename2,
1516                     "p->s->o->p clear %s", keytypes[i]);
1517
1518             /*
1519              * Finally, do a round-trip conversion between PuTTY
1520              * and ssh.com without involving OpenSSH, to test that
1521              * the key comment is preserved in that case.
1522              */
1523             setup_passphrases(NULL);
1524             test(0, "puttygen", "-O", "private-sshcom", "-o", tmpfilename1,
1525                  filename, NULL);
1526             setup_passphrases(NULL);
1527             test(0, "puttygen", tmpfilename1, "-o", tmpfilename2, NULL);
1528             filecmp(filename, tmpfilename2,
1529                     "p->s->p clear %s", keytypes[i]);
1530         }
1531
1532         /*
1533          * Check that mismatched passphrases cause an error.
1534          */
1535         setup_passphrases("sponge2", "sponge3", NULL);
1536         test(1, "puttygen", "-P", filename, NULL);
1537
1538         /*
1539          * Put a passphrase back on.
1540          */
1541         setup_passphrases("sponge2", "sponge2", NULL);
1542         test(0, "puttygen", "-P", filename, NULL);
1543
1544         /*
1545          * Export the private key into OpenSSH format, this time
1546          * while encrypted. For RSA1 keys, this should give an
1547          * error.
1548          */
1549         if (i == 0)
1550             setup_passphrases(NULL);   /* error, hence no passphrase read */
1551         else
1552             setup_passphrases("sponge2", NULL);
1553         test((i==0), "puttygen", "-O", "private-openssh", "-o", osfilename,
1554              filename, NULL);
1555
1556         if (i) {
1557             /*
1558              * List the fingerprint of the OpenSSH-formatted key.
1559              */
1560             setup_passphrases("sponge2", NULL);
1561             test(0, "puttygen", "-l", osfilename, "-o", tmpfilename1, NULL);
1562             check_fp(tmpfilename1, fp, "%s openssh encrypted fp", keytypes[i]);
1563
1564             /*
1565              * List the public half of the OpenSSH-formatted key in
1566              * OpenSSH format.
1567              */
1568             setup_passphrases("sponge2", NULL);
1569             test(0, "puttygen", "-L", osfilename, NULL);
1570
1571             /*
1572              * List the public half of the OpenSSH-formatted key in
1573              * IETF/ssh.com format.
1574              */
1575             setup_passphrases("sponge2", NULL);
1576             test(0, "puttygen", "-p", osfilename, NULL);
1577         }
1578
1579         /*
1580          * Export the private key into ssh.com format, this time
1581          * while encrypted. For RSA1 keys, this should give an
1582          * error.
1583          */
1584         if (i == 0)
1585             setup_passphrases(NULL);   /* error, hence no passphrase read */
1586         else
1587             setup_passphrases("sponge2", NULL);
1588         test((i==0), "puttygen", "-O", "private-sshcom", "-o", scfilename,
1589              filename, NULL);
1590
1591         if (i) {
1592             /*
1593              * List the fingerprint of the ssh.com-formatted key.
1594              */
1595             setup_passphrases("sponge2", NULL);
1596             test(0, "puttygen", "-l", scfilename, "-o", tmpfilename1, NULL);
1597             check_fp(tmpfilename1, fp, "%s ssh.com encrypted fp", keytypes[i]);
1598
1599             /*
1600              * List the public half of the ssh.com-formatted key in
1601              * OpenSSH format.
1602              */
1603             setup_passphrases("sponge2", NULL);
1604             test(0, "puttygen", "-L", scfilename, NULL);
1605
1606             /*
1607              * List the public half of the ssh.com-formatted key in
1608              * IETF/ssh.com format.
1609              */
1610             setup_passphrases("sponge2", NULL);
1611             test(0, "puttygen", "-p", scfilename, NULL);
1612         }
1613
1614         if (i) {
1615             /*
1616              * Convert from OpenSSH into ssh.com.
1617              */
1618             setup_passphrases("sponge2", NULL);
1619             test(0, "puttygen", osfilename, "-o", tmpfilename1,
1620                  "-O", "private-sshcom", NULL);
1621
1622             /*
1623              * Convert from ssh.com back into a PuTTY key,
1624              * supplying the same comment as we had before we
1625              * started to ensure the comparison works.
1626              */
1627             setup_passphrases("sponge2", NULL);
1628             test(0, "puttygen", tmpfilename1, "-C", "new-comment-2",
1629                  "-o", tmpfilename2, NULL);
1630
1631             /*
1632              * See if the PuTTY key thus generated is the same as
1633              * the original.
1634              */
1635             filecmp(filename, tmpfilename2,
1636                     "p->o->s->p encrypted %s", keytypes[i]);
1637
1638             /*
1639              * Convert from ssh.com to OpenSSH.
1640              */
1641             setup_passphrases("sponge2", NULL);
1642             test(0, "puttygen", scfilename, "-o", tmpfilename1,
1643                  "-O", "private-openssh", NULL);
1644
1645             /*
1646              * Convert from OpenSSH back into a PuTTY key,
1647              * supplying the same comment as we had before we
1648              * started to ensure the comparison works.
1649              */
1650             setup_passphrases("sponge2", NULL);
1651             test(0, "puttygen", tmpfilename1, "-C", "new-comment-2",
1652                  "-o", tmpfilename2, NULL);
1653
1654             /*
1655              * See if the PuTTY key thus generated is the same as
1656              * the original.
1657              */
1658             filecmp(filename, tmpfilename2,
1659                     "p->s->o->p encrypted %s", keytypes[i]);
1660
1661             /*
1662              * Finally, do a round-trip conversion between PuTTY
1663              * and ssh.com without involving OpenSSH, to test that
1664              * the key comment is preserved in that case.
1665              */
1666             setup_passphrases("sponge2", NULL);
1667             test(0, "puttygen", "-O", "private-sshcom", "-o", tmpfilename1,
1668                  filename, NULL);
1669             setup_passphrases("sponge2", NULL);
1670             test(0, "puttygen", tmpfilename1, "-o", tmpfilename2, NULL);
1671             filecmp(filename, tmpfilename2,
1672                     "p->s->p encrypted %s", keytypes[i]);
1673         }
1674
1675         /*
1676          * Load with the wrong passphrase.
1677          */
1678         setup_passphrases("sponge8", NULL);
1679         test(1, "puttygen", "-C", "spurious-new-comment", filename, NULL);
1680
1681         /*
1682          * Load a totally bogus file.
1683          */
1684         setup_passphrases(NULL);
1685         test(1, "puttygen", "-C", "spurious-new-comment", pubfilename, NULL);
1686     }
1687     printf("%d passes, %d fails\n", passes, fails);
1688     return 0;
1689 }
1690
1691 #endif