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