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