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