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