1 /* $OpenBSD: ssh-keygen.c,v 1.329 2019/03/25 16:19:44 dtucker 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>
22 #include <openssl/evp.h>
23 #include <openssl/pem.h>
24 #include "openbsd-compat/openssl-compat.h"
48 #include "pathnames.h"
57 #include "ssh-pkcs11.h"
65 # define DEFAULT_KEY_TYPE_NAME "rsa"
67 # define DEFAULT_KEY_TYPE_NAME "ed25519"
71 * Default number of bits in the RSA, DSA and ECDSA keys. These value can be
72 * overridden on the command line.
74 * These values, with the exception of DSA, provide security equivalent to at
75 * least 128 bits of security according to NIST Special Publication 800-57:
76 * Recommendation for Key Management Part 1 rev 4 section 5.6.1.
77 * For DSA it (and FIPS-186-4 section 4.2) specifies that the only size for
78 * which a 160bit hash is acceptable is 1kbit, and since ssh-dss specifies only
79 * SHA1 we limit the DSA key size 1k bits.
81 #define DEFAULT_BITS 3072
82 #define DEFAULT_BITS_DSA 1024
83 #define DEFAULT_BITS_ECDSA 256
87 /* Flag indicating that we just want to see the key fingerprint */
88 static int print_fingerprint = 0;
89 static int print_bubblebabble = 0;
91 /* Hash algorithm to use for fingerprints. */
92 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
94 /* The identity file name, given on the command line or entered by the user. */
95 static char identity_file[1024];
96 static int have_identity = 0;
98 /* This is set to the passphrase if given on the command line. */
99 static char *identity_passphrase = NULL;
101 /* This is set to the new passphrase if given on the command line. */
102 static char *identity_new_passphrase = NULL;
104 /* Key type when certifying */
105 static u_int cert_key_type = SSH2_CERT_TYPE_USER;
107 /* "key ID" of signed key */
108 static char *cert_key_id = NULL;
110 /* Comma-separated list of principal names for certifying keys */
111 static char *cert_principals = NULL;
113 /* Validity period for certificates */
114 static u_int64_t cert_valid_from = 0;
115 static u_int64_t cert_valid_to = ~0ULL;
117 /* Certificate options */
118 #define CERTOPT_X_FWD (1)
119 #define CERTOPT_AGENT_FWD (1<<1)
120 #define CERTOPT_PORT_FWD (1<<2)
121 #define CERTOPT_PTY (1<<3)
122 #define CERTOPT_USER_RC (1<<4)
123 #define CERTOPT_DEFAULT (CERTOPT_X_FWD|CERTOPT_AGENT_FWD| \
124 CERTOPT_PORT_FWD|CERTOPT_PTY|CERTOPT_USER_RC)
125 static u_int32_t certflags_flags = CERTOPT_DEFAULT;
126 static char *certflags_command = NULL;
127 static char *certflags_src_addr = NULL;
129 /* Arbitrary extensions specified by user */
130 struct cert_userext {
135 static struct cert_userext *cert_userext;
136 static size_t ncert_userext;
138 /* Conversion to/from various formats */
143 } convert_format = FMT_RFC4716;
145 static char *key_type_name = NULL;
147 /* Load key from this PKCS#11 provider */
148 static char *pkcs11provider = NULL;
150 /* Use new OpenSSH private key format when writing SSH2 keys instead of PEM */
151 static int use_new_format = 1;
153 /* Cipher for new-format private keys */
154 static char *new_format_cipher = NULL;
157 * Number of KDF rounds to derive new format keys /
158 * number of primality trials when screening moduli.
160 static int rounds = 0;
163 extern char *__progname;
165 static char hostname[NI_MAXHOST];
169 int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
170 int prime_test(FILE *, FILE *, u_int32_t, u_int32_t, char *, unsigned long,
175 type_bits_valid(int type, const char *name, u_int32_t *bitsp)
181 if (type == KEY_UNSPEC)
182 fatal("unknown key type %s", key_type_name);
186 *bitsp = DEFAULT_BITS_DSA;
187 else if (type == KEY_ECDSA) {
189 (nid = sshkey_ecdsa_nid_from_name(name)) > 0)
190 *bitsp = sshkey_curve_nid_to_bits(nid);
192 *bitsp = DEFAULT_BITS_ECDSA;
195 *bitsp = DEFAULT_BITS;
198 maxbits = (type == KEY_DSA) ?
199 OPENSSL_DSA_MAX_MODULUS_BITS : OPENSSL_RSA_MAX_MODULUS_BITS;
200 if (*bitsp > maxbits)
201 fatal("key bits exceeds maximum %d", maxbits);
205 fatal("Invalid DSA key length: must be 1024 bits");
208 if (*bitsp < SSH_RSA_MINIMUM_MODULUS_SIZE)
209 fatal("Invalid RSA key length: minimum is %d bits",
210 SSH_RSA_MINIMUM_MODULUS_SIZE);
213 if (sshkey_ecdsa_bits_to_nid(*bitsp) == -1)
214 fatal("Invalid ECDSA key length: valid lengths are "
215 #ifdef OPENSSL_HAS_NISTP521
216 "256, 384 or 521 bits");
225 ask_filename(struct passwd *pw, const char *prompt)
230 if (key_type_name == NULL)
231 name = _PATH_SSH_CLIENT_ID_RSA;
233 switch (sshkey_type_from_name(key_type_name)) {
236 name = _PATH_SSH_CLIENT_ID_DSA;
238 #ifdef OPENSSL_HAS_ECC
241 name = _PATH_SSH_CLIENT_ID_ECDSA;
246 name = _PATH_SSH_CLIENT_ID_RSA;
249 case KEY_ED25519_CERT:
250 name = _PATH_SSH_CLIENT_ID_ED25519;
254 name = _PATH_SSH_CLIENT_ID_XMSS;
257 fatal("bad key type");
260 snprintf(identity_file, sizeof(identity_file),
261 "%s/%s", pw->pw_dir, name);
262 printf("%s (%s): ", prompt, identity_file);
264 if (fgets(buf, sizeof(buf), stdin) == NULL)
266 buf[strcspn(buf, "\n")] = '\0';
267 if (strcmp(buf, "") != 0)
268 strlcpy(identity_file, buf, sizeof(identity_file));
272 static struct sshkey *
273 load_identity(char *filename)
279 if ((r = sshkey_load_private(filename, "", &prv, NULL)) == 0)
281 if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
282 fatal("Load key \"%s\": %s", filename, ssh_err(r));
283 if (identity_passphrase)
284 pass = xstrdup(identity_passphrase);
286 pass = read_passphrase("Enter passphrase: ", RP_ALLOW_STDIN);
287 r = sshkey_load_private(filename, pass, &prv, NULL);
288 explicit_bzero(pass, strlen(pass));
291 fatal("Load key \"%s\": %s", filename, ssh_err(r));
295 #define SSH_COM_PUBLIC_BEGIN "---- BEGIN SSH2 PUBLIC KEY ----"
296 #define SSH_COM_PUBLIC_END "---- END SSH2 PUBLIC KEY ----"
297 #define SSH_COM_PRIVATE_BEGIN "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
298 #define SSH_COM_PRIVATE_KEY_MAGIC 0x3f6ff9eb
302 do_convert_to_ssh2(struct passwd *pw, struct sshkey *k)
309 if ((r = sshkey_to_blob(k, &blob, &len)) != 0)
310 fatal("key_to_blob failed: %s", ssh_err(r));
311 /* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
312 snprintf(comment, sizeof(comment),
313 "%u-bit %s, converted by %s@%s from OpenSSH",
314 sshkey_size(k), sshkey_type(k),
315 pw->pw_name, hostname);
317 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
318 fprintf(stdout, "Comment: \"%s\"\n", comment);
319 dump_base64(stdout, blob, len);
320 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
327 do_convert_to_pkcs8(struct sshkey *k)
329 switch (sshkey_type_plain(k->type)) {
331 if (!PEM_write_RSA_PUBKEY(stdout, k->rsa))
332 fatal("PEM_write_RSA_PUBKEY failed");
335 if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
336 fatal("PEM_write_DSA_PUBKEY failed");
338 #ifdef OPENSSL_HAS_ECC
340 if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
341 fatal("PEM_write_EC_PUBKEY failed");
345 fatal("%s: unsupported key type %s", __func__, sshkey_type(k));
351 do_convert_to_pem(struct sshkey *k)
353 switch (sshkey_type_plain(k->type)) {
355 if (!PEM_write_RSAPublicKey(stdout, k->rsa))
356 fatal("PEM_write_RSAPublicKey failed");
359 fatal("%s: unsupported key type %s", __func__, sshkey_type(k));
365 do_convert_to(struct passwd *pw)
372 ask_filename(pw, "Enter file in which the key is");
373 if (stat(identity_file, &st) < 0)
374 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
375 if ((r = sshkey_load_public(identity_file, &k, NULL)) != 0)
376 k = load_identity(identity_file);
377 switch (convert_format) {
379 do_convert_to_ssh2(pw, k);
382 do_convert_to_pkcs8(k);
385 do_convert_to_pem(k);
388 fatal("%s: unknown key format %d", __func__, convert_format);
394 * This is almost exactly the bignum1 encoding, but with 32 bit for length
398 buffer_get_bignum_bits(struct sshbuf *b, BIGNUM *value)
400 u_int bytes, bignum_bits;
403 if ((r = sshbuf_get_u32(b, &bignum_bits)) != 0)
404 fatal("%s: buffer error: %s", __func__, ssh_err(r));
405 bytes = (bignum_bits + 7) / 8;
406 if (sshbuf_len(b) < bytes)
407 fatal("%s: input buffer too small: need %d have %zu",
408 __func__, bytes, sshbuf_len(b));
409 if (BN_bin2bn(sshbuf_ptr(b), bytes, value) == NULL)
410 fatal("%s: BN_bin2bn failed", __func__);
411 if ((r = sshbuf_consume(b, bytes)) != 0)
412 fatal("%s: buffer error: %s", __func__, ssh_err(r));
415 static struct sshkey *
416 do_convert_private_ssh2_from_blob(u_char *blob, u_int blen)
419 struct sshkey *key = NULL;
421 u_char e1, e2, e3, *sig = NULL, data[] = "abcde12345";
423 u_int magic, i1, i2, i3, i4;
426 BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL;
427 BIGNUM *dsa_pub_key = NULL, *dsa_priv_key = NULL;
428 BIGNUM *rsa_n = NULL, *rsa_e = NULL, *rsa_d = NULL;
429 BIGNUM *rsa_p = NULL, *rsa_q = NULL, *rsa_iqmp = NULL;
430 if ((b = sshbuf_from(blob, blen)) == NULL)
431 fatal("%s: sshbuf_from failed", __func__);
432 if ((r = sshbuf_get_u32(b, &magic)) != 0)
433 fatal("%s: buffer error: %s", __func__, ssh_err(r));
435 if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
436 error("bad magic 0x%x != 0x%x", magic,
437 SSH_COM_PRIVATE_KEY_MAGIC);
441 if ((r = sshbuf_get_u32(b, &i1)) != 0 ||
442 (r = sshbuf_get_cstring(b, &type, NULL)) != 0 ||
443 (r = sshbuf_get_cstring(b, &cipher, NULL)) != 0 ||
444 (r = sshbuf_get_u32(b, &i2)) != 0 ||
445 (r = sshbuf_get_u32(b, &i3)) != 0 ||
446 (r = sshbuf_get_u32(b, &i4)) != 0)
447 fatal("%s: buffer error: %s", __func__, ssh_err(r));
448 debug("ignore (%d %d %d %d)", i1, i2, i3, i4);
449 if (strcmp(cipher, "none") != 0) {
450 error("unsupported cipher %s", cipher);
458 if (strstr(type, "dsa")) {
460 } else if (strstr(type, "rsa")) {
467 if ((key = sshkey_new(ktype)) == NULL)
468 fatal("sshkey_new failed");
473 if ((dsa_p = BN_new()) == NULL ||
474 (dsa_q = BN_new()) == NULL ||
475 (dsa_g = BN_new()) == NULL ||
476 (dsa_pub_key = BN_new()) == NULL ||
477 (dsa_priv_key = BN_new()) == NULL)
478 fatal("%s: BN_new", __func__);
479 buffer_get_bignum_bits(b, dsa_p);
480 buffer_get_bignum_bits(b, dsa_g);
481 buffer_get_bignum_bits(b, dsa_q);
482 buffer_get_bignum_bits(b, dsa_pub_key);
483 buffer_get_bignum_bits(b, dsa_priv_key);
484 if (!DSA_set0_pqg(key->dsa, dsa_p, dsa_q, dsa_g))
485 fatal("%s: DSA_set0_pqg failed", __func__);
486 dsa_p = dsa_q = dsa_g = NULL; /* transferred */
487 if (!DSA_set0_key(key->dsa, dsa_pub_key, dsa_priv_key))
488 fatal("%s: DSA_set0_key failed", __func__);
489 dsa_pub_key = dsa_priv_key = NULL; /* transferred */
492 if ((r = sshbuf_get_u8(b, &e1)) != 0 ||
493 (e1 < 30 && (r = sshbuf_get_u8(b, &e2)) != 0) ||
494 (e1 < 30 && (r = sshbuf_get_u8(b, &e3)) != 0))
495 fatal("%s: buffer error: %s", __func__, ssh_err(r));
506 if ((rsa_e = BN_new()) == NULL)
507 fatal("%s: BN_new", __func__);
508 if (!BN_set_word(rsa_e, e)) {
509 BN_clear_free(rsa_e);
514 if ((rsa_n = BN_new()) == NULL ||
515 (rsa_d = BN_new()) == NULL ||
516 (rsa_p = BN_new()) == NULL ||
517 (rsa_q = BN_new()) == NULL ||
518 (rsa_iqmp = BN_new()) == NULL)
519 fatal("%s: BN_new", __func__);
520 buffer_get_bignum_bits(b, rsa_d);
521 buffer_get_bignum_bits(b, rsa_n);
522 buffer_get_bignum_bits(b, rsa_iqmp);
523 buffer_get_bignum_bits(b, rsa_q);
524 buffer_get_bignum_bits(b, rsa_p);
525 if (!RSA_set0_key(key->rsa, rsa_n, rsa_e, rsa_d))
526 fatal("%s: RSA_set0_key failed", __func__);
527 rsa_n = rsa_e = rsa_d = NULL; /* transferred */
528 if (!RSA_set0_factors(key->rsa, rsa_p, rsa_q))
529 fatal("%s: RSA_set0_factors failed", __func__);
530 rsa_p = rsa_q = NULL; /* transferred */
531 if ((r = ssh_rsa_complete_crt_parameters(key, rsa_iqmp)) != 0)
532 fatal("generate RSA parameters failed: %s", ssh_err(r));
533 BN_clear_free(rsa_iqmp);
536 rlen = sshbuf_len(b);
538 error("do_convert_private_ssh2_from_blob: "
539 "remaining bytes in key blob %d", rlen);
543 if (sshkey_sign(key, &sig, &slen, data, sizeof(data), NULL, 0) != 0 ||
544 sshkey_verify(key, sig, slen, data, sizeof(data), NULL, 0) != 0) {
554 get_line(FILE *fp, char *line, size_t len)
560 while ((c = fgetc(fp)) != EOF) {
562 fatal("input line too long.");
566 if (c != EOF && c != '\n' && ungetc(c, fp) == EOF)
567 fatal("unget: %s", strerror(errno));
580 do_convert_from_ssh2(struct passwd *pw, struct sshkey **k, int *private)
582 int r, blen, escaped = 0;
589 if ((fp = fopen(identity_file, "r")) == NULL)
590 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
592 while ((blen = get_line(fp, line, sizeof(line))) != -1) {
593 if (blen > 0 && line[blen - 1] == '\\')
595 if (strncmp(line, "----", 4) == 0 ||
596 strstr(line, ": ") != NULL) {
597 if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
599 if (strstr(line, " END ") != NULL) {
602 /* fprintf(stderr, "ignore: %s", line); */
607 /* fprintf(stderr, "escaped: %s", line); */
610 strlcat(encoded, line, sizeof(encoded));
612 len = strlen(encoded);
613 if (((len % 4) == 3) &&
614 (encoded[len-1] == '=') &&
615 (encoded[len-2] == '=') &&
616 (encoded[len-3] == '='))
617 encoded[len-3] = '\0';
618 blen = uudecode(encoded, blob, sizeof(blob));
620 fatal("uudecode failed.");
622 *k = do_convert_private_ssh2_from_blob(blob, blen);
623 else if ((r = sshkey_from_blob(blob, blen, k)) != 0)
624 fatal("decode blob failed: %s", ssh_err(r));
629 do_convert_from_pkcs8(struct sshkey **k, int *private)
634 if ((fp = fopen(identity_file, "r")) == NULL)
635 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
636 if ((pubkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL)) == NULL) {
637 fatal("%s: %s is not a recognised public key format", __func__,
641 switch (EVP_PKEY_base_id(pubkey)) {
643 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
644 fatal("sshkey_new failed");
645 (*k)->type = KEY_RSA;
646 (*k)->rsa = EVP_PKEY_get1_RSA(pubkey);
649 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
650 fatal("sshkey_new failed");
651 (*k)->type = KEY_DSA;
652 (*k)->dsa = EVP_PKEY_get1_DSA(pubkey);
654 #ifdef OPENSSL_HAS_ECC
656 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
657 fatal("sshkey_new failed");
658 (*k)->type = KEY_ECDSA;
659 (*k)->ecdsa = EVP_PKEY_get1_EC_KEY(pubkey);
660 (*k)->ecdsa_nid = sshkey_ecdsa_key_to_nid((*k)->ecdsa);
664 fatal("%s: unsupported pubkey type %d", __func__,
665 EVP_PKEY_base_id(pubkey));
667 EVP_PKEY_free(pubkey);
672 do_convert_from_pem(struct sshkey **k, int *private)
677 if ((fp = fopen(identity_file, "r")) == NULL)
678 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
679 if ((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
680 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
681 fatal("sshkey_new failed");
682 (*k)->type = KEY_RSA;
687 fatal("%s: unrecognised raw private key format", __func__);
691 do_convert_from(struct passwd *pw)
693 struct sshkey *k = NULL;
694 int r, private = 0, ok = 0;
698 ask_filename(pw, "Enter file in which the key is");
699 if (stat(identity_file, &st) < 0)
700 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
702 switch (convert_format) {
704 do_convert_from_ssh2(pw, &k, &private);
707 do_convert_from_pkcs8(&k, &private);
710 do_convert_from_pem(&k, &private);
713 fatal("%s: unknown key format %d", __func__, convert_format);
717 if ((r = sshkey_write(k, stdout)) == 0)
720 fprintf(stdout, "\n");
724 ok = PEM_write_DSAPrivateKey(stdout, k->dsa, NULL,
725 NULL, 0, NULL, NULL);
727 #ifdef OPENSSL_HAS_ECC
729 ok = PEM_write_ECPrivateKey(stdout, k->ecdsa, NULL,
730 NULL, 0, NULL, NULL);
734 ok = PEM_write_RSAPrivateKey(stdout, k->rsa, NULL,
735 NULL, 0, NULL, NULL);
738 fatal("%s: unsupported key type %s", __func__,
744 fatal("key write failed");
751 do_print_public(struct passwd *pw)
758 ask_filename(pw, "Enter file in which the key is");
759 if (stat(identity_file, &st) < 0)
760 fatal("%s: %s", identity_file, strerror(errno));
761 prv = load_identity(identity_file);
762 if ((r = sshkey_write(prv, stdout)) != 0)
763 error("sshkey_write failed: %s", ssh_err(r));
765 fprintf(stdout, "\n");
770 do_download(struct passwd *pw)
773 struct sshkey **keys = NULL;
775 enum sshkey_fp_rep rep;
779 fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
780 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
783 nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys);
785 fatal("cannot read public key from pkcs11");
786 for (i = 0; i < nkeys; i++) {
787 if (print_fingerprint) {
788 fp = sshkey_fingerprint(keys[i], fptype, rep);
789 ra = sshkey_fingerprint(keys[i], fingerprint_hash,
791 if (fp == NULL || ra == NULL)
792 fatal("%s: sshkey_fingerprint fail", __func__);
793 printf("%u %s %s (PKCS11 key)\n", sshkey_size(keys[i]),
794 fp, sshkey_type(keys[i]));
795 if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
800 (void) sshkey_write(keys[i], stdout); /* XXX check */
801 fprintf(stdout, "\n");
803 sshkey_free(keys[i]);
809 fatal("no pkcs11 support");
810 #endif /* ENABLE_PKCS11 */
813 static struct sshkey *
814 try_read_key(char **cpp)
819 if ((ret = sshkey_new(KEY_UNSPEC)) == NULL)
820 fatal("sshkey_new failed");
821 if ((r = sshkey_read(ret, cpp)) == 0)
829 fingerprint_one_key(const struct sshkey *public, const char *comment)
831 char *fp = NULL, *ra = NULL;
832 enum sshkey_fp_rep rep;
835 fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
836 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
837 fp = sshkey_fingerprint(public, fptype, rep);
838 ra = sshkey_fingerprint(public, fingerprint_hash, SSH_FP_RANDOMART);
839 if (fp == NULL || ra == NULL)
840 fatal("%s: sshkey_fingerprint failed", __func__);
841 mprintf("%u %s %s (%s)\n", sshkey_size(public), fp,
842 comment ? comment : "no comment", sshkey_type(public));
843 if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
850 fingerprint_private(const char *path)
853 char *comment = NULL;
854 struct sshkey *public = NULL;
857 if (stat(identity_file, &st) < 0)
858 fatal("%s: %s", path, strerror(errno));
859 if ((r = sshkey_load_public(path, &public, &comment)) != 0) {
860 debug("load public \"%s\": %s", path, ssh_err(r));
861 if ((r = sshkey_load_private(path, NULL,
862 &public, &comment)) != 0) {
863 debug("load private \"%s\": %s", path, ssh_err(r));
864 fatal("%s is not a key file.", path);
868 fingerprint_one_key(public, comment);
874 do_fingerprint(struct passwd *pw)
877 struct sshkey *public = NULL;
878 char *comment = NULL, *cp, *ep, *line = NULL;
885 ask_filename(pw, "Enter file in which the key is");
886 path = identity_file;
888 if (strcmp(identity_file, "-") == 0) {
891 } else if ((f = fopen(path, "r")) == NULL)
892 fatal("%s: %s: %s", __progname, path, strerror(errno));
894 while (getline(&line, &linesize, f) != -1) {
897 cp[strcspn(cp, "\n")] = '\0';
898 /* Trim leading space and comments */
899 cp = line + strspn(line, " \t");
900 if (*cp == '#' || *cp == '\0')
904 * Input may be plain keys, private keys, authorized_keys
909 * Try private keys first. Assume a key is private if
910 * "SSH PRIVATE KEY" appears on the first line and we're
911 * not reading from stdin (XXX support private keys on stdin).
913 if (lnum == 1 && strcmp(identity_file, "-") != 0 &&
914 strstr(cp, "PRIVATE KEY") != NULL) {
917 fingerprint_private(path);
922 * If it's not a private key, then this must be prepared to
923 * accept a public key prefixed with a hostname or options.
924 * Try a bare key first, otherwise skip the leading stuff.
926 if ((public = try_read_key(&cp)) == NULL) {
927 i = strtol(cp, &ep, 10);
928 if (i == 0 || ep == NULL ||
929 (*ep != ' ' && *ep != '\t')) {
933 for (; *cp && (quoted || (*cp != ' ' &&
934 *cp != '\t')); cp++) {
935 if (*cp == '\\' && cp[1] == '"')
936 cp++; /* Skip both */
945 /* Retry after parsing leading hostname/key options */
946 if (public == NULL && (public = try_read_key(&cp)) == NULL) {
947 debug("%s:%lu: not a public key", path, lnum);
951 /* Find trailing comment, if any */
952 for (; *cp == ' ' || *cp == '\t'; cp++)
954 if (*cp != '\0' && *cp != '#')
957 fingerprint_one_key(public, comment);
959 invalid = 0; /* One good key in the file is sufficient */
965 fatal("%s is not a public key file.", path);
970 do_gen_all_hostkeys(struct passwd *pw)
974 char *key_type_display;
978 { "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE },
979 { "dsa", "DSA", _PATH_HOST_DSA_KEY_FILE },
980 #ifdef OPENSSL_HAS_ECC
981 { "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE },
982 #endif /* OPENSSL_HAS_ECC */
983 #endif /* WITH_OPENSSL */
984 { "ed25519", "ED25519",_PATH_HOST_ED25519_KEY_FILE },
986 { "xmss", "XMSS",_PATH_HOST_XMSS_KEY_FILE },
987 #endif /* WITH_XMSS */
994 struct sshkey *private, *public;
995 char comment[1024], *prv_tmp, *pub_tmp, *prv_file, *pub_file;
999 for (i = 0; key_types[i].key_type; i++) {
1000 public = private = NULL;
1001 prv_tmp = pub_tmp = prv_file = pub_file = NULL;
1003 xasprintf(&prv_file, "%s%s",
1004 identity_file, key_types[i].path);
1006 /* Check whether private key exists and is not zero-length */
1007 if (stat(prv_file, &st) == 0) {
1008 if (st.st_size != 0)
1010 } else if (errno != ENOENT) {
1011 error("Could not stat %s: %s", key_types[i].path,
1017 * Private key doesn't exist or is invalid; proceed with
1020 xasprintf(&prv_tmp, "%s%s.XXXXXXXXXX",
1021 identity_file, key_types[i].path);
1022 xasprintf(&pub_tmp, "%s%s.pub.XXXXXXXXXX",
1023 identity_file, key_types[i].path);
1024 xasprintf(&pub_file, "%s%s.pub",
1025 identity_file, key_types[i].path);
1029 printf("%s: generating new host keys: ", __progname);
1031 printf("%s ", key_types[i].key_type_display);
1033 type = sshkey_type_from_name(key_types[i].key_type);
1034 if ((fd = mkstemp(prv_tmp)) == -1) {
1035 error("Could not save your public key in %s: %s",
1036 prv_tmp, strerror(errno));
1039 close(fd); /* just using mkstemp() to generate/reserve a name */
1041 type_bits_valid(type, NULL, &bits);
1042 if ((r = sshkey_generate(type, bits, &private)) != 0) {
1043 error("sshkey_generate failed: %s", ssh_err(r));
1046 if ((r = sshkey_from_private(private, &public)) != 0)
1047 fatal("sshkey_from_private failed: %s", ssh_err(r));
1048 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name,
1050 if ((r = sshkey_save_private(private, prv_tmp, "",
1051 comment, use_new_format, new_format_cipher, rounds)) != 0) {
1052 error("Saving key \"%s\" failed: %s",
1053 prv_tmp, ssh_err(r));
1056 if ((fd = mkstemp(pub_tmp)) == -1) {
1057 error("Could not save your public key in %s: %s",
1058 pub_tmp, strerror(errno));
1061 (void)fchmod(fd, 0644);
1062 f = fdopen(fd, "w");
1064 error("fdopen %s failed: %s", pub_tmp, strerror(errno));
1068 if ((r = sshkey_write(public, f)) != 0) {
1069 error("write key failed: %s", ssh_err(r));
1073 fprintf(f, " %s\n", comment);
1074 if (ferror(f) != 0) {
1075 error("write key failed: %s", strerror(errno));
1079 if (fclose(f) != 0) {
1080 error("key close failed: %s", strerror(errno));
1084 /* Rename temporary files to their permanent locations. */
1085 if (rename(pub_tmp, pub_file) != 0) {
1086 error("Unable to move %s into position: %s",
1087 pub_file, strerror(errno));
1090 if (rename(prv_tmp, prv_file) != 0) {
1091 error("Unable to move %s into position: %s",
1092 key_types[i].path, strerror(errno));
1098 sshkey_free(private);
1099 sshkey_free(public);
1109 struct known_hosts_ctx {
1110 const char *host; /* Hostname searched for in find/delete case */
1111 FILE *out; /* Output file, stdout for find_hosts case */
1112 int has_unhashed; /* When hashing, original had unhashed hosts */
1113 int found_key; /* For find/delete, host was found */
1114 int invalid; /* File contained invalid items; don't delete */
1115 int hash_hosts; /* Hash hostnames as we go */
1116 int find_host; /* Search for specific hostname */
1117 int delete_host; /* Delete host from known_hosts */
1121 known_hosts_hash(struct hostkey_foreach_line *l, void *_ctx)
1123 struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1124 char *hashed, *cp, *hosts, *ohosts;
1125 int has_wild = l->hosts && strcspn(l->hosts, "*?!") != strlen(l->hosts);
1126 int was_hashed = l->hosts && l->hosts[0] == HASH_DELIM;
1128 switch (l->status) {
1130 case HKF_STATUS_MATCHED:
1132 * Don't hash hosts already already hashed, with wildcard
1133 * characters or a CA/revocation marker.
1135 if (was_hashed || has_wild || l->marker != MRK_NONE) {
1136 fprintf(ctx->out, "%s\n", l->line);
1137 if (has_wild && !ctx->find_host) {
1138 logit("%s:%lu: ignoring host name "
1139 "with wildcard: %.64s", l->path,
1140 l->linenum, l->hosts);
1145 * Split any comma-separated hostnames from the host list,
1146 * hash and store separately.
1148 ohosts = hosts = xstrdup(l->hosts);
1149 while ((cp = strsep(&hosts, ",")) != NULL && *cp != '\0') {
1151 if ((hashed = host_hash(cp, NULL, 0)) == NULL)
1152 fatal("hash_host failed");
1153 fprintf(ctx->out, "%s %s\n", hashed, l->rawkey);
1154 ctx->has_unhashed = 1;
1158 case HKF_STATUS_INVALID:
1159 /* Retain invalid lines, but mark file as invalid. */
1161 logit("%s:%lu: invalid line", l->path, l->linenum);
1164 fprintf(ctx->out, "%s\n", l->line);
1172 known_hosts_find_delete(struct hostkey_foreach_line *l, void *_ctx)
1174 struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1175 enum sshkey_fp_rep rep;
1179 fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
1180 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1182 if (l->status == HKF_STATUS_MATCHED) {
1183 if (ctx->delete_host) {
1184 if (l->marker != MRK_NONE) {
1185 /* Don't remove CA and revocation lines */
1186 fprintf(ctx->out, "%s\n", l->line);
1189 * Hostname matches and has no CA/revoke
1190 * marker, delete it by *not* writing the
1195 printf("# Host %s found: line %lu\n",
1196 ctx->host, l->linenum);
1199 } else if (ctx->find_host) {
1202 printf("# Host %s found: line %lu %s\n",
1204 l->linenum, l->marker == MRK_CA ? "CA" :
1205 (l->marker == MRK_REVOKE ? "REVOKED" : ""));
1207 if (ctx->hash_hosts)
1208 known_hosts_hash(l, ctx);
1209 else if (print_fingerprint) {
1210 fp = sshkey_fingerprint(l->key, fptype, rep);
1211 mprintf("%s %s %s %s\n", ctx->host,
1212 sshkey_type(l->key), fp, l->comment);
1215 fprintf(ctx->out, "%s\n", l->line);
1218 } else if (ctx->delete_host) {
1219 /* Retain non-matching hosts when deleting */
1220 if (l->status == HKF_STATUS_INVALID) {
1222 logit("%s:%lu: invalid line", l->path, l->linenum);
1224 fprintf(ctx->out, "%s\n", l->line);
1230 do_known_hosts(struct passwd *pw, const char *name, int find_host,
1231 int delete_host, int hash_hosts)
1233 char *cp, tmp[PATH_MAX], old[PATH_MAX];
1234 int r, fd, oerrno, inplace = 0;
1235 struct known_hosts_ctx ctx;
1236 u_int foreach_options;
1238 if (!have_identity) {
1239 cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
1240 if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
1241 sizeof(identity_file))
1242 fatal("Specified known hosts path too long");
1247 memset(&ctx, 0, sizeof(ctx));
1250 ctx.hash_hosts = hash_hosts;
1251 ctx.find_host = find_host;
1252 ctx.delete_host = delete_host;
1255 * Find hosts goes to stdout, hash and deletions happen in-place
1256 * A corner case is ssh-keygen -HF foo, which should go to stdout
1258 if (!find_host && (hash_hosts || delete_host)) {
1259 if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
1260 strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
1261 strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
1262 strlcat(old, ".old", sizeof(old)) >= sizeof(old))
1263 fatal("known_hosts path too long");
1265 if ((fd = mkstemp(tmp)) == -1)
1266 fatal("mkstemp: %s", strerror(errno));
1267 if ((ctx.out = fdopen(fd, "w")) == NULL) {
1270 fatal("fdopen: %s", strerror(oerrno));
1274 /* XXX support identity_file == "-" for stdin */
1275 foreach_options = find_host ? HKF_WANT_MATCH : 0;
1276 foreach_options |= print_fingerprint ? HKF_WANT_PARSE_KEY : 0;
1277 if ((r = hostkeys_foreach(identity_file, (find_host || !hash_hosts) ?
1278 known_hosts_find_delete : known_hosts_hash, &ctx, name, NULL,
1279 foreach_options)) != 0) {
1282 fatal("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
1289 error("%s is not a valid known_hosts file.", identity_file);
1291 error("Not replacing existing known_hosts "
1292 "file because of errors");
1296 } else if (delete_host && !ctx.found_key) {
1297 logit("Host %s not found in %s", name, identity_file);
1300 } else if (inplace) {
1301 /* Backup existing file */
1302 if (unlink(old) == -1 && errno != ENOENT)
1303 fatal("unlink %.100s: %s", old, strerror(errno));
1304 if (link(identity_file, old) == -1)
1305 fatal("link %.100s to %.100s: %s", identity_file, old,
1307 /* Move new one into place */
1308 if (rename(tmp, identity_file) == -1) {
1309 error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
1316 printf("%s updated.\n", identity_file);
1317 printf("Original contents retained as %s\n", old);
1318 if (ctx.has_unhashed) {
1319 logit("WARNING: %s contains unhashed entries", old);
1320 logit("Delete this file to ensure privacy "
1325 exit (find_host && !ctx.found_key);
1329 * Perform changing a passphrase. The argument is the passwd structure
1330 * for the current user.
1333 do_change_passphrase(struct passwd *pw)
1336 char *old_passphrase, *passphrase1, *passphrase2;
1338 struct sshkey *private;
1342 ask_filename(pw, "Enter file in which the key is");
1343 if (stat(identity_file, &st) < 0)
1344 fatal("%s: %s", identity_file, strerror(errno));
1345 /* Try to load the file with empty passphrase. */
1346 r = sshkey_load_private(identity_file, "", &private, &comment);
1347 if (r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
1348 if (identity_passphrase)
1349 old_passphrase = xstrdup(identity_passphrase);
1352 read_passphrase("Enter old passphrase: ",
1354 r = sshkey_load_private(identity_file, old_passphrase,
1355 &private, &comment);
1356 explicit_bzero(old_passphrase, strlen(old_passphrase));
1357 free(old_passphrase);
1360 } else if (r != 0) {
1362 fatal("Failed to load key %s: %s", identity_file, ssh_err(r));
1365 mprintf("Key has comment '%s'\n", comment);
1367 /* Ask the new passphrase (twice). */
1368 if (identity_new_passphrase) {
1369 passphrase1 = xstrdup(identity_new_passphrase);
1373 read_passphrase("Enter new passphrase (empty for no "
1374 "passphrase): ", RP_ALLOW_STDIN);
1375 passphrase2 = read_passphrase("Enter same passphrase again: ",
1378 /* Verify that they are the same. */
1379 if (strcmp(passphrase1, passphrase2) != 0) {
1380 explicit_bzero(passphrase1, strlen(passphrase1));
1381 explicit_bzero(passphrase2, strlen(passphrase2));
1384 printf("Pass phrases do not match. Try again.\n");
1387 /* Destroy the other copy. */
1388 explicit_bzero(passphrase2, strlen(passphrase2));
1392 /* Save the file using the new passphrase. */
1393 if ((r = sshkey_save_private(private, identity_file, passphrase1,
1394 comment, use_new_format, new_format_cipher, rounds)) != 0) {
1395 error("Saving key \"%s\" failed: %s.",
1396 identity_file, ssh_err(r));
1397 explicit_bzero(passphrase1, strlen(passphrase1));
1399 sshkey_free(private);
1403 /* Destroy the passphrase and the copy of the key in memory. */
1404 explicit_bzero(passphrase1, strlen(passphrase1));
1406 sshkey_free(private); /* Destroys contents */
1409 printf("Your identification has been saved with the new passphrase.\n");
1414 * Print the SSHFP RR.
1417 do_print_resource_record(struct passwd *pw, char *fname, char *hname,
1420 struct sshkey *public;
1421 char *comment = NULL;
1426 fatal("%s: no filename", __func__);
1427 if (stat(fname, &st) < 0) {
1428 if (errno == ENOENT)
1430 fatal("%s: %s", fname, strerror(errno));
1432 if ((r = sshkey_load_public(fname, &public, &comment)) != 0)
1433 fatal("Failed to read v2 public key from \"%s\": %s.",
1435 export_dns_rr(hname, public, stdout, print_generic);
1436 sshkey_free(public);
1442 * Change the comment of a private key file.
1445 do_change_comment(struct passwd *pw, const char *identity_comment)
1447 char new_comment[1024], *comment, *passphrase;
1448 struct sshkey *private;
1449 struct sshkey *public;
1455 ask_filename(pw, "Enter file in which the key is");
1456 if (stat(identity_file, &st) < 0)
1457 fatal("%s: %s", identity_file, strerror(errno));
1458 if ((r = sshkey_load_private(identity_file, "",
1459 &private, &comment)) == 0)
1460 passphrase = xstrdup("");
1461 else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
1462 fatal("Cannot load private key \"%s\": %s.",
1463 identity_file, ssh_err(r));
1465 if (identity_passphrase)
1466 passphrase = xstrdup(identity_passphrase);
1467 else if (identity_new_passphrase)
1468 passphrase = xstrdup(identity_new_passphrase);
1470 passphrase = read_passphrase("Enter passphrase: ",
1472 /* Try to load using the passphrase. */
1473 if ((r = sshkey_load_private(identity_file, passphrase,
1474 &private, &comment)) != 0) {
1475 explicit_bzero(passphrase, strlen(passphrase));
1477 fatal("Cannot load private key \"%s\": %s.",
1478 identity_file, ssh_err(r));
1482 if (private->type != KEY_ED25519 && private->type != KEY_XMSS &&
1484 error("Comments are only supported for keys stored in "
1485 "the new format (-o).");
1486 explicit_bzero(passphrase, strlen(passphrase));
1487 sshkey_free(private);
1491 printf("Key now has comment '%s'\n", comment);
1493 printf("Key now has no comment\n");
1495 if (identity_comment) {
1496 strlcpy(new_comment, identity_comment, sizeof(new_comment));
1498 printf("Enter new comment: ");
1500 if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1501 explicit_bzero(passphrase, strlen(passphrase));
1502 sshkey_free(private);
1505 new_comment[strcspn(new_comment, "\n")] = '\0';
1508 /* Save the file using the new passphrase. */
1509 if ((r = sshkey_save_private(private, identity_file, passphrase,
1510 new_comment, use_new_format, new_format_cipher, rounds)) != 0) {
1511 error("Saving key \"%s\" failed: %s",
1512 identity_file, ssh_err(r));
1513 explicit_bzero(passphrase, strlen(passphrase));
1515 sshkey_free(private);
1519 explicit_bzero(passphrase, strlen(passphrase));
1521 if ((r = sshkey_from_private(private, &public)) != 0)
1522 fatal("sshkey_from_private failed: %s", ssh_err(r));
1523 sshkey_free(private);
1525 strlcat(identity_file, ".pub", sizeof(identity_file));
1526 fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1528 fatal("Could not save your public key in %s", identity_file);
1529 f = fdopen(fd, "w");
1531 fatal("fdopen %s failed: %s", identity_file, strerror(errno));
1532 if ((r = sshkey_write(public, f)) != 0)
1533 fatal("write key failed: %s", ssh_err(r));
1534 sshkey_free(public);
1535 fprintf(f, " %s\n", new_comment);
1540 printf("The comment in your key file has been changed.\n");
1545 add_flag_option(struct sshbuf *c, const char *name)
1549 debug3("%s: %s", __func__, name);
1550 if ((r = sshbuf_put_cstring(c, name)) != 0 ||
1551 (r = sshbuf_put_string(c, NULL, 0)) != 0)
1552 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1556 add_string_option(struct sshbuf *c, const char *name, const char *value)
1561 debug3("%s: %s=%s", __func__, name, value);
1562 if ((b = sshbuf_new()) == NULL)
1563 fatal("%s: sshbuf_new failed", __func__);
1564 if ((r = sshbuf_put_cstring(b, value)) != 0 ||
1565 (r = sshbuf_put_cstring(c, name)) != 0 ||
1566 (r = sshbuf_put_stringb(c, b)) != 0)
1567 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1572 #define OPTIONS_CRITICAL 1
1573 #define OPTIONS_EXTENSIONS 2
1575 prepare_options_buf(struct sshbuf *c, int which)
1580 if ((which & OPTIONS_CRITICAL) != 0 &&
1581 certflags_command != NULL)
1582 add_string_option(c, "force-command", certflags_command);
1583 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1584 (certflags_flags & CERTOPT_X_FWD) != 0)
1585 add_flag_option(c, "permit-X11-forwarding");
1586 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1587 (certflags_flags & CERTOPT_AGENT_FWD) != 0)
1588 add_flag_option(c, "permit-agent-forwarding");
1589 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1590 (certflags_flags & CERTOPT_PORT_FWD) != 0)
1591 add_flag_option(c, "permit-port-forwarding");
1592 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1593 (certflags_flags & CERTOPT_PTY) != 0)
1594 add_flag_option(c, "permit-pty");
1595 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1596 (certflags_flags & CERTOPT_USER_RC) != 0)
1597 add_flag_option(c, "permit-user-rc");
1598 if ((which & OPTIONS_CRITICAL) != 0 &&
1599 certflags_src_addr != NULL)
1600 add_string_option(c, "source-address", certflags_src_addr);
1601 for (i = 0; i < ncert_userext; i++) {
1602 if ((cert_userext[i].crit && (which & OPTIONS_EXTENSIONS)) ||
1603 (!cert_userext[i].crit && (which & OPTIONS_CRITICAL)))
1605 if (cert_userext[i].val == NULL)
1606 add_flag_option(c, cert_userext[i].key);
1608 add_string_option(c, cert_userext[i].key,
1609 cert_userext[i].val);
1614 static struct sshkey *
1615 load_pkcs11_key(char *path)
1617 #ifdef ENABLE_PKCS11
1618 struct sshkey **keys = NULL, *public, *private = NULL;
1621 if ((r = sshkey_load_public(path, &public, NULL)) != 0)
1622 fatal("Couldn't load CA public key \"%s\": %s",
1625 nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase, &keys);
1626 debug3("%s: %d keys", __func__, nkeys);
1628 fatal("cannot read public key from pkcs11");
1629 for (i = 0; i < nkeys; i++) {
1630 if (sshkey_equal_public(public, keys[i])) {
1634 sshkey_free(keys[i]);
1637 sshkey_free(public);
1640 fatal("no pkcs11 support");
1641 #endif /* ENABLE_PKCS11 */
1644 /* Signer for sshkey_certify_custom that uses the agent */
1646 agent_signer(const struct sshkey *key, u_char **sigp, size_t *lenp,
1647 const u_char *data, size_t datalen,
1648 const char *alg, u_int compat, void *ctx)
1650 int *agent_fdp = (int *)ctx;
1652 return ssh_agent_sign(*agent_fdp, key, sigp, lenp,
1653 data, datalen, alg, compat);
1657 do_ca_sign(struct passwd *pw, const char *ca_key_path, int prefer_agent,
1658 unsigned long long cert_serial, int cert_serial_autoinc,
1659 int argc, char **argv)
1661 int r, i, fd, found, agent_fd = -1;
1663 struct sshkey *ca, *public;
1664 char valid[64], *otmp, *tmp, *cp, *out, *comment, **plist = NULL;
1666 struct ssh_identitylist *agent_ids;
1669 #ifdef ENABLE_PKCS11
1672 tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
1673 if (pkcs11provider != NULL) {
1674 /* If a PKCS#11 token was specified then try to use it */
1675 if ((ca = load_pkcs11_key(tmp)) == NULL)
1676 fatal("No PKCS#11 key matching %s found", ca_key_path);
1677 } else if (prefer_agent) {
1679 * Agent signature requested. Try to use agent after making
1680 * sure the public key specified is actually present in the
1683 if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
1684 fatal("Cannot load CA public key %s: %s",
1686 if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
1687 fatal("Cannot use public key for CA signature: %s",
1689 if ((r = ssh_fetch_identitylist(agent_fd, &agent_ids)) != 0)
1690 fatal("Retrieve agent key list: %s", ssh_err(r));
1692 for (j = 0; j < agent_ids->nkeys; j++) {
1693 if (sshkey_equal(ca, agent_ids->keys[j])) {
1699 fatal("CA key %s not found in agent", tmp);
1700 ssh_free_identitylist(agent_ids);
1701 ca->flags |= SSHKEY_FLAG_EXT;
1703 /* CA key is assumed to be a private key on the filesystem */
1704 ca = load_identity(tmp);
1708 if (key_type_name != NULL &&
1709 sshkey_type_from_name(key_type_name) != ca->type) {
1710 fatal("CA key type %s doesn't match specified %s",
1711 sshkey_ssh_name(ca), key_type_name);
1714 for (i = 0; i < argc; i++) {
1715 /* Split list of principals */
1717 if (cert_principals != NULL) {
1718 otmp = tmp = xstrdup(cert_principals);
1720 for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1721 plist = xreallocarray(plist, n + 1, sizeof(*plist));
1722 if (*(plist[n] = xstrdup(cp)) == '\0')
1723 fatal("Empty principal name");
1727 if (n > SSHKEY_CERT_MAX_PRINCIPALS)
1728 fatal("Too many certificate principals specified");
1730 tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1731 if ((r = sshkey_load_public(tmp, &public, &comment)) != 0)
1732 fatal("%s: unable to open \"%s\": %s",
1733 __func__, tmp, ssh_err(r));
1734 if (public->type != KEY_RSA && public->type != KEY_DSA &&
1735 public->type != KEY_ECDSA && public->type != KEY_ED25519 &&
1736 public->type != KEY_XMSS)
1737 fatal("%s: key \"%s\" type %s cannot be certified",
1738 __func__, tmp, sshkey_type(public));
1740 /* Prepare certificate to sign */
1741 if ((r = sshkey_to_certified(public)) != 0)
1742 fatal("Could not upgrade key %s to certificate: %s",
1744 public->cert->type = cert_key_type;
1745 public->cert->serial = (u_int64_t)cert_serial;
1746 public->cert->key_id = xstrdup(cert_key_id);
1747 public->cert->nprincipals = n;
1748 public->cert->principals = plist;
1749 public->cert->valid_after = cert_valid_from;
1750 public->cert->valid_before = cert_valid_to;
1751 prepare_options_buf(public->cert->critical, OPTIONS_CRITICAL);
1752 prepare_options_buf(public->cert->extensions,
1753 OPTIONS_EXTENSIONS);
1754 if ((r = sshkey_from_private(ca,
1755 &public->cert->signature_key)) != 0)
1756 fatal("sshkey_from_private (ca key): %s", ssh_err(r));
1758 if (agent_fd != -1 && (ca->flags & SSHKEY_FLAG_EXT) != 0) {
1759 if ((r = sshkey_certify_custom(public, ca,
1760 key_type_name, agent_signer, &agent_fd)) != 0)
1761 fatal("Couldn't certify key %s via agent: %s",
1764 if ((sshkey_certify(public, ca, key_type_name)) != 0)
1765 fatal("Couldn't certify key %s: %s",
1769 if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
1771 xasprintf(&out, "%s-cert.pub", tmp);
1774 if ((fd = open(out, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
1775 fatal("Could not open \"%s\" for writing: %s", out,
1777 if ((f = fdopen(fd, "w")) == NULL)
1778 fatal("%s: fdopen: %s", __func__, strerror(errno));
1779 if ((r = sshkey_write(public, f)) != 0)
1780 fatal("Could not write certified key to %s: %s",
1782 fprintf(f, " %s\n", comment);
1786 sshkey_format_cert_validity(public->cert,
1787 valid, sizeof(valid));
1788 logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1789 "valid %s", sshkey_cert_type(public),
1790 out, public->cert->key_id,
1791 (unsigned long long)public->cert->serial,
1792 cert_principals != NULL ? " for " : "",
1793 cert_principals != NULL ? cert_principals : "",
1797 sshkey_free(public);
1799 if (cert_serial_autoinc)
1802 #ifdef ENABLE_PKCS11
1809 parse_relative_time(const char *s, time_t now)
1813 mul = *s == '-' ? -1 : 1;
1815 if ((secs = convtime(s + 1)) == -1)
1816 fatal("Invalid relative certificate time %s", s);
1817 if (mul == -1 && secs > now)
1818 fatal("Certificate time %s cannot be represented", s);
1819 return now + (u_int64_t)(secs * mul);
1823 parse_cert_times(char *timespec)
1826 time_t now = time(NULL);
1829 /* +timespec relative to now */
1830 if (*timespec == '+' && strchr(timespec, ':') == NULL) {
1831 if ((secs = convtime(timespec + 1)) == -1)
1832 fatal("Invalid relative certificate life %s", timespec);
1833 cert_valid_to = now + secs;
1835 * Backdate certificate one minute to avoid problems on hosts
1836 * with poorly-synchronised clocks.
1838 cert_valid_from = ((now - 59)/ 60) * 60;
1844 * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "always"
1845 * to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "forever"
1847 from = xstrdup(timespec);
1848 to = strchr(from, ':');
1849 if (to == NULL || from == to || *(to + 1) == '\0')
1850 fatal("Invalid certificate life specification %s", timespec);
1853 if (*from == '-' || *from == '+')
1854 cert_valid_from = parse_relative_time(from, now);
1855 else if (strcmp(from, "always") == 0)
1856 cert_valid_from = 0;
1857 else if (parse_absolute_time(from, &cert_valid_from) != 0)
1858 fatal("Invalid from time \"%s\"", from);
1860 if (*to == '-' || *to == '+')
1861 cert_valid_to = parse_relative_time(to, now);
1862 else if (strcmp(to, "forever") == 0)
1863 cert_valid_to = ~(u_int64_t)0;
1864 else if (parse_absolute_time(to, &cert_valid_to) != 0)
1865 fatal("Invalid to time \"%s\"", to);
1867 if (cert_valid_to <= cert_valid_from)
1868 fatal("Empty certificate validity interval");
1873 add_cert_option(char *opt)
1878 if (strcasecmp(opt, "clear") == 0)
1879 certflags_flags = 0;
1880 else if (strcasecmp(opt, "no-x11-forwarding") == 0)
1881 certflags_flags &= ~CERTOPT_X_FWD;
1882 else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
1883 certflags_flags |= CERTOPT_X_FWD;
1884 else if (strcasecmp(opt, "no-agent-forwarding") == 0)
1885 certflags_flags &= ~CERTOPT_AGENT_FWD;
1886 else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
1887 certflags_flags |= CERTOPT_AGENT_FWD;
1888 else if (strcasecmp(opt, "no-port-forwarding") == 0)
1889 certflags_flags &= ~CERTOPT_PORT_FWD;
1890 else if (strcasecmp(opt, "permit-port-forwarding") == 0)
1891 certflags_flags |= CERTOPT_PORT_FWD;
1892 else if (strcasecmp(opt, "no-pty") == 0)
1893 certflags_flags &= ~CERTOPT_PTY;
1894 else if (strcasecmp(opt, "permit-pty") == 0)
1895 certflags_flags |= CERTOPT_PTY;
1896 else if (strcasecmp(opt, "no-user-rc") == 0)
1897 certflags_flags &= ~CERTOPT_USER_RC;
1898 else if (strcasecmp(opt, "permit-user-rc") == 0)
1899 certflags_flags |= CERTOPT_USER_RC;
1900 else if (strncasecmp(opt, "force-command=", 14) == 0) {
1903 fatal("Empty force-command option");
1904 if (certflags_command != NULL)
1905 fatal("force-command already specified");
1906 certflags_command = xstrdup(val);
1907 } else if (strncasecmp(opt, "source-address=", 15) == 0) {
1910 fatal("Empty source-address option");
1911 if (certflags_src_addr != NULL)
1912 fatal("source-address already specified");
1913 if (addr_match_cidr_list(NULL, val) != 0)
1914 fatal("Invalid source-address list");
1915 certflags_src_addr = xstrdup(val);
1916 } else if (strncasecmp(opt, "extension:", 10) == 0 ||
1917 (iscrit = (strncasecmp(opt, "critical:", 9) == 0))) {
1918 val = xstrdup(strchr(opt, ':') + 1);
1919 if ((cp = strchr(val, '=')) != NULL)
1921 cert_userext = xreallocarray(cert_userext, ncert_userext + 1,
1922 sizeof(*cert_userext));
1923 cert_userext[ncert_userext].key = val;
1924 cert_userext[ncert_userext].val = cp == NULL ?
1926 cert_userext[ncert_userext].crit = iscrit;
1929 fatal("Unsupported certificate option \"%s\"", opt);
1933 show_options(struct sshbuf *optbuf, int in_critical)
1936 struct sshbuf *options, *option = NULL;
1939 if ((options = sshbuf_fromb(optbuf)) == NULL)
1940 fatal("%s: sshbuf_fromb failed", __func__);
1941 while (sshbuf_len(options) != 0) {
1942 sshbuf_free(option);
1944 if ((r = sshbuf_get_cstring(options, &name, NULL)) != 0 ||
1945 (r = sshbuf_froms(options, &option)) != 0)
1946 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1947 printf(" %s", name);
1949 (strcmp(name, "permit-X11-forwarding") == 0 ||
1950 strcmp(name, "permit-agent-forwarding") == 0 ||
1951 strcmp(name, "permit-port-forwarding") == 0 ||
1952 strcmp(name, "permit-pty") == 0 ||
1953 strcmp(name, "permit-user-rc") == 0))
1955 else if (in_critical &&
1956 (strcmp(name, "force-command") == 0 ||
1957 strcmp(name, "source-address") == 0)) {
1958 if ((r = sshbuf_get_cstring(option, &arg, NULL)) != 0)
1959 fatal("%s: buffer error: %s",
1960 __func__, ssh_err(r));
1961 printf(" %s\n", arg);
1964 printf(" UNKNOWN OPTION (len %zu)\n",
1965 sshbuf_len(option));
1966 sshbuf_reset(option);
1969 if (sshbuf_len(option) != 0)
1970 fatal("Option corrupt: extra data at end");
1972 sshbuf_free(option);
1973 sshbuf_free(options);
1977 print_cert(struct sshkey *key)
1979 char valid[64], *key_fp, *ca_fp;
1982 key_fp = sshkey_fingerprint(key, fingerprint_hash, SSH_FP_DEFAULT);
1983 ca_fp = sshkey_fingerprint(key->cert->signature_key,
1984 fingerprint_hash, SSH_FP_DEFAULT);
1985 if (key_fp == NULL || ca_fp == NULL)
1986 fatal("%s: sshkey_fingerprint fail", __func__);
1987 sshkey_format_cert_validity(key->cert, valid, sizeof(valid));
1989 printf(" Type: %s %s certificate\n", sshkey_ssh_name(key),
1990 sshkey_cert_type(key));
1991 printf(" Public key: %s %s\n", sshkey_type(key), key_fp);
1992 printf(" Signing CA: %s %s (using %s)\n",
1993 sshkey_type(key->cert->signature_key), ca_fp,
1994 key->cert->signature_type);
1995 printf(" Key ID: \"%s\"\n", key->cert->key_id);
1996 printf(" Serial: %llu\n", (unsigned long long)key->cert->serial);
1997 printf(" Valid: %s\n", valid);
1998 printf(" Principals: ");
1999 if (key->cert->nprincipals == 0)
2002 for (i = 0; i < key->cert->nprincipals; i++)
2004 key->cert->principals[i]);
2007 printf(" Critical Options: ");
2008 if (sshbuf_len(key->cert->critical) == 0)
2012 show_options(key->cert->critical, 1);
2014 printf(" Extensions: ");
2015 if (sshbuf_len(key->cert->extensions) == 0)
2019 show_options(key->cert->extensions, 0);
2024 do_show_cert(struct passwd *pw)
2026 struct sshkey *key = NULL;
2028 int r, is_stdin = 0, ok = 0;
2030 char *cp, *line = NULL;
2032 size_t linesize = 0;
2036 ask_filename(pw, "Enter file in which the key is");
2037 if (strcmp(identity_file, "-") != 0 && stat(identity_file, &st) < 0)
2038 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
2040 path = identity_file;
2041 if (strcmp(path, "-") == 0) {
2045 } else if ((f = fopen(identity_file, "r")) == NULL)
2046 fatal("fopen %s: %s", identity_file, strerror(errno));
2048 while (getline(&line, &linesize, f) != -1) {
2052 /* Trim leading space and comments */
2053 cp = line + strspn(line, " \t");
2054 if (*cp == '#' || *cp == '\0')
2056 if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2057 fatal("sshkey_new");
2058 if ((r = sshkey_read(key, &cp)) != 0) {
2059 error("%s:%lu: invalid key: %s", path,
2063 if (!sshkey_is_cert(key)) {
2064 error("%s:%lu is not a certificate", path, lnum);
2068 if (!is_stdin && lnum == 1)
2069 printf("%s:\n", path);
2071 printf("%s:%lu:\n", path, lnum);
2081 load_krl(const char *path, struct ssh_krl **krlp)
2083 struct sshbuf *krlbuf;
2086 if ((krlbuf = sshbuf_new()) == NULL)
2087 fatal("sshbuf_new failed");
2088 if ((fd = open(path, O_RDONLY)) == -1)
2089 fatal("open %s: %s", path, strerror(errno));
2090 if ((r = sshkey_load_file(fd, krlbuf)) != 0)
2091 fatal("Unable to load KRL: %s", ssh_err(r));
2093 /* XXX check sigs */
2094 if ((r = ssh_krl_from_blob(krlbuf, krlp, NULL, 0)) != 0 ||
2096 fatal("Invalid KRL file: %s", ssh_err(r));
2097 sshbuf_free(krlbuf);
2101 hash_to_blob(const char *cp, u_char **blobp, size_t *lenp,
2102 const char *file, u_long lnum)
2109 if (strncmp(cp, "SHA256:", 7) != 0)
2110 fatal("%s:%lu: unsupported hash algorithm", file, lnum);
2114 * OpenSSH base64 hashes omit trailing '='
2115 * characters; put them back for decode.
2118 tmp = xmalloc(tlen + 4 + 1);
2119 strlcpy(tmp, cp, tlen + 1);
2120 while ((tlen % 4) != 0) {
2124 if ((b = sshbuf_new()) == NULL)
2125 fatal("%s: sshbuf_new failed", __func__);
2126 if ((r = sshbuf_b64tod(b, tmp)) != 0)
2127 fatal("%s:%lu: decode hash failed: %s", file, lnum, ssh_err(r));
2129 *lenp = sshbuf_len(b);
2130 *blobp = xmalloc(*lenp);
2131 memcpy(*blobp, sshbuf_ptr(b), *lenp);
2136 update_krl_from_file(struct passwd *pw, const char *file, int wild_ca,
2137 const struct sshkey *ca, struct ssh_krl *krl)
2139 struct sshkey *key = NULL;
2141 char *path, *cp, *ep, *line = NULL;
2142 u_char *blob = NULL;
2143 size_t blen = 0, linesize = 0;
2144 unsigned long long serial, serial2;
2145 int i, was_explicit_key, was_sha1, was_sha256, was_hash, r;
2148 path = tilde_expand_filename(file, pw->pw_uid);
2149 if (strcmp(path, "-") == 0) {
2152 path = xstrdup("(standard input)");
2153 } else if ((krl_spec = fopen(path, "r")) == NULL)
2154 fatal("fopen %s: %s", path, strerror(errno));
2157 printf("Revoking from %s\n", path);
2158 while (getline(&line, &linesize, krl_spec) != -1) {
2160 was_explicit_key = was_sha1 = was_sha256 = was_hash = 0;
2161 cp = line + strspn(line, " \t");
2162 /* Trim trailing space, comments and strip \n */
2163 for (i = 0, r = -1; cp[i] != '\0'; i++) {
2164 if (cp[i] == '#' || cp[i] == '\n') {
2168 if (cp[i] == ' ' || cp[i] == '\t') {
2169 /* Remember the start of a span of whitespace */
2179 if (strncasecmp(cp, "serial:", 7) == 0) {
2180 if (ca == NULL && !wild_ca) {
2181 fatal("revoking certificates by serial number "
2182 "requires specification of a CA key");
2185 cp = cp + strspn(cp, " \t");
2187 serial = strtoull(cp, &ep, 0);
2188 if (*cp == '\0' || (*ep != '\0' && *ep != '-'))
2189 fatal("%s:%lu: invalid serial \"%s\"",
2191 if (errno == ERANGE && serial == ULLONG_MAX)
2192 fatal("%s:%lu: serial out of range",
2198 serial2 = strtoull(cp, &ep, 0);
2199 if (*cp == '\0' || *ep != '\0')
2200 fatal("%s:%lu: invalid serial \"%s\"",
2202 if (errno == ERANGE && serial2 == ULLONG_MAX)
2203 fatal("%s:%lu: serial out of range",
2205 if (serial2 <= serial)
2206 fatal("%s:%lu: invalid serial range "
2207 "%llu:%llu", path, lnum,
2208 (unsigned long long)serial,
2209 (unsigned long long)serial2);
2211 if (ssh_krl_revoke_cert_by_serial_range(krl,
2212 ca, serial, serial2) != 0) {
2213 fatal("%s: revoke serial failed",
2216 } else if (strncasecmp(cp, "id:", 3) == 0) {
2217 if (ca == NULL && !wild_ca) {
2218 fatal("revoking certificates by key ID "
2219 "requires specification of a CA key");
2222 cp = cp + strspn(cp, " \t");
2223 if (ssh_krl_revoke_cert_by_key_id(krl, ca, cp) != 0)
2224 fatal("%s: revoke key ID failed", __func__);
2225 } else if (strncasecmp(cp, "hash:", 5) == 0) {
2227 cp = cp + strspn(cp, " \t");
2228 hash_to_blob(cp, &blob, &blen, file, lnum);
2229 r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2231 if (strncasecmp(cp, "key:", 4) == 0) {
2233 cp = cp + strspn(cp, " \t");
2234 was_explicit_key = 1;
2235 } else if (strncasecmp(cp, "sha1:", 5) == 0) {
2237 cp = cp + strspn(cp, " \t");
2239 } else if (strncasecmp(cp, "sha256:", 7) == 0) {
2241 cp = cp + strspn(cp, " \t");
2244 * Just try to process the line as a key.
2245 * Parsing will fail if it isn't.
2248 if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2249 fatal("sshkey_new");
2250 if ((r = sshkey_read(key, &cp)) != 0)
2251 fatal("%s:%lu: invalid key: %s",
2252 path, lnum, ssh_err(r));
2253 if (was_explicit_key)
2254 r = ssh_krl_revoke_key_explicit(krl, key);
2255 else if (was_sha1) {
2256 if (sshkey_fingerprint_raw(key,
2257 SSH_DIGEST_SHA1, &blob, &blen) != 0) {
2258 fatal("%s:%lu: fingerprint failed",
2261 r = ssh_krl_revoke_key_sha1(krl, blob, blen);
2262 } else if (was_sha256) {
2263 if (sshkey_fingerprint_raw(key,
2264 SSH_DIGEST_SHA256, &blob, &blen) != 0) {
2265 fatal("%s:%lu: fingerprint failed",
2268 r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2270 r = ssh_krl_revoke_key(krl, key);
2272 fatal("%s: revoke key failed: %s",
2273 __func__, ssh_err(r));
2274 freezero(blob, blen);
2280 if (strcmp(path, "-") != 0)
2287 do_gen_krl(struct passwd *pw, int updating, const char *ca_key_path,
2288 unsigned long long krl_version, const char *krl_comment,
2289 int argc, char **argv)
2291 struct ssh_krl *krl;
2293 struct sshkey *ca = NULL;
2294 int fd, i, r, wild_ca = 0;
2296 struct sshbuf *kbuf;
2298 if (*identity_file == '\0')
2299 fatal("KRL generation requires an output file");
2300 if (stat(identity_file, &sb) == -1) {
2301 if (errno != ENOENT)
2302 fatal("Cannot access KRL \"%s\": %s",
2303 identity_file, strerror(errno));
2305 fatal("KRL \"%s\" does not exist", identity_file);
2307 if (ca_key_path != NULL) {
2308 if (strcasecmp(ca_key_path, "none") == 0)
2311 tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
2312 if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
2313 fatal("Cannot load CA public key %s: %s",
2320 load_krl(identity_file, &krl);
2321 else if ((krl = ssh_krl_init()) == NULL)
2322 fatal("couldn't create KRL");
2324 if (krl_version != 0)
2325 ssh_krl_set_version(krl, krl_version);
2326 if (krl_comment != NULL)
2327 ssh_krl_set_comment(krl, krl_comment);
2329 for (i = 0; i < argc; i++)
2330 update_krl_from_file(pw, argv[i], wild_ca, ca, krl);
2332 if ((kbuf = sshbuf_new()) == NULL)
2333 fatal("sshbuf_new failed");
2334 if (ssh_krl_to_blob(krl, kbuf, NULL, 0) != 0)
2335 fatal("Couldn't generate KRL");
2336 if ((fd = open(identity_file, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
2337 fatal("open %s: %s", identity_file, strerror(errno));
2338 if (atomicio(vwrite, fd, sshbuf_mutable_ptr(kbuf), sshbuf_len(kbuf)) !=
2340 fatal("write %s: %s", identity_file, strerror(errno));
2348 do_check_krl(struct passwd *pw, int argc, char **argv)
2352 struct ssh_krl *krl;
2355 if (*identity_file == '\0')
2356 fatal("KRL checking requires an input file");
2357 load_krl(identity_file, &krl);
2358 for (i = 0; i < argc; i++) {
2359 if ((r = sshkey_load_public(argv[i], &k, &comment)) != 0)
2360 fatal("Cannot load public key %s: %s",
2361 argv[i], ssh_err(r));
2362 r = ssh_krl_check_key(krl, k);
2363 printf("%s%s%s%s: %s\n", argv[i],
2364 *comment ? " (" : "", comment, *comment ? ")" : "",
2365 r == 0 ? "ok" : "REVOKED");
2379 "usage: ssh-keygen [-q] [-b bits] [-t dsa | ecdsa | ed25519 | rsa] [-m format]\n"
2380 " [-N new_passphrase] [-C comment] [-f output_keyfile]\n"
2381 " ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-m format]\n"
2383 " ssh-keygen -i [-m key_format] [-f input_keyfile]\n"
2384 " ssh-keygen -e [-m key_format] [-f input_keyfile]\n"
2385 " ssh-keygen -y [-f input_keyfile]\n"
2386 " ssh-keygen -c [-P passphrase] [-C comment] [-f keyfile]\n"
2387 " ssh-keygen -l [-v] [-E fingerprint_hash] [-f input_keyfile]\n"
2388 " ssh-keygen -B [-f input_keyfile]\n");
2389 #ifdef ENABLE_PKCS11
2391 " ssh-keygen -D pkcs11\n");
2394 " ssh-keygen -F hostname [-f known_hosts_file] [-l]\n"
2395 " ssh-keygen -H [-f known_hosts_file]\n"
2396 " ssh-keygen -R hostname [-f known_hosts_file]\n"
2397 " ssh-keygen -r hostname [-f input_keyfile] [-g]\n"
2399 " ssh-keygen -G output_file [-v] [-b bits] [-M memory] [-S start_point]\n"
2400 " ssh-keygen -T output_file -f input_file [-v] [-a rounds] [-J num_lines]\n"
2401 " [-j start_line] [-K checkpt] [-W generator]\n"
2403 " ssh-keygen -s ca_key -I certificate_identity [-h] [-U]\n"
2404 " [-D pkcs11_provider] [-n principals] [-O option]\n"
2405 " [-V validity_interval] [-z serial_number] file ...\n"
2406 " ssh-keygen -L [-f input_keyfile]\n"
2408 " ssh-keygen -k -f krl_file [-u] [-s ca_public] [-z version_number]\n"
2410 " ssh-keygen -Q -f krl_file file ...\n");
2415 * Main program for key management.
2418 main(int argc, char **argv)
2420 char dotsshdir[PATH_MAX], comment[1024], *passphrase1, *passphrase2;
2421 char *rr_hostname = NULL, *ep, *fp, *ra;
2422 struct sshkey *private, *public;
2425 int r, opt, type, fd;
2426 int change_passphrase = 0, change_comment = 0, show_cert = 0;
2427 int find_host = 0, delete_host = 0, hash_hosts = 0;
2428 int gen_all_hostkeys = 0, gen_krl = 0, update_krl = 0, check_krl = 0;
2429 int prefer_agent = 0, convert_to = 0, convert_from = 0;
2430 int print_public = 0, print_generic = 0, cert_serial_autoinc = 0;
2431 unsigned long long cert_serial = 0;
2432 char *identity_comment = NULL, *ca_key_path = NULL;
2436 int log_level = SYSLOG_LEVEL_INFO;
2438 /* Moduli generation/screening */
2439 char out_file[PATH_MAX], *checkpoint = NULL;
2440 u_int32_t memory = 0, generator_wanted = 0;
2441 int do_gen_candidates = 0, do_screen_candidates = 0;
2442 unsigned long start_lineno = 0, lines_to_process = 0;
2443 BIGNUM *start = NULL;
2447 extern char *optarg;
2449 ssh_malloc_init(); /* must be called before any mallocs */
2450 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
2453 __progname = ssh_get_progname(argv[0]);
2457 log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
2461 /* we need this for the home * directory. */
2462 pw = getpwuid(getuid());
2464 fatal("No user exists for uid %lu", (u_long)getuid());
2465 if (gethostname(hostname, sizeof(hostname)) < 0)
2466 fatal("gethostname: %s", strerror(errno));
2468 /* Remaining characters: Ydw */
2469 while ((opt = getopt(argc, argv, "ABHLQUXceghiklopquvxy"
2470 "C:D:E:F:G:I:J:K:M:N:O:P:R:S:T:V:W:Z:"
2471 "a:b:f:g:j:m:n:r:s:t:z:")) != -1) {
2474 gen_all_hostkeys = 1;
2477 bits = (u_int32_t)strtonum(optarg, 10, 32768, &errstr);
2479 fatal("Bits has bad value %s (%s)",
2483 fingerprint_hash = ssh_digest_alg_by_name(optarg);
2484 if (fingerprint_hash == -1)
2485 fatal("Invalid hash algorithm \"%s\"", optarg);
2489 rr_hostname = optarg;
2495 cert_key_id = optarg;
2499 rr_hostname = optarg;
2505 print_fingerprint = 1;
2508 print_bubblebabble = 1;
2511 if (strcasecmp(optarg, "RFC4716") == 0 ||
2512 strcasecmp(optarg, "ssh2") == 0) {
2513 convert_format = FMT_RFC4716;
2516 if (strcasecmp(optarg, "PKCS8") == 0) {
2517 convert_format = FMT_PKCS8;
2520 if (strcasecmp(optarg, "PEM") == 0) {
2521 convert_format = FMT_PEM;
2525 fatal("Unsupported conversion format \"%s\"", optarg);
2527 cert_principals = optarg;
2530 /* no-op; new format is already the default */
2533 change_passphrase = 1;
2539 if (strlcpy(identity_file, optarg,
2540 sizeof(identity_file)) >= sizeof(identity_file))
2541 fatal("Identity filename too long");
2548 identity_passphrase = optarg;
2551 identity_new_passphrase = optarg;
2557 add_cert_option(optarg);
2560 new_format_cipher = optarg;
2563 identity_comment = optarg;
2574 cert_key_type = SSH2_CERT_TYPE_HOST;
2575 certflags_flags = 0;
2589 ca_key_path = optarg;
2592 key_type_name = optarg;
2595 pkcs11provider = optarg;
2604 if (log_level == SYSLOG_LEVEL_INFO)
2605 log_level = SYSLOG_LEVEL_DEBUG1;
2607 if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
2608 log_level < SYSLOG_LEVEL_DEBUG3)
2613 rr_hostname = optarg;
2616 rounds = (int)strtonum(optarg, 1, INT_MAX, &errstr);
2618 fatal("Invalid number: %s (%s)",
2622 parse_cert_times(optarg);
2626 if (*optarg == '+') {
2627 cert_serial_autoinc = 1;
2630 cert_serial = strtoull(optarg, &ep, 10);
2631 if (*optarg < '0' || *optarg > '9' || *ep != '\0' ||
2632 (errno == ERANGE && cert_serial == ULLONG_MAX))
2633 fatal("Invalid serial number \"%s\"", optarg);
2636 /* Moduli generation/screening */
2638 do_gen_candidates = 1;
2639 if (strlcpy(out_file, optarg, sizeof(out_file)) >=
2641 fatal("Output filename too long");
2644 lines_to_process = strtoul(optarg, NULL, 10);
2647 start_lineno = strtoul(optarg, NULL, 10);
2650 if (strlen(optarg) >= PATH_MAX)
2651 fatal("Checkpoint filename too long");
2652 checkpoint = xstrdup(optarg);
2655 memory = (u_int32_t)strtonum(optarg, 1, UINT_MAX,
2658 fatal("Memory limit is %s: %s", errstr, optarg);
2661 /* XXX - also compare length against bits */
2662 if (BN_hex2bn(&start, optarg) == 0)
2663 fatal("Invalid start point.");
2666 do_screen_candidates = 1;
2667 if (strlcpy(out_file, optarg, sizeof(out_file)) >=
2669 fatal("Output filename too long");
2672 generator_wanted = (u_int32_t)strtonum(optarg, 1,
2675 fatal("Desired generator invalid: %s (%s)",
2678 #endif /* WITH_OPENSSL */
2686 log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
2691 if (ca_key_path != NULL) {
2692 if (argc < 1 && !gen_krl) {
2693 error("Too few arguments.");
2696 } else if (argc > 0 && !gen_krl && !check_krl) {
2697 error("Too many arguments.");
2700 if (change_passphrase && change_comment) {
2701 error("Can only have one of -p and -c.");
2704 if (print_fingerprint && (delete_host || hash_hosts)) {
2705 error("Cannot use -l with -H or -R.");
2709 do_gen_krl(pw, update_krl, ca_key_path,
2710 cert_serial, identity_comment, argc, argv);
2714 do_check_krl(pw, argc, argv);
2717 if (ca_key_path != NULL) {
2718 if (cert_key_id == NULL)
2719 fatal("Must specify key id (-I) when certifying");
2720 do_ca_sign(pw, ca_key_path, prefer_agent,
2721 cert_serial, cert_serial_autoinc, argc, argv);
2725 if (delete_host || hash_hosts || find_host) {
2726 do_known_hosts(pw, rr_hostname, find_host,
2727 delete_host, hash_hosts);
2729 if (pkcs11provider != NULL)
2731 if (print_fingerprint || print_bubblebabble)
2733 if (change_passphrase)
2734 do_change_passphrase(pw);
2736 do_change_comment(pw, identity_comment);
2741 do_convert_from(pw);
2744 do_print_public(pw);
2745 if (rr_hostname != NULL) {
2748 if (have_identity) {
2749 n = do_print_resource_record(pw, identity_file,
2750 rr_hostname, print_generic);
2752 fatal("%s: %s", identity_file, strerror(errno));
2756 n += do_print_resource_record(pw,
2757 _PATH_HOST_RSA_KEY_FILE, rr_hostname,
2759 n += do_print_resource_record(pw,
2760 _PATH_HOST_DSA_KEY_FILE, rr_hostname,
2762 n += do_print_resource_record(pw,
2763 _PATH_HOST_ECDSA_KEY_FILE, rr_hostname,
2765 n += do_print_resource_record(pw,
2766 _PATH_HOST_ED25519_KEY_FILE, rr_hostname,
2768 n += do_print_resource_record(pw,
2769 _PATH_HOST_XMSS_KEY_FILE, rr_hostname,
2772 fatal("no keys found.");
2778 if (do_gen_candidates) {
2779 FILE *out = fopen(out_file, "w");
2782 error("Couldn't open modulus candidate file \"%s\": %s",
2783 out_file, strerror(errno));
2787 bits = DEFAULT_BITS;
2788 if (gen_candidates(out, memory, bits, start) != 0)
2789 fatal("modulus candidate generation failed");
2794 if (do_screen_candidates) {
2796 FILE *out = fopen(out_file, "a");
2798 if (have_identity && strcmp(identity_file, "-") != 0) {
2799 if ((in = fopen(identity_file, "r")) == NULL) {
2800 fatal("Couldn't open modulus candidate "
2801 "file \"%s\": %s", identity_file,
2808 fatal("Couldn't open moduli file \"%s\": %s",
2809 out_file, strerror(errno));
2811 if (prime_test(in, out, rounds == 0 ? 100 : rounds,
2812 generator_wanted, checkpoint,
2813 start_lineno, lines_to_process) != 0)
2814 fatal("modulus screening failed");
2819 if (gen_all_hostkeys) {
2820 do_gen_all_hostkeys(pw);
2824 if (key_type_name == NULL)
2825 key_type_name = DEFAULT_KEY_TYPE_NAME;
2827 type = sshkey_type_from_name(key_type_name);
2828 type_bits_valid(type, key_type_name, &bits);
2831 printf("Generating public/private %s key pair.\n",
2833 if ((r = sshkey_generate(type, bits, &private)) != 0)
2834 fatal("sshkey_generate failed");
2835 if ((r = sshkey_from_private(private, &public)) != 0)
2836 fatal("sshkey_from_private failed: %s\n", ssh_err(r));
2839 ask_filename(pw, "Enter file in which to save the key");
2841 /* Create ~/.ssh directory if it doesn't already exist. */
2842 snprintf(dotsshdir, sizeof dotsshdir, "%s/%s",
2843 pw->pw_dir, _PATH_SSH_USER_DIR);
2844 if (strstr(identity_file, dotsshdir) != NULL) {
2845 if (stat(dotsshdir, &st) < 0) {
2846 if (errno != ENOENT) {
2847 error("Could not stat %s: %s", dotsshdir,
2849 } else if (mkdir(dotsshdir, 0700) < 0) {
2850 error("Could not create directory '%s': %s",
2851 dotsshdir, strerror(errno));
2853 printf("Created directory '%s'.\n", dotsshdir);
2856 /* If the file already exists, ask the user to confirm. */
2857 if (stat(identity_file, &st) >= 0) {
2859 printf("%s already exists.\n", identity_file);
2860 printf("Overwrite (y/n)? ");
2862 if (fgets(yesno, sizeof(yesno), stdin) == NULL)
2864 if (yesno[0] != 'y' && yesno[0] != 'Y')
2867 /* Ask for a passphrase (twice). */
2868 if (identity_passphrase)
2869 passphrase1 = xstrdup(identity_passphrase);
2870 else if (identity_new_passphrase)
2871 passphrase1 = xstrdup(identity_new_passphrase);
2875 read_passphrase("Enter passphrase (empty for no "
2876 "passphrase): ", RP_ALLOW_STDIN);
2877 passphrase2 = read_passphrase("Enter same passphrase again: ",
2879 if (strcmp(passphrase1, passphrase2) != 0) {
2881 * The passphrases do not match. Clear them and
2884 explicit_bzero(passphrase1, strlen(passphrase1));
2885 explicit_bzero(passphrase2, strlen(passphrase2));
2888 printf("Passphrases do not match. Try again.\n");
2889 goto passphrase_again;
2891 /* Clear the other copy of the passphrase. */
2892 explicit_bzero(passphrase2, strlen(passphrase2));
2896 if (identity_comment) {
2897 strlcpy(comment, identity_comment, sizeof(comment));
2899 /* Create default comment field for the passphrase. */
2900 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
2903 /* Save the key with the given passphrase and comment. */
2904 if ((r = sshkey_save_private(private, identity_file, passphrase1,
2905 comment, use_new_format, new_format_cipher, rounds)) != 0) {
2906 error("Saving key \"%s\" failed: %s",
2907 identity_file, ssh_err(r));
2908 explicit_bzero(passphrase1, strlen(passphrase1));
2912 /* Clear the passphrase. */
2913 explicit_bzero(passphrase1, strlen(passphrase1));
2916 /* Clear the private key and the random number generator. */
2917 sshkey_free(private);
2920 printf("Your identification has been saved in %s.\n", identity_file);
2922 strlcat(identity_file, ".pub", sizeof(identity_file));
2923 if ((fd = open(identity_file, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
2924 fatal("Unable to save public key to %s: %s",
2925 identity_file, strerror(errno));
2926 if ((f = fdopen(fd, "w")) == NULL)
2927 fatal("fdopen %s failed: %s", identity_file, strerror(errno));
2928 if ((r = sshkey_write(public, f)) != 0)
2929 error("write key failed: %s", ssh_err(r));
2930 fprintf(f, " %s\n", comment);
2931 if (ferror(f) || fclose(f) != 0)
2932 fatal("write public failed: %s", strerror(errno));
2935 fp = sshkey_fingerprint(public, fingerprint_hash,
2937 ra = sshkey_fingerprint(public, fingerprint_hash,
2939 if (fp == NULL || ra == NULL)
2940 fatal("sshkey_fingerprint failed");
2941 printf("Your public key has been saved in %s.\n",
2943 printf("The key fingerprint is:\n");
2944 printf("%s %s\n", fp, comment);
2945 printf("The key's randomart image is:\n");
2951 sshkey_free(public);