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