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