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.104 2003/05/11 16:56:48 markus 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);
112 if (fgets(buf, sizeof(buf), stdin) == NULL)
114 if (strchr(buf, '\n'))
115 *strchr(buf, '\n') = 0;
116 if (strcmp(buf, "") != 0)
117 strlcpy(identity_file, buf, sizeof(identity_file));
122 load_identity(char *filename)
127 prv = key_load_private(filename, "", NULL);
129 if (identity_passphrase)
130 pass = xstrdup(identity_passphrase);
132 pass = read_passphrase("Enter passphrase: ",
134 prv = key_load_private(filename, pass, NULL);
135 memset(pass, 0, strlen(pass));
141 #define SSH_COM_PUBLIC_BEGIN "---- BEGIN SSH2 PUBLIC KEY ----"
142 #define SSH_COM_PUBLIC_END "---- END SSH2 PUBLIC KEY ----"
143 #define SSH_COM_PRIVATE_BEGIN "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
144 #define SSH_COM_PRIVATE_KEY_MAGIC 0x3f6ff9eb
147 do_convert_to_ssh2(struct passwd *pw)
155 ask_filename(pw, "Enter file in which the key is");
156 if (stat(identity_file, &st) < 0) {
157 perror(identity_file);
160 if ((k = key_load_public(identity_file, NULL)) == NULL) {
161 if ((k = load_identity(identity_file)) == NULL) {
162 fprintf(stderr, "load failed\n");
166 if (k->type == KEY_RSA1) {
167 fprintf(stderr, "version 1 keys are not supported\n");
170 if (key_to_blob(k, &blob, &len) <= 0) {
171 fprintf(stderr, "key_to_blob failed\n");
174 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
176 "Comment: \"%u-bit %s, converted from OpenSSH by %s@%s\"\n",
177 key_size(k), key_type(k),
178 pw->pw_name, hostname);
179 dump_base64(stdout, blob, len);
180 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
187 buffer_get_bignum_bits(Buffer *b, BIGNUM *value)
189 int bits = buffer_get_int(b);
190 int bytes = (bits + 7) / 8;
192 if (buffer_len(b) < bytes)
193 fatal("buffer_get_bignum_bits: input buffer too small: "
194 "need %d have %d", bytes, buffer_len(b));
195 BN_bin2bn(buffer_ptr(b), bytes, value);
196 buffer_consume(b, bytes);
200 do_convert_private_ssh2_from_blob(u_char *blob, u_int blen)
205 u_char *sig, data[] = "abcde12345";
206 int magic, rlen, ktype, i1, i2, i3, i4;
211 buffer_append(&b, blob, blen);
213 magic = buffer_get_int(&b);
214 if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
215 error("bad magic 0x%x != 0x%x", magic, SSH_COM_PRIVATE_KEY_MAGIC);
219 i1 = buffer_get_int(&b);
220 type = buffer_get_string(&b, NULL);
221 cipher = buffer_get_string(&b, NULL);
222 i2 = buffer_get_int(&b);
223 i3 = buffer_get_int(&b);
224 i4 = buffer_get_int(&b);
225 debug("ignore (%d %d %d %d)", i1,i2,i3,i4);
226 if (strcmp(cipher, "none") != 0) {
227 error("unsupported cipher %s", cipher);
235 if (strstr(type, "dsa")) {
237 } else if (strstr(type, "rsa")) {
243 key = key_new_private(ktype);
248 buffer_get_bignum_bits(&b, key->dsa->p);
249 buffer_get_bignum_bits(&b, key->dsa->g);
250 buffer_get_bignum_bits(&b, key->dsa->q);
251 buffer_get_bignum_bits(&b, key->dsa->pub_key);
252 buffer_get_bignum_bits(&b, key->dsa->priv_key);
255 e = buffer_get_char(&b);
259 e += buffer_get_char(&b);
262 e += buffer_get_char(&b);
265 if (!BN_set_word(key->rsa->e, e)) {
270 buffer_get_bignum_bits(&b, key->rsa->d);
271 buffer_get_bignum_bits(&b, key->rsa->n);
272 buffer_get_bignum_bits(&b, key->rsa->iqmp);
273 buffer_get_bignum_bits(&b, key->rsa->q);
274 buffer_get_bignum_bits(&b, key->rsa->p);
275 rsa_generate_additional_parameters(key->rsa);
278 rlen = buffer_len(&b);
280 error("do_convert_private_ssh2_from_blob: "
281 "remaining bytes in key blob %d", rlen);
285 key_sign(key, &sig, &slen, data, sizeof(data));
286 key_verify(key, sig, slen, data, sizeof(data));
292 do_convert_from_ssh2(struct passwd *pw)
301 int escaped = 0, private = 0, ok;
305 ask_filename(pw, "Enter file in which the key is");
306 if (stat(identity_file, &st) < 0) {
307 perror(identity_file);
310 fp = fopen(identity_file, "r");
312 perror(identity_file);
316 while (fgets(line, sizeof(line), fp)) {
317 if (!(p = strchr(line, '\n'))) {
318 fprintf(stderr, "input line too long.\n");
321 if (p > line && p[-1] == '\\')
323 if (strncmp(line, "----", 4) == 0 ||
324 strstr(line, ": ") != NULL) {
325 if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
327 if (strstr(line, " END ") != NULL) {
330 /* fprintf(stderr, "ignore: %s", line); */
335 /* fprintf(stderr, "escaped: %s", line); */
339 strlcat(encoded, line, sizeof(encoded));
341 len = strlen(encoded);
342 if (((len % 4) == 3) &&
343 (encoded[len-1] == '=') &&
344 (encoded[len-2] == '=') &&
345 (encoded[len-3] == '='))
346 encoded[len-3] = '\0';
347 blen = uudecode(encoded, blob, sizeof(blob));
349 fprintf(stderr, "uudecode failed.\n");
353 do_convert_private_ssh2_from_blob(blob, blen) :
354 key_from_blob(blob, blen);
356 fprintf(stderr, "decode blob failed.\n");
360 (k->type == KEY_DSA ?
361 PEM_write_DSAPrivateKey(stdout, k->dsa, NULL, NULL, 0, NULL, NULL) :
362 PEM_write_RSAPrivateKey(stdout, k->rsa, NULL, NULL, 0, NULL, NULL)) :
363 key_write(k, stdout);
365 fprintf(stderr, "key write failed");
370 fprintf(stdout, "\n");
376 do_print_public(struct passwd *pw)
382 ask_filename(pw, "Enter file in which the key is");
383 if (stat(identity_file, &st) < 0) {
384 perror(identity_file);
387 prv = load_identity(identity_file);
389 fprintf(stderr, "load failed\n");
392 if (!key_write(prv, stdout))
393 fprintf(stderr, "key_write failed");
395 fprintf(stdout, "\n");
401 do_upload(struct passwd *pw, const char *sc_reader_id)
408 ask_filename(pw, "Enter file in which the key is");
409 if (stat(identity_file, &st) < 0) {
410 perror(identity_file);
413 prv = load_identity(identity_file);
415 error("load failed");
418 ret = sc_put_key(prv, sc_reader_id);
422 logit("loading key done");
427 do_download(struct passwd *pw, const char *sc_reader_id)
432 keys = sc_get_keys(sc_reader_id, NULL);
434 fatal("cannot read public key from smartcard");
435 for (i = 0; keys[i]; i++) {
436 key_write(keys[i], stdout);
438 fprintf(stdout, "\n");
443 #endif /* SMARTCARD */
446 do_fingerprint(struct passwd *pw)
450 char *comment = NULL, *cp, *ep, line[16*1024], *fp;
451 int i, skip = 0, num = 1, invalid = 1;
456 fptype = print_bubblebabble ? SSH_FP_SHA1 : SSH_FP_MD5;
457 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_HEX;
460 ask_filename(pw, "Enter file in which the key is");
461 if (stat(identity_file, &st) < 0) {
462 perror(identity_file);
465 public = key_load_public(identity_file, &comment);
466 if (public != NULL) {
467 fp = key_fingerprint(public, fptype, rep);
468 printf("%u %s %s\n", key_size(public), fp, comment);
477 f = fopen(identity_file, "r");
479 while (fgets(line, sizeof(line), f)) {
480 i = strlen(line) - 1;
481 if (line[i] != '\n') {
482 error("line %d too long: %.40s...", num, line);
493 /* Skip leading whitespace, empty and comment lines. */
494 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
496 if (!*cp || *cp == '\n' || *cp == '#')
498 i = strtol(cp, &ep, 10);
499 if (i == 0 || ep == NULL || (*ep != ' ' && *ep != '\t')) {
502 for (; *cp && (quoted || (*cp != ' ' &&
503 *cp != '\t')); cp++) {
504 if (*cp == '\\' && cp[1] == '"')
505 cp++; /* Skip both */
514 public = key_new(KEY_RSA1);
515 if (key_read(public, &cp) != 1) {
518 public = key_new(KEY_UNSPEC);
519 if (key_read(public, &cp) != 1) {
524 comment = *cp ? cp : comment;
525 fp = key_fingerprint(public, fptype, rep);
526 printf("%u %s %s\n", key_size(public), fp,
527 comment ? comment : "no comment");
535 printf("%s is not a public key file.\n", identity_file);
542 * Perform changing a passphrase. The argument is the passwd structure
543 * for the current user.
546 do_change_passphrase(struct passwd *pw)
549 char *old_passphrase, *passphrase1, *passphrase2;
554 ask_filename(pw, "Enter file in which the key is");
555 if (stat(identity_file, &st) < 0) {
556 perror(identity_file);
559 /* Try to load the file with empty passphrase. */
560 private = key_load_private(identity_file, "", &comment);
561 if (private == NULL) {
562 if (identity_passphrase)
563 old_passphrase = xstrdup(identity_passphrase);
566 read_passphrase("Enter old passphrase: ",
568 private = key_load_private(identity_file, old_passphrase,
570 memset(old_passphrase, 0, strlen(old_passphrase));
571 xfree(old_passphrase);
572 if (private == NULL) {
573 printf("Bad passphrase.\n");
577 printf("Key has comment '%s'\n", comment);
579 /* Ask the new passphrase (twice). */
580 if (identity_new_passphrase) {
581 passphrase1 = xstrdup(identity_new_passphrase);
585 read_passphrase("Enter new passphrase (empty for no "
586 "passphrase): ", RP_ALLOW_STDIN);
587 passphrase2 = read_passphrase("Enter same passphrase again: ",
590 /* Verify that they are the same. */
591 if (strcmp(passphrase1, passphrase2) != 0) {
592 memset(passphrase1, 0, strlen(passphrase1));
593 memset(passphrase2, 0, strlen(passphrase2));
596 printf("Pass phrases do not match. Try again.\n");
599 /* Destroy the other copy. */
600 memset(passphrase2, 0, strlen(passphrase2));
604 /* Save the file using the new passphrase. */
605 if (!key_save_private(private, identity_file, passphrase1, comment)) {
606 printf("Saving the key failed: %s.\n", identity_file);
607 memset(passphrase1, 0, strlen(passphrase1));
613 /* Destroy the passphrase and the copy of the key in memory. */
614 memset(passphrase1, 0, strlen(passphrase1));
616 key_free(private); /* Destroys contents */
619 printf("Your identification has been saved with the new passphrase.\n");
624 * Change the comment of a private key file.
627 do_change_comment(struct passwd *pw)
629 char new_comment[1024], *comment, *passphrase;
637 ask_filename(pw, "Enter file in which the key is");
638 if (stat(identity_file, &st) < 0) {
639 perror(identity_file);
642 private = key_load_private(identity_file, "", &comment);
643 if (private == NULL) {
644 if (identity_passphrase)
645 passphrase = xstrdup(identity_passphrase);
646 else if (identity_new_passphrase)
647 passphrase = xstrdup(identity_new_passphrase);
649 passphrase = read_passphrase("Enter passphrase: ",
651 /* Try to load using the passphrase. */
652 private = key_load_private(identity_file, passphrase, &comment);
653 if (private == NULL) {
654 memset(passphrase, 0, strlen(passphrase));
656 printf("Bad passphrase.\n");
660 passphrase = xstrdup("");
662 if (private->type != KEY_RSA1) {
663 fprintf(stderr, "Comments are only supported for RSA1 keys.\n");
667 printf("Key now has comment '%s'\n", comment);
669 if (identity_comment) {
670 strlcpy(new_comment, identity_comment, sizeof(new_comment));
672 printf("Enter new comment: ");
674 if (!fgets(new_comment, sizeof(new_comment), stdin)) {
675 memset(passphrase, 0, strlen(passphrase));
679 if (strchr(new_comment, '\n'))
680 *strchr(new_comment, '\n') = 0;
683 /* Save the file using the new passphrase. */
684 if (!key_save_private(private, identity_file, passphrase, new_comment)) {
685 printf("Saving the key failed: %s.\n", identity_file);
686 memset(passphrase, 0, strlen(passphrase));
692 memset(passphrase, 0, strlen(passphrase));
694 public = key_from_private(private);
697 strlcat(identity_file, ".pub", sizeof(identity_file));
698 fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
700 printf("Could not save your public key in %s\n", identity_file);
705 printf("fdopen %s failed", identity_file);
708 if (!key_write(public, f))
709 fprintf(stderr, "write key failed");
711 fprintf(f, " %s\n", new_comment);
716 printf("The comment in your key file has been changed.\n");
723 fprintf(stderr, "Usage: %s [options]\n", __progname);
724 fprintf(stderr, "Options:\n");
725 fprintf(stderr, " -b bits Number of bits in the key to create.\n");
726 fprintf(stderr, " -c Change comment in private and public key files.\n");
727 fprintf(stderr, " -e Convert OpenSSH to IETF SECSH key file.\n");
728 fprintf(stderr, " -f filename Filename of the key file.\n");
729 fprintf(stderr, " -i Convert IETF SECSH to OpenSSH key file.\n");
730 fprintf(stderr, " -l Show fingerprint of key file.\n");
731 fprintf(stderr, " -p Change passphrase of private key file.\n");
732 fprintf(stderr, " -q Quiet.\n");
733 fprintf(stderr, " -y Read private key file and print public key.\n");
734 fprintf(stderr, " -t type Specify type of key to create.\n");
735 fprintf(stderr, " -B Show bubblebabble digest of key file.\n");
736 fprintf(stderr, " -C comment Provide new comment.\n");
737 fprintf(stderr, " -N phrase Provide new passphrase.\n");
738 fprintf(stderr, " -P phrase Provide old passphrase.\n");
740 fprintf(stderr, " -D reader Download public key from smartcard.\n");
741 fprintf(stderr, " -U reader Upload private key to smartcard.\n");
742 #endif /* SMARTCARD */
748 * Main program for key management.
751 main(int ac, char **av)
753 char dotsshdir[MAXPATHLEN], comment[1024], *passphrase1, *passphrase2;
754 char *reader_id = NULL;
755 Key *private, *public;
758 int opt, type, fd, download = 0;
764 __progname = get_progname(av[0]);
766 SSLeay_add_all_algorithms();
770 /* we need this for the home * directory. */
771 pw = getpwuid(getuid());
773 printf("You don't exist, go away!\n");
776 if (gethostname(hostname, sizeof(hostname)) < 0) {
777 perror("gethostname");
781 while ((opt = getopt(ac, av, "deiqpclBRxXyb:f:t:U:D:P:N:C:")) != -1) {
785 if (bits < 512 || bits > 32768) {
786 printf("Bits has bad value.\n");
791 print_fingerprint = 1;
794 print_bubblebabble = 1;
797 change_passphrase = 1;
803 strlcpy(identity_file, optarg, sizeof(identity_file));
807 identity_passphrase = optarg;
810 identity_new_passphrase = optarg;
813 identity_comment = optarg;
830 convert_from_ssh2 = 1;
836 key_type_name = "dsa";
839 key_type_name = optarg;
852 printf("Too many arguments.\n");
855 if (change_passphrase && change_comment) {
856 printf("Can only have one of -p and -c.\n");
859 if (print_fingerprint || print_bubblebabble)
861 if (change_passphrase)
862 do_change_passphrase(pw);
864 do_change_comment(pw);
866 do_convert_to_ssh2(pw);
867 if (convert_from_ssh2)
868 do_convert_from_ssh2(pw);
871 if (reader_id != NULL) {
874 do_download(pw, reader_id);
876 do_upload(pw, reader_id);
877 #else /* SMARTCARD */
878 fatal("no support for smartcards.");
879 #endif /* SMARTCARD */
884 if (key_type_name == NULL) {
885 printf("You must specify a key type (-t).\n");
888 type = key_type_from_name(key_type_name);
889 if (type == KEY_UNSPEC) {
890 fprintf(stderr, "unknown key type %s\n", key_type_name);
894 printf("Generating public/private %s key pair.\n", key_type_name);
895 private = key_generate(type, bits);
896 if (private == NULL) {
897 fprintf(stderr, "key_generate failed");
900 public = key_from_private(private);
903 ask_filename(pw, "Enter file in which to save the key");
905 /* Create ~/.ssh directory if it doesn\'t already exist. */
906 snprintf(dotsshdir, sizeof dotsshdir, "%s/%s", pw->pw_dir, _PATH_SSH_USER_DIR);
907 if (strstr(identity_file, dotsshdir) != NULL &&
908 stat(dotsshdir, &st) < 0) {
909 if (mkdir(dotsshdir, 0700) < 0)
910 error("Could not create directory '%s'.", dotsshdir);
912 printf("Created directory '%s'.\n", dotsshdir);
914 /* If the file already exists, ask the user to confirm. */
915 if (stat(identity_file, &st) >= 0) {
917 printf("%s already exists.\n", identity_file);
918 printf("Overwrite (y/n)? ");
920 if (fgets(yesno, sizeof(yesno), stdin) == NULL)
922 if (yesno[0] != 'y' && yesno[0] != 'Y')
925 /* Ask for a passphrase (twice). */
926 if (identity_passphrase)
927 passphrase1 = xstrdup(identity_passphrase);
928 else if (identity_new_passphrase)
929 passphrase1 = xstrdup(identity_new_passphrase);
933 read_passphrase("Enter passphrase (empty for no "
934 "passphrase): ", RP_ALLOW_STDIN);
935 passphrase2 = read_passphrase("Enter same passphrase again: ",
937 if (strcmp(passphrase1, passphrase2) != 0) {
939 * The passphrases do not match. Clear them and
942 memset(passphrase1, 0, strlen(passphrase1));
943 memset(passphrase2, 0, strlen(passphrase2));
946 printf("Passphrases do not match. Try again.\n");
947 goto passphrase_again;
949 /* Clear the other copy of the passphrase. */
950 memset(passphrase2, 0, strlen(passphrase2));
954 if (identity_comment) {
955 strlcpy(comment, identity_comment, sizeof(comment));
957 /* Create default commend field for the passphrase. */
958 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
961 /* Save the key with the given passphrase and comment. */
962 if (!key_save_private(private, identity_file, passphrase1, comment)) {
963 printf("Saving the key failed: %s.\n", identity_file);
964 memset(passphrase1, 0, strlen(passphrase1));
968 /* Clear the passphrase. */
969 memset(passphrase1, 0, strlen(passphrase1));
972 /* Clear the private key and the random number generator. */
977 printf("Your identification has been saved in %s.\n", identity_file);
979 strlcat(identity_file, ".pub", sizeof(identity_file));
980 fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
982 printf("Could not save your public key in %s\n", identity_file);
987 printf("fdopen %s failed", identity_file);
990 if (!key_write(public, f))
991 fprintf(stderr, "write key failed");
992 fprintf(f, " %s\n", comment);
996 char *fp = key_fingerprint(public, SSH_FP_MD5, SSH_FP_HEX);
997 printf("Your public key has been saved in %s.\n",
999 printf("The key fingerprint is:\n");
1000 printf("%s %s\n", fp, comment);