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