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