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