2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1994 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * Identity and host key generation and maintenance.
7 * As far as I am concerned, the code I have written for this software
8 * can be used freely for any purpose. Any derived versions of this
9 * software must be clearly marked as such, and if the derived work is
10 * incompatible with the protocol description in the RFC file, it must be
11 * called by a name other than "ssh" or "Secure Shell".
15 RCSID("$OpenBSD: ssh-keygen.c,v 1.101 2002/06/23 09:39:55 deraadt Exp $");
17 #include <openssl/evp.h>
18 #include <openssl/pem.h>
27 #include "pathnames.h"
35 /* Number of bits in the RSA/DSA key. This value can be changed on the command line. */
39 * Flag indicating that we just want to change the passphrase. This can be
40 * set on the command line.
42 int change_passphrase = 0;
45 * Flag indicating that we just want to change the comment. This can be set
46 * on the command line.
48 int change_comment = 0;
52 /* Flag indicating that we just want to see the key fingerprint */
53 int print_fingerprint = 0;
54 int print_bubblebabble = 0;
56 /* The identity file name, given on the command line or entered by the user. */
57 char identity_file[1024];
58 int have_identity = 0;
60 /* This is set to the passphrase if given on the command line. */
61 char *identity_passphrase = NULL;
63 /* This is set to the new passphrase if given on the command line. */
64 char *identity_new_passphrase = NULL;
66 /* This is set to the new comment if given on the command line. */
67 char *identity_comment = NULL;
69 /* Dump public key file in format used by real and the original SSH 2 */
70 int convert_to_ssh2 = 0;
71 int convert_from_ssh2 = 0;
74 char *key_type_name = NULL;
77 #ifdef HAVE___PROGNAME
78 extern char *__progname;
83 char hostname[MAXHOSTNAMELEN];
86 ask_filename(struct passwd *pw, const char *prompt)
91 if (key_type_name == NULL)
92 name = _PATH_SSH_CLIENT_ID_RSA;
94 switch (key_type_from_name(key_type_name)) {
96 name = _PATH_SSH_CLIENT_IDENTITY;
99 name = _PATH_SSH_CLIENT_ID_DSA;
102 name = _PATH_SSH_CLIENT_ID_RSA;
105 fprintf(stderr, "bad key type");
110 snprintf(identity_file, sizeof(identity_file), "%s/%s", pw->pw_dir, name);
111 fprintf(stderr, "%s (%s): ", prompt, identity_file);
113 if (fgets(buf, sizeof(buf), stdin) == NULL)
115 if (strchr(buf, '\n'))
116 *strchr(buf, '\n') = 0;
117 if (strcmp(buf, "") != 0)
118 strlcpy(identity_file, buf, sizeof(identity_file));
123 load_identity(char *filename)
128 prv = key_load_private(filename, "", NULL);
130 if (identity_passphrase)
131 pass = xstrdup(identity_passphrase);
133 pass = read_passphrase("Enter passphrase: ",
135 prv = key_load_private(filename, pass, NULL);
136 memset(pass, 0, strlen(pass));
142 #define SSH_COM_PUBLIC_BEGIN "---- BEGIN SSH2 PUBLIC KEY ----"
143 #define SSH_COM_PUBLIC_END "---- END SSH2 PUBLIC KEY ----"
144 #define SSH_COM_PRIVATE_BEGIN "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
145 #define SSH_COM_PRIVATE_KEY_MAGIC 0x3f6ff9eb
148 do_convert_to_ssh2(struct passwd *pw)
156 ask_filename(pw, "Enter file in which the key is");
157 if (stat(identity_file, &st) < 0) {
158 perror(identity_file);
161 if ((k = key_load_public(identity_file, NULL)) == NULL) {
162 if ((k = load_identity(identity_file)) == NULL) {
163 fprintf(stderr, "load failed\n");
167 if (key_to_blob(k, &blob, &len) <= 0) {
168 fprintf(stderr, "key_to_blob failed\n");
171 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
173 "Comment: \"%u-bit %s, converted from OpenSSH by %s@%s\"\n",
174 key_size(k), key_type(k),
175 pw->pw_name, hostname);
176 dump_base64(stdout, blob, len);
177 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
184 buffer_get_bignum_bits(Buffer *b, BIGNUM *value)
186 int bits = buffer_get_int(b);
187 int bytes = (bits + 7) / 8;
189 if (buffer_len(b) < bytes)
190 fatal("buffer_get_bignum_bits: input buffer too small: "
191 "need %d have %d", bytes, buffer_len(b));
192 BN_bin2bn(buffer_ptr(b), bytes, value);
193 buffer_consume(b, bytes);
197 do_convert_private_ssh2_from_blob(u_char *blob, u_int blen)
202 u_char *sig, data[] = "abcde12345";
203 int magic, rlen, ktype, i1, i2, i3, i4;
208 buffer_append(&b, blob, blen);
210 magic = buffer_get_int(&b);
211 if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
212 error("bad magic 0x%x != 0x%x", magic, SSH_COM_PRIVATE_KEY_MAGIC);
216 i1 = buffer_get_int(&b);
217 type = buffer_get_string(&b, NULL);
218 cipher = buffer_get_string(&b, NULL);
219 i2 = buffer_get_int(&b);
220 i3 = buffer_get_int(&b);
221 i4 = buffer_get_int(&b);
222 debug("ignore (%d %d %d %d)", i1,i2,i3,i4);
223 if (strcmp(cipher, "none") != 0) {
224 error("unsupported cipher %s", cipher);
232 if (strstr(type, "dsa")) {
234 } else if (strstr(type, "rsa")) {
240 key = key_new_private(ktype);
245 buffer_get_bignum_bits(&b, key->dsa->p);
246 buffer_get_bignum_bits(&b, key->dsa->g);
247 buffer_get_bignum_bits(&b, key->dsa->q);
248 buffer_get_bignum_bits(&b, key->dsa->pub_key);
249 buffer_get_bignum_bits(&b, key->dsa->priv_key);
252 e = buffer_get_char(&b);
256 e += buffer_get_char(&b);
259 e += buffer_get_char(&b);
262 if (!BN_set_word(key->rsa->e, e)) {
267 buffer_get_bignum_bits(&b, key->rsa->d);
268 buffer_get_bignum_bits(&b, key->rsa->n);
269 buffer_get_bignum_bits(&b, key->rsa->iqmp);
270 buffer_get_bignum_bits(&b, key->rsa->q);
271 buffer_get_bignum_bits(&b, key->rsa->p);
272 rsa_generate_additional_parameters(key->rsa);
275 rlen = buffer_len(&b);
277 error("do_convert_private_ssh2_from_blob: "
278 "remaining bytes in key blob %d", rlen);
282 key_sign(key, &sig, &slen, data, sizeof(data));
283 key_verify(key, sig, slen, data, sizeof(data));
289 do_convert_from_ssh2(struct passwd *pw)
298 int escaped = 0, private = 0, ok;
302 ask_filename(pw, "Enter file in which the key is");
303 if (stat(identity_file, &st) < 0) {
304 perror(identity_file);
307 fp = fopen(identity_file, "r");
309 perror(identity_file);
313 while (fgets(line, sizeof(line), fp)) {
314 if (!(p = strchr(line, '\n'))) {
315 fprintf(stderr, "input line too long.\n");
318 if (p > line && p[-1] == '\\')
320 if (strncmp(line, "----", 4) == 0 ||
321 strstr(line, ": ") != NULL) {
322 if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
324 if (strstr(line, " END ") != NULL) {
327 /* fprintf(stderr, "ignore: %s", line); */
332 /* fprintf(stderr, "escaped: %s", line); */
336 strlcat(encoded, line, sizeof(encoded));
338 len = strlen(encoded);
339 if (((len % 4) == 3) &&
340 (encoded[len-1] == '=') &&
341 (encoded[len-2] == '=') &&
342 (encoded[len-3] == '='))
343 encoded[len-3] = '\0';
344 blen = uudecode(encoded, blob, sizeof(blob));
346 fprintf(stderr, "uudecode failed.\n");
350 do_convert_private_ssh2_from_blob(blob, blen) :
351 key_from_blob(blob, blen);
353 fprintf(stderr, "decode blob failed.\n");
357 (k->type == KEY_DSA ?
358 PEM_write_DSAPrivateKey(stdout, k->dsa, NULL, NULL, 0, NULL, NULL) :
359 PEM_write_RSAPrivateKey(stdout, k->rsa, NULL, NULL, 0, NULL, NULL)) :
360 key_write(k, stdout);
362 fprintf(stderr, "key write failed");
367 fprintf(stdout, "\n");
373 do_print_public(struct passwd *pw)
379 ask_filename(pw, "Enter file in which the key is");
380 if (stat(identity_file, &st) < 0) {
381 perror(identity_file);
384 prv = load_identity(identity_file);
386 fprintf(stderr, "load failed\n");
389 if (!key_write(prv, stdout))
390 fprintf(stderr, "key_write failed");
392 fprintf(stdout, "\n");
398 do_upload(struct passwd *pw, const char *sc_reader_id)
405 ask_filename(pw, "Enter file in which the key is");
406 if (stat(identity_file, &st) < 0) {
407 perror(identity_file);
410 prv = load_identity(identity_file);
412 error("load failed");
415 ret = sc_put_key(prv, sc_reader_id);
419 log("loading key done");
424 do_download(struct passwd *pw, const char *sc_reader_id)
429 keys = sc_get_keys(sc_reader_id, NULL);
431 fatal("cannot read public key from smartcard");
432 for (i = 0; keys[i]; i++) {
433 key_write(keys[i], stdout);
435 fprintf(stdout, "\n");
440 #endif /* SMARTCARD */
443 do_fingerprint(struct passwd *pw)
447 char *comment = NULL, *cp, *ep, line[16*1024], *fp;
448 int i, skip = 0, num = 1, invalid = 1;
453 fptype = print_bubblebabble ? SSH_FP_SHA1 : SSH_FP_MD5;
454 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_HEX;
457 ask_filename(pw, "Enter file in which the key is");
458 if (stat(identity_file, &st) < 0) {
459 perror(identity_file);
462 public = key_load_public(identity_file, &comment);
463 if (public != NULL) {
464 fp = key_fingerprint(public, fptype, rep);
465 printf("%u %s %s\n", key_size(public), fp, comment);
474 f = fopen(identity_file, "r");
476 while (fgets(line, sizeof(line), f)) {
477 i = strlen(line) - 1;
478 if (line[i] != '\n') {
479 error("line %d too long: %.40s...", num, line);
490 /* Skip leading whitespace, empty and comment lines. */
491 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
493 if (!*cp || *cp == '\n' || *cp == '#')
495 i = strtol(cp, &ep, 10);
496 if (i == 0 || ep == NULL || (*ep != ' ' && *ep != '\t')) {
499 for (; *cp && (quoted || (*cp != ' ' &&
500 *cp != '\t')); cp++) {
501 if (*cp == '\\' && cp[1] == '"')
502 cp++; /* Skip both */
511 public = key_new(KEY_RSA1);
512 if (key_read(public, &cp) != 1) {
515 public = key_new(KEY_UNSPEC);
516 if (key_read(public, &cp) != 1) {
521 comment = *cp ? cp : comment;
522 fp = key_fingerprint(public, fptype, rep);
523 printf("%u %s %s\n", key_size(public), fp,
524 comment ? comment : "no comment");
532 printf("%s is not a public key file.\n", identity_file);
539 * Perform changing a passphrase. The argument is the passwd structure
540 * for the current user.
543 do_change_passphrase(struct passwd *pw)
546 char *old_passphrase, *passphrase1, *passphrase2;
551 ask_filename(pw, "Enter file in which the key is");
552 if (stat(identity_file, &st) < 0) {
553 perror(identity_file);
556 /* Try to load the file with empty passphrase. */
557 private = key_load_private(identity_file, "", &comment);
558 if (private == NULL) {
559 if (identity_passphrase)
560 old_passphrase = xstrdup(identity_passphrase);
563 read_passphrase("Enter old passphrase: ",
565 private = key_load_private(identity_file, old_passphrase,
567 memset(old_passphrase, 0, strlen(old_passphrase));
568 xfree(old_passphrase);
569 if (private == NULL) {
570 printf("Bad passphrase.\n");
574 printf("Key has comment '%s'\n", comment);
576 /* Ask the new passphrase (twice). */
577 if (identity_new_passphrase) {
578 passphrase1 = xstrdup(identity_new_passphrase);
582 read_passphrase("Enter new passphrase (empty for no "
583 "passphrase): ", RP_ALLOW_STDIN);
584 passphrase2 = read_passphrase("Enter same passphrase again: ",
587 /* Verify that they are the same. */
588 if (strcmp(passphrase1, passphrase2) != 0) {
589 memset(passphrase1, 0, strlen(passphrase1));
590 memset(passphrase2, 0, strlen(passphrase2));
593 printf("Pass phrases do not match. Try again.\n");
596 /* Destroy the other copy. */
597 memset(passphrase2, 0, strlen(passphrase2));
601 /* Save the file using the new passphrase. */
602 if (!key_save_private(private, identity_file, passphrase1, comment)) {
603 printf("Saving the key failed: %s.\n", identity_file);
604 memset(passphrase1, 0, strlen(passphrase1));
610 /* Destroy the passphrase and the copy of the key in memory. */
611 memset(passphrase1, 0, strlen(passphrase1));
613 key_free(private); /* Destroys contents */
616 printf("Your identification has been saved with the new passphrase.\n");
621 * Change the comment of a private key file.
624 do_change_comment(struct passwd *pw)
626 char new_comment[1024], *comment, *passphrase;
634 ask_filename(pw, "Enter file in which the key is");
635 if (stat(identity_file, &st) < 0) {
636 perror(identity_file);
639 private = key_load_private(identity_file, "", &comment);
640 if (private == NULL) {
641 if (identity_passphrase)
642 passphrase = xstrdup(identity_passphrase);
643 else if (identity_new_passphrase)
644 passphrase = xstrdup(identity_new_passphrase);
646 passphrase = read_passphrase("Enter passphrase: ",
648 /* Try to load using the passphrase. */
649 private = key_load_private(identity_file, passphrase, &comment);
650 if (private == NULL) {
651 memset(passphrase, 0, strlen(passphrase));
653 printf("Bad passphrase.\n");
657 passphrase = xstrdup("");
659 if (private->type != KEY_RSA1) {
660 fprintf(stderr, "Comments are only supported for RSA1 keys.\n");
664 printf("Key now has comment '%s'\n", comment);
666 if (identity_comment) {
667 strlcpy(new_comment, identity_comment, sizeof(new_comment));
669 printf("Enter new comment: ");
671 if (!fgets(new_comment, sizeof(new_comment), stdin)) {
672 memset(passphrase, 0, strlen(passphrase));
676 if (strchr(new_comment, '\n'))
677 *strchr(new_comment, '\n') = 0;
680 /* Save the file using the new passphrase. */
681 if (!key_save_private(private, identity_file, passphrase, new_comment)) {
682 printf("Saving the key failed: %s.\n", identity_file);
683 memset(passphrase, 0, strlen(passphrase));
689 memset(passphrase, 0, strlen(passphrase));
691 public = key_from_private(private);
694 strlcat(identity_file, ".pub", sizeof(identity_file));
695 fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
697 printf("Could not save your public key in %s\n", identity_file);
702 printf("fdopen %s failed", identity_file);
705 if (!key_write(public, f))
706 fprintf(stderr, "write key failed");
708 fprintf(f, " %s\n", new_comment);
713 printf("The comment in your key file has been changed.\n");
720 fprintf(stderr, "Usage: %s [options]\n", __progname);
721 fprintf(stderr, "Options:\n");
722 fprintf(stderr, " -b bits Number of bits in the key to create.\n");
723 fprintf(stderr, " -c Change comment in private and public key files.\n");
724 fprintf(stderr, " -e Convert OpenSSH to IETF SECSH key file.\n");
725 fprintf(stderr, " -f filename Filename of the key file.\n");
726 fprintf(stderr, " -i Convert IETF SECSH to OpenSSH key file.\n");
727 fprintf(stderr, " -l Show fingerprint of key file.\n");
728 fprintf(stderr, " -p Change passphrase of private key file.\n");
729 fprintf(stderr, " -q Quiet.\n");
730 fprintf(stderr, " -y Read private key file and print public key.\n");
731 fprintf(stderr, " -t type Specify type of key to create.\n");
732 fprintf(stderr, " -B Show bubblebabble digest of key file.\n");
733 fprintf(stderr, " -C comment Provide new comment.\n");
734 fprintf(stderr, " -N phrase Provide new passphrase.\n");
735 fprintf(stderr, " -P phrase Provide old passphrase.\n");
737 fprintf(stderr, " -D reader Download public key from smartcard.\n");
738 fprintf(stderr, " -U reader Upload private key to smartcard.\n");
739 #endif /* SMARTCARD */
745 * Main program for key management.
748 main(int ac, char **av)
750 char dotsshdir[MAXPATHLEN], comment[1024], *passphrase1, *passphrase2;
751 char *reader_id = NULL;
752 Key *private, *public;
755 int opt, type, fd, download = 0;
761 __progname = get_progname(av[0]);
763 SSLeay_add_all_algorithms();
767 /* we need this for the home * directory. */
768 pw = getpwuid(getuid());
770 printf("You don't exist, go away!\n");
773 if (gethostname(hostname, sizeof(hostname)) < 0) {
774 perror("gethostname");
778 while ((opt = getopt(ac, av, "deiqpclBRxXyb:f:t:U:D:P:N:C:")) != -1) {
782 if (bits < 512 || bits > 32768) {
783 printf("Bits has bad value.\n");
788 print_fingerprint = 1;
791 print_bubblebabble = 1;
794 change_passphrase = 1;
800 strlcpy(identity_file, optarg, sizeof(identity_file));
804 identity_passphrase = optarg;
807 identity_new_passphrase = optarg;
810 identity_comment = optarg;
827 convert_from_ssh2 = 1;
833 key_type_name = "dsa";
836 key_type_name = optarg;
849 printf("Too many arguments.\n");
852 if (change_passphrase && change_comment) {
853 printf("Can only have one of -p and -c.\n");
856 if (print_fingerprint || print_bubblebabble)
858 if (change_passphrase)
859 do_change_passphrase(pw);
861 do_change_comment(pw);
863 do_convert_to_ssh2(pw);
864 if (convert_from_ssh2)
865 do_convert_from_ssh2(pw);
868 if (reader_id != NULL) {
871 do_download(pw, reader_id);
873 do_upload(pw, reader_id);
874 #else /* SMARTCARD */
875 fatal("no support for smartcards.");
876 #endif /* SMARTCARD */
881 if (key_type_name == NULL) {
882 printf("You must specify a key type (-t).\n");
885 type = key_type_from_name(key_type_name);
886 if (type == KEY_UNSPEC) {
887 fprintf(stderr, "unknown key type %s\n", key_type_name);
891 printf("Generating public/private %s key pair.\n", key_type_name);
892 private = key_generate(type, bits);
893 if (private == NULL) {
894 fprintf(stderr, "key_generate failed");
897 public = key_from_private(private);
900 ask_filename(pw, "Enter file in which to save the key");
902 /* Create ~/.ssh directory if it doesn\'t already exist. */
903 snprintf(dotsshdir, sizeof dotsshdir, "%s/%s", pw->pw_dir, _PATH_SSH_USER_DIR);
904 if (strstr(identity_file, dotsshdir) != NULL &&
905 stat(dotsshdir, &st) < 0) {
906 if (mkdir(dotsshdir, 0700) < 0)
907 error("Could not create directory '%s'.", dotsshdir);
909 printf("Created directory '%s'.\n", dotsshdir);
911 /* If the file already exists, ask the user to confirm. */
912 if (stat(identity_file, &st) >= 0) {
914 printf("%s already exists.\n", identity_file);
915 printf("Overwrite (y/n)? ");
917 if (fgets(yesno, sizeof(yesno), stdin) == NULL)
919 if (yesno[0] != 'y' && yesno[0] != 'Y')
922 /* Ask for a passphrase (twice). */
923 if (identity_passphrase)
924 passphrase1 = xstrdup(identity_passphrase);
925 else if (identity_new_passphrase)
926 passphrase1 = xstrdup(identity_new_passphrase);
930 read_passphrase("Enter passphrase (empty for no "
931 "passphrase): ", RP_ALLOW_STDIN);
932 passphrase2 = read_passphrase("Enter same passphrase again: ",
934 if (strcmp(passphrase1, passphrase2) != 0) {
936 * The passphrases do not match. Clear them and
939 memset(passphrase1, 0, strlen(passphrase1));
940 memset(passphrase2, 0, strlen(passphrase2));
943 printf("Passphrases do not match. Try again.\n");
944 goto passphrase_again;
946 /* Clear the other copy of the passphrase. */
947 memset(passphrase2, 0, strlen(passphrase2));
951 if (identity_comment) {
952 strlcpy(comment, identity_comment, sizeof(comment));
954 /* Create default commend field for the passphrase. */
955 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
958 /* Save the key with the given passphrase and comment. */
959 if (!key_save_private(private, identity_file, passphrase1, comment)) {
960 printf("Saving the key failed: %s.\n", identity_file);
961 memset(passphrase1, 0, strlen(passphrase1));
965 /* Clear the passphrase. */
966 memset(passphrase1, 0, strlen(passphrase1));
969 /* Clear the private key and the random number generator. */
974 printf("Your identification has been saved in %s.\n", identity_file);
976 strlcat(identity_file, ".pub", sizeof(identity_file));
977 fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
979 printf("Could not save your public key in %s\n", identity_file);
984 printf("fdopen %s failed", identity_file);
987 if (!key_write(public, f))
988 fprintf(stderr, "write key failed");
989 fprintf(f, " %s\n", comment);
993 char *fp = key_fingerprint(public, SSH_FP_MD5, SSH_FP_HEX);
994 printf("Your public key has been saved in %s.\n",
996 printf("The key fingerprint is:\n");
997 printf("%s %s\n", fp, comment);