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