1 /* $OpenBSD: ssh-keygen.c,v 1.210 2011/04/18 00:46:05 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1994 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * Identity and host key generation and maintenance.
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose. Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
17 #include <sys/types.h>
18 #include <sys/socket.h>
20 #include <sys/param.h>
22 #include <openssl/evp.h>
23 #include <openssl/pem.h>
24 #include "openbsd-compat/openssl-compat.h"
45 #include "pathnames.h"
52 #include "ssh-pkcs11.h"
54 /* Number of bits in the RSA/DSA key. This value can be set on the command line. */
55 #define DEFAULT_BITS 2048
56 #define DEFAULT_BITS_DSA 1024
57 #define DEFAULT_BITS_ECDSA 256
61 * Flag indicating that we just want to change the passphrase. This can be
62 * set on the command line.
64 int change_passphrase = 0;
67 * Flag indicating that we just want to change the comment. This can be set
68 * on the command line.
70 int change_comment = 0;
74 int log_level = SYSLOG_LEVEL_INFO;
76 /* Flag indicating that we want to hash a known_hosts file */
78 /* Flag indicating that we want lookup a host in known_hosts file */
80 /* Flag indicating that we want to delete a host from a known_hosts file */
83 /* Flag indicating that we want to show the contents of a certificate */
86 /* Flag indicating that we just want to see the key fingerprint */
87 int print_fingerprint = 0;
88 int print_bubblebabble = 0;
90 /* The identity file name, given on the command line or entered by the user. */
91 char identity_file[1024];
92 int have_identity = 0;
94 /* This is set to the passphrase if given on the command line. */
95 char *identity_passphrase = NULL;
97 /* This is set to the new passphrase if given on the command line. */
98 char *identity_new_passphrase = NULL;
100 /* This is set to the new comment if given on the command line. */
101 char *identity_comment = NULL;
103 /* Path to CA key when certifying keys. */
104 char *ca_key_path = NULL;
106 /* Certificate serial number */
107 long long cert_serial = 0;
109 /* Key type when certifying */
110 u_int cert_key_type = SSH2_CERT_TYPE_USER;
112 /* "key ID" of signed key */
113 char *cert_key_id = NULL;
115 /* Comma-separated list of principal names for certifying keys */
116 char *cert_principals = NULL;
118 /* Validity period for certificates */
119 u_int64_t cert_valid_from = 0;
120 u_int64_t cert_valid_to = ~0ULL;
122 /* Certificate options */
123 #define CERTOPT_X_FWD (1)
124 #define CERTOPT_AGENT_FWD (1<<1)
125 #define CERTOPT_PORT_FWD (1<<2)
126 #define CERTOPT_PTY (1<<3)
127 #define CERTOPT_USER_RC (1<<4)
128 #define CERTOPT_DEFAULT (CERTOPT_X_FWD|CERTOPT_AGENT_FWD| \
129 CERTOPT_PORT_FWD|CERTOPT_PTY|CERTOPT_USER_RC)
130 u_int32_t certflags_flags = CERTOPT_DEFAULT;
131 char *certflags_command = NULL;
132 char *certflags_src_addr = NULL;
134 /* Conversion to/from various formats */
136 int convert_from = 0;
141 } convert_format = FMT_RFC4716;
142 int print_public = 0;
143 int print_generic = 0;
145 char *key_type_name = NULL;
147 /* Load key from this PKCS#11 provider */
148 char *pkcs11provider = NULL;
151 extern char *__progname;
153 char hostname[MAXHOSTNAMELEN];
156 int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
157 int prime_test(FILE *, FILE *, u_int32_t, u_int32_t);
160 type_bits_valid(int type, u_int32_t *bitsp)
164 if (type == KEY_UNSPEC) {
165 fprintf(stderr, "unknown key type %s\n", key_type_name);
170 *bitsp = DEFAULT_BITS_DSA;
171 else if (type == KEY_ECDSA)
172 *bitsp = DEFAULT_BITS_ECDSA;
174 *bitsp = DEFAULT_BITS;
176 maxbits = (type == KEY_DSA) ?
177 OPENSSL_DSA_MAX_MODULUS_BITS : OPENSSL_RSA_MAX_MODULUS_BITS;
178 if (*bitsp > maxbits) {
179 fprintf(stderr, "key bits exceeds maximum %d\n", maxbits);
182 if (type == KEY_DSA && *bitsp != 1024)
183 fatal("DSA keys must be 1024 bits");
184 else if (type != KEY_ECDSA && *bitsp < 768)
185 fatal("Key must at least be 768 bits");
186 else if (type == KEY_ECDSA && key_ecdsa_bits_to_nid(*bitsp) == -1)
187 fatal("Invalid ECDSA key length - valid lengths are "
188 "256, 384 or 521 bits");
192 ask_filename(struct passwd *pw, const char *prompt)
197 if (key_type_name == NULL)
198 name = _PATH_SSH_CLIENT_ID_RSA;
200 switch (key_type_from_name(key_type_name)) {
202 name = _PATH_SSH_CLIENT_IDENTITY;
205 case KEY_DSA_CERT_V00:
207 name = _PATH_SSH_CLIENT_ID_DSA;
209 #ifdef OPENSSL_HAS_ECC
212 name = _PATH_SSH_CLIENT_ID_ECDSA;
216 case KEY_RSA_CERT_V00:
218 name = _PATH_SSH_CLIENT_ID_RSA;
221 fprintf(stderr, "bad key type\n");
226 snprintf(identity_file, sizeof(identity_file), "%s/%s", pw->pw_dir, name);
227 fprintf(stderr, "%s (%s): ", prompt, identity_file);
228 if (fgets(buf, sizeof(buf), stdin) == NULL)
230 buf[strcspn(buf, "\n")] = '\0';
231 if (strcmp(buf, "") != 0)
232 strlcpy(identity_file, buf, sizeof(identity_file));
237 load_identity(char *filename)
242 prv = key_load_private(filename, "", NULL);
244 if (identity_passphrase)
245 pass = xstrdup(identity_passphrase);
247 pass = read_passphrase("Enter passphrase: ",
249 prv = key_load_private(filename, pass, NULL);
250 memset(pass, 0, strlen(pass));
256 #define SSH_COM_PUBLIC_BEGIN "---- BEGIN SSH2 PUBLIC KEY ----"
257 #define SSH_COM_PUBLIC_END "---- END SSH2 PUBLIC KEY ----"
258 #define SSH_COM_PRIVATE_BEGIN "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
259 #define SSH_COM_PRIVATE_KEY_MAGIC 0x3f6ff9eb
262 do_convert_to_ssh2(struct passwd *pw, Key *k)
268 if (key_to_blob(k, &blob, &len) <= 0) {
269 fprintf(stderr, "key_to_blob failed\n");
272 /* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
273 snprintf(comment, sizeof(comment),
274 "%u-bit %s, converted by %s@%s from OpenSSH",
275 key_size(k), key_type(k),
276 pw->pw_name, hostname);
278 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
279 fprintf(stdout, "Comment: \"%s\"\n", comment);
280 dump_base64(stdout, blob, len);
281 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
288 do_convert_to_pkcs8(Key *k)
290 switch (key_type_plain(k->type)) {
292 if (!PEM_write_RSA_PUBKEY(stdout, k->rsa))
293 fatal("PEM_write_RSA_PUBKEY failed");
296 if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
297 fatal("PEM_write_DSA_PUBKEY failed");
299 #ifdef OPENSSL_HAS_ECC
301 if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
302 fatal("PEM_write_EC_PUBKEY failed");
306 fatal("%s: unsupported key type %s", __func__, key_type(k));
312 do_convert_to_pem(Key *k)
314 switch (key_type_plain(k->type)) {
316 if (!PEM_write_RSAPublicKey(stdout, k->rsa))
317 fatal("PEM_write_RSAPublicKey failed");
319 #if notyet /* OpenSSH 0.9.8 lacks this function */
321 if (!PEM_write_DSAPublicKey(stdout, k->dsa))
322 fatal("PEM_write_DSAPublicKey failed");
327 fatal("%s: unsupported key type %s", __func__, key_type(k));
333 do_convert_to(struct passwd *pw)
339 ask_filename(pw, "Enter file in which the key is");
340 if (stat(identity_file, &st) < 0)
341 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
342 if ((k = key_load_public(identity_file, NULL)) == NULL) {
343 if ((k = load_identity(identity_file)) == NULL) {
344 fprintf(stderr, "load failed\n");
348 if (k->type == KEY_RSA1) {
349 fprintf(stderr, "version 1 keys are not supported\n");
353 switch (convert_format) {
355 do_convert_to_ssh2(pw, k);
358 do_convert_to_pkcs8(k);
361 do_convert_to_pem(k);
364 fatal("%s: unknown key format %d", __func__, convert_format);
370 buffer_get_bignum_bits(Buffer *b, BIGNUM *value)
372 u_int bignum_bits = buffer_get_int(b);
373 u_int bytes = (bignum_bits + 7) / 8;
375 if (buffer_len(b) < bytes)
376 fatal("buffer_get_bignum_bits: input buffer too small: "
377 "need %d have %d", bytes, buffer_len(b));
378 if (BN_bin2bn(buffer_ptr(b), bytes, value) == NULL)
379 fatal("buffer_get_bignum_bits: BN_bin2bn failed");
380 buffer_consume(b, bytes);
384 do_convert_private_ssh2_from_blob(u_char *blob, u_int blen)
389 u_char *sig, data[] = "abcde12345";
390 int magic, rlen, ktype, i1, i2, i3, i4;
395 buffer_append(&b, blob, blen);
397 magic = buffer_get_int(&b);
398 if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
399 error("bad magic 0x%x != 0x%x", magic, SSH_COM_PRIVATE_KEY_MAGIC);
403 i1 = buffer_get_int(&b);
404 type = buffer_get_string(&b, NULL);
405 cipher = buffer_get_string(&b, NULL);
406 i2 = buffer_get_int(&b);
407 i3 = buffer_get_int(&b);
408 i4 = buffer_get_int(&b);
409 debug("ignore (%d %d %d %d)", i1, i2, i3, i4);
410 if (strcmp(cipher, "none") != 0) {
411 error("unsupported cipher %s", cipher);
419 if (strstr(type, "dsa")) {
421 } else if (strstr(type, "rsa")) {
428 key = key_new_private(ktype);
433 buffer_get_bignum_bits(&b, key->dsa->p);
434 buffer_get_bignum_bits(&b, key->dsa->g);
435 buffer_get_bignum_bits(&b, key->dsa->q);
436 buffer_get_bignum_bits(&b, key->dsa->pub_key);
437 buffer_get_bignum_bits(&b, key->dsa->priv_key);
440 e = buffer_get_char(&b);
444 e += buffer_get_char(&b);
447 e += buffer_get_char(&b);
450 if (!BN_set_word(key->rsa->e, e)) {
455 buffer_get_bignum_bits(&b, key->rsa->d);
456 buffer_get_bignum_bits(&b, key->rsa->n);
457 buffer_get_bignum_bits(&b, key->rsa->iqmp);
458 buffer_get_bignum_bits(&b, key->rsa->q);
459 buffer_get_bignum_bits(&b, key->rsa->p);
460 rsa_generate_additional_parameters(key->rsa);
463 rlen = buffer_len(&b);
465 error("do_convert_private_ssh2_from_blob: "
466 "remaining bytes in key blob %d", rlen);
470 key_sign(key, &sig, &slen, data, sizeof(data));
471 key_verify(key, sig, slen, data, sizeof(data));
477 get_line(FILE *fp, char *line, size_t len)
483 while ((c = fgetc(fp)) != EOF) {
484 if (pos >= len - 1) {
485 fprintf(stderr, "input line too long.\n");
491 if (c != EOF && c != '\n' && ungetc(c, fp) == EOF) {
492 fprintf(stderr, "unget: %s\n", strerror(errno));
507 do_convert_from_ssh2(struct passwd *pw, Key **k, int *private)
517 if ((fp = fopen(identity_file, "r")) == NULL)
518 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
520 while ((blen = get_line(fp, line, sizeof(line))) != -1) {
521 if (line[blen - 1] == '\\')
523 if (strncmp(line, "----", 4) == 0 ||
524 strstr(line, ": ") != NULL) {
525 if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
527 if (strstr(line, " END ") != NULL) {
530 /* fprintf(stderr, "ignore: %s", line); */
535 /* fprintf(stderr, "escaped: %s", line); */
538 strlcat(encoded, line, sizeof(encoded));
540 len = strlen(encoded);
541 if (((len % 4) == 3) &&
542 (encoded[len-1] == '=') &&
543 (encoded[len-2] == '=') &&
544 (encoded[len-3] == '='))
545 encoded[len-3] = '\0';
546 blen = uudecode(encoded, blob, sizeof(blob));
548 fprintf(stderr, "uudecode failed.\n");
552 do_convert_private_ssh2_from_blob(blob, blen) :
553 key_from_blob(blob, blen);
555 fprintf(stderr, "decode blob failed.\n");
562 do_convert_from_pkcs8(Key **k, int *private)
567 if ((fp = fopen(identity_file, "r")) == NULL)
568 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
569 if ((pubkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL)) == NULL) {
570 fatal("%s: %s is not a recognised public key format", __func__,
574 switch (EVP_PKEY_type(pubkey->type)) {
576 *k = key_new(KEY_UNSPEC);
577 (*k)->type = KEY_RSA;
578 (*k)->rsa = EVP_PKEY_get1_RSA(pubkey);
581 *k = key_new(KEY_UNSPEC);
582 (*k)->type = KEY_DSA;
583 (*k)->dsa = EVP_PKEY_get1_DSA(pubkey);
585 #ifdef OPENSSL_HAS_ECC
587 *k = key_new(KEY_UNSPEC);
588 (*k)->type = KEY_ECDSA;
589 (*k)->ecdsa = EVP_PKEY_get1_EC_KEY(pubkey);
590 (*k)->ecdsa_nid = key_ecdsa_key_to_nid((*k)->ecdsa);
594 fatal("%s: unsupported pubkey type %d", __func__,
595 EVP_PKEY_type(pubkey->type));
597 EVP_PKEY_free(pubkey);
602 do_convert_from_pem(Key **k, int *private)
610 if ((fp = fopen(identity_file, "r")) == NULL)
611 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
612 if ((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
613 *k = key_new(KEY_UNSPEC);
614 (*k)->type = KEY_RSA;
619 #if notyet /* OpenSSH 0.9.8 lacks this function */
621 if ((dsa = PEM_read_DSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
622 *k = key_new(KEY_UNSPEC);
623 (*k)->type = KEY_DSA;
630 fatal("%s: unrecognised raw private key format", __func__);
634 do_convert_from(struct passwd *pw)
637 int private = 0, ok = 0;
641 ask_filename(pw, "Enter file in which the key is");
642 if (stat(identity_file, &st) < 0)
643 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
645 switch (convert_format) {
647 do_convert_from_ssh2(pw, &k, &private);
650 do_convert_from_pkcs8(&k, &private);
653 do_convert_from_pem(&k, &private);
656 fatal("%s: unknown key format %d", __func__, convert_format);
660 ok = key_write(k, stdout);
662 fprintf(stdout, "\n");
666 ok = PEM_write_DSAPrivateKey(stdout, k->dsa, NULL,
667 NULL, 0, NULL, NULL);
669 #ifdef OPENSSL_HAS_ECC
671 ok = PEM_write_ECPrivateKey(stdout, k->ecdsa, NULL,
672 NULL, 0, NULL, NULL);
676 ok = PEM_write_RSAPrivateKey(stdout, k->rsa, NULL,
677 NULL, 0, NULL, NULL);
680 fatal("%s: unsupported key type %s", __func__,
686 fprintf(stderr, "key write failed\n");
694 do_print_public(struct passwd *pw)
700 ask_filename(pw, "Enter file in which the key is");
701 if (stat(identity_file, &st) < 0) {
702 perror(identity_file);
705 prv = load_identity(identity_file);
707 fprintf(stderr, "load failed\n");
710 if (!key_write(prv, stdout))
711 fprintf(stderr, "key_write failed");
713 fprintf(stdout, "\n");
718 do_download(struct passwd *pw)
725 nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys);
727 fatal("cannot read public key from pkcs11");
728 for (i = 0; i < nkeys; i++) {
729 key_write(keys[i], stdout);
731 fprintf(stdout, "\n");
737 fatal("no pkcs11 support");
738 #endif /* ENABLE_PKCS11 */
742 do_fingerprint(struct passwd *pw)
746 char *comment = NULL, *cp, *ep, line[16*1024], *fp, *ra;
747 int i, skip = 0, num = 0, invalid = 1;
752 fptype = print_bubblebabble ? SSH_FP_SHA1 : SSH_FP_MD5;
753 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_HEX;
756 ask_filename(pw, "Enter file in which the key is");
757 if (stat(identity_file, &st) < 0) {
758 perror(identity_file);
761 public = key_load_public(identity_file, &comment);
762 if (public != NULL) {
763 fp = key_fingerprint(public, fptype, rep);
764 ra = key_fingerprint(public, SSH_FP_MD5, SSH_FP_RANDOMART);
765 printf("%u %s %s (%s)\n", key_size(public), fp, comment,
767 if (log_level >= SYSLOG_LEVEL_VERBOSE)
780 if ((f = fopen(identity_file, "r")) == NULL)
781 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
783 while (fgets(line, sizeof(line), f)) {
784 if ((cp = strchr(line, '\n')) == NULL) {
785 error("line %d too long: %.40s...",
797 /* Skip leading whitespace, empty and comment lines. */
798 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
800 if (!*cp || *cp == '\n' || *cp == '#')
802 i = strtol(cp, &ep, 10);
803 if (i == 0 || ep == NULL || (*ep != ' ' && *ep != '\t')) {
806 for (; *cp && (quoted || (*cp != ' ' &&
807 *cp != '\t')); cp++) {
808 if (*cp == '\\' && cp[1] == '"')
809 cp++; /* Skip both */
818 public = key_new(KEY_RSA1);
819 if (key_read(public, &cp) != 1) {
822 public = key_new(KEY_UNSPEC);
823 if (key_read(public, &cp) != 1) {
828 comment = *cp ? cp : comment;
829 fp = key_fingerprint(public, fptype, rep);
830 ra = key_fingerprint(public, SSH_FP_MD5, SSH_FP_RANDOMART);
831 printf("%u %s %s (%s)\n", key_size(public), fp,
832 comment ? comment : "no comment", key_type(public));
833 if (log_level >= SYSLOG_LEVEL_VERBOSE)
843 printf("%s is not a public key file.\n", identity_file);
850 do_gen_all_hostkeys(struct passwd *pw)
854 char *key_type_display;
857 { "rsa1", "RSA1", _PATH_HOST_KEY_FILE },
858 { "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE },
859 { "dsa", "DSA", _PATH_HOST_DSA_KEY_FILE },
860 { "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE },
866 Key *private, *public;
871 for (i = 0; key_types[i].key_type; i++) {
872 if (stat(key_types[i].path, &st) == 0)
874 if (errno != ENOENT) {
875 printf("Could not stat %s: %s", key_types[i].path,
883 printf("%s: generating new host keys: ", __progname);
885 printf("%s ", key_types[i].key_type_display);
888 type = key_type_from_name(key_types[i].key_type);
889 strlcpy(identity_file, key_types[i].path, sizeof(identity_file));
891 type_bits_valid(type, &bits);
892 private = key_generate(type, bits);
893 if (private == NULL) {
894 fprintf(stderr, "key_generate failed\n");
898 public = key_from_private(private);
899 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name,
901 if (!key_save_private(private, identity_file, "", comment)) {
902 printf("Saving the key failed: %s.\n", identity_file);
910 strlcat(identity_file, ".pub", sizeof(identity_file));
911 fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
913 printf("Could not save your public key in %s\n",
921 printf("fdopen %s failed\n", identity_file);
926 if (!key_write(public, f)) {
927 fprintf(stderr, "write key failed\n");
932 fprintf(f, " %s\n", comment);
942 printhost(FILE *f, const char *name, Key *public, int ca, int hash)
944 if (print_fingerprint) {
949 fptype = print_bubblebabble ? SSH_FP_SHA1 : SSH_FP_MD5;
950 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_HEX;
951 fp = key_fingerprint(public, fptype, rep);
952 ra = key_fingerprint(public, SSH_FP_MD5, SSH_FP_RANDOMART);
953 printf("%u %s %s (%s)\n", key_size(public), fp, name,
955 if (log_level >= SYSLOG_LEVEL_VERBOSE)
960 if (hash && (name = host_hash(name, NULL, 0)) == NULL)
961 fatal("hash_host failed");
962 fprintf(f, "%s%s%s ", ca ? CA_MARKER : "", ca ? " " : "", name);
963 if (!key_write(public, f))
964 fatal("key_write failed");
970 do_known_hosts(struct passwd *pw, const char *name)
972 FILE *in, *out = stdout;
974 char *cp, *cp2, *kp, *kp2;
975 char line[16*1024], tmp[MAXPATHLEN], old[MAXPATHLEN];
976 int c, skip = 0, inplace = 0, num = 0, invalid = 0, has_unhashed = 0;
979 if (!have_identity) {
980 cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
981 if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
982 sizeof(identity_file))
983 fatal("Specified known hosts path too long");
987 if ((in = fopen(identity_file, "r")) == NULL)
988 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
991 * Find hosts goes to stdout, hash and deletions happen in-place
992 * A corner case is ssh-keygen -HF foo, which should go to stdout
994 if (!find_host && (hash_hosts || delete_host)) {
995 if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
996 strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
997 strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
998 strlcat(old, ".old", sizeof(old)) >= sizeof(old))
999 fatal("known_hosts path too long");
1001 if ((c = mkstemp(tmp)) == -1)
1002 fatal("mkstemp: %s", strerror(errno));
1003 if ((out = fdopen(c, "w")) == NULL) {
1006 fatal("fdopen: %s", strerror(c));
1011 while (fgets(line, sizeof(line), in)) {
1012 if ((cp = strchr(line, '\n')) == NULL) {
1013 error("line %d too long: %.40s...", num + 1, line);
1025 /* Skip leading whitespace, empty and comment lines. */
1026 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
1028 if (!*cp || *cp == '\n' || *cp == '#') {
1030 fprintf(out, "%s\n", cp);
1033 /* Check whether this is a CA key */
1034 if (strncasecmp(cp, CA_MARKER, sizeof(CA_MARKER) - 1) == 0 &&
1035 (cp[sizeof(CA_MARKER) - 1] == ' ' ||
1036 cp[sizeof(CA_MARKER) - 1] == '\t')) {
1038 cp += sizeof(CA_MARKER);
1042 /* Find the end of the host name portion. */
1043 for (kp = cp; *kp && *kp != ' ' && *kp != '\t'; kp++)
1046 if (*kp == '\0' || *(kp + 1) == '\0') {
1047 error("line %d missing key: %.40s...",
1055 pub = key_new(KEY_RSA1);
1056 if (key_read(pub, &kp) != 1) {
1059 pub = key_new(KEY_UNSPEC);
1060 if (key_read(pub, &kp) != 1) {
1061 error("line %d invalid key: %.40s...",
1069 if (*cp == HASH_DELIM) {
1070 if (find_host || delete_host) {
1071 cp2 = host_hash(name, cp, strlen(cp));
1073 error("line %d: invalid hashed "
1074 "name: %.64s...", num, line);
1078 c = (strcmp(cp2, cp) == 0);
1079 if (find_host && c) {
1080 printf("# Host %s found: "
1081 "line %d type %s%s\n", name,
1083 ca ? " (CA key)" : "");
1084 printhost(out, cp, pub, ca, 0);
1086 if (delete_host && !c && !ca)
1087 printhost(out, cp, pub, ca, 0);
1088 } else if (hash_hosts)
1089 printhost(out, cp, pub, ca, 0);
1091 if (find_host || delete_host) {
1092 c = (match_hostname(name, cp,
1094 if (find_host && c) {
1095 printf("# Host %s found: "
1096 "line %d type %s%s\n", name,
1098 ca ? " (CA key)" : "");
1099 printhost(out, name, pub,
1100 ca, hash_hosts && !ca);
1102 if (delete_host && !c && !ca)
1103 printhost(out, cp, pub, ca, 0);
1104 } else if (hash_hosts) {
1105 for (cp2 = strsep(&cp, ",");
1106 cp2 != NULL && *cp2 != '\0';
1107 cp2 = strsep(&cp, ",")) {
1109 fprintf(stderr, "Warning: "
1110 "ignoring CA key for host: "
1112 printhost(out, cp2, pub, ca, 0);
1113 } else if (strcspn(cp2, "*?!") !=
1115 fprintf(stderr, "Warning: "
1116 "ignoring host name with "
1117 "metacharacters: %.64s\n",
1119 printhost(out, cp2, pub, ca, 0);
1121 printhost(out, cp2, pub, ca, 1);
1131 fprintf(stderr, "%s is not a valid known_hosts file.\n",
1134 fprintf(stderr, "Not replacing existing known_hosts "
1135 "file because of errors\n");
1145 /* Backup existing file */
1146 if (unlink(old) == -1 && errno != ENOENT)
1147 fatal("unlink %.100s: %s", old, strerror(errno));
1148 if (link(identity_file, old) == -1)
1149 fatal("link %.100s to %.100s: %s", identity_file, old,
1151 /* Move new one into place */
1152 if (rename(tmp, identity_file) == -1) {
1153 error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
1160 fprintf(stderr, "%s updated.\n", identity_file);
1161 fprintf(stderr, "Original contents retained as %s\n", old);
1163 fprintf(stderr, "WARNING: %s contains unhashed "
1165 fprintf(stderr, "Delete this file to ensure privacy "
1174 * Perform changing a passphrase. The argument is the passwd structure
1175 * for the current user.
1178 do_change_passphrase(struct passwd *pw)
1181 char *old_passphrase, *passphrase1, *passphrase2;
1186 ask_filename(pw, "Enter file in which the key is");
1187 if (stat(identity_file, &st) < 0) {
1188 perror(identity_file);
1191 /* Try to load the file with empty passphrase. */
1192 private = key_load_private(identity_file, "", &comment);
1193 if (private == NULL) {
1194 if (identity_passphrase)
1195 old_passphrase = xstrdup(identity_passphrase);
1198 read_passphrase("Enter old passphrase: ",
1200 private = key_load_private(identity_file, old_passphrase,
1202 memset(old_passphrase, 0, strlen(old_passphrase));
1203 xfree(old_passphrase);
1204 if (private == NULL) {
1205 printf("Bad passphrase.\n");
1209 printf("Key has comment '%s'\n", comment);
1211 /* Ask the new passphrase (twice). */
1212 if (identity_new_passphrase) {
1213 passphrase1 = xstrdup(identity_new_passphrase);
1217 read_passphrase("Enter new passphrase (empty for no "
1218 "passphrase): ", RP_ALLOW_STDIN);
1219 passphrase2 = read_passphrase("Enter same passphrase again: ",
1222 /* Verify that they are the same. */
1223 if (strcmp(passphrase1, passphrase2) != 0) {
1224 memset(passphrase1, 0, strlen(passphrase1));
1225 memset(passphrase2, 0, strlen(passphrase2));
1228 printf("Pass phrases do not match. Try again.\n");
1231 /* Destroy the other copy. */
1232 memset(passphrase2, 0, strlen(passphrase2));
1236 /* Save the file using the new passphrase. */
1237 if (!key_save_private(private, identity_file, passphrase1, comment)) {
1238 printf("Saving the key failed: %s.\n", identity_file);
1239 memset(passphrase1, 0, strlen(passphrase1));
1245 /* Destroy the passphrase and the copy of the key in memory. */
1246 memset(passphrase1, 0, strlen(passphrase1));
1248 key_free(private); /* Destroys contents */
1251 printf("Your identification has been saved with the new passphrase.\n");
1256 * Print the SSHFP RR.
1259 do_print_resource_record(struct passwd *pw, char *fname, char *hname)
1262 char *comment = NULL;
1266 ask_filename(pw, "Enter file in which the key is");
1267 if (stat(fname, &st) < 0) {
1268 if (errno == ENOENT)
1273 public = key_load_public(fname, &comment);
1274 if (public != NULL) {
1275 export_dns_rr(hname, public, stdout, print_generic);
1283 printf("failed to read v2 public key from %s.\n", fname);
1288 * Change the comment of a private key file.
1291 do_change_comment(struct passwd *pw)
1293 char new_comment[1024], *comment, *passphrase;
1301 ask_filename(pw, "Enter file in which the key is");
1302 if (stat(identity_file, &st) < 0) {
1303 perror(identity_file);
1306 private = key_load_private(identity_file, "", &comment);
1307 if (private == NULL) {
1308 if (identity_passphrase)
1309 passphrase = xstrdup(identity_passphrase);
1310 else if (identity_new_passphrase)
1311 passphrase = xstrdup(identity_new_passphrase);
1313 passphrase = read_passphrase("Enter passphrase: ",
1315 /* Try to load using the passphrase. */
1316 private = key_load_private(identity_file, passphrase, &comment);
1317 if (private == NULL) {
1318 memset(passphrase, 0, strlen(passphrase));
1320 printf("Bad passphrase.\n");
1324 passphrase = xstrdup("");
1326 if (private->type != KEY_RSA1) {
1327 fprintf(stderr, "Comments are only supported for RSA1 keys.\n");
1331 printf("Key now has comment '%s'\n", comment);
1333 if (identity_comment) {
1334 strlcpy(new_comment, identity_comment, sizeof(new_comment));
1336 printf("Enter new comment: ");
1338 if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1339 memset(passphrase, 0, strlen(passphrase));
1343 new_comment[strcspn(new_comment, "\n")] = '\0';
1346 /* Save the file using the new passphrase. */
1347 if (!key_save_private(private, identity_file, passphrase, new_comment)) {
1348 printf("Saving the key failed: %s.\n", identity_file);
1349 memset(passphrase, 0, strlen(passphrase));
1355 memset(passphrase, 0, strlen(passphrase));
1357 public = key_from_private(private);
1360 strlcat(identity_file, ".pub", sizeof(identity_file));
1361 fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1363 printf("Could not save your public key in %s\n", identity_file);
1366 f = fdopen(fd, "w");
1368 printf("fdopen %s failed\n", identity_file);
1371 if (!key_write(public, f))
1372 fprintf(stderr, "write key failed\n");
1374 fprintf(f, " %s\n", new_comment);
1379 printf("The comment in your key file has been changed.\n");
1384 fmt_validity(u_int64_t valid_from, u_int64_t valid_to)
1386 char from[32], to[32];
1387 static char ret[64];
1392 if (valid_from == 0 && valid_to == 0xffffffffffffffffULL)
1395 if (valid_from != 0) {
1396 /* XXX revisit INT_MAX in 2038 :) */
1397 tt = valid_from > INT_MAX ? INT_MAX : valid_from;
1398 tm = localtime(&tt);
1399 strftime(from, sizeof(from), "%Y-%m-%dT%H:%M:%S", tm);
1401 if (valid_to != 0xffffffffffffffffULL) {
1402 /* XXX revisit INT_MAX in 2038 :) */
1403 tt = valid_to > INT_MAX ? INT_MAX : valid_to;
1404 tm = localtime(&tt);
1405 strftime(to, sizeof(to), "%Y-%m-%dT%H:%M:%S", tm);
1408 if (valid_from == 0) {
1409 snprintf(ret, sizeof(ret), "before %s", to);
1412 if (valid_to == 0xffffffffffffffffULL) {
1413 snprintf(ret, sizeof(ret), "after %s", from);
1417 snprintf(ret, sizeof(ret), "from %s to %s", from, to);
1422 add_flag_option(Buffer *c, const char *name)
1424 debug3("%s: %s", __func__, name);
1425 buffer_put_cstring(c, name);
1426 buffer_put_string(c, NULL, 0);
1430 add_string_option(Buffer *c, const char *name, const char *value)
1434 debug3("%s: %s=%s", __func__, name, value);
1436 buffer_put_cstring(&b, value);
1438 buffer_put_cstring(c, name);
1439 buffer_put_string(c, buffer_ptr(&b), buffer_len(&b));
1444 #define OPTIONS_CRITICAL 1
1445 #define OPTIONS_EXTENSIONS 2
1447 prepare_options_buf(Buffer *c, int which)
1450 if ((which & OPTIONS_CRITICAL) != 0 &&
1451 certflags_command != NULL)
1452 add_string_option(c, "force-command", certflags_command);
1453 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1454 (certflags_flags & CERTOPT_X_FWD) != 0)
1455 add_flag_option(c, "permit-X11-forwarding");
1456 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1457 (certflags_flags & CERTOPT_AGENT_FWD) != 0)
1458 add_flag_option(c, "permit-agent-forwarding");
1459 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1460 (certflags_flags & CERTOPT_PORT_FWD) != 0)
1461 add_flag_option(c, "permit-port-forwarding");
1462 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1463 (certflags_flags & CERTOPT_PTY) != 0)
1464 add_flag_option(c, "permit-pty");
1465 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1466 (certflags_flags & CERTOPT_USER_RC) != 0)
1467 add_flag_option(c, "permit-user-rc");
1468 if ((which & OPTIONS_CRITICAL) != 0 &&
1469 certflags_src_addr != NULL)
1470 add_string_option(c, "source-address", certflags_src_addr);
1474 load_pkcs11_key(char *path)
1476 #ifdef ENABLE_PKCS11
1477 Key **keys = NULL, *public, *private = NULL;
1480 if ((public = key_load_public(path, NULL)) == NULL)
1481 fatal("Couldn't load CA public key \"%s\"", path);
1483 nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase, &keys);
1484 debug3("%s: %d keys", __func__, nkeys);
1486 fatal("cannot read public key from pkcs11");
1487 for (i = 0; i < nkeys; i++) {
1488 if (key_equal_public(public, keys[i])) {
1498 fatal("no pkcs11 support");
1499 #endif /* ENABLE_PKCS11 */
1503 do_ca_sign(struct passwd *pw, int argc, char **argv)
1508 char *otmp, *tmp, *cp, *out, *comment, **plist = NULL;
1510 int v00 = 0; /* legacy keys */
1512 if (key_type_name != NULL) {
1513 switch (key_type_from_name(key_type_name)) {
1514 case KEY_RSA_CERT_V00:
1515 case KEY_DSA_CERT_V00:
1519 if (strcasecmp(key_type_name, "v00") == 0) {
1522 } else if (strcasecmp(key_type_name, "v01") == 0)
1526 fprintf(stderr, "unknown key type %s\n", key_type_name);
1532 tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
1533 if (pkcs11provider != NULL) {
1534 if ((ca = load_pkcs11_key(tmp)) == NULL)
1535 fatal("No PKCS#11 key matching %s found", ca_key_path);
1536 } else if ((ca = load_identity(tmp)) == NULL)
1537 fatal("Couldn't load CA key \"%s\"", tmp);
1540 for (i = 0; i < argc; i++) {
1541 /* Split list of principals */
1543 if (cert_principals != NULL) {
1544 otmp = tmp = xstrdup(cert_principals);
1546 for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1547 plist = xrealloc(plist, n + 1, sizeof(*plist));
1548 if (*(plist[n] = xstrdup(cp)) == '\0')
1549 fatal("Empty principal name");
1554 tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1555 if ((public = key_load_public(tmp, &comment)) == NULL)
1556 fatal("%s: unable to open \"%s\"", __func__, tmp);
1557 if (public->type != KEY_RSA && public->type != KEY_DSA &&
1558 public->type != KEY_ECDSA)
1559 fatal("%s: key \"%s\" type %s cannot be certified",
1560 __func__, tmp, key_type(public));
1562 /* Prepare certificate to sign */
1563 if (key_to_certified(public, v00) != 0)
1564 fatal("Could not upgrade key %s to certificate", tmp);
1565 public->cert->type = cert_key_type;
1566 public->cert->serial = (u_int64_t)cert_serial;
1567 public->cert->key_id = xstrdup(cert_key_id);
1568 public->cert->nprincipals = n;
1569 public->cert->principals = plist;
1570 public->cert->valid_after = cert_valid_from;
1571 public->cert->valid_before = cert_valid_to;
1573 prepare_options_buf(&public->cert->critical,
1574 OPTIONS_CRITICAL|OPTIONS_EXTENSIONS);
1576 prepare_options_buf(&public->cert->critical,
1578 prepare_options_buf(&public->cert->extensions,
1579 OPTIONS_EXTENSIONS);
1581 public->cert->signature_key = key_from_private(ca);
1583 if (key_certify(public, ca) != 0)
1584 fatal("Couldn't not certify key %s", tmp);
1586 if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
1588 xasprintf(&out, "%s-cert.pub", tmp);
1591 if ((fd = open(out, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
1592 fatal("Could not open \"%s\" for writing: %s", out,
1594 if ((f = fdopen(fd, "w")) == NULL)
1595 fatal("%s: fdopen: %s", __func__, strerror(errno));
1596 if (!key_write(public, f))
1597 fatal("Could not write certified key to %s", out);
1598 fprintf(f, " %s\n", comment);
1602 logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1603 "valid %s", key_cert_type(public),
1604 out, public->cert->key_id,
1605 (unsigned long long)public->cert->serial,
1606 cert_principals != NULL ? " for " : "",
1607 cert_principals != NULL ? cert_principals : "",
1608 fmt_validity(cert_valid_from, cert_valid_to));
1619 parse_relative_time(const char *s, time_t now)
1623 mul = *s == '-' ? -1 : 1;
1625 if ((secs = convtime(s + 1)) == -1)
1626 fatal("Invalid relative certificate time %s", s);
1627 if (mul == -1 && secs > now)
1628 fatal("Certificate time %s cannot be represented", s);
1629 return now + (u_int64_t)(secs * mul);
1633 parse_absolute_time(const char *s)
1640 * POSIX strptime says "The application shall ensure that there
1641 * is white-space or other non-alphanumeric characters between
1642 * any two conversion specifications" so arrange things this way.
1644 switch (strlen(s)) {
1647 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
1650 fmt = "%Y-%m-%dT%H:%M:%S";
1651 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
1652 s, s + 4, s + 6, s + 8, s + 10, s + 12);
1655 fatal("Invalid certificate time format %s", s);
1658 bzero(&tm, sizeof(tm));
1659 if (strptime(buf, fmt, &tm) == NULL)
1660 fatal("Invalid certificate time %s", s);
1661 if ((tt = mktime(&tm)) < 0)
1662 fatal("Certificate time %s cannot be represented", s);
1663 return (u_int64_t)tt;
1667 parse_cert_times(char *timespec)
1670 time_t now = time(NULL);
1673 /* +timespec relative to now */
1674 if (*timespec == '+' && strchr(timespec, ':') == NULL) {
1675 if ((secs = convtime(timespec + 1)) == -1)
1676 fatal("Invalid relative certificate life %s", timespec);
1677 cert_valid_to = now + secs;
1679 * Backdate certificate one minute to avoid problems on hosts
1680 * with poorly-synchronised clocks.
1682 cert_valid_from = ((now - 59)/ 60) * 60;
1688 * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS
1689 * to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS
1691 from = xstrdup(timespec);
1692 to = strchr(from, ':');
1693 if (to == NULL || from == to || *(to + 1) == '\0')
1694 fatal("Invalid certificate life specification %s", timespec);
1697 if (*from == '-' || *from == '+')
1698 cert_valid_from = parse_relative_time(from, now);
1700 cert_valid_from = parse_absolute_time(from);
1702 if (*to == '-' || *to == '+')
1703 cert_valid_to = parse_relative_time(to, cert_valid_from);
1705 cert_valid_to = parse_absolute_time(to);
1707 if (cert_valid_to <= cert_valid_from)
1708 fatal("Empty certificate validity interval");
1713 add_cert_option(char *opt)
1717 if (strcasecmp(opt, "clear") == 0)
1718 certflags_flags = 0;
1719 else if (strcasecmp(opt, "no-x11-forwarding") == 0)
1720 certflags_flags &= ~CERTOPT_X_FWD;
1721 else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
1722 certflags_flags |= CERTOPT_X_FWD;
1723 else if (strcasecmp(opt, "no-agent-forwarding") == 0)
1724 certflags_flags &= ~CERTOPT_AGENT_FWD;
1725 else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
1726 certflags_flags |= CERTOPT_AGENT_FWD;
1727 else if (strcasecmp(opt, "no-port-forwarding") == 0)
1728 certflags_flags &= ~CERTOPT_PORT_FWD;
1729 else if (strcasecmp(opt, "permit-port-forwarding") == 0)
1730 certflags_flags |= CERTOPT_PORT_FWD;
1731 else if (strcasecmp(opt, "no-pty") == 0)
1732 certflags_flags &= ~CERTOPT_PTY;
1733 else if (strcasecmp(opt, "permit-pty") == 0)
1734 certflags_flags |= CERTOPT_PTY;
1735 else if (strcasecmp(opt, "no-user-rc") == 0)
1736 certflags_flags &= ~CERTOPT_USER_RC;
1737 else if (strcasecmp(opt, "permit-user-rc") == 0)
1738 certflags_flags |= CERTOPT_USER_RC;
1739 else if (strncasecmp(opt, "force-command=", 14) == 0) {
1742 fatal("Empty force-command option");
1743 if (certflags_command != NULL)
1744 fatal("force-command already specified");
1745 certflags_command = xstrdup(val);
1746 } else if (strncasecmp(opt, "source-address=", 15) == 0) {
1749 fatal("Empty source-address option");
1750 if (certflags_src_addr != NULL)
1751 fatal("source-address already specified");
1752 if (addr_match_cidr_list(NULL, val) != 0)
1753 fatal("Invalid source-address list");
1754 certflags_src_addr = xstrdup(val);
1756 fatal("Unsupported certificate option \"%s\"", opt);
1760 show_options(const Buffer *optbuf, int v00, int in_critical)
1762 u_char *name, *data;
1764 Buffer options, option;
1766 buffer_init(&options);
1767 buffer_append(&options, buffer_ptr(optbuf), buffer_len(optbuf));
1769 buffer_init(&option);
1770 while (buffer_len(&options) != 0) {
1771 name = buffer_get_string(&options, NULL);
1772 data = buffer_get_string_ptr(&options, &dlen);
1773 buffer_append(&option, data, dlen);
1774 printf(" %s", name);
1775 if ((v00 || !in_critical) &&
1776 (strcmp(name, "permit-X11-forwarding") == 0 ||
1777 strcmp(name, "permit-agent-forwarding") == 0 ||
1778 strcmp(name, "permit-port-forwarding") == 0 ||
1779 strcmp(name, "permit-pty") == 0 ||
1780 strcmp(name, "permit-user-rc") == 0))
1782 else if ((v00 || in_critical) &&
1783 (strcmp(name, "force-command") == 0 ||
1784 strcmp(name, "source-address") == 0)) {
1785 data = buffer_get_string(&option, NULL);
1786 printf(" %s\n", data);
1789 printf(" UNKNOWN OPTION (len %u)\n",
1790 buffer_len(&option));
1791 buffer_clear(&option);
1794 if (buffer_len(&option) != 0)
1795 fatal("Option corrupt: extra data at end");
1797 buffer_free(&option);
1798 buffer_free(&options);
1802 do_show_cert(struct passwd *pw)
1806 char *key_fp, *ca_fp;
1810 ask_filename(pw, "Enter file in which the key is");
1811 if (stat(identity_file, &st) < 0)
1812 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
1813 if ((key = key_load_public(identity_file, NULL)) == NULL)
1814 fatal("%s is not a public key", identity_file);
1815 if (!key_is_cert(key))
1816 fatal("%s is not a certificate", identity_file);
1817 v00 = key->type == KEY_RSA_CERT_V00 || key->type == KEY_DSA_CERT_V00;
1819 key_fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
1820 ca_fp = key_fingerprint(key->cert->signature_key,
1821 SSH_FP_MD5, SSH_FP_HEX);
1823 printf("%s:\n", identity_file);
1824 printf(" Type: %s %s certificate\n", key_ssh_name(key),
1825 key_cert_type(key));
1826 printf(" Public key: %s %s\n", key_type(key), key_fp);
1827 printf(" Signing CA: %s %s\n",
1828 key_type(key->cert->signature_key), ca_fp);
1829 printf(" Key ID: \"%s\"\n", key->cert->key_id);
1831 printf(" Serial: %llu\n",
1832 (unsigned long long)key->cert->serial);
1834 printf(" Valid: %s\n",
1835 fmt_validity(key->cert->valid_after, key->cert->valid_before));
1836 printf(" Principals: ");
1837 if (key->cert->nprincipals == 0)
1840 for (i = 0; i < key->cert->nprincipals; i++)
1842 key->cert->principals[i]);
1845 printf(" Critical Options: ");
1846 if (buffer_len(&key->cert->critical) == 0)
1850 show_options(&key->cert->critical, v00, 1);
1853 printf(" Extensions: ");
1854 if (buffer_len(&key->cert->extensions) == 0)
1858 show_options(&key->cert->extensions, v00, 0);
1867 fprintf(stderr, "usage: %s [options]\n", __progname);
1868 fprintf(stderr, "Options:\n");
1869 fprintf(stderr, " -A Generate non-existent host keys for all key types.\n");
1870 fprintf(stderr, " -a trials Number of trials for screening DH-GEX moduli.\n");
1871 fprintf(stderr, " -B Show bubblebabble digest of key file.\n");
1872 fprintf(stderr, " -b bits Number of bits in the key to create.\n");
1873 fprintf(stderr, " -C comment Provide new comment.\n");
1874 fprintf(stderr, " -c Change comment in private and public key files.\n");
1875 #ifdef ENABLE_PKCS11
1876 fprintf(stderr, " -D pkcs11 Download public key from pkcs11 token.\n");
1878 fprintf(stderr, " -e Export OpenSSH to foreign format key file.\n");
1879 fprintf(stderr, " -F hostname Find hostname in known hosts file.\n");
1880 fprintf(stderr, " -f filename Filename of the key file.\n");
1881 fprintf(stderr, " -G file Generate candidates for DH-GEX moduli.\n");
1882 fprintf(stderr, " -g Use generic DNS resource record format.\n");
1883 fprintf(stderr, " -H Hash names in known_hosts file.\n");
1884 fprintf(stderr, " -h Generate host certificate instead of a user certificate.\n");
1885 fprintf(stderr, " -I key_id Key identifier to include in certificate.\n");
1886 fprintf(stderr, " -i Import foreign format to OpenSSH key file.\n");
1887 fprintf(stderr, " -L Print the contents of a certificate.\n");
1888 fprintf(stderr, " -l Show fingerprint of key file.\n");
1889 fprintf(stderr, " -M memory Amount of memory (MB) to use for generating DH-GEX moduli.\n");
1890 fprintf(stderr, " -m key_fmt Conversion format for -e/-i (PEM|PKCS8|RFC4716).\n");
1891 fprintf(stderr, " -N phrase Provide new passphrase.\n");
1892 fprintf(stderr, " -n name,... User/host principal names to include in certificate\n");
1893 fprintf(stderr, " -O option Specify a certificate option.\n");
1894 fprintf(stderr, " -P phrase Provide old passphrase.\n");
1895 fprintf(stderr, " -p Change passphrase of private key file.\n");
1896 fprintf(stderr, " -q Quiet.\n");
1897 fprintf(stderr, " -R hostname Remove host from known_hosts file.\n");
1898 fprintf(stderr, " -r hostname Print DNS resource record.\n");
1899 fprintf(stderr, " -S start Start point (hex) for generating DH-GEX moduli.\n");
1900 fprintf(stderr, " -s ca_key Certify keys with CA key.\n");
1901 fprintf(stderr, " -T file Screen candidates for DH-GEX moduli.\n");
1902 fprintf(stderr, " -t type Specify type of key to create.\n");
1903 fprintf(stderr, " -V from:to Specify certificate validity interval.\n");
1904 fprintf(stderr, " -v Verbose.\n");
1905 fprintf(stderr, " -W gen Generator to use for generating DH-GEX moduli.\n");
1906 fprintf(stderr, " -y Read private key file and print public key.\n");
1907 fprintf(stderr, " -z serial Specify a serial number.\n");
1913 * Main program for key management.
1916 main(int argc, char **argv)
1918 char dotsshdir[MAXPATHLEN], comment[1024], *passphrase1, *passphrase2;
1919 char out_file[MAXPATHLEN], *rr_hostname = NULL;
1920 Key *private, *public;
1924 u_int32_t memory = 0, generator_wanted = 0, trials = 100;
1925 int do_gen_candidates = 0, do_screen_candidates = 0;
1926 int gen_all_hostkeys = 0;
1927 BIGNUM *start = NULL;
1932 extern char *optarg;
1934 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1937 __progname = ssh_get_progname(argv[0]);
1939 OpenSSL_add_all_algorithms();
1940 log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
1944 /* we need this for the home * directory. */
1945 pw = getpwuid(getuid());
1947 printf("You don't exist, go away!\n");
1950 if (gethostname(hostname, sizeof(hostname)) < 0) {
1951 perror("gethostname");
1955 while ((opt = getopt(argc, argv, "AegiqpclBHLhvxXyF:b:f:t:D:I:P:m:N:n:"
1956 "O:C:r:g:R:T:G:M:S:s:a:V:W:z:")) != -1) {
1959 gen_all_hostkeys = 1;
1962 bits = (u_int32_t)strtonum(optarg, 256, 32768, &errstr);
1964 fatal("Bits has bad value %s (%s)",
1969 rr_hostname = optarg;
1975 cert_key_id = optarg;
1979 rr_hostname = optarg;
1985 print_fingerprint = 1;
1988 print_bubblebabble = 1;
1991 if (strcasecmp(optarg, "RFC4716") == 0 ||
1992 strcasecmp(optarg, "ssh2") == 0) {
1993 convert_format = FMT_RFC4716;
1996 if (strcasecmp(optarg, "PKCS8") == 0) {
1997 convert_format = FMT_PKCS8;
2000 if (strcasecmp(optarg, "PEM") == 0) {
2001 convert_format = FMT_PEM;
2004 fatal("Unsupported conversion format \"%s\"", optarg);
2006 cert_principals = optarg;
2009 change_passphrase = 1;
2015 if (strlcpy(identity_file, optarg, sizeof(identity_file)) >=
2016 sizeof(identity_file))
2017 fatal("Identity filename too long");
2024 identity_passphrase = optarg;
2027 identity_new_passphrase = optarg;
2030 add_cert_option(optarg);
2033 identity_comment = optarg;
2044 cert_key_type = SSH2_CERT_TYPE_HOST;
2045 certflags_flags = 0;
2056 ca_key_path = optarg;
2059 key_type_name = optarg;
2062 pkcs11provider = optarg;
2065 if (log_level == SYSLOG_LEVEL_INFO)
2066 log_level = SYSLOG_LEVEL_DEBUG1;
2068 if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
2069 log_level < SYSLOG_LEVEL_DEBUG3)
2074 rr_hostname = optarg;
2077 generator_wanted = (u_int32_t)strtonum(optarg, 1,
2080 fatal("Desired generator has bad value: %s (%s)",
2084 trials = (u_int32_t)strtonum(optarg, 1, UINT_MAX, &errstr);
2086 fatal("Invalid number of trials: %s (%s)",
2090 memory = (u_int32_t)strtonum(optarg, 1, UINT_MAX, &errstr);
2092 fatal("Memory limit is %s: %s", errstr, optarg);
2095 do_gen_candidates = 1;
2096 if (strlcpy(out_file, optarg, sizeof(out_file)) >=
2098 fatal("Output filename too long");
2101 do_screen_candidates = 1;
2102 if (strlcpy(out_file, optarg, sizeof(out_file)) >=
2104 fatal("Output filename too long");
2107 /* XXX - also compare length against bits */
2108 if (BN_hex2bn(&start, optarg) == 0)
2109 fatal("Invalid start point.");
2112 parse_cert_times(optarg);
2115 cert_serial = strtonum(optarg, 0, LLONG_MAX, &errstr);
2117 fatal("Invalid serial number: %s", errstr);
2126 log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
2131 if (ca_key_path != NULL) {
2133 printf("Too few arguments.\n");
2136 } else if (argc > 0) {
2137 printf("Too many arguments.\n");
2140 if (change_passphrase && change_comment) {
2141 printf("Can only have one of -p and -c.\n");
2144 if (print_fingerprint && (delete_host || hash_hosts)) {
2145 printf("Cannot use -l with -D or -R.\n");
2148 if (ca_key_path != NULL) {
2149 if (cert_key_id == NULL)
2150 fatal("Must specify key id (-I) when certifying");
2151 do_ca_sign(pw, argc, argv);
2155 if (delete_host || hash_hosts || find_host)
2156 do_known_hosts(pw, rr_hostname);
2157 if (print_fingerprint || print_bubblebabble)
2159 if (change_passphrase)
2160 do_change_passphrase(pw);
2162 do_change_comment(pw);
2166 do_convert_from(pw);
2168 do_print_public(pw);
2169 if (rr_hostname != NULL) {
2172 if (have_identity) {
2173 n = do_print_resource_record(pw,
2174 identity_file, rr_hostname);
2176 perror(identity_file);
2182 n += do_print_resource_record(pw,
2183 _PATH_HOST_RSA_KEY_FILE, rr_hostname);
2184 n += do_print_resource_record(pw,
2185 _PATH_HOST_DSA_KEY_FILE, rr_hostname);
2188 fatal("no keys found.");
2192 if (pkcs11provider != NULL)
2195 if (do_gen_candidates) {
2196 FILE *out = fopen(out_file, "w");
2199 error("Couldn't open modulus candidate file \"%s\": %s",
2200 out_file, strerror(errno));
2204 bits = DEFAULT_BITS;
2205 if (gen_candidates(out, memory, bits, start) != 0)
2206 fatal("modulus candidate generation failed");
2211 if (do_screen_candidates) {
2213 FILE *out = fopen(out_file, "w");
2215 if (have_identity && strcmp(identity_file, "-") != 0) {
2216 if ((in = fopen(identity_file, "r")) == NULL) {
2217 fatal("Couldn't open modulus candidate "
2218 "file \"%s\": %s", identity_file,
2225 fatal("Couldn't open moduli file \"%s\": %s",
2226 out_file, strerror(errno));
2228 if (prime_test(in, out, trials, generator_wanted) != 0)
2229 fatal("modulus screening failed");
2233 if (gen_all_hostkeys) {
2234 do_gen_all_hostkeys(pw);
2240 if (key_type_name == NULL)
2241 key_type_name = "rsa";
2243 type = key_type_from_name(key_type_name);
2244 type_bits_valid(type, &bits);
2247 printf("Generating public/private %s key pair.\n", key_type_name);
2248 private = key_generate(type, bits);
2249 if (private == NULL) {
2250 fprintf(stderr, "key_generate failed\n");
2253 public = key_from_private(private);
2256 ask_filename(pw, "Enter file in which to save the key");
2258 /* Create ~/.ssh directory if it doesn't already exist. */
2259 snprintf(dotsshdir, sizeof dotsshdir, "%s/%s",
2260 pw->pw_dir, _PATH_SSH_USER_DIR);
2261 if (strstr(identity_file, dotsshdir) != NULL) {
2262 if (stat(dotsshdir, &st) < 0) {
2263 if (errno != ENOENT) {
2264 error("Could not stat %s: %s", dotsshdir,
2266 } else if (mkdir(dotsshdir, 0700) < 0) {
2267 error("Could not create directory '%s': %s",
2268 dotsshdir, strerror(errno));
2270 printf("Created directory '%s'.\n", dotsshdir);
2273 /* If the file already exists, ask the user to confirm. */
2274 if (stat(identity_file, &st) >= 0) {
2276 printf("%s already exists.\n", identity_file);
2277 printf("Overwrite (y/n)? ");
2279 if (fgets(yesno, sizeof(yesno), stdin) == NULL)
2281 if (yesno[0] != 'y' && yesno[0] != 'Y')
2284 /* Ask for a passphrase (twice). */
2285 if (identity_passphrase)
2286 passphrase1 = xstrdup(identity_passphrase);
2287 else if (identity_new_passphrase)
2288 passphrase1 = xstrdup(identity_new_passphrase);
2292 read_passphrase("Enter passphrase (empty for no "
2293 "passphrase): ", RP_ALLOW_STDIN);
2294 passphrase2 = read_passphrase("Enter same passphrase again: ",
2296 if (strcmp(passphrase1, passphrase2) != 0) {
2298 * The passphrases do not match. Clear them and
2301 memset(passphrase1, 0, strlen(passphrase1));
2302 memset(passphrase2, 0, strlen(passphrase2));
2305 printf("Passphrases do not match. Try again.\n");
2306 goto passphrase_again;
2308 /* Clear the other copy of the passphrase. */
2309 memset(passphrase2, 0, strlen(passphrase2));
2313 if (identity_comment) {
2314 strlcpy(comment, identity_comment, sizeof(comment));
2316 /* Create default comment field for the passphrase. */
2317 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
2320 /* Save the key with the given passphrase and comment. */
2321 if (!key_save_private(private, identity_file, passphrase1, comment)) {
2322 printf("Saving the key failed: %s.\n", identity_file);
2323 memset(passphrase1, 0, strlen(passphrase1));
2327 /* Clear the passphrase. */
2328 memset(passphrase1, 0, strlen(passphrase1));
2331 /* Clear the private key and the random number generator. */
2336 printf("Your identification has been saved in %s.\n", identity_file);
2338 strlcat(identity_file, ".pub", sizeof(identity_file));
2339 fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
2341 printf("Could not save your public key in %s\n", identity_file);
2344 f = fdopen(fd, "w");
2346 printf("fdopen %s failed\n", identity_file);
2349 if (!key_write(public, f))
2350 fprintf(stderr, "write key failed\n");
2351 fprintf(f, " %s\n", comment);
2355 char *fp = key_fingerprint(public, SSH_FP_MD5, SSH_FP_HEX);
2356 char *ra = key_fingerprint(public, SSH_FP_MD5,
2358 printf("Your public key has been saved in %s.\n",
2360 printf("The key fingerprint is:\n");
2361 printf("%s %s\n", fp, comment);
2362 printf("The key's randomart image is:\n");