]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - cmdgen.c
New function ltime() returns a struct tm of the current local time.
[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         struct tm tm;
606         struct progress prog;
607
608         prog.phase = -1;
609         prog.current = -1;
610
611         tm = ltime();
612         if (keytype == DSA)
613             strftime(default_comment, 30, "dsa-key-%Y%m%d", &tm);
614         else
615             strftime(default_comment, 30, "rsa-key-%Y%m%d", &tm);
616
617         random_ref();
618         entropy = get_random_data(bits / 8);
619         random_add_heavynoise(entropy, bits / 8);
620         memset(entropy, 0, bits/8);
621         sfree(entropy);
622
623         if (keytype == DSA) {
624             struct dss_key *dsskey = snew(struct dss_key);
625             dsa_generate(dsskey, bits, progressfn, &prog);
626             ssh2key = snew(struct ssh2_userkey);
627             ssh2key->data = dsskey;
628             ssh2key->alg = &ssh_dss;
629             ssh1key = NULL;
630         } else {
631             struct RSAKey *rsakey = snew(struct RSAKey);
632             rsa_generate(rsakey, bits, progressfn, &prog);
633             rsakey->comment = NULL;
634             if (keytype == RSA1) {
635                 ssh1key = rsakey;
636             } else {
637                 ssh2key = snew(struct ssh2_userkey);
638                 ssh2key->data = rsakey;
639                 ssh2key->alg = &ssh_rsa;
640             }
641         }
642         progressfn(&prog, PROGFN_PROGRESS, INT_MAX, -1);
643
644         if (ssh2key)
645             ssh2key->comment = dupstr(default_comment);
646         if (ssh1key)
647             ssh1key->comment = dupstr(default_comment);
648
649     } else {
650         const char *error = NULL;
651         int encrypted;
652
653         assert(infile != NULL);
654
655         /*
656          * Find out whether the input key is encrypted.
657          */
658         if (intype == SSH_KEYTYPE_SSH1)
659             encrypted = rsakey_encrypted(&infilename, &origcomment);
660         else if (intype == SSH_KEYTYPE_SSH2)
661             encrypted = ssh2_userkey_encrypted(&infilename, &origcomment);
662         else
663             encrypted = import_encrypted(&infilename, intype, &origcomment);
664
665         /*
666          * If so, ask for a passphrase.
667          */
668         if (encrypted && load_encrypted) {
669             passphrase = snewn(512, char);
670             if (!console_get_line("Enter passphrase to load key: ",
671                                   passphrase, 512, TRUE)) {
672                 perror("puttygen: unable to read passphrase");
673                 return 1;
674             }
675         } else {
676             passphrase = NULL;
677         }
678
679         switch (intype) {
680             int ret;
681
682           case SSH_KEYTYPE_SSH1:
683             ssh1key = snew(struct RSAKey);
684             if (!load_encrypted) {
685                 void *vblob;
686                 char *blob;
687                 int n, l, bloblen;
688
689                 ret = rsakey_pubblob(&infilename, &vblob, &bloblen, &error);
690                 blob = (char *)vblob;
691
692                 n = 4;                 /* skip modulus bits */
693                 
694                 l = ssh1_read_bignum(blob + n, bloblen - n,
695                                      &ssh1key->exponent);
696                 if (l < 0) {
697                     error = "SSH1 public key blob was too short";
698                 } else {
699                     n += l;
700                     l = ssh1_read_bignum(blob + n, bloblen - n,
701                                          &ssh1key->modulus);
702                     if (l < 0) {
703                         error = "SSH1 public key blob was too short";
704                     } else
705                         n += l;
706                 }
707                 ssh1key->comment = NULL;
708                 ssh1key->private_exponent = NULL;
709             } else {
710                 ret = loadrsakey(&infilename, ssh1key, passphrase, &error);
711             }
712             if (ret > 0)
713                 error = NULL;
714             else if (!error)
715                 error = "unknown error";
716             break;
717
718           case SSH_KEYTYPE_SSH2:
719             if (!load_encrypted) {
720                 ssh2blob = ssh2_userkey_loadpub(&infilename, &ssh2alg,
721                                                 &ssh2bloblen, &error);
722                 ssh2algf = find_pubkey_alg(ssh2alg);
723                 if (ssh2algf)
724                     bits = ssh2algf->pubkey_bits(ssh2blob, ssh2bloblen);
725                 else
726                     bits = -1;
727             } else {
728                 ssh2key = ssh2_load_userkey(&infilename, passphrase, &error);
729             }
730             if ((ssh2key && ssh2key != SSH2_WRONG_PASSPHRASE) || ssh2blob)
731                 error = NULL;
732             else if (!error) {
733                 if (ssh2key == SSH2_WRONG_PASSPHRASE)
734                     error = "wrong passphrase";
735                 else
736                     error = "unknown error";
737             }
738             break;
739
740           case SSH_KEYTYPE_OPENSSH:
741           case SSH_KEYTYPE_SSHCOM:
742             ssh2key = import_ssh2(&infilename, intype, passphrase);
743             if (ssh2key && ssh2key != SSH2_WRONG_PASSPHRASE)
744                 error = NULL;
745             else if (!error) {
746                 if (ssh2key == SSH2_WRONG_PASSPHRASE)
747                     error = "wrong passphrase";
748                 else
749                     error = "unknown error";
750             }
751             break;
752
753           default:
754             assert(0);
755         }
756
757         if (error) {
758             fprintf(stderr, "puttygen: error loading `%s': %s\n",
759                     infile, error);
760             return 1;
761         }
762     }
763
764     /*
765      * Change the comment if asked to.
766      */
767     if (comment) {
768         if (sshver == 1) {
769             assert(ssh1key);
770             sfree(ssh1key->comment);
771             ssh1key->comment = dupstr(comment);
772         } else {
773             assert(ssh2key);
774             sfree(ssh2key->comment);
775             ssh2key->comment = dupstr(comment);
776         }
777     }
778
779     /*
780      * Prompt for a new passphrase if we have been asked to, or if
781      * we have just generated a key.
782      */
783     if (change_passphrase || keytype != NOKEYGEN) {
784         char *passphrase2;
785
786         if (passphrase) {
787             memset(passphrase, 0, strlen(passphrase));
788             sfree(passphrase);
789         }
790
791         passphrase = snewn(512, char);
792         passphrase2 = snewn(512, char);
793         if (!console_get_line("Enter passphrase to save key: ",
794                               passphrase, 512, TRUE) ||
795             !console_get_line("Re-enter passphrase to verify: ",
796                               passphrase2, 512, TRUE)) {
797             perror("puttygen: unable to read new passphrase");
798             return 1;
799         }
800         if (strcmp(passphrase, passphrase2)) {
801             fprintf(stderr, "puttygen: passphrases do not match\n");
802             return 1;
803         }
804         memset(passphrase2, 0, strlen(passphrase2));
805         sfree(passphrase2);
806         if (!*passphrase) {
807             sfree(passphrase);
808             passphrase = NULL;
809         }
810     }
811
812     /*
813      * Write output.
814      * 
815      * (In the case where outfile and outfiletmp are both NULL,
816      * there is no semantic reason to initialise outfilename at
817      * all; but we have to write _something_ to it or some compiler
818      * will probably complain that it might be used uninitialised.)
819      */
820     if (outfiletmp)
821         outfilename = filename_from_str(outfiletmp);
822     else
823         outfilename = filename_from_str(outfile ? outfile : "");
824
825     switch (outtype) {
826         int ret;
827
828       case PRIVATE:
829         if (sshver == 1) {
830             assert(ssh1key);
831             ret = saversakey(&outfilename, ssh1key, passphrase);
832             if (!ret) {
833                 fprintf(stderr, "puttygen: unable to save SSH1 private key\n");
834                 return 1;
835             }
836         } else {
837             assert(ssh2key);
838             ret = ssh2_save_userkey(&outfilename, ssh2key, passphrase);
839             if (!ret) {
840                 fprintf(stderr, "puttygen: unable to save SSH2 private key\n");
841                 return 1;
842             }
843         }
844         if (outfiletmp) {
845             if (!move(outfiletmp, outfile))
846                 return 1;              /* rename failed */
847         }
848         break;
849
850       case PUBLIC:
851       case PUBLICO:
852         if (sshver == 1) {
853             FILE *fp;
854             char *dec1, *dec2;
855
856             assert(ssh1key);
857
858             if (outfile)
859                 fp = f_open(outfilename, "w");
860             else
861                 fp = stdout;
862             dec1 = bignum_decimal(ssh1key->exponent);
863             dec2 = bignum_decimal(ssh1key->modulus);
864             fprintf(fp, "%d %s %s %s\n", bignum_bitcount(ssh1key->modulus),
865                     dec1, dec2, ssh1key->comment);
866             sfree(dec1);
867             sfree(dec2);
868             if (outfile)
869                 fclose(fp);
870         } else if (outtype == PUBLIC) {
871             if (!ssh2blob) {
872                 assert(ssh2key);
873                 ssh2blob = ssh2key->alg->public_blob(ssh2key->data,
874                                                      &ssh2bloblen);
875             }
876             save_ssh2_pubkey(outfile, ssh2key ? ssh2key->comment : origcomment,
877                              ssh2blob, ssh2bloblen);
878         } else if (outtype == PUBLICO) {
879             char *buffer, *p;
880             int i;
881             FILE *fp;
882
883             if (!ssh2blob) {
884                 assert(ssh2key);
885                 ssh2blob = ssh2key->alg->public_blob(ssh2key->data,
886                                                      &ssh2bloblen);
887             }
888             if (!ssh2alg) {
889                 assert(ssh2key);
890                 ssh2alg = ssh2key->alg->name;
891             }
892             if (ssh2key)
893                 comment = ssh2key->comment;
894             else
895                 comment = origcomment;
896
897             buffer = snewn(strlen(ssh2alg) +
898                            4 * ((ssh2bloblen+2) / 3) +
899                            strlen(comment) + 3, char);
900             strcpy(buffer, ssh2alg);
901             p = buffer + strlen(buffer);
902             *p++ = ' ';
903             i = 0;
904             while (i < ssh2bloblen) {
905                 int n = (ssh2bloblen - i < 3 ? ssh2bloblen - i : 3);
906                 base64_encode_atom(ssh2blob + i, n, p);
907                 i += n;
908                 p += 4;
909             }
910             if (*comment) {
911                 *p++ = ' ';
912                 strcpy(p, comment);
913             } else
914                 *p++ = '\0';
915
916             if (outfile)
917                 fp = f_open(outfilename, "w");
918             else
919                 fp = stdout;
920             fprintf(fp, "%s\n", buffer);
921             if (outfile)
922                 fclose(fp);
923
924             sfree(buffer);
925         }
926         break;
927
928       case FP:
929         {
930             FILE *fp;
931             char *fingerprint;
932
933             if (sshver == 1) {
934                 assert(ssh1key);
935                 fingerprint = snewn(128, char);
936                 rsa_fingerprint(fingerprint, 128, ssh1key);
937             } else {
938                 if (ssh2key) {
939                     fingerprint = ssh2key->alg->fingerprint(ssh2key->data);
940                 } else {
941                     assert(ssh2blob);
942                     fingerprint = blobfp(ssh2alg, bits, ssh2blob, ssh2bloblen);
943                 }
944             }
945
946             if (outfile)
947                 fp = f_open(outfilename, "w");
948             else
949                 fp = stdout;
950             fprintf(fp, "%s\n", fingerprint);
951             if (outfile)
952                 fclose(fp);
953
954             sfree(fingerprint);
955         }
956         break;
957         
958       case OPENSSH:
959       case SSHCOM:
960         assert(sshver == 2);
961         assert(ssh2key);
962         ret = export_ssh2(&outfilename, outtype, ssh2key, passphrase);
963         if (!ret) {
964             fprintf(stderr, "puttygen: unable to export key\n");
965             return 1;
966         }
967         if (outfiletmp) {
968             if (!move(outfiletmp, outfile))
969                 return 1;              /* rename failed */
970         }
971         break;
972     }
973
974     if (passphrase) {
975         memset(passphrase, 0, strlen(passphrase));
976         sfree(passphrase);
977     }
978
979     if (ssh1key)
980         freersakey(ssh1key);
981     if (ssh2key) {
982         ssh2key->alg->freekey(ssh2key->data);
983         sfree(ssh2key);
984     }
985
986     return 0;
987 }
988
989 #ifdef TEST_CMDGEN
990
991 #undef main
992
993 #include <stdarg.h>
994
995 int passes, fails;
996
997 void setup_passphrases(char *first, ...)
998 {
999     va_list ap;
1000     char *next;
1001
1002     nprompts = 0;
1003     if (first) {
1004         prompts[nprompts++] = first;
1005         va_start(ap, first);
1006         while ((next = va_arg(ap, char *)) != NULL) {
1007             assert(nprompts < lenof(prompts));
1008             prompts[nprompts++] = next;
1009         }
1010         va_end(ap);
1011     }
1012 }
1013
1014 void test(int retval, ...)
1015 {
1016     va_list ap;
1017     int i, argc, ret;
1018     char **argv;
1019
1020     argc = 0;
1021     va_start(ap, retval);
1022     while (va_arg(ap, char *) != NULL)
1023         argc++;
1024     va_end(ap);
1025
1026     argv = snewn(argc+1, char *);
1027     va_start(ap, retval);
1028     for (i = 0; i <= argc; i++)
1029         argv[i] = va_arg(ap, char *);
1030     va_end(ap);
1031
1032     promptsgot = 0;
1033     ret = cmdgen_main(argc, argv);
1034
1035     if (ret != retval) {
1036         printf("FAILED retval (exp %d got %d):", retval, ret);
1037         for (i = 0; i < argc; i++)
1038             printf(" %s", argv[i]);
1039         printf("\n");
1040         fails++;
1041     } else if (promptsgot != nprompts) {
1042         printf("FAILED nprompts (exp %d got %d):", nprompts, promptsgot);
1043         for (i = 0; i < argc; i++)
1044             printf(" %s", argv[i]);
1045         printf("\n");
1046         fails++;
1047     } else {
1048         passes++;
1049     }
1050 }
1051
1052 void filecmp(char *file1, char *file2, char *fmt, ...)
1053 {
1054     /*
1055      * Ideally I should do file comparison myself, to maximise the
1056      * portability of this test suite once this application begins
1057      * running on non-Unix platforms. For the moment, though,
1058      * calling Unix diff is perfectly adequate.
1059      */
1060     char *buf;
1061     int ret;
1062
1063     buf = dupprintf("diff -q '%s' '%s'", file1, file2);
1064     ret = system(buf);
1065     sfree(buf);
1066
1067     if (ret) {
1068         va_list ap;
1069
1070         printf("FAILED diff (ret=%d): ", ret);
1071
1072         va_start(ap, fmt);
1073         vprintf(fmt, ap);
1074         va_end(ap);
1075
1076         printf("\n");
1077
1078         fails++;
1079     } else
1080         passes++;
1081 }
1082
1083 char *cleanup_fp(char *s)
1084 {
1085     char *p;
1086
1087     if (!strncmp(s, "ssh-", 4)) {
1088         s += strcspn(s, " \n\t");
1089         s += strspn(s, " \n\t");
1090     }
1091
1092     p = s;
1093     s += strcspn(s, " \n\t");
1094     s += strspn(s, " \n\t");
1095     s += strcspn(s, " \n\t");
1096
1097     return dupprintf("%.*s", s - p, p);
1098 }
1099
1100 char *get_fp(char *filename)
1101 {
1102     FILE *fp;
1103     char buf[256], *ret;
1104
1105     fp = fopen(filename, "r");
1106     if (!fp)
1107         return NULL;
1108     ret = fgets(buf, sizeof(buf), fp);
1109     fclose(fp);
1110     if (!ret)
1111         return NULL;
1112     return cleanup_fp(buf);
1113 }
1114
1115 void check_fp(char *filename, char *fp, char *fmt, ...)
1116 {
1117     char *newfp;
1118
1119     if (!fp)
1120         return;
1121
1122     newfp = get_fp(filename);
1123
1124     if (!strcmp(fp, newfp)) {
1125         passes++;
1126     } else {
1127         va_list ap;
1128
1129         printf("FAILED check_fp ['%s' != '%s']: ", newfp, fp);
1130
1131         va_start(ap, fmt);
1132         vprintf(fmt, ap);
1133         va_end(ap);
1134
1135         printf("\n");
1136
1137         fails++;
1138     }
1139
1140     sfree(newfp);
1141 }
1142
1143 int main(int argc, char **argv)
1144 {
1145     int i;
1146     static char *const keytypes[] = { "rsa1", "dsa", "rsa" };
1147
1148     /*
1149      * Even when this thing is compiled for automatic test mode,
1150      * it's helpful to be able to invoke it with command-line
1151      * options for _manual_ tests.
1152      */
1153     if (argc > 1)
1154         return cmdgen_main(argc, argv);
1155
1156     passes = fails = 0;
1157
1158     for (i = 0; i < lenof(keytypes); i++) {
1159         char filename[128], osfilename[128], scfilename[128];
1160         char pubfilename[128], tmpfilename1[128], tmpfilename2[128];
1161         char *fp;
1162
1163         sprintf(filename, "test-%s.ppk", keytypes[i]);
1164         sprintf(pubfilename, "test-%s.pub", keytypes[i]);
1165         sprintf(osfilename, "test-%s.os", keytypes[i]);
1166         sprintf(scfilename, "test-%s.sc", keytypes[i]);
1167         sprintf(tmpfilename1, "test-%s.tmp1", keytypes[i]);
1168         sprintf(tmpfilename2, "test-%s.tmp2", keytypes[i]);
1169
1170         /*
1171          * Create an encrypted key.
1172          */
1173         setup_passphrases("sponge", "sponge", NULL);
1174         test(0, "puttygen", "-t", keytypes[i], "-o", filename, NULL);
1175
1176         /*
1177          * List the public key in OpenSSH format.
1178          */
1179         setup_passphrases(NULL);
1180         test(0, "puttygen", "-L", filename, "-o", pubfilename, NULL);
1181         {
1182             char cmdbuf[256];
1183             fp = NULL;
1184             sprintf(cmdbuf, "ssh-keygen -l -f '%s' > '%s'",
1185                     pubfilename, tmpfilename1);
1186             if (system(cmdbuf) ||
1187                 (fp = get_fp(tmpfilename1)) == NULL) {
1188                 printf("UNABLE to test fingerprint matching against OpenSSH");
1189             }
1190         }
1191
1192         /*
1193          * List the public key in IETF/ssh.com format.
1194          */
1195         setup_passphrases(NULL);
1196         test(0, "puttygen", "-p", filename, NULL);
1197
1198         /*
1199          * List the fingerprint of the key.
1200          */
1201         setup_passphrases(NULL);
1202         test(0, "puttygen", "-l", filename, "-o", tmpfilename1, NULL);
1203         if (!fp) {
1204             /*
1205              * If we can't test fingerprints against OpenSSH, we
1206              * can at the very least test equality of all the
1207              * fingerprints we generate of this key throughout
1208              * testing.
1209              */
1210             fp = get_fp(tmpfilename1);
1211         } else {
1212             check_fp(tmpfilename1, fp, "%s initial fp", keytypes[i]);
1213         }
1214
1215         /*
1216          * Change the comment of the key; this _does_ require a
1217          * passphrase owing to the tamperproofing.
1218          * 
1219          * NOTE: In SSH1, this only requires a passphrase because
1220          * of inadequacies of the loading and saving mechanisms. In
1221          * _principle_, it should be perfectly possible to modify
1222          * the comment on an SSH1 key without requiring a
1223          * passphrase; the only reason I can't do it is because my
1224          * loading and saving mechanisms don't include a method of
1225          * loading all the key data without also trying to decrypt
1226          * the private section.
1227          * 
1228          * I don't consider this to be a problem worth solving,
1229          * because (a) to fix it would probably end up bloating
1230          * PuTTY proper, and (b) SSH1 is on the way out anyway so
1231          * it shouldn't be highly significant. If it seriously
1232          * bothers anyone then perhaps I _might_ be persuadable.
1233          */
1234         setup_passphrases("sponge", NULL);
1235         test(0, "puttygen", "-C", "new-comment", filename, NULL);
1236
1237         /*
1238          * Change the passphrase to nothing.
1239          */
1240         setup_passphrases("sponge", "", "", NULL);
1241         test(0, "puttygen", "-P", filename, NULL);
1242
1243         /*
1244          * Change the comment of the key again; this time we expect no
1245          * passphrase to be required.
1246          */
1247         setup_passphrases(NULL);
1248         test(0, "puttygen", "-C", "new-comment-2", filename, NULL);
1249
1250         /*
1251          * Export the private key into OpenSSH format; no passphrase
1252          * should be required since the key is currently unencrypted.
1253          * For RSA1 keys, this should give an error.
1254          */
1255         setup_passphrases(NULL);
1256         test((i==0), "puttygen", "-O", "private-openssh", "-o", osfilename,
1257              filename, NULL);
1258
1259         if (i) {
1260             /*
1261              * List the fingerprint of the OpenSSH-formatted key.
1262              */
1263             setup_passphrases(NULL);
1264             test(0, "puttygen", "-l", osfilename, "-o", tmpfilename1, NULL);
1265             check_fp(tmpfilename1, fp, "%s openssh clear fp", keytypes[i]);
1266
1267             /*
1268              * List the public half of the OpenSSH-formatted key in
1269              * OpenSSH format.
1270              */
1271             setup_passphrases(NULL);
1272             test(0, "puttygen", "-L", osfilename, NULL);
1273
1274             /*
1275              * List the public half of the OpenSSH-formatted key in
1276              * IETF/ssh.com format.
1277              */
1278             setup_passphrases(NULL);
1279             test(0, "puttygen", "-p", osfilename, NULL);
1280         }
1281
1282         /*
1283          * Export the private key into ssh.com format; no passphrase
1284          * should be required since the key is currently unencrypted.
1285          * For RSA1 keys, this should give an error.
1286          */
1287         setup_passphrases(NULL);
1288         test((i==0), "puttygen", "-O", "private-sshcom", "-o", scfilename,
1289              filename, NULL);
1290
1291         if (i) {
1292             /*
1293              * List the fingerprint of the ssh.com-formatted key.
1294              */
1295             setup_passphrases(NULL);
1296             test(0, "puttygen", "-l", scfilename, "-o", tmpfilename1, NULL);
1297             check_fp(tmpfilename1, fp, "%s ssh.com clear fp", keytypes[i]);
1298
1299             /*
1300              * List the public half of the ssh.com-formatted key in
1301              * OpenSSH format.
1302              */
1303             setup_passphrases(NULL);
1304             test(0, "puttygen", "-L", scfilename, NULL);
1305
1306             /*
1307              * List the public half of the ssh.com-formatted key in
1308              * IETF/ssh.com format.
1309              */
1310             setup_passphrases(NULL);
1311             test(0, "puttygen", "-p", scfilename, NULL);
1312         }
1313
1314         if (i) {
1315             /*
1316              * Convert from OpenSSH into ssh.com.
1317              */
1318             setup_passphrases(NULL);
1319             test(0, "puttygen", osfilename, "-o", tmpfilename1,
1320                  "-O", "private-sshcom", NULL);
1321
1322             /*
1323              * Convert from ssh.com back into a PuTTY key,
1324              * supplying the same comment as we had before we
1325              * started to ensure the comparison works.
1326              */
1327             setup_passphrases(NULL);
1328             test(0, "puttygen", tmpfilename1, "-C", "new-comment-2",
1329                  "-o", tmpfilename2, NULL);
1330
1331             /*
1332              * See if the PuTTY key thus generated is the same as
1333              * the original.
1334              */
1335             filecmp(filename, tmpfilename2,
1336                     "p->o->s->p clear %s", keytypes[i]);
1337
1338             /*
1339              * Convert from ssh.com to OpenSSH.
1340              */
1341             setup_passphrases(NULL);
1342             test(0, "puttygen", scfilename, "-o", tmpfilename1,
1343                  "-O", "private-openssh", NULL);
1344
1345             /*
1346              * Convert from OpenSSH back into a PuTTY key,
1347              * supplying the same comment as we had before we
1348              * started to ensure the comparison works.
1349              */
1350             setup_passphrases(NULL);
1351             test(0, "puttygen", tmpfilename1, "-C", "new-comment-2",
1352                  "-o", tmpfilename2, NULL);
1353
1354             /*
1355              * See if the PuTTY key thus generated is the same as
1356              * the original.
1357              */
1358             filecmp(filename, tmpfilename2,
1359                     "p->s->o->p clear %s", keytypes[i]);
1360
1361             /*
1362              * Finally, do a round-trip conversion between PuTTY
1363              * and ssh.com without involving OpenSSH, to test that
1364              * the key comment is preserved in that case.
1365              */
1366             setup_passphrases(NULL);
1367             test(0, "puttygen", "-O", "private-sshcom", "-o", tmpfilename1,
1368                  filename, NULL);
1369             setup_passphrases(NULL);
1370             test(0, "puttygen", tmpfilename1, "-o", tmpfilename2, NULL);
1371             filecmp(filename, tmpfilename2,
1372                     "p->s->p clear %s", keytypes[i]);
1373         }
1374
1375         /*
1376          * Check that mismatched passphrases cause an error.
1377          */
1378         setup_passphrases("sponge2", "sponge3", NULL);
1379         test(1, "puttygen", "-P", filename, NULL);
1380
1381         /*
1382          * Put a passphrase back on.
1383          */
1384         setup_passphrases("sponge2", "sponge2", NULL);
1385         test(0, "puttygen", "-P", filename, NULL);
1386
1387         /*
1388          * Export the private key into OpenSSH format, this time
1389          * while encrypted. For RSA1 keys, this should give an
1390          * error.
1391          */
1392         if (i == 0)
1393             setup_passphrases(NULL);   /* error, hence no passphrase read */
1394         else
1395             setup_passphrases("sponge2", NULL);
1396         test((i==0), "puttygen", "-O", "private-openssh", "-o", osfilename,
1397              filename, NULL);
1398
1399         if (i) {
1400             /*
1401              * List the fingerprint of the OpenSSH-formatted key.
1402              */
1403             setup_passphrases("sponge2", NULL);
1404             test(0, "puttygen", "-l", osfilename, "-o", tmpfilename1, NULL);
1405             check_fp(tmpfilename1, fp, "%s openssh encrypted fp", keytypes[i]);
1406
1407             /*
1408              * List the public half of the OpenSSH-formatted key in
1409              * OpenSSH format.
1410              */
1411             setup_passphrases("sponge2", NULL);
1412             test(0, "puttygen", "-L", osfilename, NULL);
1413
1414             /*
1415              * List the public half of the OpenSSH-formatted key in
1416              * IETF/ssh.com format.
1417              */
1418             setup_passphrases("sponge2", NULL);
1419             test(0, "puttygen", "-p", osfilename, NULL);
1420         }
1421
1422         /*
1423          * Export the private key into ssh.com format, this time
1424          * while encrypted. For RSA1 keys, this should give an
1425          * error.
1426          */
1427         if (i == 0)
1428             setup_passphrases(NULL);   /* error, hence no passphrase read */
1429         else
1430             setup_passphrases("sponge2", NULL);
1431         test((i==0), "puttygen", "-O", "private-sshcom", "-o", scfilename,
1432              filename, NULL);
1433
1434         if (i) {
1435             /*
1436              * List the fingerprint of the ssh.com-formatted key.
1437              */
1438             setup_passphrases("sponge2", NULL);
1439             test(0, "puttygen", "-l", scfilename, "-o", tmpfilename1, NULL);
1440             check_fp(tmpfilename1, fp, "%s ssh.com encrypted fp", keytypes[i]);
1441
1442             /*
1443              * List the public half of the ssh.com-formatted key in
1444              * OpenSSH format.
1445              */
1446             setup_passphrases("sponge2", NULL);
1447             test(0, "puttygen", "-L", scfilename, NULL);
1448
1449             /*
1450              * List the public half of the ssh.com-formatted key in
1451              * IETF/ssh.com format.
1452              */
1453             setup_passphrases("sponge2", NULL);
1454             test(0, "puttygen", "-p", scfilename, NULL);
1455         }
1456
1457         if (i) {
1458             /*
1459              * Convert from OpenSSH into ssh.com.
1460              */
1461             setup_passphrases("sponge2", NULL);
1462             test(0, "puttygen", osfilename, "-o", tmpfilename1,
1463                  "-O", "private-sshcom", NULL);
1464
1465             /*
1466              * Convert from ssh.com back into a PuTTY key,
1467              * supplying the same comment as we had before we
1468              * started to ensure the comparison works.
1469              */
1470             setup_passphrases("sponge2", NULL);
1471             test(0, "puttygen", tmpfilename1, "-C", "new-comment-2",
1472                  "-o", tmpfilename2, NULL);
1473
1474             /*
1475              * See if the PuTTY key thus generated is the same as
1476              * the original.
1477              */
1478             filecmp(filename, tmpfilename2,
1479                     "p->o->s->p encrypted %s", keytypes[i]);
1480
1481             /*
1482              * Convert from ssh.com to OpenSSH.
1483              */
1484             setup_passphrases("sponge2", NULL);
1485             test(0, "puttygen", scfilename, "-o", tmpfilename1,
1486                  "-O", "private-openssh", NULL);
1487
1488             /*
1489              * Convert from OpenSSH back into a PuTTY key,
1490              * supplying the same comment as we had before we
1491              * started to ensure the comparison works.
1492              */
1493             setup_passphrases("sponge2", NULL);
1494             test(0, "puttygen", tmpfilename1, "-C", "new-comment-2",
1495                  "-o", tmpfilename2, NULL);
1496
1497             /*
1498              * See if the PuTTY key thus generated is the same as
1499              * the original.
1500              */
1501             filecmp(filename, tmpfilename2,
1502                     "p->s->o->p encrypted %s", keytypes[i]);
1503
1504             /*
1505              * Finally, do a round-trip conversion between PuTTY
1506              * and ssh.com without involving OpenSSH, to test that
1507              * the key comment is preserved in that case.
1508              */
1509             setup_passphrases("sponge2", NULL);
1510             test(0, "puttygen", "-O", "private-sshcom", "-o", tmpfilename1,
1511                  filename, NULL);
1512             setup_passphrases("sponge2", NULL);
1513             test(0, "puttygen", tmpfilename1, "-o", tmpfilename2, NULL);
1514             filecmp(filename, tmpfilename2,
1515                     "p->s->p encrypted %s", keytypes[i]);
1516         }
1517
1518         /*
1519          * Load with the wrong passphrase.
1520          */
1521         setup_passphrases("sponge8", NULL);
1522         test(1, "puttygen", "-C", "spurious-new-comment", filename, NULL);
1523
1524         /*
1525          * Load a totally bogus file.
1526          */
1527         setup_passphrases(NULL);
1528         test(1, "puttygen", "-C", "spurious-new-comment", pubfilename, NULL);
1529     }
1530     printf("%d passes, %d fails\n", passes, fails);
1531     return 0;
1532 }
1533
1534 #endif