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