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