1 /* $OpenBSD: ssh-keygen.c,v 1.241 2014/02/05 20:13:25 naddy 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"
53 #include "ssh-pkcs11.h"
57 /* Number of bits in the RSA/DSA key. This value can be set on the command line. */
58 #define DEFAULT_BITS 2048
59 #define DEFAULT_BITS_DSA 1024
60 #define DEFAULT_BITS_ECDSA 256
64 * Flag indicating that we just want to change the passphrase. This can be
65 * set on the command line.
67 int change_passphrase = 0;
70 * Flag indicating that we just want to change the comment. This can be set
71 * on the command line.
73 int change_comment = 0;
77 int log_level = SYSLOG_LEVEL_INFO;
79 /* Flag indicating that we want to hash a known_hosts file */
81 /* Flag indicating that we want lookup a host in known_hosts file */
83 /* Flag indicating that we want to delete a host from a known_hosts file */
86 /* Flag indicating that we want to show the contents of a certificate */
89 /* Flag indicating that we just want to see the key fingerprint */
90 int print_fingerprint = 0;
91 int print_bubblebabble = 0;
93 /* The identity file name, given on the command line or entered by the user. */
94 char identity_file[1024];
95 int have_identity = 0;
97 /* This is set to the passphrase if given on the command line. */
98 char *identity_passphrase = NULL;
100 /* This is set to the new passphrase if given on the command line. */
101 char *identity_new_passphrase = NULL;
103 /* This is set to the new comment if given on the command line. */
104 char *identity_comment = NULL;
106 /* Path to CA key when certifying keys. */
107 char *ca_key_path = NULL;
109 /* Certificate serial number */
110 unsigned long long cert_serial = 0;
112 /* Key type when certifying */
113 u_int cert_key_type = SSH2_CERT_TYPE_USER;
115 /* "key ID" of signed key */
116 char *cert_key_id = NULL;
118 /* Comma-separated list of principal names for certifying keys */
119 char *cert_principals = NULL;
121 /* Validity period for certificates */
122 u_int64_t cert_valid_from = 0;
123 u_int64_t cert_valid_to = ~0ULL;
125 /* Certificate options */
126 #define CERTOPT_X_FWD (1)
127 #define CERTOPT_AGENT_FWD (1<<1)
128 #define CERTOPT_PORT_FWD (1<<2)
129 #define CERTOPT_PTY (1<<3)
130 #define CERTOPT_USER_RC (1<<4)
131 #define CERTOPT_DEFAULT (CERTOPT_X_FWD|CERTOPT_AGENT_FWD| \
132 CERTOPT_PORT_FWD|CERTOPT_PTY|CERTOPT_USER_RC)
133 u_int32_t certflags_flags = CERTOPT_DEFAULT;
134 char *certflags_command = NULL;
135 char *certflags_src_addr = NULL;
137 /* Conversion to/from various formats */
139 int convert_from = 0;
144 } convert_format = FMT_RFC4716;
145 int print_public = 0;
146 int print_generic = 0;
148 char *key_type_name = NULL;
150 /* Load key from this PKCS#11 provider */
151 char *pkcs11provider = NULL;
153 /* Use new OpenSSH private key format when writing SSH2 keys instead of PEM */
154 int use_new_format = 0;
156 /* Cipher for new-format private keys */
157 char *new_format_cipher = NULL;
160 * Number of KDF rounds to derive new format keys /
161 * number of primality trials when screening moduli.
166 extern char *__progname;
168 char hostname[MAXHOSTNAMELEN];
171 int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
172 int prime_test(FILE *, FILE *, u_int32_t, u_int32_t, char *, unsigned long,
176 type_bits_valid(int type, u_int32_t *bitsp)
180 if (type == KEY_UNSPEC) {
181 fprintf(stderr, "unknown key type %s\n", key_type_name);
186 *bitsp = DEFAULT_BITS_DSA;
187 else if (type == KEY_ECDSA)
188 *bitsp = DEFAULT_BITS_ECDSA;
190 *bitsp = DEFAULT_BITS;
192 maxbits = (type == KEY_DSA) ?
193 OPENSSL_DSA_MAX_MODULUS_BITS : OPENSSL_RSA_MAX_MODULUS_BITS;
194 if (*bitsp > maxbits) {
195 fprintf(stderr, "key bits exceeds maximum %d\n", maxbits);
198 if (type == KEY_DSA && *bitsp != 1024)
199 fatal("DSA keys must be 1024 bits");
200 else if (type != KEY_ECDSA && type != KEY_ED25519 && *bitsp < 768)
201 fatal("Key must at least be 768 bits");
202 else if (type == KEY_ECDSA && key_ecdsa_bits_to_nid(*bitsp) == -1)
203 fatal("Invalid ECDSA key length - valid lengths are "
204 "256, 384 or 521 bits");
208 ask_filename(struct passwd *pw, const char *prompt)
213 if (key_type_name == NULL)
214 name = _PATH_SSH_CLIENT_ID_RSA;
216 switch (key_type_from_name(key_type_name)) {
218 name = _PATH_SSH_CLIENT_IDENTITY;
221 case KEY_DSA_CERT_V00:
223 name = _PATH_SSH_CLIENT_ID_DSA;
225 #ifdef OPENSSL_HAS_ECC
228 name = _PATH_SSH_CLIENT_ID_ECDSA;
232 case KEY_RSA_CERT_V00:
234 name = _PATH_SSH_CLIENT_ID_RSA;
237 case KEY_ED25519_CERT:
238 name = _PATH_SSH_CLIENT_ID_ED25519;
241 fprintf(stderr, "bad key type\n");
246 snprintf(identity_file, sizeof(identity_file), "%s/%s", pw->pw_dir, name);
247 fprintf(stderr, "%s (%s): ", prompt, identity_file);
248 if (fgets(buf, sizeof(buf), stdin) == NULL)
250 buf[strcspn(buf, "\n")] = '\0';
251 if (strcmp(buf, "") != 0)
252 strlcpy(identity_file, buf, sizeof(identity_file));
257 load_identity(char *filename)
262 prv = key_load_private(filename, "", NULL);
264 if (identity_passphrase)
265 pass = xstrdup(identity_passphrase);
267 pass = read_passphrase("Enter passphrase: ",
269 prv = key_load_private(filename, pass, NULL);
270 explicit_bzero(pass, strlen(pass));
276 #define SSH_COM_PUBLIC_BEGIN "---- BEGIN SSH2 PUBLIC KEY ----"
277 #define SSH_COM_PUBLIC_END "---- END SSH2 PUBLIC KEY ----"
278 #define SSH_COM_PRIVATE_BEGIN "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
279 #define SSH_COM_PRIVATE_KEY_MAGIC 0x3f6ff9eb
282 do_convert_to_ssh2(struct passwd *pw, Key *k)
288 if (k->type == KEY_RSA1) {
289 fprintf(stderr, "version 1 keys are not supported\n");
292 if (key_to_blob(k, &blob, &len) <= 0) {
293 fprintf(stderr, "key_to_blob failed\n");
296 /* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
297 snprintf(comment, sizeof(comment),
298 "%u-bit %s, converted by %s@%s from OpenSSH",
299 key_size(k), key_type(k),
300 pw->pw_name, hostname);
302 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
303 fprintf(stdout, "Comment: \"%s\"\n", comment);
304 dump_base64(stdout, blob, len);
305 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
312 do_convert_to_pkcs8(Key *k)
314 switch (key_type_plain(k->type)) {
317 if (!PEM_write_RSA_PUBKEY(stdout, k->rsa))
318 fatal("PEM_write_RSA_PUBKEY failed");
321 if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
322 fatal("PEM_write_DSA_PUBKEY failed");
324 #ifdef OPENSSL_HAS_ECC
326 if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
327 fatal("PEM_write_EC_PUBKEY failed");
331 fatal("%s: unsupported key type %s", __func__, key_type(k));
337 do_convert_to_pem(Key *k)
339 switch (key_type_plain(k->type)) {
342 if (!PEM_write_RSAPublicKey(stdout, k->rsa))
343 fatal("PEM_write_RSAPublicKey failed");
345 #if notyet /* OpenSSH 0.9.8 lacks this function */
347 if (!PEM_write_DSAPublicKey(stdout, k->dsa))
348 fatal("PEM_write_DSAPublicKey failed");
353 fatal("%s: unsupported key type %s", __func__, key_type(k));
359 do_convert_to(struct passwd *pw)
365 ask_filename(pw, "Enter file in which the key is");
366 if (stat(identity_file, &st) < 0)
367 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
368 if ((k = key_load_public(identity_file, NULL)) == NULL) {
369 if ((k = load_identity(identity_file)) == NULL) {
370 fprintf(stderr, "load failed\n");
375 switch (convert_format) {
377 do_convert_to_ssh2(pw, k);
380 do_convert_to_pkcs8(k);
383 do_convert_to_pem(k);
386 fatal("%s: unknown key format %d", __func__, convert_format);
392 buffer_get_bignum_bits(Buffer *b, BIGNUM *value)
394 u_int bignum_bits = buffer_get_int(b);
395 u_int bytes = (bignum_bits + 7) / 8;
397 if (buffer_len(b) < bytes)
398 fatal("buffer_get_bignum_bits: input buffer too small: "
399 "need %d have %d", bytes, buffer_len(b));
400 if (BN_bin2bn(buffer_ptr(b), bytes, value) == NULL)
401 fatal("buffer_get_bignum_bits: BN_bin2bn failed");
402 buffer_consume(b, bytes);
406 do_convert_private_ssh2_from_blob(u_char *blob, u_int blen)
411 u_char *sig, data[] = "abcde12345";
412 int magic, rlen, ktype, i1, i2, i3, i4;
417 buffer_append(&b, blob, blen);
419 magic = buffer_get_int(&b);
420 if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
421 error("bad magic 0x%x != 0x%x", magic, SSH_COM_PRIVATE_KEY_MAGIC);
425 i1 = buffer_get_int(&b);
426 type = buffer_get_string(&b, NULL);
427 cipher = buffer_get_string(&b, NULL);
428 i2 = buffer_get_int(&b);
429 i3 = buffer_get_int(&b);
430 i4 = buffer_get_int(&b);
431 debug("ignore (%d %d %d %d)", i1, i2, i3, i4);
432 if (strcmp(cipher, "none") != 0) {
433 error("unsupported cipher %s", cipher);
441 if (strstr(type, "dsa")) {
443 } else if (strstr(type, "rsa")) {
450 key = key_new_private(ktype);
455 buffer_get_bignum_bits(&b, key->dsa->p);
456 buffer_get_bignum_bits(&b, key->dsa->g);
457 buffer_get_bignum_bits(&b, key->dsa->q);
458 buffer_get_bignum_bits(&b, key->dsa->pub_key);
459 buffer_get_bignum_bits(&b, key->dsa->priv_key);
462 e = buffer_get_char(&b);
466 e += buffer_get_char(&b);
469 e += buffer_get_char(&b);
472 if (!BN_set_word(key->rsa->e, e)) {
477 buffer_get_bignum_bits(&b, key->rsa->d);
478 buffer_get_bignum_bits(&b, key->rsa->n);
479 buffer_get_bignum_bits(&b, key->rsa->iqmp);
480 buffer_get_bignum_bits(&b, key->rsa->q);
481 buffer_get_bignum_bits(&b, key->rsa->p);
482 rsa_generate_additional_parameters(key->rsa);
485 rlen = buffer_len(&b);
487 error("do_convert_private_ssh2_from_blob: "
488 "remaining bytes in key blob %d", rlen);
492 key_sign(key, &sig, &slen, data, sizeof(data));
493 key_verify(key, sig, slen, data, sizeof(data));
499 get_line(FILE *fp, char *line, size_t len)
505 while ((c = fgetc(fp)) != EOF) {
506 if (pos >= len - 1) {
507 fprintf(stderr, "input line too long.\n");
513 if (c != EOF && c != '\n' && ungetc(c, fp) == EOF) {
514 fprintf(stderr, "unget: %s\n", strerror(errno));
529 do_convert_from_ssh2(struct passwd *pw, Key **k, int *private)
539 if ((fp = fopen(identity_file, "r")) == NULL)
540 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
542 while ((blen = get_line(fp, line, sizeof(line))) != -1) {
543 if (blen > 0 && line[blen - 1] == '\\')
545 if (strncmp(line, "----", 4) == 0 ||
546 strstr(line, ": ") != NULL) {
547 if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
549 if (strstr(line, " END ") != NULL) {
552 /* fprintf(stderr, "ignore: %s", line); */
557 /* fprintf(stderr, "escaped: %s", line); */
560 strlcat(encoded, line, sizeof(encoded));
562 len = strlen(encoded);
563 if (((len % 4) == 3) &&
564 (encoded[len-1] == '=') &&
565 (encoded[len-2] == '=') &&
566 (encoded[len-3] == '='))
567 encoded[len-3] = '\0';
568 blen = uudecode(encoded, blob, sizeof(blob));
570 fprintf(stderr, "uudecode failed.\n");
574 do_convert_private_ssh2_from_blob(blob, blen) :
575 key_from_blob(blob, blen);
577 fprintf(stderr, "decode blob failed.\n");
584 do_convert_from_pkcs8(Key **k, int *private)
589 if ((fp = fopen(identity_file, "r")) == NULL)
590 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
591 if ((pubkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL)) == NULL) {
592 fatal("%s: %s is not a recognised public key format", __func__,
596 switch (EVP_PKEY_type(pubkey->type)) {
598 *k = key_new(KEY_UNSPEC);
599 (*k)->type = KEY_RSA;
600 (*k)->rsa = EVP_PKEY_get1_RSA(pubkey);
603 *k = key_new(KEY_UNSPEC);
604 (*k)->type = KEY_DSA;
605 (*k)->dsa = EVP_PKEY_get1_DSA(pubkey);
607 #ifdef OPENSSL_HAS_ECC
609 *k = key_new(KEY_UNSPEC);
610 (*k)->type = KEY_ECDSA;
611 (*k)->ecdsa = EVP_PKEY_get1_EC_KEY(pubkey);
612 (*k)->ecdsa_nid = key_ecdsa_key_to_nid((*k)->ecdsa);
616 fatal("%s: unsupported pubkey type %d", __func__,
617 EVP_PKEY_type(pubkey->type));
619 EVP_PKEY_free(pubkey);
624 do_convert_from_pem(Key **k, int *private)
632 if ((fp = fopen(identity_file, "r")) == NULL)
633 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
634 if ((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
635 *k = key_new(KEY_UNSPEC);
636 (*k)->type = KEY_RSA;
641 #if notyet /* OpenSSH 0.9.8 lacks this function */
643 if ((dsa = PEM_read_DSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
644 *k = key_new(KEY_UNSPEC);
645 (*k)->type = KEY_DSA;
652 fatal("%s: unrecognised raw private key format", __func__);
656 do_convert_from(struct passwd *pw)
659 int private = 0, ok = 0;
663 ask_filename(pw, "Enter file in which the key is");
664 if (stat(identity_file, &st) < 0)
665 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
667 switch (convert_format) {
669 do_convert_from_ssh2(pw, &k, &private);
672 do_convert_from_pkcs8(&k, &private);
675 do_convert_from_pem(&k, &private);
678 fatal("%s: unknown key format %d", __func__, convert_format);
682 ok = key_write(k, stdout);
684 fprintf(stdout, "\n");
688 ok = PEM_write_DSAPrivateKey(stdout, k->dsa, NULL,
689 NULL, 0, NULL, NULL);
691 #ifdef OPENSSL_HAS_ECC
693 ok = PEM_write_ECPrivateKey(stdout, k->ecdsa, NULL,
694 NULL, 0, NULL, NULL);
698 ok = PEM_write_RSAPrivateKey(stdout, k->rsa, NULL,
699 NULL, 0, NULL, NULL);
702 fatal("%s: unsupported key type %s", __func__,
708 fprintf(stderr, "key write failed\n");
716 do_print_public(struct passwd *pw)
722 ask_filename(pw, "Enter file in which the key is");
723 if (stat(identity_file, &st) < 0) {
724 perror(identity_file);
727 prv = load_identity(identity_file);
729 fprintf(stderr, "load failed\n");
732 if (!key_write(prv, stdout))
733 fprintf(stderr, "key_write failed");
735 fprintf(stdout, "\n");
740 do_download(struct passwd *pw)
749 fptype = print_bubblebabble ? SSH_FP_SHA1 : SSH_FP_MD5;
750 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_HEX;
753 nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys);
755 fatal("cannot read public key from pkcs11");
756 for (i = 0; i < nkeys; i++) {
757 if (print_fingerprint) {
758 fp = key_fingerprint(keys[i], fptype, rep);
759 ra = key_fingerprint(keys[i], SSH_FP_MD5,
761 printf("%u %s %s (PKCS11 key)\n", key_size(keys[i]),
762 fp, key_type(keys[i]));
763 if (log_level >= SYSLOG_LEVEL_VERBOSE)
768 key_write(keys[i], stdout);
769 fprintf(stdout, "\n");
777 fatal("no pkcs11 support");
778 #endif /* ENABLE_PKCS11 */
782 do_fingerprint(struct passwd *pw)
786 char *comment = NULL, *cp, *ep, line[16*1024], *fp, *ra;
787 int i, skip = 0, num = 0, invalid = 1;
792 fptype = print_bubblebabble ? SSH_FP_SHA1 : SSH_FP_MD5;
793 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_HEX;
796 ask_filename(pw, "Enter file in which the key is");
797 if (stat(identity_file, &st) < 0) {
798 perror(identity_file);
801 public = key_load_public(identity_file, &comment);
802 if (public != NULL) {
803 fp = key_fingerprint(public, fptype, rep);
804 ra = key_fingerprint(public, SSH_FP_MD5, SSH_FP_RANDOMART);
805 printf("%u %s %s (%s)\n", key_size(public), fp, comment,
807 if (log_level >= SYSLOG_LEVEL_VERBOSE)
820 if ((f = fopen(identity_file, "r")) == NULL)
821 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
823 while (fgets(line, sizeof(line), f)) {
824 if ((cp = strchr(line, '\n')) == NULL) {
825 error("line %d too long: %.40s...",
837 /* Skip leading whitespace, empty and comment lines. */
838 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
840 if (!*cp || *cp == '\n' || *cp == '#')
842 i = strtol(cp, &ep, 10);
843 if (i == 0 || ep == NULL || (*ep != ' ' && *ep != '\t')) {
846 for (; *cp && (quoted || (*cp != ' ' &&
847 *cp != '\t')); cp++) {
848 if (*cp == '\\' && cp[1] == '"')
849 cp++; /* Skip both */
858 public = key_new(KEY_RSA1);
859 if (key_read(public, &cp) != 1) {
862 public = key_new(KEY_UNSPEC);
863 if (key_read(public, &cp) != 1) {
868 comment = *cp ? cp : comment;
869 fp = key_fingerprint(public, fptype, rep);
870 ra = key_fingerprint(public, SSH_FP_MD5, SSH_FP_RANDOMART);
871 printf("%u %s %s (%s)\n", key_size(public), fp,
872 comment ? comment : "no comment", key_type(public));
873 if (log_level >= SYSLOG_LEVEL_VERBOSE)
883 printf("%s is not a public key file.\n", identity_file);
890 do_gen_all_hostkeys(struct passwd *pw)
894 char *key_type_display;
897 { "rsa1", "RSA1", _PATH_HOST_KEY_FILE },
898 { "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE },
899 { "dsa", "DSA", _PATH_HOST_DSA_KEY_FILE },
900 #ifdef OPENSSL_HAS_ECC
901 { "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE },
903 { "ed25519", "ED25519",_PATH_HOST_ED25519_KEY_FILE },
909 Key *private, *public;
914 for (i = 0; key_types[i].key_type; i++) {
915 if (stat(key_types[i].path, &st) == 0)
917 if (errno != ENOENT) {
918 printf("Could not stat %s: %s", key_types[i].path,
926 printf("%s: generating new host keys: ", __progname);
928 printf("%s ", key_types[i].key_type_display);
930 type = key_type_from_name(key_types[i].key_type);
931 strlcpy(identity_file, key_types[i].path, sizeof(identity_file));
933 type_bits_valid(type, &bits);
934 private = key_generate(type, bits);
935 if (private == NULL) {
936 fprintf(stderr, "key_generate failed\n");
940 public = key_from_private(private);
941 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name,
943 if (!key_save_private(private, identity_file, "", comment,
944 use_new_format, new_format_cipher, rounds)) {
945 printf("Saving the key failed: %s.\n", identity_file);
952 strlcat(identity_file, ".pub", sizeof(identity_file));
953 fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
955 printf("Could not save your public key in %s\n",
963 printf("fdopen %s failed\n", identity_file);
968 if (!key_write(public, f)) {
969 fprintf(stderr, "write key failed\n");
974 fprintf(f, " %s\n", comment);
984 printhost(FILE *f, const char *name, Key *public, int ca, int hash)
986 if (print_fingerprint) {
991 fptype = print_bubblebabble ? SSH_FP_SHA1 : SSH_FP_MD5;
992 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_HEX;
993 fp = key_fingerprint(public, fptype, rep);
994 ra = key_fingerprint(public, SSH_FP_MD5, SSH_FP_RANDOMART);
995 printf("%u %s %s (%s)\n", key_size(public), fp, name,
997 if (log_level >= SYSLOG_LEVEL_VERBOSE)
1002 if (hash && (name = host_hash(name, NULL, 0)) == NULL)
1003 fatal("hash_host failed");
1004 fprintf(f, "%s%s%s ", ca ? CA_MARKER : "", ca ? " " : "", name);
1005 if (!key_write(public, f))
1006 fatal("key_write failed");
1012 do_known_hosts(struct passwd *pw, const char *name)
1014 FILE *in, *out = stdout;
1016 char *cp, *cp2, *kp, *kp2;
1017 char line[16*1024], tmp[MAXPATHLEN], old[MAXPATHLEN];
1018 int c, skip = 0, inplace = 0, num = 0, invalid = 0, has_unhashed = 0;
1022 if (!have_identity) {
1023 cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
1024 if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
1025 sizeof(identity_file))
1026 fatal("Specified known hosts path too long");
1030 if ((in = fopen(identity_file, "r")) == NULL)
1031 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
1034 * Find hosts goes to stdout, hash and deletions happen in-place
1035 * A corner case is ssh-keygen -HF foo, which should go to stdout
1037 if (!find_host && (hash_hosts || delete_host)) {
1038 if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
1039 strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
1040 strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
1041 strlcat(old, ".old", sizeof(old)) >= sizeof(old))
1042 fatal("known_hosts path too long");
1044 if ((c = mkstemp(tmp)) == -1)
1045 fatal("mkstemp: %s", strerror(errno));
1046 if ((out = fdopen(c, "w")) == NULL) {
1049 fatal("fdopen: %s", strerror(c));
1054 while (fgets(line, sizeof(line), in)) {
1055 if ((cp = strchr(line, '\n')) == NULL) {
1056 error("line %d too long: %.40s...", num + 1, line);
1068 /* Skip leading whitespace, empty and comment lines. */
1069 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
1071 if (!*cp || *cp == '\n' || *cp == '#') {
1073 fprintf(out, "%s\n", cp);
1076 /* Check whether this is a CA key */
1077 if (strncasecmp(cp, CA_MARKER, sizeof(CA_MARKER) - 1) == 0 &&
1078 (cp[sizeof(CA_MARKER) - 1] == ' ' ||
1079 cp[sizeof(CA_MARKER) - 1] == '\t')) {
1081 cp += sizeof(CA_MARKER);
1085 /* Find the end of the host name portion. */
1086 for (kp = cp; *kp && *kp != ' ' && *kp != '\t'; kp++)
1089 if (*kp == '\0' || *(kp + 1) == '\0') {
1090 error("line %d missing key: %.40s...",
1098 pub = key_new(KEY_RSA1);
1099 if (key_read(pub, &kp) != 1) {
1102 pub = key_new(KEY_UNSPEC);
1103 if (key_read(pub, &kp) != 1) {
1104 error("line %d invalid key: %.40s...",
1112 if (*cp == HASH_DELIM) {
1113 if (find_host || delete_host) {
1114 cp2 = host_hash(name, cp, strlen(cp));
1116 error("line %d: invalid hashed "
1117 "name: %.64s...", num, line);
1121 c = (strcmp(cp2, cp) == 0);
1122 if (find_host && c) {
1124 printf("# Host %s found: "
1125 "line %d type %s%s\n", name,
1127 ca ? " (CA key)" : "");
1128 printhost(out, cp, pub, ca, 0);
1133 printhost(out, cp, pub, ca, 0);
1135 printf("# Host %s found: "
1136 "line %d type %s\n", name,
1137 num, key_type(pub));
1139 } else if (hash_hosts)
1140 printhost(out, cp, pub, ca, 0);
1142 if (find_host || delete_host) {
1143 c = (match_hostname(name, cp,
1145 if (find_host && c) {
1147 printf("# Host %s found: "
1148 "line %d type %s%s\n", name,
1150 ca ? " (CA key)" : "");
1151 printhost(out, name, pub,
1152 ca, hash_hosts && !ca);
1157 printhost(out, cp, pub, ca, 0);
1159 printf("# Host %s found: "
1160 "line %d type %s\n", name,
1161 num, key_type(pub));
1163 } else if (hash_hosts) {
1164 for (cp2 = strsep(&cp, ",");
1165 cp2 != NULL && *cp2 != '\0';
1166 cp2 = strsep(&cp, ",")) {
1168 fprintf(stderr, "Warning: "
1169 "ignoring CA key for host: "
1171 printhost(out, cp2, pub, ca, 0);
1172 } else if (strcspn(cp2, "*?!") !=
1174 fprintf(stderr, "Warning: "
1175 "ignoring host name with "
1176 "metacharacters: %.64s\n",
1178 printhost(out, cp2, pub, ca, 0);
1180 printhost(out, cp2, pub, ca, 1);
1190 fprintf(stderr, "%s is not a valid known_hosts file.\n",
1193 fprintf(stderr, "Not replacing existing known_hosts "
1194 "file because of errors\n");
1204 /* Backup existing file */
1205 if (unlink(old) == -1 && errno != ENOENT)
1206 fatal("unlink %.100s: %s", old, strerror(errno));
1207 if (link(identity_file, old) == -1)
1208 fatal("link %.100s to %.100s: %s", identity_file, old,
1210 /* Move new one into place */
1211 if (rename(tmp, identity_file) == -1) {
1212 error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
1219 fprintf(stderr, "%s updated.\n", identity_file);
1220 fprintf(stderr, "Original contents retained as %s\n", old);
1222 fprintf(stderr, "WARNING: %s contains unhashed "
1224 fprintf(stderr, "Delete this file to ensure privacy "
1229 exit (find_host && !found_key);
1233 * Perform changing a passphrase. The argument is the passwd structure
1234 * for the current user.
1237 do_change_passphrase(struct passwd *pw)
1240 char *old_passphrase, *passphrase1, *passphrase2;
1245 ask_filename(pw, "Enter file in which the key is");
1246 if (stat(identity_file, &st) < 0) {
1247 perror(identity_file);
1250 /* Try to load the file with empty passphrase. */
1251 private = key_load_private(identity_file, "", &comment);
1252 if (private == NULL) {
1253 if (identity_passphrase)
1254 old_passphrase = xstrdup(identity_passphrase);
1257 read_passphrase("Enter old passphrase: ",
1259 private = key_load_private(identity_file, old_passphrase,
1261 explicit_bzero(old_passphrase, strlen(old_passphrase));
1262 free(old_passphrase);
1263 if (private == NULL) {
1264 printf("Bad passphrase.\n");
1268 printf("Key has comment '%s'\n", comment);
1270 /* Ask the new passphrase (twice). */
1271 if (identity_new_passphrase) {
1272 passphrase1 = xstrdup(identity_new_passphrase);
1276 read_passphrase("Enter new passphrase (empty for no "
1277 "passphrase): ", RP_ALLOW_STDIN);
1278 passphrase2 = read_passphrase("Enter same passphrase again: ",
1281 /* Verify that they are the same. */
1282 if (strcmp(passphrase1, passphrase2) != 0) {
1283 explicit_bzero(passphrase1, strlen(passphrase1));
1284 explicit_bzero(passphrase2, strlen(passphrase2));
1287 printf("Pass phrases do not match. Try again.\n");
1290 /* Destroy the other copy. */
1291 explicit_bzero(passphrase2, strlen(passphrase2));
1295 /* Save the file using the new passphrase. */
1296 if (!key_save_private(private, identity_file, passphrase1, comment,
1297 use_new_format, new_format_cipher, rounds)) {
1298 printf("Saving the key failed: %s.\n", identity_file);
1299 explicit_bzero(passphrase1, strlen(passphrase1));
1305 /* Destroy the passphrase and the copy of the key in memory. */
1306 explicit_bzero(passphrase1, strlen(passphrase1));
1308 key_free(private); /* Destroys contents */
1311 printf("Your identification has been saved with the new passphrase.\n");
1316 * Print the SSHFP RR.
1319 do_print_resource_record(struct passwd *pw, char *fname, char *hname)
1322 char *comment = NULL;
1326 fatal("%s: no filename", __func__);
1327 if (stat(fname, &st) < 0) {
1328 if (errno == ENOENT)
1333 public = key_load_public(fname, &comment);
1334 if (public != NULL) {
1335 export_dns_rr(hname, public, stdout, print_generic);
1343 printf("failed to read v2 public key from %s.\n", fname);
1348 * Change the comment of a private key file.
1351 do_change_comment(struct passwd *pw)
1353 char new_comment[1024], *comment, *passphrase;
1361 ask_filename(pw, "Enter file in which the key is");
1362 if (stat(identity_file, &st) < 0) {
1363 perror(identity_file);
1366 private = key_load_private(identity_file, "", &comment);
1367 if (private == NULL) {
1368 if (identity_passphrase)
1369 passphrase = xstrdup(identity_passphrase);
1370 else if (identity_new_passphrase)
1371 passphrase = xstrdup(identity_new_passphrase);
1373 passphrase = read_passphrase("Enter passphrase: ",
1375 /* Try to load using the passphrase. */
1376 private = key_load_private(identity_file, passphrase, &comment);
1377 if (private == NULL) {
1378 explicit_bzero(passphrase, strlen(passphrase));
1380 printf("Bad passphrase.\n");
1384 passphrase = xstrdup("");
1386 if (private->type != KEY_RSA1) {
1387 fprintf(stderr, "Comments are only supported for RSA1 keys.\n");
1391 printf("Key now has comment '%s'\n", comment);
1393 if (identity_comment) {
1394 strlcpy(new_comment, identity_comment, sizeof(new_comment));
1396 printf("Enter new comment: ");
1398 if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1399 explicit_bzero(passphrase, strlen(passphrase));
1403 new_comment[strcspn(new_comment, "\n")] = '\0';
1406 /* Save the file using the new passphrase. */
1407 if (!key_save_private(private, identity_file, passphrase, new_comment,
1408 use_new_format, new_format_cipher, rounds)) {
1409 printf("Saving the key failed: %s.\n", identity_file);
1410 explicit_bzero(passphrase, strlen(passphrase));
1416 explicit_bzero(passphrase, strlen(passphrase));
1418 public = key_from_private(private);
1421 strlcat(identity_file, ".pub", sizeof(identity_file));
1422 fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1424 printf("Could not save your public key in %s\n", identity_file);
1427 f = fdopen(fd, "w");
1429 printf("fdopen %s failed\n", identity_file);
1432 if (!key_write(public, f))
1433 fprintf(stderr, "write key failed\n");
1435 fprintf(f, " %s\n", new_comment);
1440 printf("The comment in your key file has been changed.\n");
1445 fmt_validity(u_int64_t valid_from, u_int64_t valid_to)
1447 char from[32], to[32];
1448 static char ret[64];
1453 if (valid_from == 0 && valid_to == 0xffffffffffffffffULL)
1456 if (valid_from != 0) {
1457 /* XXX revisit INT_MAX in 2038 :) */
1458 tt = valid_from > INT_MAX ? INT_MAX : valid_from;
1459 tm = localtime(&tt);
1460 strftime(from, sizeof(from), "%Y-%m-%dT%H:%M:%S", tm);
1462 if (valid_to != 0xffffffffffffffffULL) {
1463 /* XXX revisit INT_MAX in 2038 :) */
1464 tt = valid_to > INT_MAX ? INT_MAX : valid_to;
1465 tm = localtime(&tt);
1466 strftime(to, sizeof(to), "%Y-%m-%dT%H:%M:%S", tm);
1469 if (valid_from == 0) {
1470 snprintf(ret, sizeof(ret), "before %s", to);
1473 if (valid_to == 0xffffffffffffffffULL) {
1474 snprintf(ret, sizeof(ret), "after %s", from);
1478 snprintf(ret, sizeof(ret), "from %s to %s", from, to);
1483 add_flag_option(Buffer *c, const char *name)
1485 debug3("%s: %s", __func__, name);
1486 buffer_put_cstring(c, name);
1487 buffer_put_string(c, NULL, 0);
1491 add_string_option(Buffer *c, const char *name, const char *value)
1495 debug3("%s: %s=%s", __func__, name, value);
1497 buffer_put_cstring(&b, value);
1499 buffer_put_cstring(c, name);
1500 buffer_put_string(c, buffer_ptr(&b), buffer_len(&b));
1505 #define OPTIONS_CRITICAL 1
1506 #define OPTIONS_EXTENSIONS 2
1508 prepare_options_buf(Buffer *c, int which)
1511 if ((which & OPTIONS_CRITICAL) != 0 &&
1512 certflags_command != NULL)
1513 add_string_option(c, "force-command", certflags_command);
1514 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1515 (certflags_flags & CERTOPT_X_FWD) != 0)
1516 add_flag_option(c, "permit-X11-forwarding");
1517 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1518 (certflags_flags & CERTOPT_AGENT_FWD) != 0)
1519 add_flag_option(c, "permit-agent-forwarding");
1520 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1521 (certflags_flags & CERTOPT_PORT_FWD) != 0)
1522 add_flag_option(c, "permit-port-forwarding");
1523 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1524 (certflags_flags & CERTOPT_PTY) != 0)
1525 add_flag_option(c, "permit-pty");
1526 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1527 (certflags_flags & CERTOPT_USER_RC) != 0)
1528 add_flag_option(c, "permit-user-rc");
1529 if ((which & OPTIONS_CRITICAL) != 0 &&
1530 certflags_src_addr != NULL)
1531 add_string_option(c, "source-address", certflags_src_addr);
1535 load_pkcs11_key(char *path)
1537 #ifdef ENABLE_PKCS11
1538 Key **keys = NULL, *public, *private = NULL;
1541 if ((public = key_load_public(path, NULL)) == NULL)
1542 fatal("Couldn't load CA public key \"%s\"", path);
1544 nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase, &keys);
1545 debug3("%s: %d keys", __func__, nkeys);
1547 fatal("cannot read public key from pkcs11");
1548 for (i = 0; i < nkeys; i++) {
1549 if (key_equal_public(public, keys[i])) {
1559 fatal("no pkcs11 support");
1560 #endif /* ENABLE_PKCS11 */
1564 do_ca_sign(struct passwd *pw, int argc, char **argv)
1569 char *otmp, *tmp, *cp, *out, *comment, **plist = NULL;
1571 int v00 = 0; /* legacy keys */
1573 if (key_type_name != NULL) {
1574 switch (key_type_from_name(key_type_name)) {
1575 case KEY_RSA_CERT_V00:
1576 case KEY_DSA_CERT_V00:
1580 if (strcasecmp(key_type_name, "v00") == 0) {
1583 } else if (strcasecmp(key_type_name, "v01") == 0)
1587 fprintf(stderr, "unknown key type %s\n", key_type_name);
1593 tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
1594 if (pkcs11provider != NULL) {
1595 if ((ca = load_pkcs11_key(tmp)) == NULL)
1596 fatal("No PKCS#11 key matching %s found", ca_key_path);
1597 } else if ((ca = load_identity(tmp)) == NULL)
1598 fatal("Couldn't load CA key \"%s\"", tmp);
1601 for (i = 0; i < argc; i++) {
1602 /* Split list of principals */
1604 if (cert_principals != NULL) {
1605 otmp = tmp = xstrdup(cert_principals);
1607 for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1608 plist = xrealloc(plist, n + 1, sizeof(*plist));
1609 if (*(plist[n] = xstrdup(cp)) == '\0')
1610 fatal("Empty principal name");
1615 tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1616 if ((public = key_load_public(tmp, &comment)) == NULL)
1617 fatal("%s: unable to open \"%s\"", __func__, tmp);
1618 if (public->type != KEY_RSA && public->type != KEY_DSA &&
1619 public->type != KEY_ECDSA && public->type != KEY_ED25519)
1620 fatal("%s: key \"%s\" type %s cannot be certified",
1621 __func__, tmp, key_type(public));
1623 /* Prepare certificate to sign */
1624 if (key_to_certified(public, v00) != 0)
1625 fatal("Could not upgrade key %s to certificate", tmp);
1626 public->cert->type = cert_key_type;
1627 public->cert->serial = (u_int64_t)cert_serial;
1628 public->cert->key_id = xstrdup(cert_key_id);
1629 public->cert->nprincipals = n;
1630 public->cert->principals = plist;
1631 public->cert->valid_after = cert_valid_from;
1632 public->cert->valid_before = cert_valid_to;
1634 prepare_options_buf(&public->cert->critical,
1635 OPTIONS_CRITICAL|OPTIONS_EXTENSIONS);
1637 prepare_options_buf(&public->cert->critical,
1639 prepare_options_buf(&public->cert->extensions,
1640 OPTIONS_EXTENSIONS);
1642 public->cert->signature_key = key_from_private(ca);
1644 if (key_certify(public, ca) != 0)
1645 fatal("Couldn't not certify key %s", tmp);
1647 if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
1649 xasprintf(&out, "%s-cert.pub", tmp);
1652 if ((fd = open(out, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
1653 fatal("Could not open \"%s\" for writing: %s", out,
1655 if ((f = fdopen(fd, "w")) == NULL)
1656 fatal("%s: fdopen: %s", __func__, strerror(errno));
1657 if (!key_write(public, f))
1658 fatal("Could not write certified key to %s", out);
1659 fprintf(f, " %s\n", comment);
1663 logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1664 "valid %s", key_cert_type(public),
1665 out, public->cert->key_id,
1666 (unsigned long long)public->cert->serial,
1667 cert_principals != NULL ? " for " : "",
1668 cert_principals != NULL ? cert_principals : "",
1669 fmt_validity(cert_valid_from, cert_valid_to));
1680 parse_relative_time(const char *s, time_t now)
1684 mul = *s == '-' ? -1 : 1;
1686 if ((secs = convtime(s + 1)) == -1)
1687 fatal("Invalid relative certificate time %s", s);
1688 if (mul == -1 && secs > now)
1689 fatal("Certificate time %s cannot be represented", s);
1690 return now + (u_int64_t)(secs * mul);
1694 parse_absolute_time(const char *s)
1701 * POSIX strptime says "The application shall ensure that there
1702 * is white-space or other non-alphanumeric characters between
1703 * any two conversion specifications" so arrange things this way.
1705 switch (strlen(s)) {
1708 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
1711 fmt = "%Y-%m-%dT%H:%M:%S";
1712 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
1713 s, s + 4, s + 6, s + 8, s + 10, s + 12);
1716 fatal("Invalid certificate time format %s", s);
1719 memset(&tm, 0, sizeof(tm));
1720 if (strptime(buf, fmt, &tm) == NULL)
1721 fatal("Invalid certificate time %s", s);
1722 if ((tt = mktime(&tm)) < 0)
1723 fatal("Certificate time %s cannot be represented", s);
1724 return (u_int64_t)tt;
1728 parse_cert_times(char *timespec)
1731 time_t now = time(NULL);
1734 /* +timespec relative to now */
1735 if (*timespec == '+' && strchr(timespec, ':') == NULL) {
1736 if ((secs = convtime(timespec + 1)) == -1)
1737 fatal("Invalid relative certificate life %s", timespec);
1738 cert_valid_to = now + secs;
1740 * Backdate certificate one minute to avoid problems on hosts
1741 * with poorly-synchronised clocks.
1743 cert_valid_from = ((now - 59)/ 60) * 60;
1749 * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS
1750 * to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS
1752 from = xstrdup(timespec);
1753 to = strchr(from, ':');
1754 if (to == NULL || from == to || *(to + 1) == '\0')
1755 fatal("Invalid certificate life specification %s", timespec);
1758 if (*from == '-' || *from == '+')
1759 cert_valid_from = parse_relative_time(from, now);
1761 cert_valid_from = parse_absolute_time(from);
1763 if (*to == '-' || *to == '+')
1764 cert_valid_to = parse_relative_time(to, now);
1766 cert_valid_to = parse_absolute_time(to);
1768 if (cert_valid_to <= cert_valid_from)
1769 fatal("Empty certificate validity interval");
1774 add_cert_option(char *opt)
1778 if (strcasecmp(opt, "clear") == 0)
1779 certflags_flags = 0;
1780 else if (strcasecmp(opt, "no-x11-forwarding") == 0)
1781 certflags_flags &= ~CERTOPT_X_FWD;
1782 else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
1783 certflags_flags |= CERTOPT_X_FWD;
1784 else if (strcasecmp(opt, "no-agent-forwarding") == 0)
1785 certflags_flags &= ~CERTOPT_AGENT_FWD;
1786 else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
1787 certflags_flags |= CERTOPT_AGENT_FWD;
1788 else if (strcasecmp(opt, "no-port-forwarding") == 0)
1789 certflags_flags &= ~CERTOPT_PORT_FWD;
1790 else if (strcasecmp(opt, "permit-port-forwarding") == 0)
1791 certflags_flags |= CERTOPT_PORT_FWD;
1792 else if (strcasecmp(opt, "no-pty") == 0)
1793 certflags_flags &= ~CERTOPT_PTY;
1794 else if (strcasecmp(opt, "permit-pty") == 0)
1795 certflags_flags |= CERTOPT_PTY;
1796 else if (strcasecmp(opt, "no-user-rc") == 0)
1797 certflags_flags &= ~CERTOPT_USER_RC;
1798 else if (strcasecmp(opt, "permit-user-rc") == 0)
1799 certflags_flags |= CERTOPT_USER_RC;
1800 else if (strncasecmp(opt, "force-command=", 14) == 0) {
1803 fatal("Empty force-command option");
1804 if (certflags_command != NULL)
1805 fatal("force-command already specified");
1806 certflags_command = xstrdup(val);
1807 } else if (strncasecmp(opt, "source-address=", 15) == 0) {
1810 fatal("Empty source-address option");
1811 if (certflags_src_addr != NULL)
1812 fatal("source-address already specified");
1813 if (addr_match_cidr_list(NULL, val) != 0)
1814 fatal("Invalid source-address list");
1815 certflags_src_addr = xstrdup(val);
1817 fatal("Unsupported certificate option \"%s\"", opt);
1821 show_options(const Buffer *optbuf, int v00, int in_critical)
1826 Buffer options, option;
1828 buffer_init(&options);
1829 buffer_append(&options, buffer_ptr(optbuf), buffer_len(optbuf));
1831 buffer_init(&option);
1832 while (buffer_len(&options) != 0) {
1833 name = buffer_get_string(&options, NULL);
1834 data = buffer_get_string_ptr(&options, &dlen);
1835 buffer_append(&option, data, dlen);
1836 printf(" %s", name);
1837 if ((v00 || !in_critical) &&
1838 (strcmp(name, "permit-X11-forwarding") == 0 ||
1839 strcmp(name, "permit-agent-forwarding") == 0 ||
1840 strcmp(name, "permit-port-forwarding") == 0 ||
1841 strcmp(name, "permit-pty") == 0 ||
1842 strcmp(name, "permit-user-rc") == 0))
1844 else if ((v00 || in_critical) &&
1845 (strcmp(name, "force-command") == 0 ||
1846 strcmp(name, "source-address") == 0)) {
1847 data = buffer_get_string(&option, NULL);
1848 printf(" %s\n", data);
1851 printf(" UNKNOWN OPTION (len %u)\n",
1852 buffer_len(&option));
1853 buffer_clear(&option);
1856 if (buffer_len(&option) != 0)
1857 fatal("Option corrupt: extra data at end");
1859 buffer_free(&option);
1860 buffer_free(&options);
1864 do_show_cert(struct passwd *pw)
1868 char *key_fp, *ca_fp;
1872 ask_filename(pw, "Enter file in which the key is");
1873 if (stat(identity_file, &st) < 0)
1874 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
1875 if ((key = key_load_public(identity_file, NULL)) == NULL)
1876 fatal("%s is not a public key", identity_file);
1877 if (!key_is_cert(key))
1878 fatal("%s is not a certificate", identity_file);
1879 v00 = key->type == KEY_RSA_CERT_V00 || key->type == KEY_DSA_CERT_V00;
1881 key_fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
1882 ca_fp = key_fingerprint(key->cert->signature_key,
1883 SSH_FP_MD5, SSH_FP_HEX);
1885 printf("%s:\n", identity_file);
1886 printf(" Type: %s %s certificate\n", key_ssh_name(key),
1887 key_cert_type(key));
1888 printf(" Public key: %s %s\n", key_type(key), key_fp);
1889 printf(" Signing CA: %s %s\n",
1890 key_type(key->cert->signature_key), ca_fp);
1891 printf(" Key ID: \"%s\"\n", key->cert->key_id);
1893 printf(" Serial: %llu\n",
1894 (unsigned long long)key->cert->serial);
1896 printf(" Valid: %s\n",
1897 fmt_validity(key->cert->valid_after, key->cert->valid_before));
1898 printf(" Principals: ");
1899 if (key->cert->nprincipals == 0)
1902 for (i = 0; i < key->cert->nprincipals; i++)
1904 key->cert->principals[i]);
1907 printf(" Critical Options: ");
1908 if (buffer_len(&key->cert->critical) == 0)
1912 show_options(&key->cert->critical, v00, 1);
1915 printf(" Extensions: ");
1916 if (buffer_len(&key->cert->extensions) == 0)
1920 show_options(&key->cert->extensions, v00, 0);
1927 load_krl(const char *path, struct ssh_krl **krlp)
1932 buffer_init(&krlbuf);
1933 if ((fd = open(path, O_RDONLY)) == -1)
1934 fatal("open %s: %s", path, strerror(errno));
1935 if (!key_load_file(fd, path, &krlbuf))
1936 fatal("Unable to load KRL");
1938 /* XXX check sigs */
1939 if (ssh_krl_from_blob(&krlbuf, krlp, NULL, 0) != 0 ||
1941 fatal("Invalid KRL file");
1942 buffer_free(&krlbuf);
1946 update_krl_from_file(struct passwd *pw, const char *file, const Key *ca,
1947 struct ssh_krl *krl)
1951 char *path, *cp, *ep, line[SSH_MAX_PUBKEY_BYTES];
1952 unsigned long long serial, serial2;
1953 int i, was_explicit_key, was_sha1, r;
1956 path = tilde_expand_filename(file, pw->pw_uid);
1957 if (strcmp(path, "-") == 0) {
1960 path = xstrdup("(standard input)");
1961 } else if ((krl_spec = fopen(path, "r")) == NULL)
1962 fatal("fopen %s: %s", path, strerror(errno));
1965 printf("Revoking from %s\n", path);
1966 while (read_keyfile_line(krl_spec, path, line, sizeof(line),
1968 was_explicit_key = was_sha1 = 0;
1969 cp = line + strspn(line, " \t");
1970 /* Trim trailing space, comments and strip \n */
1971 for (i = 0, r = -1; cp[i] != '\0'; i++) {
1972 if (cp[i] == '#' || cp[i] == '\n') {
1976 if (cp[i] == ' ' || cp[i] == '\t') {
1977 /* Remember the start of a span of whitespace */
1987 if (strncasecmp(cp, "serial:", 7) == 0) {
1989 fatal("revoking certificates by serial number "
1990 "requires specification of a CA key");
1993 cp = cp + strspn(cp, " \t");
1995 serial = strtoull(cp, &ep, 0);
1996 if (*cp == '\0' || (*ep != '\0' && *ep != '-'))
1997 fatal("%s:%lu: invalid serial \"%s\"",
1999 if (errno == ERANGE && serial == ULLONG_MAX)
2000 fatal("%s:%lu: serial out of range",
2006 serial2 = strtoull(cp, &ep, 0);
2007 if (*cp == '\0' || *ep != '\0')
2008 fatal("%s:%lu: invalid serial \"%s\"",
2010 if (errno == ERANGE && serial2 == ULLONG_MAX)
2011 fatal("%s:%lu: serial out of range",
2013 if (serial2 <= serial)
2014 fatal("%s:%lu: invalid serial range "
2015 "%llu:%llu", path, lnum,
2016 (unsigned long long)serial,
2017 (unsigned long long)serial2);
2019 if (ssh_krl_revoke_cert_by_serial_range(krl,
2020 ca, serial, serial2) != 0) {
2021 fatal("%s: revoke serial failed",
2024 } else if (strncasecmp(cp, "id:", 3) == 0) {
2026 fatal("revoking certificates by key ID "
2027 "requires specification of a CA key");
2030 cp = cp + strspn(cp, " \t");
2031 if (ssh_krl_revoke_cert_by_key_id(krl, ca, cp) != 0)
2032 fatal("%s: revoke key ID failed", __func__);
2034 if (strncasecmp(cp, "key:", 4) == 0) {
2036 cp = cp + strspn(cp, " \t");
2037 was_explicit_key = 1;
2038 } else if (strncasecmp(cp, "sha1:", 5) == 0) {
2040 cp = cp + strspn(cp, " \t");
2044 * Just try to process the line as a key.
2045 * Parsing will fail if it isn't.
2048 if ((key = key_new(KEY_UNSPEC)) == NULL)
2050 if (key_read(key, &cp) != 1)
2051 fatal("%s:%lu: invalid key", path, lnum);
2052 if (was_explicit_key)
2053 r = ssh_krl_revoke_key_explicit(krl, key);
2055 r = ssh_krl_revoke_key_sha1(krl, key);
2057 r = ssh_krl_revoke_key(krl, key);
2059 fatal("%s: revoke key failed", __func__);
2063 if (strcmp(path, "-") != 0)
2069 do_gen_krl(struct passwd *pw, int updating, int argc, char **argv)
2071 struct ssh_krl *krl;
2078 if (*identity_file == '\0')
2079 fatal("KRL generation requires an output file");
2080 if (stat(identity_file, &sb) == -1) {
2081 if (errno != ENOENT)
2082 fatal("Cannot access KRL \"%s\": %s",
2083 identity_file, strerror(errno));
2085 fatal("KRL \"%s\" does not exist", identity_file);
2087 if (ca_key_path != NULL) {
2088 tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
2089 if ((ca = key_load_public(tmp, NULL)) == NULL)
2090 fatal("Cannot load CA public key %s", tmp);
2095 load_krl(identity_file, &krl);
2096 else if ((krl = ssh_krl_init()) == NULL)
2097 fatal("couldn't create KRL");
2099 if (cert_serial != 0)
2100 ssh_krl_set_version(krl, cert_serial);
2101 if (identity_comment != NULL)
2102 ssh_krl_set_comment(krl, identity_comment);
2104 for (i = 0; i < argc; i++)
2105 update_krl_from_file(pw, argv[i], ca, krl);
2108 if (ssh_krl_to_blob(krl, &kbuf, NULL, 0) != 0)
2109 fatal("Couldn't generate KRL");
2110 if ((fd = open(identity_file, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
2111 fatal("open %s: %s", identity_file, strerror(errno));
2112 if (atomicio(vwrite, fd, buffer_ptr(&kbuf), buffer_len(&kbuf)) !=
2114 fatal("write %s: %s", identity_file, strerror(errno));
2123 do_check_krl(struct passwd *pw, int argc, char **argv)
2127 struct ssh_krl *krl;
2130 if (*identity_file == '\0')
2131 fatal("KRL checking requires an input file");
2132 load_krl(identity_file, &krl);
2133 for (i = 0; i < argc; i++) {
2134 if ((k = key_load_public(argv[i], &comment)) == NULL)
2135 fatal("Cannot load public key %s", argv[i]);
2136 r = ssh_krl_check_key(krl, k);
2137 printf("%s%s%s%s: %s\n", argv[i],
2138 *comment ? " (" : "", comment, *comment ? ")" : "",
2139 r == 0 ? "ok" : "REVOKED");
2152 fprintf(stderr, "usage: %s [options]\n", __progname);
2153 fprintf(stderr, "Options:\n");
2154 fprintf(stderr, " -A Generate non-existent host keys for all key types.\n");
2155 fprintf(stderr, " -a number Number of KDF rounds for new key format or moduli primality tests.\n");
2156 fprintf(stderr, " -B Show bubblebabble digest of key file.\n");
2157 fprintf(stderr, " -b bits Number of bits in the key to create.\n");
2158 fprintf(stderr, " -C comment Provide new comment.\n");
2159 fprintf(stderr, " -c Change comment in private and public key files.\n");
2160 #ifdef ENABLE_PKCS11
2161 fprintf(stderr, " -D pkcs11 Download public key from pkcs11 token.\n");
2163 fprintf(stderr, " -e Export OpenSSH to foreign format key file.\n");
2164 fprintf(stderr, " -F hostname Find hostname in known hosts file.\n");
2165 fprintf(stderr, " -f filename Filename of the key file.\n");
2166 fprintf(stderr, " -G file Generate candidates for DH-GEX moduli.\n");
2167 fprintf(stderr, " -g Use generic DNS resource record format.\n");
2168 fprintf(stderr, " -H Hash names in known_hosts file.\n");
2169 fprintf(stderr, " -h Generate host certificate instead of a user certificate.\n");
2170 fprintf(stderr, " -I key_id Key identifier to include in certificate.\n");
2171 fprintf(stderr, " -i Import foreign format to OpenSSH key file.\n");
2172 fprintf(stderr, " -J number Screen this number of moduli lines.\n");
2173 fprintf(stderr, " -j number Start screening moduli at specified line.\n");
2174 fprintf(stderr, " -K checkpt Write checkpoints to this file.\n");
2175 fprintf(stderr, " -k Generate a KRL file.\n");
2176 fprintf(stderr, " -L Print the contents of a certificate.\n");
2177 fprintf(stderr, " -l Show fingerprint of key file.\n");
2178 fprintf(stderr, " -M memory Amount of memory (MB) to use for generating DH-GEX moduli.\n");
2179 fprintf(stderr, " -m key_fmt Conversion format for -e/-i (PEM|PKCS8|RFC4716).\n");
2180 fprintf(stderr, " -N phrase Provide new passphrase.\n");
2181 fprintf(stderr, " -n name,... User/host principal names to include in certificate\n");
2182 fprintf(stderr, " -O option Specify a certificate option.\n");
2183 fprintf(stderr, " -o Enforce new private key format.\n");
2184 fprintf(stderr, " -P phrase Provide old passphrase.\n");
2185 fprintf(stderr, " -p Change passphrase of private key file.\n");
2186 fprintf(stderr, " -Q Test whether key(s) are revoked in KRL.\n");
2187 fprintf(stderr, " -q Quiet.\n");
2188 fprintf(stderr, " -R hostname Remove host from known_hosts file.\n");
2189 fprintf(stderr, " -r hostname Print DNS resource record.\n");
2190 fprintf(stderr, " -S start Start point (hex) for generating DH-GEX moduli.\n");
2191 fprintf(stderr, " -s ca_key Certify keys with CA key.\n");
2192 fprintf(stderr, " -T file Screen candidates for DH-GEX moduli.\n");
2193 fprintf(stderr, " -t type Specify type of key to create.\n");
2194 fprintf(stderr, " -u Update KRL rather than creating a new one.\n");
2195 fprintf(stderr, " -V from:to Specify certificate validity interval.\n");
2196 fprintf(stderr, " -v Verbose.\n");
2197 fprintf(stderr, " -W gen Generator to use for generating DH-GEX moduli.\n");
2198 fprintf(stderr, " -y Read private key file and print public key.\n");
2199 fprintf(stderr, " -Z cipher Specify a cipher for new private key format.\n");
2200 fprintf(stderr, " -z serial Specify a serial number.\n");
2206 * Main program for key management.
2209 main(int argc, char **argv)
2211 char dotsshdir[MAXPATHLEN], comment[1024], *passphrase1, *passphrase2;
2212 char *checkpoint = NULL;
2213 char out_file[MAXPATHLEN], *ep, *rr_hostname = NULL;
2214 Key *private, *public;
2218 u_int32_t memory = 0, generator_wanted = 0;
2219 int do_gen_candidates = 0, do_screen_candidates = 0;
2220 int gen_all_hostkeys = 0, gen_krl = 0, update_krl = 0, check_krl = 0;
2221 unsigned long start_lineno = 0, lines_to_process = 0;
2222 BIGNUM *start = NULL;
2227 extern char *optarg;
2229 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
2232 __progname = ssh_get_progname(argv[0]);
2234 OpenSSL_add_all_algorithms();
2235 log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
2239 /* we need this for the home * directory. */
2240 pw = getpwuid(getuid());
2242 printf("No user exists for uid %lu\n", (u_long)getuid());
2245 if (gethostname(hostname, sizeof(hostname)) < 0) {
2246 perror("gethostname");
2250 /* Remaining characters: EUYdw */
2251 while ((opt = getopt(argc, argv, "ABHLQXceghiklopquvxy"
2252 "C:D:F:G:I:J:K:M:N:O:P:R:S:T:V:W:Z:a:b:f:g:j:m:n:r:s:t:z:")) != -1) {
2255 gen_all_hostkeys = 1;
2258 bits = (u_int32_t)strtonum(optarg, 256, 32768, &errstr);
2260 fatal("Bits has bad value %s (%s)",
2265 rr_hostname = optarg;
2271 cert_key_id = optarg;
2274 lines_to_process = strtoul(optarg, NULL, 10);
2277 start_lineno = strtoul(optarg, NULL, 10);
2281 rr_hostname = optarg;
2287 print_fingerprint = 1;
2290 print_bubblebabble = 1;
2293 if (strcasecmp(optarg, "RFC4716") == 0 ||
2294 strcasecmp(optarg, "ssh2") == 0) {
2295 convert_format = FMT_RFC4716;
2298 if (strcasecmp(optarg, "PKCS8") == 0) {
2299 convert_format = FMT_PKCS8;
2302 if (strcasecmp(optarg, "PEM") == 0) {
2303 convert_format = FMT_PEM;
2306 fatal("Unsupported conversion format \"%s\"", optarg);
2308 cert_principals = optarg;
2314 change_passphrase = 1;
2320 if (strlcpy(identity_file, optarg, sizeof(identity_file)) >=
2321 sizeof(identity_file))
2322 fatal("Identity filename too long");
2329 identity_passphrase = optarg;
2332 identity_new_passphrase = optarg;
2338 add_cert_option(optarg);
2341 new_format_cipher = optarg;
2344 identity_comment = optarg;
2355 cert_key_type = SSH2_CERT_TYPE_HOST;
2356 certflags_flags = 0;
2370 ca_key_path = optarg;
2373 key_type_name = optarg;
2376 pkcs11provider = optarg;
2382 if (log_level == SYSLOG_LEVEL_INFO)
2383 log_level = SYSLOG_LEVEL_DEBUG1;
2385 if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
2386 log_level < SYSLOG_LEVEL_DEBUG3)
2391 rr_hostname = optarg;
2394 generator_wanted = (u_int32_t)strtonum(optarg, 1,
2397 fatal("Desired generator has bad value: %s (%s)",
2401 rounds = (int)strtonum(optarg, 1, INT_MAX, &errstr);
2403 fatal("Invalid number: %s (%s)",
2407 memory = (u_int32_t)strtonum(optarg, 1, UINT_MAX, &errstr);
2409 fatal("Memory limit is %s: %s", errstr, optarg);
2412 do_gen_candidates = 1;
2413 if (strlcpy(out_file, optarg, sizeof(out_file)) >=
2415 fatal("Output filename too long");
2418 do_screen_candidates = 1;
2419 if (strlcpy(out_file, optarg, sizeof(out_file)) >=
2421 fatal("Output filename too long");
2424 if (strlen(optarg) >= MAXPATHLEN)
2425 fatal("Checkpoint filename too long");
2426 checkpoint = xstrdup(optarg);
2429 /* XXX - also compare length against bits */
2430 if (BN_hex2bn(&start, optarg) == 0)
2431 fatal("Invalid start point.");
2434 parse_cert_times(optarg);
2438 cert_serial = strtoull(optarg, &ep, 10);
2439 if (*optarg < '0' || *optarg > '9' || *ep != '\0' ||
2440 (errno == ERANGE && cert_serial == ULLONG_MAX))
2441 fatal("Invalid serial number \"%s\"", optarg);
2450 log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
2455 if (ca_key_path != NULL) {
2456 if (argc < 1 && !gen_krl) {
2457 printf("Too few arguments.\n");
2460 } else if (argc > 0 && !gen_krl && !check_krl) {
2461 printf("Too many arguments.\n");
2464 if (change_passphrase && change_comment) {
2465 printf("Can only have one of -p and -c.\n");
2468 if (print_fingerprint && (delete_host || hash_hosts)) {
2469 printf("Cannot use -l with -H or -R.\n");
2473 do_gen_krl(pw, update_krl, argc, argv);
2477 do_check_krl(pw, argc, argv);
2480 if (ca_key_path != NULL) {
2481 if (cert_key_id == NULL)
2482 fatal("Must specify key id (-I) when certifying");
2483 do_ca_sign(pw, argc, argv);
2487 if (delete_host || hash_hosts || find_host)
2488 do_known_hosts(pw, rr_hostname);
2489 if (pkcs11provider != NULL)
2491 if (print_fingerprint || print_bubblebabble)
2493 if (change_passphrase)
2494 do_change_passphrase(pw);
2496 do_change_comment(pw);
2500 do_convert_from(pw);
2502 do_print_public(pw);
2503 if (rr_hostname != NULL) {
2506 if (have_identity) {
2507 n = do_print_resource_record(pw,
2508 identity_file, rr_hostname);
2510 perror(identity_file);
2516 n += do_print_resource_record(pw,
2517 _PATH_HOST_RSA_KEY_FILE, rr_hostname);
2518 n += do_print_resource_record(pw,
2519 _PATH_HOST_DSA_KEY_FILE, rr_hostname);
2520 n += do_print_resource_record(pw,
2521 _PATH_HOST_ECDSA_KEY_FILE, rr_hostname);
2524 fatal("no keys found.");
2529 if (do_gen_candidates) {
2530 FILE *out = fopen(out_file, "w");
2533 error("Couldn't open modulus candidate file \"%s\": %s",
2534 out_file, strerror(errno));
2538 bits = DEFAULT_BITS;
2539 if (gen_candidates(out, memory, bits, start) != 0)
2540 fatal("modulus candidate generation failed");
2545 if (do_screen_candidates) {
2547 FILE *out = fopen(out_file, "a");
2549 if (have_identity && strcmp(identity_file, "-") != 0) {
2550 if ((in = fopen(identity_file, "r")) == NULL) {
2551 fatal("Couldn't open modulus candidate "
2552 "file \"%s\": %s", identity_file,
2559 fatal("Couldn't open moduli file \"%s\": %s",
2560 out_file, strerror(errno));
2562 if (prime_test(in, out, rounds == 0 ? 100 : rounds,
2563 generator_wanted, checkpoint,
2564 start_lineno, lines_to_process) != 0)
2565 fatal("modulus screening failed");
2569 if (gen_all_hostkeys) {
2570 do_gen_all_hostkeys(pw);
2574 if (key_type_name == NULL)
2575 key_type_name = "rsa";
2577 type = key_type_from_name(key_type_name);
2578 type_bits_valid(type, &bits);
2581 printf("Generating public/private %s key pair.\n", key_type_name);
2582 private = key_generate(type, bits);
2583 if (private == NULL) {
2584 fprintf(stderr, "key_generate failed\n");
2587 public = key_from_private(private);
2590 ask_filename(pw, "Enter file in which to save the key");
2592 /* Create ~/.ssh directory if it doesn't already exist. */
2593 snprintf(dotsshdir, sizeof dotsshdir, "%s/%s",
2594 pw->pw_dir, _PATH_SSH_USER_DIR);
2595 if (strstr(identity_file, dotsshdir) != NULL) {
2596 if (stat(dotsshdir, &st) < 0) {
2597 if (errno != ENOENT) {
2598 error("Could not stat %s: %s", dotsshdir,
2600 } else if (mkdir(dotsshdir, 0700) < 0) {
2601 error("Could not create directory '%s': %s",
2602 dotsshdir, strerror(errno));
2604 printf("Created directory '%s'.\n", dotsshdir);
2607 /* If the file already exists, ask the user to confirm. */
2608 if (stat(identity_file, &st) >= 0) {
2610 printf("%s already exists.\n", identity_file);
2611 printf("Overwrite (y/n)? ");
2613 if (fgets(yesno, sizeof(yesno), stdin) == NULL)
2615 if (yesno[0] != 'y' && yesno[0] != 'Y')
2618 /* Ask for a passphrase (twice). */
2619 if (identity_passphrase)
2620 passphrase1 = xstrdup(identity_passphrase);
2621 else if (identity_new_passphrase)
2622 passphrase1 = xstrdup(identity_new_passphrase);
2626 read_passphrase("Enter passphrase (empty for no "
2627 "passphrase): ", RP_ALLOW_STDIN);
2628 passphrase2 = read_passphrase("Enter same passphrase again: ",
2630 if (strcmp(passphrase1, passphrase2) != 0) {
2632 * The passphrases do not match. Clear them and
2635 explicit_bzero(passphrase1, strlen(passphrase1));
2636 explicit_bzero(passphrase2, strlen(passphrase2));
2639 printf("Passphrases do not match. Try again.\n");
2640 goto passphrase_again;
2642 /* Clear the other copy of the passphrase. */
2643 explicit_bzero(passphrase2, strlen(passphrase2));
2647 if (identity_comment) {
2648 strlcpy(comment, identity_comment, sizeof(comment));
2650 /* Create default comment field for the passphrase. */
2651 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
2654 /* Save the key with the given passphrase and comment. */
2655 if (!key_save_private(private, identity_file, passphrase1, comment,
2656 use_new_format, new_format_cipher, rounds)) {
2657 printf("Saving the key failed: %s.\n", identity_file);
2658 explicit_bzero(passphrase1, strlen(passphrase1));
2662 /* Clear the passphrase. */
2663 explicit_bzero(passphrase1, strlen(passphrase1));
2666 /* Clear the private key and the random number generator. */
2670 printf("Your identification has been saved in %s.\n", identity_file);
2672 strlcat(identity_file, ".pub", sizeof(identity_file));
2673 fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
2675 printf("Could not save your public key in %s\n", identity_file);
2678 f = fdopen(fd, "w");
2680 printf("fdopen %s failed\n", identity_file);
2683 if (!key_write(public, f))
2684 fprintf(stderr, "write key failed\n");
2685 fprintf(f, " %s\n", comment);
2689 char *fp = key_fingerprint(public, SSH_FP_MD5, SSH_FP_HEX);
2690 char *ra = key_fingerprint(public, SSH_FP_MD5,
2692 printf("Your public key has been saved in %s.\n",
2694 printf("The key fingerprint is:\n");
2695 printf("%s %s\n", fp, comment);
2696 printf("The key's randomart image is:\n");