2 * cmdgen.c - command-line form of PuTTYgen
9 * + a neat way to do this might be to have a -DTESTMODE for
10 * this file, which #defines console_get_line and
11 * get_random_noise to different names in order to be able to
12 * link them to test stubs rather than the real ones. That
13 * way I can have a test rig which checks whether passphrases
14 * are being prompted for.
17 #define PUTTY_DO_GLOBALS
30 #define get_random_data get_random_data_diagnostic
31 char *get_random_data(int len)
33 char *buf = snewn(len, char);
34 memset(buf, 'x', len);
43 static void progress_update(void *param, int action, int phase, int iprogress)
45 struct progress *p = (struct progress *)param;
46 if (action != PROGFN_PROGRESS)
48 if (phase > p->phase) {
53 p->current = iprogress - 1;
55 p->current = iprogress;
57 while (p->current < iprogress) {
64 static void no_progress(void *param, int action, int phase, int iprogress)
68 void modalfatalbox(char *p, ...)
71 fprintf(stderr, "FATAL ERROR: ");
73 vfprintf(stderr, p, ap);
80 * Stubs to let everything else link sensibly.
82 void log_eventlog(void *handle, const char *event)
85 char *x_get_default(const char *key)
93 void showversion(void)
95 char *verstr = dupstr(ver);
96 verstr[0] = tolower(verstr[0]);
97 printf("PuTTYgen %s\n", verstr);
104 "Usage: puttygen ( keyfile | -t type [ -b bits ] )\n"
105 " [ -C comment ] [ -P ]\n"
106 " [ -o output-keyfile ] [ -O type | -l | -L"
113 * Help message is an extended version of the usage message. So
114 * start with that, plus a version heading.
119 " -t specify key type when generating (rsa, dsa, rsa1)\n"
120 " -b specify number of bits when generating key\n"
121 " -C change or specify key comment\n"
122 " -P change key passphrase\n"
123 " -O specify output type:\n"
124 " private output PuTTY private key format\n"
125 " private-openssh export OpenSSH private key\n"
126 " private-sshcom export ssh.com private key\n"
127 " public standard / ssh.com public key\n"
128 " public-openssh OpenSSH public key\n"
129 " fingerprint output the key fingerprint\n"
130 " -o specify output file\n"
131 " -l equivalent to `-O fingerprint'\n"
132 " -L equivalent to `-O public-openssh'\n"
133 " -p equivalent to `-O public'\n"
137 static int save_ssh2_pubkey(char *filename, char *comment,
138 void *v_pub_blob, int pub_len)
140 unsigned char *pub_blob = (unsigned char *)v_pub_blob;
146 fp = fopen(filename, "wb");
152 fprintf(fp, "---- BEGIN SSH2 PUBLIC KEY ----\n");
155 fprintf(fp, "Comment: \"");
156 for (p = comment; *p; p++) {
157 if (*p == '\\' || *p == '\"')
166 while (i < pub_len) {
168 int n = (pub_len - i < 3 ? pub_len - i : 3);
169 base64_encode_atom(pub_blob + i, n, buf);
173 if (++column >= 16) {
181 fprintf(fp, "---- END SSH2 PUBLIC KEY ----\n");
187 static void move(char *from, char *to)
191 ret = rename(from, to);
194 * This OS may require us to remove the original file first.
197 ret = rename(from, to);
200 perror("puttygen: cannot move new file on to old one");
205 static char *blobfp(char *alg, int bits, char *blob, int bloblen)
208 unsigned char digest[16];
209 struct MD5Context md5c;
213 MD5Update(&md5c, blob, bloblen);
214 MD5Final(digest, &md5c);
216 sprintf(buffer, "%s ", alg);
218 sprintf(buffer + strlen(buffer), "%d ", bits);
219 for (i = 0; i < 16; i++)
220 sprintf(buffer + strlen(buffer), "%s%02x", i ? ":" : "",
223 return dupstr(buffer);
226 int main(int argc, char **argv)
230 enum { NOKEYGEN, RSA1, RSA2, DSA } keytype = NOKEYGEN;
231 char *outfile = NULL, *outfiletmp = NULL;
232 Filename outfilename;
233 enum { PRIVATE, PUBLIC, PUBLICO, FP, OPENSSH, SSHCOM } outtype = PRIVATE;
235 char *comment = NULL, *origcomment = NULL;
236 int change_passphrase = FALSE;
237 int errs = FALSE, nogo = FALSE;
238 int intype = SSH_KEYTYPE_UNOPENABLE;
240 struct ssh2_userkey *ssh2key = NULL;
241 struct RSAKey *ssh1key = NULL;
242 char *ssh2blob = NULL, *ssh2alg = NULL;
243 const struct ssh_signkey *ssh2algf = NULL;
245 char *passphrase = NULL;
247 progfn_t progressfn = is_interactive() ? progress_update : no_progress;
249 /* ------------------------------------------------------------------
250 * Parse the command line to figure out what we've been asked to do.
254 * If run with no arguments at all, print the usage message and
263 * Parse command line arguments.
280 opt = p++; /* opt will have _one_ leading - */
281 while (*p && *p != '=')
282 p++; /* find end of option */
288 if (!strcmp(opt, "-help")) {
291 } else if (!strcmp(opt, "-version")) {
296 * A sample option requiring an argument:
298 * else if (!strcmp(opt, "-output")) {
300 * errs = TRUE, error(err_optnoarg, opt);
308 "puttygen: no such option `--%s'\n", opt);
321 * Option requiring no parameter.
333 change_passphrase = TRUE;
345 progressfn = no_progress;
355 * Option requiring parameter.
361 fprintf(stderr, "puttygen: option `-%c' expects a"
366 * Now c is the option and p is the parameter.
370 if (!strcmp(p, "rsa") || !strcmp(p, "rsa2"))
371 keytype = RSA2, sshver = 2;
372 else if (!strcmp(p, "rsa1"))
373 keytype = RSA1, sshver = 1;
374 else if (!strcmp(p, "dsa") || !strcmp(p, "dss"))
375 keytype = DSA, sshver = 2;
378 "puttygen: unknown key type `%s'\n", p);
389 if (!strcmp(p, "public"))
391 else if (!strcmp(p, "public-openssh"))
393 else if (!strcmp(p, "private"))
395 else if (!strcmp(p, "fingerprint"))
397 else if (!strcmp(p, "private-openssh"))
398 outtype = OPENSSH, sshver = 2;
399 else if (!strcmp(p, "private-sshcom"))
400 outtype = SSHCOM, sshver = 2;
403 "puttygen: unknown output type `%s'\n", p);
411 p = NULL; /* prevent continued processing */
415 * Unrecognised option.
418 fprintf(stderr, "puttygen: no such option `-%c'\n", c);
424 * A non-option argument.
430 fprintf(stderr, "puttygen: cannot handle more than one"
443 * If run with at least one argument _but_ not the required
444 * ones, print the usage message and return failure.
446 if (!infile && keytype == NOKEYGEN) {
451 /* ------------------------------------------------------------------
452 * Figure out further details of exactly what we're going to do.
456 * Bomb out if we've been asked to both load and generate a
459 if (keytype != NOKEYGEN && intype) {
460 fprintf(stderr, "puttygen: cannot both load and generate a key\n");
465 * Analyse the type of the input file, in case this affects our
469 infilename = filename_from_str(infile);
471 intype = key_type(&infilename);
475 * It would be nice here to be able to load _public_
476 * key files, in any of a number of forms, and (a)
477 * convert them to other public key types, (b) print
478 * out their fingerprints. Or, I suppose, for real
479 * orthogonality, (c) change their comment!
481 * In fact this opens some interesting possibilities.
482 * Suppose ssh2_userkey_loadpub() were able to load
483 * public key files as well as extracting the public
484 * key from private ones. And suppose I did the thing
485 * I've been wanting to do, where specifying a
486 * particular private key file for authentication
487 * causes any _other_ key in the agent to be discarded.
488 * Then, if you had an agent forwarded to the machine
489 * you were running Unix PuTTY or Plink on, and you
490 * needed to specify which of the keys in the agent it
491 * should use, you could do that by supplying a
492 * _public_ key file, thus not needing to trust even
493 * your encrypted private key file to the network. Ooh!
496 case SSH_KEYTYPE_UNOPENABLE:
497 case SSH_KEYTYPE_UNKNOWN:
498 fprintf(stderr, "puttygen: unable to load file `%s': %s\n",
499 infile, key_type_to_str(intype));
502 case SSH_KEYTYPE_SSH1:
504 fprintf(stderr, "puttygen: conversion from SSH1 to SSH2 keys"
511 case SSH_KEYTYPE_SSH2:
512 case SSH_KEYTYPE_OPENSSH:
513 case SSH_KEYTYPE_SSHCOM:
515 fprintf(stderr, "puttygen: conversion from SSH2 to SSH1 keys"
525 * Determine the default output file, if none is provided.
527 * This will usually be equal to stdout, except that if the
528 * input and output file formats are the same then the default
529 * output is to overwrite the input.
531 * Also in this code, we bomb out if the input and output file
532 * formats are the same and no other action is performed.
534 if ((intype == SSH_KEYTYPE_SSH1 && outtype == PRIVATE) ||
535 (intype == SSH_KEYTYPE_SSH2 && outtype == PRIVATE) ||
536 (intype == SSH_KEYTYPE_OPENSSH && outtype == OPENSSH) ||
537 (intype == SSH_KEYTYPE_SSHCOM && outtype == SSHCOM)) {
540 outfiletmp = dupcat(outfile, ".tmp");
543 if (!change_passphrase && !comment) {
544 fprintf(stderr, "puttygen: this command would perform no useful"
551 * Bomb out rather than automatically choosing to write
552 * a private key file to stdout.
554 if (outtype==PRIVATE || outtype==OPENSSH || outtype==SSHCOM) {
555 fprintf(stderr, "puttygen: need to specify an output file\n");
562 * Figure out whether we need to load the encrypted part of the
563 * key. This will be the case if either (a) we need to write
564 * out a private key format, or (b) the entire input key file
567 if (outtype == PRIVATE || outtype == OPENSSH || outtype == SSHCOM ||
568 intype == SSH_KEYTYPE_OPENSSH || intype == SSH_KEYTYPE_SSHCOM)
569 load_encrypted = TRUE;
571 load_encrypted = FALSE;
573 /* ------------------------------------------------------------------
574 * Now we're ready to actually do some stuff.
578 * Either load or generate a key.
580 if (keytype != NOKEYGEN) {
582 char default_comment[80];
585 struct progress prog;
593 strftime(default_comment, 30, "dsa-key-%Y%m%d", tm);
595 strftime(default_comment, 30, "rsa-key-%Y%m%d", tm);
598 entropy = get_random_data(bits / 8);
599 random_add_heavynoise(entropy, bits / 8);
600 memset(entropy, 0, bits/8);
603 if (keytype == DSA) {
604 struct dss_key *dsskey = snew(struct dss_key);
605 dsa_generate(dsskey, bits, progressfn, &prog);
606 ssh2key = snew(struct ssh2_userkey);
607 ssh2key->data = dsskey;
608 ssh2key->alg = &ssh_dss;
611 struct RSAKey *rsakey = snew(struct RSAKey);
612 rsa_generate(rsakey, bits, progressfn, &prog);
613 if (keytype == RSA1) {
616 ssh2key = snew(struct ssh2_userkey);
617 ssh2key->data = rsakey;
618 ssh2key->alg = &ssh_rsa;
621 progressfn(&prog, PROGFN_PROGRESS, INT_MAX, -1);
624 ssh2key->comment = dupstr(default_comment);
626 ssh1key->comment = dupstr(default_comment);
629 const char *error = NULL;
632 assert(infile != NULL);
635 * Find out whether the input key is encrypted.
637 if (intype == SSH_KEYTYPE_SSH1)
638 encrypted = rsakey_encrypted(&infilename, &origcomment);
639 else if (intype == SSH_KEYTYPE_SSH2)
640 encrypted = ssh2_userkey_encrypted(&infilename, &origcomment);
642 encrypted = import_encrypted(&infilename, intype, &origcomment);
645 * If so, ask for a passphrase.
647 if (encrypted && load_encrypted) {
648 passphrase = snewn(512, char);
649 if (!console_get_line("Enter passphrase to load key: ",
650 passphrase, 512, TRUE)) {
651 perror("puttygen: unable to read passphrase");
661 case SSH_KEYTYPE_SSH1:
662 ssh1key = snew(struct RSAKey);
663 if (!load_encrypted) {
668 ret = rsakey_pubblob(&infilename, &vblob, &bloblen, &error);
669 blob = (char *)vblob;
671 n = 4; /* skip modulus bits */
672 n += ssh1_read_bignum(blob + n, &ssh1key->exponent);
673 n += ssh1_read_bignum(blob + n, &ssh1key->modulus);
674 ssh1key->comment = NULL;
676 ret = loadrsakey(&infilename, ssh1key, passphrase, &error);
681 error = "unknown error";
684 case SSH_KEYTYPE_SSH2:
685 if (!load_encrypted) {
686 ssh2blob = ssh2_userkey_loadpub(&infilename, &ssh2alg,
687 &ssh2bloblen, &error);
688 ssh2algf = find_pubkey_alg(ssh2alg);
690 bits = ssh2algf->pubkey_bits(ssh2blob, ssh2bloblen);
694 ssh2key = ssh2_load_userkey(&infilename, passphrase, &error);
696 if (ssh2key || ssh2blob)
699 if (ssh2key == SSH2_WRONG_PASSPHRASE)
700 error = "wrong passphrase";
702 error = "unknown error";
706 case SSH_KEYTYPE_OPENSSH:
707 case SSH_KEYTYPE_SSHCOM:
708 ssh2key = import_ssh2(&infilename, intype, passphrase);
712 if (ssh2key == SSH2_WRONG_PASSPHRASE)
713 error = "wrong passphrase";
715 error = "unknown error";
724 fprintf(stderr, "puttygen: error loading `%s': %s\n",
731 * Change the comment if asked to.
736 sfree(ssh1key->comment);
737 ssh1key->comment = dupstr(comment);
740 sfree(ssh2key->comment);
741 ssh2key->comment = dupstr(comment);
746 * Prompt for a new passphrase if we have been asked to, or if
747 * we have just generated a key.
749 if (change_passphrase || keytype != NOKEYGEN) {
753 memset(passphrase, 0, strlen(passphrase));
757 passphrase = snewn(512, char);
758 passphrase2 = snewn(512, char);
759 if (!console_get_line("Enter passphrase to save key: ",
760 passphrase, 512, TRUE) ||
761 !console_get_line("Re-enter passphrase to verify: ",
762 passphrase2, 512, TRUE)) {
763 perror("puttygen: unable to read new passphrase");
766 if (strcmp(passphrase, passphrase2)) {
767 fprintf(stderr, "puttygen: passphrases do not match\n");
770 memset(passphrase2, 0, strlen(passphrase2));
781 * (In the case where outfile and outfiletmp are both NULL,
782 * there is no semantic reason to initialise outfilename at
783 * all; but we have to write _something_ to it or some compiler
784 * will probably complain that it might be used uninitialised.)
787 outfilename = filename_from_str(outfiletmp);
789 outfilename = filename_from_str(outfile ? outfile : "");
797 ret = saversakey(&outfilename, ssh1key, passphrase);
799 fprintf(stderr, "puttygen: unable to save SSH1 private key\n");
804 ret = ssh2_save_userkey(&outfilename, ssh2key, passphrase);
806 fprintf(stderr, "puttygen: unable to save SSH2 private key\n");
811 move(outfiletmp, outfile);
823 fp = f_open(outfilename, "w");
826 dec1 = bignum_decimal(ssh1key->exponent);
827 dec2 = bignum_decimal(ssh1key->modulus);
828 fprintf(fp, "%d %s %s %s\n", bignum_bitcount(ssh1key->modulus),
829 dec1, dec2, ssh1key->comment);
834 } else if (outtype == PUBLIC) {
837 ssh2blob = ssh2key->alg->public_blob(ssh2key->data,
840 save_ssh2_pubkey(outfile, ssh2key ? ssh2key->comment : origcomment,
841 ssh2blob, ssh2bloblen);
842 } else if (outtype == PUBLICO) {
849 ssh2blob = ssh2key->alg->public_blob(ssh2key->data,
854 ssh2alg = ssh2key->alg->name;
857 comment = ssh2key->comment;
859 comment = origcomment;
861 buffer = snewn(strlen(ssh2alg) +
862 4 * ((ssh2bloblen+2) / 3) +
863 strlen(comment) + 3, char);
864 strcpy(buffer, ssh2alg);
865 p = buffer + strlen(buffer);
868 while (i < ssh2bloblen) {
869 int n = (ssh2bloblen - i < 3 ? ssh2bloblen - i : 3);
870 base64_encode_atom(ssh2blob + i, n, p);
881 fp = f_open(outfilename, "w");
884 fprintf(fp, "%s\n", buffer);
899 fingerprint = snewn(128, char);
900 rsa_fingerprint(fingerprint, 128, ssh1key);
903 fingerprint = ssh2key->alg->fingerprint(ssh2key->data);
906 fingerprint = blobfp(ssh2alg, bits, ssh2blob, ssh2bloblen);
911 fp = f_open(outfilename, "w");
914 fprintf(fp, "%s\n", fingerprint);
926 ret = export_ssh2(&outfilename, outtype, ssh2key, passphrase);
928 fprintf(stderr, "puttygen: unable to export key\n");
932 move(outfiletmp, outfile);
937 memset(passphrase, 0, strlen(passphrase));
944 ssh2key->alg->freekey(ssh2key->data);