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