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