1 /* $OpenBSD: ssh-keygen.c,v 1.459 2022/08/11 01:56:51 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1994 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * Identity and host key generation and maintenance.
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose. Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
17 #include <sys/types.h>
18 #include <sys/socket.h>
22 #include <openssl/evp.h>
23 #include <openssl/pem.h>
24 #include "openbsd-compat/openssl-compat.h"
50 #include "pathnames.h"
59 #include "ssh-pkcs11.h"
67 #include "sk-api.h" /* XXX for SSH_SK_USER_PRESENCE_REQD; remove */
71 # define DEFAULT_KEY_TYPE_NAME "rsa"
73 # define DEFAULT_KEY_TYPE_NAME "ed25519"
77 * Default number of bits in the RSA, DSA and ECDSA keys. These value can be
78 * overridden on the command line.
80 * These values, with the exception of DSA, provide security equivalent to at
81 * least 128 bits of security according to NIST Special Publication 800-57:
82 * Recommendation for Key Management Part 1 rev 4 section 5.6.1.
83 * For DSA it (and FIPS-186-4 section 4.2) specifies that the only size for
84 * which a 160bit hash is acceptable is 1kbit, and since ssh-dss specifies only
85 * SHA1 we limit the DSA key size 1k bits.
87 #define DEFAULT_BITS 3072
88 #define DEFAULT_BITS_DSA 1024
89 #define DEFAULT_BITS_ECDSA 256
93 /* Flag indicating that we just want to see the key fingerprint */
94 static int print_fingerprint = 0;
95 static int print_bubblebabble = 0;
97 /* Hash algorithm to use for fingerprints. */
98 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
100 /* The identity file name, given on the command line or entered by the user. */
101 static char identity_file[PATH_MAX];
102 static int have_identity = 0;
104 /* This is set to the passphrase if given on the command line. */
105 static char *identity_passphrase = NULL;
107 /* This is set to the new passphrase if given on the command line. */
108 static char *identity_new_passphrase = NULL;
110 /* Key type when certifying */
111 static u_int cert_key_type = SSH2_CERT_TYPE_USER;
113 /* "key ID" of signed key */
114 static char *cert_key_id = NULL;
116 /* Comma-separated list of principal names for certifying keys */
117 static char *cert_principals = NULL;
119 /* Validity period for certificates */
120 static u_int64_t cert_valid_from = 0;
121 static u_int64_t cert_valid_to = ~0ULL;
123 /* Certificate options */
124 #define CERTOPT_X_FWD (1)
125 #define CERTOPT_AGENT_FWD (1<<1)
126 #define CERTOPT_PORT_FWD (1<<2)
127 #define CERTOPT_PTY (1<<3)
128 #define CERTOPT_USER_RC (1<<4)
129 #define CERTOPT_NO_REQUIRE_USER_PRESENCE (1<<5)
130 #define CERTOPT_REQUIRE_VERIFY (1<<6)
131 #define CERTOPT_DEFAULT (CERTOPT_X_FWD|CERTOPT_AGENT_FWD| \
132 CERTOPT_PORT_FWD|CERTOPT_PTY|CERTOPT_USER_RC)
133 static u_int32_t certflags_flags = CERTOPT_DEFAULT;
134 static char *certflags_command = NULL;
135 static char *certflags_src_addr = NULL;
137 /* Arbitrary extensions specified by user */
143 static struct cert_ext *cert_ext;
144 static size_t ncert_ext;
146 /* Conversion to/from various formats */
151 } convert_format = FMT_RFC4716;
153 static char *key_type_name = NULL;
155 /* Load key from this PKCS#11 provider */
156 static char *pkcs11provider = NULL;
158 /* FIDO/U2F provider to use */
159 static char *sk_provider = NULL;
161 /* Format for writing private keys */
162 static int private_key_format = SSHKEY_PRIVATE_OPENSSH;
164 /* Cipher for new-format private keys */
165 static char *openssh_format_cipher = NULL;
167 /* Number of KDF rounds to derive new format keys. */
168 static int rounds = 0;
171 extern char *__progname;
173 static char hostname[NI_MAXHOST];
177 int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
178 int prime_test(FILE *, FILE *, u_int32_t, u_int32_t, char *, unsigned long,
183 type_bits_valid(int type, const char *name, u_int32_t *bitsp)
185 if (type == KEY_UNSPEC)
186 fatal("unknown key type %s", key_type_name);
193 *bitsp = DEFAULT_BITS_DSA;
197 (nid = sshkey_ecdsa_nid_from_name(name)) > 0)
198 *bitsp = sshkey_curve_nid_to_bits(nid);
200 *bitsp = DEFAULT_BITS_ECDSA;
203 *bitsp = DEFAULT_BITS;
212 fatal("Invalid DSA key length: must be 1024 bits");
215 if (*bitsp < SSH_RSA_MINIMUM_MODULUS_SIZE)
216 fatal("Invalid RSA key length: minimum is %d bits",
217 SSH_RSA_MINIMUM_MODULUS_SIZE);
218 else if (*bitsp > OPENSSL_RSA_MAX_MODULUS_BITS)
219 fatal("Invalid RSA key length: maximum is %d bits",
220 OPENSSL_RSA_MAX_MODULUS_BITS);
223 if (sshkey_ecdsa_bits_to_nid(*bitsp) == -1)
224 #ifdef OPENSSL_HAS_NISTP521
225 fatal("Invalid ECDSA key length: valid lengths are "
226 "256, 384 or 521 bits");
228 fatal("Invalid ECDSA key length: valid lengths are "
236 * Checks whether a file exists and, if so, asks the user whether they wish
238 * Returns nonzero if the file does not already exist or if the user agrees to
239 * overwrite, or zero otherwise.
242 confirm_overwrite(const char *filename)
247 if (stat(filename, &st) != 0)
249 printf("%s already exists.\n", filename);
250 printf("Overwrite (y/n)? ");
252 if (fgets(yesno, sizeof(yesno), stdin) == NULL)
254 if (yesno[0] != 'y' && yesno[0] != 'Y')
260 ask_filename(struct passwd *pw, const char *prompt)
265 if (key_type_name == NULL)
266 name = _PATH_SSH_CLIENT_ID_RSA;
268 switch (sshkey_type_from_name(key_type_name)) {
271 name = _PATH_SSH_CLIENT_ID_DSA;
273 #ifdef OPENSSL_HAS_ECC
276 name = _PATH_SSH_CLIENT_ID_ECDSA;
278 case KEY_ECDSA_SK_CERT:
280 name = _PATH_SSH_CLIENT_ID_ECDSA_SK;
285 name = _PATH_SSH_CLIENT_ID_RSA;
288 case KEY_ED25519_CERT:
289 name = _PATH_SSH_CLIENT_ID_ED25519;
292 case KEY_ED25519_SK_CERT:
293 name = _PATH_SSH_CLIENT_ID_ED25519_SK;
297 name = _PATH_SSH_CLIENT_ID_XMSS;
300 fatal("bad key type");
303 snprintf(identity_file, sizeof(identity_file),
304 "%s/%s", pw->pw_dir, name);
305 printf("%s (%s): ", prompt, identity_file);
307 if (fgets(buf, sizeof(buf), stdin) == NULL)
309 buf[strcspn(buf, "\n")] = '\0';
310 if (strcmp(buf, "") != 0)
311 strlcpy(identity_file, buf, sizeof(identity_file));
315 static struct sshkey *
316 load_identity(const char *filename, char **commentp)
322 if (commentp != NULL)
324 if ((r = sshkey_load_private(filename, "", &prv, commentp)) == 0)
326 if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
327 fatal_r(r, "Load key \"%s\"", filename);
328 if (identity_passphrase)
329 pass = xstrdup(identity_passphrase);
331 pass = read_passphrase("Enter passphrase: ", RP_ALLOW_STDIN);
332 r = sshkey_load_private(filename, pass, &prv, commentp);
333 freezero(pass, strlen(pass));
335 fatal_r(r, "Load key \"%s\"", filename);
339 #define SSH_COM_PUBLIC_BEGIN "---- BEGIN SSH2 PUBLIC KEY ----"
340 #define SSH_COM_PUBLIC_END "---- END SSH2 PUBLIC KEY ----"
341 #define SSH_COM_PRIVATE_BEGIN "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
342 #define SSH_COM_PRIVATE_KEY_MAGIC 0x3f6ff9eb
346 do_convert_to_ssh2(struct passwd *pw, struct sshkey *k)
349 char comment[61], *b64;
352 if ((b = sshbuf_new()) == NULL)
353 fatal_f("sshbuf_new failed");
354 if ((r = sshkey_putb(k, b)) != 0)
355 fatal_fr(r, "put key");
356 if ((b64 = sshbuf_dtob64_string(b, 1)) == NULL)
357 fatal_f("sshbuf_dtob64_string failed");
359 /* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
360 snprintf(comment, sizeof(comment),
361 "%u-bit %s, converted by %s@%s from OpenSSH",
362 sshkey_size(k), sshkey_type(k),
363 pw->pw_name, hostname);
368 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
369 fprintf(stdout, "Comment: \"%s\"\n%s", comment, b64);
370 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
376 do_convert_to_pkcs8(struct sshkey *k)
378 switch (sshkey_type_plain(k->type)) {
380 if (!PEM_write_RSA_PUBKEY(stdout, k->rsa))
381 fatal("PEM_write_RSA_PUBKEY failed");
384 if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
385 fatal("PEM_write_DSA_PUBKEY failed");
387 #ifdef OPENSSL_HAS_ECC
389 if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
390 fatal("PEM_write_EC_PUBKEY failed");
394 fatal_f("unsupported key type %s", sshkey_type(k));
400 do_convert_to_pem(struct sshkey *k)
402 switch (sshkey_type_plain(k->type)) {
404 if (!PEM_write_RSAPublicKey(stdout, k->rsa))
405 fatal("PEM_write_RSAPublicKey failed");
408 if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
409 fatal("PEM_write_DSA_PUBKEY failed");
411 #ifdef OPENSSL_HAS_ECC
413 if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
414 fatal("PEM_write_EC_PUBKEY failed");
418 fatal_f("unsupported key type %s", sshkey_type(k));
424 do_convert_to(struct passwd *pw)
431 ask_filename(pw, "Enter file in which the key is");
432 if (stat(identity_file, &st) == -1)
433 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
434 if ((r = sshkey_load_public(identity_file, &k, NULL)) != 0)
435 k = load_identity(identity_file, NULL);
436 switch (convert_format) {
438 do_convert_to_ssh2(pw, k);
441 do_convert_to_pkcs8(k);
444 do_convert_to_pem(k);
447 fatal_f("unknown key format %d", convert_format);
453 * This is almost exactly the bignum1 encoding, but with 32 bit for length
457 buffer_get_bignum_bits(struct sshbuf *b, BIGNUM *value)
459 u_int bytes, bignum_bits;
462 if ((r = sshbuf_get_u32(b, &bignum_bits)) != 0)
463 fatal_fr(r, "parse");
464 bytes = (bignum_bits + 7) / 8;
465 if (sshbuf_len(b) < bytes)
466 fatal_f("input buffer too small: need %d have %zu",
467 bytes, sshbuf_len(b));
468 if (BN_bin2bn(sshbuf_ptr(b), bytes, value) == NULL)
469 fatal_f("BN_bin2bn failed");
470 if ((r = sshbuf_consume(b, bytes)) != 0)
471 fatal_fr(r, "consume");
474 static struct sshkey *
475 do_convert_private_ssh2(struct sshbuf *b)
477 struct sshkey *key = NULL;
479 u_char e1, e2, e3, *sig = NULL, data[] = "abcde12345";
481 u_int magic, i1, i2, i3, i4;
484 BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL;
485 BIGNUM *dsa_pub_key = NULL, *dsa_priv_key = NULL;
486 BIGNUM *rsa_n = NULL, *rsa_e = NULL, *rsa_d = NULL;
487 BIGNUM *rsa_p = NULL, *rsa_q = NULL, *rsa_iqmp = NULL;
489 if ((r = sshbuf_get_u32(b, &magic)) != 0)
490 fatal_fr(r, "parse magic");
492 if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
493 error("bad magic 0x%x != 0x%x", magic,
494 SSH_COM_PRIVATE_KEY_MAGIC);
497 if ((r = sshbuf_get_u32(b, &i1)) != 0 ||
498 (r = sshbuf_get_cstring(b, &type, NULL)) != 0 ||
499 (r = sshbuf_get_cstring(b, &cipher, NULL)) != 0 ||
500 (r = sshbuf_get_u32(b, &i2)) != 0 ||
501 (r = sshbuf_get_u32(b, &i3)) != 0 ||
502 (r = sshbuf_get_u32(b, &i4)) != 0)
503 fatal_fr(r, "parse");
504 debug("ignore (%d %d %d %d)", i1, i2, i3, i4);
505 if (strcmp(cipher, "none") != 0) {
506 error("unsupported cipher %s", cipher);
513 if (strstr(type, "dsa")) {
515 } else if (strstr(type, "rsa")) {
521 if ((key = sshkey_new(ktype)) == NULL)
522 fatal("sshkey_new failed");
527 if ((dsa_p = BN_new()) == NULL ||
528 (dsa_q = BN_new()) == NULL ||
529 (dsa_g = BN_new()) == NULL ||
530 (dsa_pub_key = BN_new()) == NULL ||
531 (dsa_priv_key = BN_new()) == NULL)
533 buffer_get_bignum_bits(b, dsa_p);
534 buffer_get_bignum_bits(b, dsa_g);
535 buffer_get_bignum_bits(b, dsa_q);
536 buffer_get_bignum_bits(b, dsa_pub_key);
537 buffer_get_bignum_bits(b, dsa_priv_key);
538 if (!DSA_set0_pqg(key->dsa, dsa_p, dsa_q, dsa_g))
539 fatal_f("DSA_set0_pqg failed");
540 dsa_p = dsa_q = dsa_g = NULL; /* transferred */
541 if (!DSA_set0_key(key->dsa, dsa_pub_key, dsa_priv_key))
542 fatal_f("DSA_set0_key failed");
543 dsa_pub_key = dsa_priv_key = NULL; /* transferred */
546 if ((r = sshbuf_get_u8(b, &e1)) != 0 ||
547 (e1 < 30 && (r = sshbuf_get_u8(b, &e2)) != 0) ||
548 (e1 < 30 && (r = sshbuf_get_u8(b, &e3)) != 0))
549 fatal_fr(r, "parse RSA");
560 if ((rsa_e = BN_new()) == NULL)
562 if (!BN_set_word(rsa_e, e)) {
563 BN_clear_free(rsa_e);
567 if ((rsa_n = BN_new()) == NULL ||
568 (rsa_d = BN_new()) == NULL ||
569 (rsa_p = BN_new()) == NULL ||
570 (rsa_q = BN_new()) == NULL ||
571 (rsa_iqmp = BN_new()) == NULL)
573 buffer_get_bignum_bits(b, rsa_d);
574 buffer_get_bignum_bits(b, rsa_n);
575 buffer_get_bignum_bits(b, rsa_iqmp);
576 buffer_get_bignum_bits(b, rsa_q);
577 buffer_get_bignum_bits(b, rsa_p);
578 if (!RSA_set0_key(key->rsa, rsa_n, rsa_e, rsa_d))
579 fatal_f("RSA_set0_key failed");
580 rsa_n = rsa_e = rsa_d = NULL; /* transferred */
581 if (!RSA_set0_factors(key->rsa, rsa_p, rsa_q))
582 fatal_f("RSA_set0_factors failed");
583 rsa_p = rsa_q = NULL; /* transferred */
584 if ((r = ssh_rsa_complete_crt_parameters(key, rsa_iqmp)) != 0)
585 fatal_fr(r, "generate RSA parameters");
586 BN_clear_free(rsa_iqmp);
589 rlen = sshbuf_len(b);
591 error_f("remaining bytes in key blob %d", rlen);
594 if ((r = sshkey_sign(key, &sig, &slen, data, sizeof(data),
595 NULL, NULL, NULL, 0)) != 0)
596 error_fr(r, "signing with converted key failed");
597 else if ((r = sshkey_verify(key, sig, slen, data, sizeof(data),
598 NULL, 0, NULL)) != 0)
599 error_fr(r, "verification with converted key failed");
610 get_line(FILE *fp, char *line, size_t len)
616 while ((c = fgetc(fp)) != EOF) {
618 fatal("input line too long.");
622 if (c != EOF && c != '\n' && ungetc(c, fp) == EOF)
623 fatal("unget: %s", strerror(errno));
636 do_convert_from_ssh2(struct passwd *pw, struct sshkey **k, int *private)
638 int r, blen, escaped = 0;
645 if ((buf = sshbuf_new()) == NULL)
646 fatal("sshbuf_new failed");
647 if ((fp = fopen(identity_file, "r")) == NULL)
648 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
650 while ((blen = get_line(fp, line, sizeof(line))) != -1) {
651 if (blen > 0 && line[blen - 1] == '\\')
653 if (strncmp(line, "----", 4) == 0 ||
654 strstr(line, ": ") != NULL) {
655 if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
657 if (strstr(line, " END ") != NULL) {
660 /* fprintf(stderr, "ignore: %s", line); */
665 /* fprintf(stderr, "escaped: %s", line); */
668 strlcat(encoded, line, sizeof(encoded));
670 len = strlen(encoded);
671 if (((len % 4) == 3) &&
672 (encoded[len-1] == '=') &&
673 (encoded[len-2] == '=') &&
674 (encoded[len-3] == '='))
675 encoded[len-3] = '\0';
676 if ((r = sshbuf_b64tod(buf, encoded)) != 0)
677 fatal_fr(r, "base64 decode");
679 if ((*k = do_convert_private_ssh2(buf)) == NULL)
680 fatal_f("private key conversion failed");
681 } else if ((r = sshkey_fromb(buf, k)) != 0)
682 fatal_fr(r, "parse key");
688 do_convert_from_pkcs8(struct sshkey **k, int *private)
693 if ((fp = fopen(identity_file, "r")) == NULL)
694 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
695 if ((pubkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL)) == NULL) {
696 fatal_f("%s is not a recognised public key format",
700 switch (EVP_PKEY_base_id(pubkey)) {
702 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
703 fatal("sshkey_new failed");
704 (*k)->type = KEY_RSA;
705 (*k)->rsa = EVP_PKEY_get1_RSA(pubkey);
708 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
709 fatal("sshkey_new failed");
710 (*k)->type = KEY_DSA;
711 (*k)->dsa = EVP_PKEY_get1_DSA(pubkey);
713 #ifdef OPENSSL_HAS_ECC
715 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
716 fatal("sshkey_new failed");
717 (*k)->type = KEY_ECDSA;
718 (*k)->ecdsa = EVP_PKEY_get1_EC_KEY(pubkey);
719 (*k)->ecdsa_nid = sshkey_ecdsa_key_to_nid((*k)->ecdsa);
723 fatal_f("unsupported pubkey type %d",
724 EVP_PKEY_base_id(pubkey));
726 EVP_PKEY_free(pubkey);
731 do_convert_from_pem(struct sshkey **k, int *private)
736 if ((fp = fopen(identity_file, "r")) == NULL)
737 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
738 if ((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
739 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
740 fatal("sshkey_new failed");
741 (*k)->type = KEY_RSA;
746 fatal_f("unrecognised raw private key format");
750 do_convert_from(struct passwd *pw)
752 struct sshkey *k = NULL;
753 int r, private = 0, ok = 0;
757 ask_filename(pw, "Enter file in which the key is");
758 if (stat(identity_file, &st) == -1)
759 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
761 switch (convert_format) {
763 do_convert_from_ssh2(pw, &k, &private);
766 do_convert_from_pkcs8(&k, &private);
769 do_convert_from_pem(&k, &private);
772 fatal_f("unknown key format %d", convert_format);
776 if ((r = sshkey_write(k, stdout)) == 0)
779 fprintf(stdout, "\n");
783 ok = PEM_write_DSAPrivateKey(stdout, k->dsa, NULL,
784 NULL, 0, NULL, NULL);
786 #ifdef OPENSSL_HAS_ECC
788 ok = PEM_write_ECPrivateKey(stdout, k->ecdsa, NULL,
789 NULL, 0, NULL, NULL);
793 ok = PEM_write_RSAPrivateKey(stdout, k->rsa, NULL,
794 NULL, 0, NULL, NULL);
797 fatal_f("unsupported key type %s", sshkey_type(k));
802 fatal("key write failed");
809 do_print_public(struct passwd *pw)
814 char *comment = NULL;
817 ask_filename(pw, "Enter file in which the key is");
818 if (stat(identity_file, &st) == -1)
819 fatal("%s: %s", identity_file, strerror(errno));
820 prv = load_identity(identity_file, &comment);
821 if ((r = sshkey_write(prv, stdout)) != 0)
822 fatal_fr(r, "write key");
823 if (comment != NULL && *comment != '\0')
824 fprintf(stdout, " %s", comment);
825 fprintf(stdout, "\n");
826 if (sshkey_is_sk(prv)) {
827 debug("sk_application: \"%s\", sk_flags 0x%02x",
828 prv->sk_application, prv->sk_flags);
836 do_download(struct passwd *pw)
839 struct sshkey **keys = NULL;
841 enum sshkey_fp_rep rep;
843 char *fp, *ra, **comments = NULL;
845 fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
846 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
849 nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys, &comments);
851 fatal("cannot read public key from pkcs11");
852 for (i = 0; i < nkeys; i++) {
853 if (print_fingerprint) {
854 fp = sshkey_fingerprint(keys[i], fptype, rep);
855 ra = sshkey_fingerprint(keys[i], fingerprint_hash,
857 if (fp == NULL || ra == NULL)
858 fatal_f("sshkey_fingerprint fail");
859 printf("%u %s %s (PKCS11 key)\n", sshkey_size(keys[i]),
860 fp, sshkey_type(keys[i]));
861 if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
866 (void) sshkey_write(keys[i], stdout); /* XXX check */
867 fprintf(stdout, "%s%s\n",
868 *(comments[i]) == '\0' ? "" : " ", comments[i]);
871 sshkey_free(keys[i]);
878 fatal("no pkcs11 support");
879 #endif /* ENABLE_PKCS11 */
882 static struct sshkey *
883 try_read_key(char **cpp)
888 if ((ret = sshkey_new(KEY_UNSPEC)) == NULL)
889 fatal("sshkey_new failed");
890 if ((r = sshkey_read(ret, cpp)) == 0)
898 fingerprint_one_key(const struct sshkey *public, const char *comment)
900 char *fp = NULL, *ra = NULL;
901 enum sshkey_fp_rep rep;
904 fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
905 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
906 fp = sshkey_fingerprint(public, fptype, rep);
907 ra = sshkey_fingerprint(public, fingerprint_hash, SSH_FP_RANDOMART);
908 if (fp == NULL || ra == NULL)
909 fatal_f("sshkey_fingerprint failed");
910 mprintf("%u %s %s (%s)\n", sshkey_size(public), fp,
911 comment ? comment : "no comment", sshkey_type(public));
912 if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
919 fingerprint_private(const char *path)
922 char *comment = NULL;
923 struct sshkey *privkey = NULL, *pubkey = NULL;
926 if (stat(identity_file, &st) == -1)
927 fatal("%s: %s", path, strerror(errno));
928 if ((r = sshkey_load_public(path, &pubkey, &comment)) != 0)
929 debug_r(r, "load public \"%s\"", path);
930 if (pubkey == NULL || comment == NULL || *comment == '\0') {
932 if ((r = sshkey_load_private(path, NULL,
933 &privkey, &comment)) != 0)
934 debug_r(r, "load private \"%s\"", path);
936 if (pubkey == NULL && privkey == NULL)
937 fatal("%s is not a key file.", path);
939 fingerprint_one_key(pubkey == NULL ? privkey : pubkey, comment);
941 sshkey_free(privkey);
946 do_fingerprint(struct passwd *pw)
949 struct sshkey *public = NULL;
950 char *comment = NULL, *cp, *ep, *line = NULL;
957 ask_filename(pw, "Enter file in which the key is");
958 path = identity_file;
960 if (strcmp(identity_file, "-") == 0) {
963 } else if ((f = fopen(path, "r")) == NULL)
964 fatal("%s: %s: %s", __progname, path, strerror(errno));
966 while (getline(&line, &linesize, f) != -1) {
969 cp[strcspn(cp, "\n")] = '\0';
970 /* Trim leading space and comments */
971 cp = line + strspn(line, " \t");
972 if (*cp == '#' || *cp == '\0')
976 * Input may be plain keys, private keys, authorized_keys
981 * Try private keys first. Assume a key is private if
982 * "SSH PRIVATE KEY" appears on the first line and we're
983 * not reading from stdin (XXX support private keys on stdin).
985 if (lnum == 1 && strcmp(identity_file, "-") != 0 &&
986 strstr(cp, "PRIVATE KEY") != NULL) {
989 fingerprint_private(path);
994 * If it's not a private key, then this must be prepared to
995 * accept a public key prefixed with a hostname or options.
996 * Try a bare key first, otherwise skip the leading stuff.
998 if ((public = try_read_key(&cp)) == NULL) {
999 i = strtol(cp, &ep, 10);
1000 if (i == 0 || ep == NULL ||
1001 (*ep != ' ' && *ep != '\t')) {
1005 for (; *cp && (quoted || (*cp != ' ' &&
1006 *cp != '\t')); cp++) {
1007 if (*cp == '\\' && cp[1] == '"')
1008 cp++; /* Skip both */
1009 else if (*cp == '"')
1017 /* Retry after parsing leading hostname/key options */
1018 if (public == NULL && (public = try_read_key(&cp)) == NULL) {
1019 debug("%s:%lu: not a public key", path, lnum);
1023 /* Find trailing comment, if any */
1024 for (; *cp == ' ' || *cp == '\t'; cp++)
1026 if (*cp != '\0' && *cp != '#')
1029 fingerprint_one_key(public, comment);
1030 sshkey_free(public);
1031 invalid = 0; /* One good key in the file is sufficient */
1037 fatal("%s is not a public key file.", path);
1042 do_gen_all_hostkeys(struct passwd *pw)
1046 char *key_type_display;
1050 { "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE },
1051 #ifdef OPENSSL_HAS_ECC
1052 { "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE },
1053 #endif /* OPENSSL_HAS_ECC */
1054 #endif /* WITH_OPENSSL */
1055 { "ed25519", "ED25519",_PATH_HOST_ED25519_KEY_FILE },
1057 { "xmss", "XMSS",_PATH_HOST_XMSS_KEY_FILE },
1058 #endif /* WITH_XMSS */
1059 { NULL, NULL, NULL }
1065 struct sshkey *private, *public;
1066 char comment[1024], *prv_tmp, *pub_tmp, *prv_file, *pub_file;
1069 for (i = 0; key_types[i].key_type; i++) {
1070 public = private = NULL;
1071 prv_tmp = pub_tmp = prv_file = pub_file = NULL;
1073 xasprintf(&prv_file, "%s%s",
1074 identity_file, key_types[i].path);
1076 /* Check whether private key exists and is not zero-length */
1077 if (stat(prv_file, &st) == 0) {
1078 if (st.st_size != 0)
1080 } else if (errno != ENOENT) {
1081 error("Could not stat %s: %s", key_types[i].path,
1087 * Private key doesn't exist or is invalid; proceed with
1090 xasprintf(&prv_tmp, "%s%s.XXXXXXXXXX",
1091 identity_file, key_types[i].path);
1092 xasprintf(&pub_tmp, "%s%s.pub.XXXXXXXXXX",
1093 identity_file, key_types[i].path);
1094 xasprintf(&pub_file, "%s%s.pub",
1095 identity_file, key_types[i].path);
1099 printf("%s: generating new host keys: ", __progname);
1101 printf("%s ", key_types[i].key_type_display);
1103 type = sshkey_type_from_name(key_types[i].key_type);
1104 if ((fd = mkstemp(prv_tmp)) == -1) {
1105 error("Could not save your private key in %s: %s",
1106 prv_tmp, strerror(errno));
1109 (void)close(fd); /* just using mkstemp() to reserve a name */
1111 type_bits_valid(type, NULL, &bits);
1112 if ((r = sshkey_generate(type, bits, &private)) != 0) {
1113 error_r(r, "sshkey_generate failed");
1116 if ((r = sshkey_from_private(private, &public)) != 0)
1117 fatal_fr(r, "sshkey_from_private");
1118 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name,
1120 if ((r = sshkey_save_private(private, prv_tmp, "",
1121 comment, private_key_format, openssh_format_cipher,
1123 error_r(r, "Saving key \"%s\" failed", prv_tmp);
1126 if ((fd = mkstemp(pub_tmp)) == -1) {
1127 error("Could not save your public key in %s: %s",
1128 pub_tmp, strerror(errno));
1131 (void)fchmod(fd, 0644);
1133 if ((r = sshkey_save_public(public, pub_tmp, comment)) != 0) {
1134 error_r(r, "Unable to save public key to %s",
1139 /* Rename temporary files to their permanent locations. */
1140 if (rename(pub_tmp, pub_file) != 0) {
1141 error("Unable to move %s into position: %s",
1142 pub_file, strerror(errno));
1145 if (rename(prv_tmp, prv_file) != 0) {
1146 error("Unable to move %s into position: %s",
1147 key_types[i].path, strerror(errno));
1153 sshkey_free(private);
1154 sshkey_free(public);
1164 struct known_hosts_ctx {
1165 const char *host; /* Hostname searched for in find/delete case */
1166 FILE *out; /* Output file, stdout for find_hosts case */
1167 int has_unhashed; /* When hashing, original had unhashed hosts */
1168 int found_key; /* For find/delete, host was found */
1169 int invalid; /* File contained invalid items; don't delete */
1170 int hash_hosts; /* Hash hostnames as we go */
1171 int find_host; /* Search for specific hostname */
1172 int delete_host; /* Delete host from known_hosts */
1176 known_hosts_hash(struct hostkey_foreach_line *l, void *_ctx)
1178 struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1179 char *hashed, *cp, *hosts, *ohosts;
1180 int has_wild = l->hosts && strcspn(l->hosts, "*?!") != strlen(l->hosts);
1181 int was_hashed = l->hosts && l->hosts[0] == HASH_DELIM;
1183 switch (l->status) {
1185 case HKF_STATUS_MATCHED:
1187 * Don't hash hosts already already hashed, with wildcard
1188 * characters or a CA/revocation marker.
1190 if (was_hashed || has_wild || l->marker != MRK_NONE) {
1191 fprintf(ctx->out, "%s\n", l->line);
1192 if (has_wild && !ctx->find_host) {
1193 logit("%s:%lu: ignoring host name "
1194 "with wildcard: %.64s", l->path,
1195 l->linenum, l->hosts);
1200 * Split any comma-separated hostnames from the host list,
1201 * hash and store separately.
1203 ohosts = hosts = xstrdup(l->hosts);
1204 while ((cp = strsep(&hosts, ",")) != NULL && *cp != '\0') {
1206 if ((hashed = host_hash(cp, NULL, 0)) == NULL)
1207 fatal("hash_host failed");
1208 fprintf(ctx->out, "%s %s\n", hashed, l->rawkey);
1210 ctx->has_unhashed = 1;
1214 case HKF_STATUS_INVALID:
1215 /* Retain invalid lines, but mark file as invalid. */
1217 logit("%s:%lu: invalid line", l->path, l->linenum);
1220 fprintf(ctx->out, "%s\n", l->line);
1228 known_hosts_find_delete(struct hostkey_foreach_line *l, void *_ctx)
1230 struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1231 enum sshkey_fp_rep rep;
1233 char *fp = NULL, *ra = NULL;
1235 fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
1236 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1238 if (l->status == HKF_STATUS_MATCHED) {
1239 if (ctx->delete_host) {
1240 if (l->marker != MRK_NONE) {
1241 /* Don't remove CA and revocation lines */
1242 fprintf(ctx->out, "%s\n", l->line);
1245 * Hostname matches and has no CA/revoke
1246 * marker, delete it by *not* writing the
1251 printf("# Host %s found: line %lu\n",
1252 ctx->host, l->linenum);
1255 } else if (ctx->find_host) {
1258 printf("# Host %s found: line %lu %s\n",
1260 l->linenum, l->marker == MRK_CA ? "CA" :
1261 (l->marker == MRK_REVOKE ? "REVOKED" : ""));
1263 if (ctx->hash_hosts)
1264 known_hosts_hash(l, ctx);
1265 else if (print_fingerprint) {
1266 fp = sshkey_fingerprint(l->key, fptype, rep);
1267 ra = sshkey_fingerprint(l->key,
1268 fingerprint_hash, SSH_FP_RANDOMART);
1269 if (fp == NULL || ra == NULL)
1270 fatal_f("sshkey_fingerprint failed");
1271 mprintf("%s %s %s%s%s\n", ctx->host,
1272 sshkey_type(l->key), fp,
1273 l->comment[0] ? " " : "",
1275 if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
1280 fprintf(ctx->out, "%s\n", l->line);
1283 } else if (ctx->delete_host) {
1284 /* Retain non-matching hosts when deleting */
1285 if (l->status == HKF_STATUS_INVALID) {
1287 logit("%s:%lu: invalid line", l->path, l->linenum);
1289 fprintf(ctx->out, "%s\n", l->line);
1295 do_known_hosts(struct passwd *pw, const char *name, int find_host,
1296 int delete_host, int hash_hosts)
1298 char *cp, tmp[PATH_MAX], old[PATH_MAX];
1299 int r, fd, oerrno, inplace = 0;
1300 struct known_hosts_ctx ctx;
1301 u_int foreach_options;
1304 if (!have_identity) {
1305 cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
1306 if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
1307 sizeof(identity_file))
1308 fatal("Specified known hosts path too long");
1312 if (stat(identity_file, &sb) != 0)
1313 fatal("Cannot stat %s: %s", identity_file, strerror(errno));
1315 memset(&ctx, 0, sizeof(ctx));
1318 ctx.hash_hosts = hash_hosts;
1319 ctx.find_host = find_host;
1320 ctx.delete_host = delete_host;
1323 * Find hosts goes to stdout, hash and deletions happen in-place
1324 * A corner case is ssh-keygen -HF foo, which should go to stdout
1326 if (!find_host && (hash_hosts || delete_host)) {
1327 if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
1328 strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
1329 strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
1330 strlcat(old, ".old", sizeof(old)) >= sizeof(old))
1331 fatal("known_hosts path too long");
1333 if ((fd = mkstemp(tmp)) == -1)
1334 fatal("mkstemp: %s", strerror(errno));
1335 if ((ctx.out = fdopen(fd, "w")) == NULL) {
1338 fatal("fdopen: %s", strerror(oerrno));
1340 fchmod(fd, sb.st_mode & 0644);
1343 /* XXX support identity_file == "-" for stdin */
1344 foreach_options = find_host ? HKF_WANT_MATCH : 0;
1345 foreach_options |= print_fingerprint ? HKF_WANT_PARSE_KEY : 0;
1346 if ((r = hostkeys_foreach(identity_file, (find_host || !hash_hosts) ?
1347 known_hosts_find_delete : known_hosts_hash, &ctx, name, NULL,
1348 foreach_options, 0)) != 0) {
1351 fatal_fr(r, "hostkeys_foreach");
1358 error("%s is not a valid known_hosts file.", identity_file);
1360 error("Not replacing existing known_hosts "
1361 "file because of errors");
1365 } else if (delete_host && !ctx.found_key) {
1366 logit("Host %s not found in %s", name, identity_file);
1369 } else if (inplace) {
1370 /* Backup existing file */
1371 if (unlink(old) == -1 && errno != ENOENT)
1372 fatal("unlink %.100s: %s", old, strerror(errno));
1373 if (link(identity_file, old) == -1)
1374 fatal("link %.100s to %.100s: %s", identity_file, old,
1376 /* Move new one into place */
1377 if (rename(tmp, identity_file) == -1) {
1378 error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
1385 printf("%s updated.\n", identity_file);
1386 printf("Original contents retained as %s\n", old);
1387 if (ctx.has_unhashed) {
1388 logit("WARNING: %s contains unhashed entries", old);
1389 logit("Delete this file to ensure privacy "
1394 exit (find_host && !ctx.found_key);
1398 * Perform changing a passphrase. The argument is the passwd structure
1399 * for the current user.
1402 do_change_passphrase(struct passwd *pw)
1405 char *old_passphrase, *passphrase1, *passphrase2;
1407 struct sshkey *private;
1411 ask_filename(pw, "Enter file in which the key is");
1412 if (stat(identity_file, &st) == -1)
1413 fatal("%s: %s", identity_file, strerror(errno));
1414 /* Try to load the file with empty passphrase. */
1415 r = sshkey_load_private(identity_file, "", &private, &comment);
1416 if (r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
1417 if (identity_passphrase)
1418 old_passphrase = xstrdup(identity_passphrase);
1421 read_passphrase("Enter old passphrase: ",
1423 r = sshkey_load_private(identity_file, old_passphrase,
1424 &private, &comment);
1425 freezero(old_passphrase, strlen(old_passphrase));
1428 } else if (r != 0) {
1430 fatal_r(r, "Failed to load key %s", identity_file);
1433 mprintf("Key has comment '%s'\n", comment);
1435 /* Ask the new passphrase (twice). */
1436 if (identity_new_passphrase) {
1437 passphrase1 = xstrdup(identity_new_passphrase);
1441 read_passphrase("Enter new passphrase (empty for no "
1442 "passphrase): ", RP_ALLOW_STDIN);
1443 passphrase2 = read_passphrase("Enter same passphrase again: ",
1446 /* Verify that they are the same. */
1447 if (strcmp(passphrase1, passphrase2) != 0) {
1448 explicit_bzero(passphrase1, strlen(passphrase1));
1449 explicit_bzero(passphrase2, strlen(passphrase2));
1452 printf("Pass phrases do not match. Try again.\n");
1455 /* Destroy the other copy. */
1456 freezero(passphrase2, strlen(passphrase2));
1459 /* Save the file using the new passphrase. */
1460 if ((r = sshkey_save_private(private, identity_file, passphrase1,
1461 comment, private_key_format, openssh_format_cipher, rounds)) != 0) {
1462 error_r(r, "Saving key \"%s\" failed", identity_file);
1463 freezero(passphrase1, strlen(passphrase1));
1464 sshkey_free(private);
1468 /* Destroy the passphrase and the copy of the key in memory. */
1469 freezero(passphrase1, strlen(passphrase1));
1470 sshkey_free(private); /* Destroys contents */
1473 printf("Your identification has been saved with the new passphrase.\n");
1478 * Print the SSHFP RR.
1481 do_print_resource_record(struct passwd *pw, char *fname, char *hname,
1484 struct sshkey *public;
1485 char *comment = NULL;
1490 fatal_f("no filename");
1491 if (stat(fname, &st) == -1) {
1492 if (errno == ENOENT)
1494 fatal("%s: %s", fname, strerror(errno));
1496 if ((r = sshkey_load_public(fname, &public, &comment)) != 0)
1497 fatal_r(r, "Failed to read v2 public key from \"%s\"", fname);
1498 export_dns_rr(hname, public, stdout, print_generic);
1499 sshkey_free(public);
1505 * Change the comment of a private key file.
1508 do_change_comment(struct passwd *pw, const char *identity_comment)
1510 char new_comment[1024], *comment, *passphrase;
1511 struct sshkey *private;
1512 struct sshkey *public;
1517 ask_filename(pw, "Enter file in which the key is");
1518 if (stat(identity_file, &st) == -1)
1519 fatal("%s: %s", identity_file, strerror(errno));
1520 if ((r = sshkey_load_private(identity_file, "",
1521 &private, &comment)) == 0)
1522 passphrase = xstrdup("");
1523 else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
1524 fatal_r(r, "Cannot load private key \"%s\"", identity_file);
1526 if (identity_passphrase)
1527 passphrase = xstrdup(identity_passphrase);
1528 else if (identity_new_passphrase)
1529 passphrase = xstrdup(identity_new_passphrase);
1531 passphrase = read_passphrase("Enter passphrase: ",
1533 /* Try to load using the passphrase. */
1534 if ((r = sshkey_load_private(identity_file, passphrase,
1535 &private, &comment)) != 0) {
1536 freezero(passphrase, strlen(passphrase));
1537 fatal_r(r, "Cannot load private key \"%s\"",
1542 if (private->type != KEY_ED25519 && private->type != KEY_XMSS &&
1543 private_key_format != SSHKEY_PRIVATE_OPENSSH) {
1544 error("Comments are only supported for keys stored in "
1545 "the new format (-o).");
1546 explicit_bzero(passphrase, strlen(passphrase));
1547 sshkey_free(private);
1551 printf("Old comment: %s\n", comment);
1553 printf("No existing comment\n");
1555 if (identity_comment) {
1556 strlcpy(new_comment, identity_comment, sizeof(new_comment));
1558 printf("New comment: ");
1560 if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1561 explicit_bzero(passphrase, strlen(passphrase));
1562 sshkey_free(private);
1565 new_comment[strcspn(new_comment, "\n")] = '\0';
1567 if (comment != NULL && strcmp(comment, new_comment) == 0) {
1568 printf("No change to comment\n");
1570 sshkey_free(private);
1575 /* Save the file using the new passphrase. */
1576 if ((r = sshkey_save_private(private, identity_file, passphrase,
1577 new_comment, private_key_format, openssh_format_cipher,
1579 error_r(r, "Saving key \"%s\" failed", identity_file);
1580 freezero(passphrase, strlen(passphrase));
1581 sshkey_free(private);
1585 freezero(passphrase, strlen(passphrase));
1586 if ((r = sshkey_from_private(private, &public)) != 0)
1587 fatal_fr(r, "sshkey_from_private");
1588 sshkey_free(private);
1590 strlcat(identity_file, ".pub", sizeof(identity_file));
1591 if ((r = sshkey_save_public(public, identity_file, new_comment)) != 0)
1592 fatal_r(r, "Unable to save public key to %s", identity_file);
1593 sshkey_free(public);
1596 if (strlen(new_comment) > 0)
1597 printf("Comment '%s' applied\n", new_comment);
1599 printf("Comment removed\n");
1605 cert_ext_add(const char *key, const char *value, int iscrit)
1607 cert_ext = xreallocarray(cert_ext, ncert_ext + 1, sizeof(*cert_ext));
1608 cert_ext[ncert_ext].key = xstrdup(key);
1609 cert_ext[ncert_ext].val = value == NULL ? NULL : xstrdup(value);
1610 cert_ext[ncert_ext].crit = iscrit;
1614 /* qsort(3) comparison function for certificate extensions */
1616 cert_ext_cmp(const void *_a, const void *_b)
1618 const struct cert_ext *a = (const struct cert_ext *)_a;
1619 const struct cert_ext *b = (const struct cert_ext *)_b;
1622 if (a->crit != b->crit)
1623 return (a->crit < b->crit) ? -1 : 1;
1624 if ((r = strcmp(a->key, b->key)) != 0)
1626 if ((a->val == NULL) != (b->val == NULL))
1627 return (a->val == NULL) ? -1 : 1;
1628 if (a->val != NULL && (r = strcmp(a->val, b->val)) != 0)
1633 #define OPTIONS_CRITICAL 1
1634 #define OPTIONS_EXTENSIONS 2
1636 prepare_options_buf(struct sshbuf *c, int which)
1641 const struct cert_ext *ext;
1643 if ((b = sshbuf_new()) == NULL)
1644 fatal_f("sshbuf_new failed");
1646 for (i = 0; i < ncert_ext; i++) {
1648 if ((ext->crit && (which & OPTIONS_EXTENSIONS)) ||
1649 (!ext->crit && (which & OPTIONS_CRITICAL)))
1651 if (ext->val == NULL) {
1653 debug3_f("%s", ext->key);
1654 if ((r = sshbuf_put_cstring(c, ext->key)) != 0 ||
1655 (r = sshbuf_put_string(c, NULL, 0)) != 0)
1656 fatal_fr(r, "prepare flag");
1658 /* key/value option */
1659 debug3_f("%s=%s", ext->key, ext->val);
1661 if ((r = sshbuf_put_cstring(c, ext->key)) != 0 ||
1662 (r = sshbuf_put_cstring(b, ext->val)) != 0 ||
1663 (r = sshbuf_put_stringb(c, b)) != 0)
1664 fatal_fr(r, "prepare k/v");
1671 finalise_cert_exts(void)
1673 /* critical options */
1674 if (certflags_command != NULL)
1675 cert_ext_add("force-command", certflags_command, 1);
1676 if (certflags_src_addr != NULL)
1677 cert_ext_add("source-address", certflags_src_addr, 1);
1678 if ((certflags_flags & CERTOPT_REQUIRE_VERIFY) != 0)
1679 cert_ext_add("verify-required", NULL, 1);
1681 if ((certflags_flags & CERTOPT_X_FWD) != 0)
1682 cert_ext_add("permit-X11-forwarding", NULL, 0);
1683 if ((certflags_flags & CERTOPT_AGENT_FWD) != 0)
1684 cert_ext_add("permit-agent-forwarding", NULL, 0);
1685 if ((certflags_flags & CERTOPT_PORT_FWD) != 0)
1686 cert_ext_add("permit-port-forwarding", NULL, 0);
1687 if ((certflags_flags & CERTOPT_PTY) != 0)
1688 cert_ext_add("permit-pty", NULL, 0);
1689 if ((certflags_flags & CERTOPT_USER_RC) != 0)
1690 cert_ext_add("permit-user-rc", NULL, 0);
1691 if ((certflags_flags & CERTOPT_NO_REQUIRE_USER_PRESENCE) != 0)
1692 cert_ext_add("no-touch-required", NULL, 0);
1693 /* order lexically by key */
1695 qsort(cert_ext, ncert_ext, sizeof(*cert_ext), cert_ext_cmp);
1698 static struct sshkey *
1699 load_pkcs11_key(char *path)
1701 #ifdef ENABLE_PKCS11
1702 struct sshkey **keys = NULL, *public, *private = NULL;
1705 if ((r = sshkey_load_public(path, &public, NULL)) != 0)
1706 fatal_r(r, "Couldn't load CA public key \"%s\"", path);
1708 nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase,
1710 debug3_f("%d keys", nkeys);
1712 fatal("cannot read public key from pkcs11");
1713 for (i = 0; i < nkeys; i++) {
1714 if (sshkey_equal_public(public, keys[i])) {
1718 sshkey_free(keys[i]);
1721 sshkey_free(public);
1724 fatal("no pkcs11 support");
1725 #endif /* ENABLE_PKCS11 */
1728 /* Signer for sshkey_certify_custom that uses the agent */
1730 agent_signer(struct sshkey *key, u_char **sigp, size_t *lenp,
1731 const u_char *data, size_t datalen,
1732 const char *alg, const char *provider, const char *pin,
1733 u_int compat, void *ctx)
1735 int *agent_fdp = (int *)ctx;
1737 return ssh_agent_sign(*agent_fdp, key, sigp, lenp,
1738 data, datalen, alg, compat);
1742 do_ca_sign(struct passwd *pw, const char *ca_key_path, int prefer_agent,
1743 unsigned long long cert_serial, int cert_serial_autoinc,
1744 int argc, char **argv)
1746 int r, i, found, agent_fd = -1;
1748 struct sshkey *ca, *public;
1749 char valid[64], *otmp, *tmp, *cp, *out, *comment;
1750 char *ca_fp = NULL, **plist = NULL, *pin = NULL;
1751 struct ssh_identitylist *agent_ids;
1753 struct notifier_ctx *notifier = NULL;
1755 #ifdef ENABLE_PKCS11
1758 tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
1759 if (pkcs11provider != NULL) {
1760 /* If a PKCS#11 token was specified then try to use it */
1761 if ((ca = load_pkcs11_key(tmp)) == NULL)
1762 fatal("No PKCS#11 key matching %s found", ca_key_path);
1763 } else if (prefer_agent) {
1765 * Agent signature requested. Try to use agent after making
1766 * sure the public key specified is actually present in the
1769 if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
1770 fatal_r(r, "Cannot load CA public key %s", tmp);
1771 if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
1772 fatal_r(r, "Cannot use public key for CA signature");
1773 if ((r = ssh_fetch_identitylist(agent_fd, &agent_ids)) != 0)
1774 fatal_r(r, "Retrieve agent key list");
1776 for (j = 0; j < agent_ids->nkeys; j++) {
1777 if (sshkey_equal(ca, agent_ids->keys[j])) {
1783 fatal("CA key %s not found in agent", tmp);
1784 ssh_free_identitylist(agent_ids);
1785 ca->flags |= SSHKEY_FLAG_EXT;
1787 /* CA key is assumed to be a private key on the filesystem */
1788 ca = load_identity(tmp, NULL);
1789 if (sshkey_is_sk(ca) &&
1790 (ca->sk_flags & SSH_SK_USER_VERIFICATION_REQD)) {
1791 if ((pin = read_passphrase("Enter PIN for CA key: ",
1792 RP_ALLOW_STDIN)) == NULL)
1793 fatal_f("couldn't read PIN");
1798 if (key_type_name != NULL) {
1799 if (sshkey_type_from_name(key_type_name) != ca->type) {
1800 fatal("CA key type %s doesn't match specified %s",
1801 sshkey_ssh_name(ca), key_type_name);
1803 } else if (ca->type == KEY_RSA) {
1804 /* Default to a good signature algorithm */
1805 key_type_name = "rsa-sha2-512";
1807 ca_fp = sshkey_fingerprint(ca, fingerprint_hash, SSH_FP_DEFAULT);
1809 finalise_cert_exts();
1810 for (i = 0; i < argc; i++) {
1811 /* Split list of principals */
1813 if (cert_principals != NULL) {
1814 otmp = tmp = xstrdup(cert_principals);
1816 for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1817 plist = xreallocarray(plist, n + 1, sizeof(*plist));
1818 if (*(plist[n] = xstrdup(cp)) == '\0')
1819 fatal("Empty principal name");
1823 if (n > SSHKEY_CERT_MAX_PRINCIPALS)
1824 fatal("Too many certificate principals specified");
1826 tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1827 if ((r = sshkey_load_public(tmp, &public, &comment)) != 0)
1828 fatal_r(r, "load pubkey \"%s\"", tmp);
1829 if (sshkey_is_cert(public))
1830 fatal_f("key \"%s\" type %s cannot be certified",
1831 tmp, sshkey_type(public));
1833 /* Prepare certificate to sign */
1834 if ((r = sshkey_to_certified(public)) != 0)
1835 fatal_r(r, "Could not upgrade key %s to certificate", tmp);
1836 public->cert->type = cert_key_type;
1837 public->cert->serial = (u_int64_t)cert_serial;
1838 public->cert->key_id = xstrdup(cert_key_id);
1839 public->cert->nprincipals = n;
1840 public->cert->principals = plist;
1841 public->cert->valid_after = cert_valid_from;
1842 public->cert->valid_before = cert_valid_to;
1843 prepare_options_buf(public->cert->critical, OPTIONS_CRITICAL);
1844 prepare_options_buf(public->cert->extensions,
1845 OPTIONS_EXTENSIONS);
1846 if ((r = sshkey_from_private(ca,
1847 &public->cert->signature_key)) != 0)
1848 fatal_r(r, "sshkey_from_private (ca key)");
1850 if (agent_fd != -1 && (ca->flags & SSHKEY_FLAG_EXT) != 0) {
1851 if ((r = sshkey_certify_custom(public, ca,
1852 key_type_name, sk_provider, NULL, agent_signer,
1854 fatal_r(r, "Couldn't certify %s via agent", tmp);
1856 if (sshkey_is_sk(ca) &&
1857 (ca->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
1858 notifier = notify_start(0,
1859 "Confirm user presence for key %s %s",
1860 sshkey_type(ca), ca_fp);
1862 r = sshkey_certify(public, ca, key_type_name,
1864 notify_complete(notifier, "User presence confirmed");
1866 fatal_r(r, "Couldn't certify key %s", tmp);
1869 if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
1871 xasprintf(&out, "%s-cert.pub", tmp);
1874 if ((r = sshkey_save_public(public, out, comment)) != 0) {
1875 fatal_r(r, "Unable to save public key to %s",
1880 sshkey_format_cert_validity(public->cert,
1881 valid, sizeof(valid));
1882 logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1883 "valid %s", sshkey_cert_type(public),
1884 out, public->cert->key_id,
1885 (unsigned long long)public->cert->serial,
1886 cert_principals != NULL ? " for " : "",
1887 cert_principals != NULL ? cert_principals : "",
1891 sshkey_free(public);
1893 if (cert_serial_autoinc)
1897 freezero(pin, strlen(pin));
1899 #ifdef ENABLE_PKCS11
1906 parse_relative_time(const char *s, time_t now)
1910 mul = *s == '-' ? -1 : 1;
1912 if ((secs = convtime(s + 1)) == -1)
1913 fatal("Invalid relative certificate time %s", s);
1914 if (mul == -1 && secs > now)
1915 fatal("Certificate time %s cannot be represented", s);
1916 return now + (u_int64_t)(secs * mul);
1920 parse_hex_u64(const char *s, uint64_t *up)
1923 unsigned long long ull;
1926 ull = strtoull(s, &ep, 16);
1927 if (*s == '\0' || *ep != '\0')
1928 fatal("Invalid certificate time: not a number");
1929 if (errno == ERANGE && ull == ULONG_MAX)
1930 fatal_fr(SSH_ERR_SYSTEM_ERROR, "Invalid certificate time");
1931 *up = (uint64_t)ull;
1935 parse_cert_times(char *timespec)
1938 time_t now = time(NULL);
1941 /* +timespec relative to now */
1942 if (*timespec == '+' && strchr(timespec, ':') == NULL) {
1943 if ((secs = convtime(timespec + 1)) == -1)
1944 fatal("Invalid relative certificate life %s", timespec);
1945 cert_valid_to = now + secs;
1947 * Backdate certificate one minute to avoid problems on hosts
1948 * with poorly-synchronised clocks.
1950 cert_valid_from = ((now - 59)/ 60) * 60;
1956 * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | 0x... | "always"
1957 * to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | 0x... | "forever"
1959 from = xstrdup(timespec);
1960 to = strchr(from, ':');
1961 if (to == NULL || from == to || *(to + 1) == '\0')
1962 fatal("Invalid certificate life specification %s", timespec);
1965 if (*from == '-' || *from == '+')
1966 cert_valid_from = parse_relative_time(from, now);
1967 else if (strcmp(from, "always") == 0)
1968 cert_valid_from = 0;
1969 else if (strncmp(from, "0x", 2) == 0)
1970 parse_hex_u64(from, &cert_valid_from);
1971 else if (parse_absolute_time(from, &cert_valid_from) != 0)
1972 fatal("Invalid from time \"%s\"", from);
1974 if (*to == '-' || *to == '+')
1975 cert_valid_to = parse_relative_time(to, now);
1976 else if (strcmp(to, "forever") == 0)
1977 cert_valid_to = ~(u_int64_t)0;
1978 else if (strncmp(from, "0x", 2) == 0)
1979 parse_hex_u64(to, &cert_valid_to);
1980 else if (parse_absolute_time(to, &cert_valid_to) != 0)
1981 fatal("Invalid to time \"%s\"", to);
1983 if (cert_valid_to <= cert_valid_from)
1984 fatal("Empty certificate validity interval");
1989 add_cert_option(char *opt)
1994 if (strcasecmp(opt, "clear") == 0)
1995 certflags_flags = 0;
1996 else if (strcasecmp(opt, "no-x11-forwarding") == 0)
1997 certflags_flags &= ~CERTOPT_X_FWD;
1998 else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
1999 certflags_flags |= CERTOPT_X_FWD;
2000 else if (strcasecmp(opt, "no-agent-forwarding") == 0)
2001 certflags_flags &= ~CERTOPT_AGENT_FWD;
2002 else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
2003 certflags_flags |= CERTOPT_AGENT_FWD;
2004 else if (strcasecmp(opt, "no-port-forwarding") == 0)
2005 certflags_flags &= ~CERTOPT_PORT_FWD;
2006 else if (strcasecmp(opt, "permit-port-forwarding") == 0)
2007 certflags_flags |= CERTOPT_PORT_FWD;
2008 else if (strcasecmp(opt, "no-pty") == 0)
2009 certflags_flags &= ~CERTOPT_PTY;
2010 else if (strcasecmp(opt, "permit-pty") == 0)
2011 certflags_flags |= CERTOPT_PTY;
2012 else if (strcasecmp(opt, "no-user-rc") == 0)
2013 certflags_flags &= ~CERTOPT_USER_RC;
2014 else if (strcasecmp(opt, "permit-user-rc") == 0)
2015 certflags_flags |= CERTOPT_USER_RC;
2016 else if (strcasecmp(opt, "touch-required") == 0)
2017 certflags_flags &= ~CERTOPT_NO_REQUIRE_USER_PRESENCE;
2018 else if (strcasecmp(opt, "no-touch-required") == 0)
2019 certflags_flags |= CERTOPT_NO_REQUIRE_USER_PRESENCE;
2020 else if (strcasecmp(opt, "no-verify-required") == 0)
2021 certflags_flags &= ~CERTOPT_REQUIRE_VERIFY;
2022 else if (strcasecmp(opt, "verify-required") == 0)
2023 certflags_flags |= CERTOPT_REQUIRE_VERIFY;
2024 else if (strncasecmp(opt, "force-command=", 14) == 0) {
2027 fatal("Empty force-command option");
2028 if (certflags_command != NULL)
2029 fatal("force-command already specified");
2030 certflags_command = xstrdup(val);
2031 } else if (strncasecmp(opt, "source-address=", 15) == 0) {
2034 fatal("Empty source-address option");
2035 if (certflags_src_addr != NULL)
2036 fatal("source-address already specified");
2037 if (addr_match_cidr_list(NULL, val) != 0)
2038 fatal("Invalid source-address list");
2039 certflags_src_addr = xstrdup(val);
2040 } else if (strncasecmp(opt, "extension:", 10) == 0 ||
2041 (iscrit = (strncasecmp(opt, "critical:", 9) == 0))) {
2042 val = xstrdup(strchr(opt, ':') + 1);
2043 if ((cp = strchr(val, '=')) != NULL)
2045 cert_ext_add(val, cp, iscrit);
2048 fatal("Unsupported certificate option \"%s\"", opt);
2052 show_options(struct sshbuf *optbuf, int in_critical)
2054 char *name, *arg, *hex;
2055 struct sshbuf *options, *option = NULL;
2058 if ((options = sshbuf_fromb(optbuf)) == NULL)
2059 fatal_f("sshbuf_fromb failed");
2060 while (sshbuf_len(options) != 0) {
2061 sshbuf_free(option);
2063 if ((r = sshbuf_get_cstring(options, &name, NULL)) != 0 ||
2064 (r = sshbuf_froms(options, &option)) != 0)
2065 fatal_fr(r, "parse option");
2066 printf(" %s", name);
2068 (strcmp(name, "permit-X11-forwarding") == 0 ||
2069 strcmp(name, "permit-agent-forwarding") == 0 ||
2070 strcmp(name, "permit-port-forwarding") == 0 ||
2071 strcmp(name, "permit-pty") == 0 ||
2072 strcmp(name, "permit-user-rc") == 0 ||
2073 strcmp(name, "no-touch-required") == 0)) {
2075 } else if (in_critical &&
2076 (strcmp(name, "force-command") == 0 ||
2077 strcmp(name, "source-address") == 0)) {
2078 if ((r = sshbuf_get_cstring(option, &arg, NULL)) != 0)
2079 fatal_fr(r, "parse critical");
2080 printf(" %s\n", arg);
2082 } else if (in_critical &&
2083 strcmp(name, "verify-required") == 0) {
2085 } else if (sshbuf_len(option) > 0) {
2086 hex = sshbuf_dtob16(option);
2087 printf(" UNKNOWN OPTION: %s (len %zu)\n",
2088 hex, sshbuf_len(option));
2089 sshbuf_reset(option);
2092 printf(" UNKNOWN FLAG OPTION\n");
2094 if (sshbuf_len(option) != 0)
2095 fatal("Option corrupt: extra data at end");
2097 sshbuf_free(option);
2098 sshbuf_free(options);
2102 print_cert(struct sshkey *key)
2104 char valid[64], *key_fp, *ca_fp;
2107 key_fp = sshkey_fingerprint(key, fingerprint_hash, SSH_FP_DEFAULT);
2108 ca_fp = sshkey_fingerprint(key->cert->signature_key,
2109 fingerprint_hash, SSH_FP_DEFAULT);
2110 if (key_fp == NULL || ca_fp == NULL)
2111 fatal_f("sshkey_fingerprint fail");
2112 sshkey_format_cert_validity(key->cert, valid, sizeof(valid));
2114 printf(" Type: %s %s certificate\n", sshkey_ssh_name(key),
2115 sshkey_cert_type(key));
2116 printf(" Public key: %s %s\n", sshkey_type(key), key_fp);
2117 printf(" Signing CA: %s %s (using %s)\n",
2118 sshkey_type(key->cert->signature_key), ca_fp,
2119 key->cert->signature_type);
2120 printf(" Key ID: \"%s\"\n", key->cert->key_id);
2121 printf(" Serial: %llu\n", (unsigned long long)key->cert->serial);
2122 printf(" Valid: %s\n", valid);
2123 printf(" Principals: ");
2124 if (key->cert->nprincipals == 0)
2127 for (i = 0; i < key->cert->nprincipals; i++)
2129 key->cert->principals[i]);
2132 printf(" Critical Options: ");
2133 if (sshbuf_len(key->cert->critical) == 0)
2137 show_options(key->cert->critical, 1);
2139 printf(" Extensions: ");
2140 if (sshbuf_len(key->cert->extensions) == 0)
2144 show_options(key->cert->extensions, 0);
2149 do_show_cert(struct passwd *pw)
2151 struct sshkey *key = NULL;
2153 int r, is_stdin = 0, ok = 0;
2155 char *cp, *line = NULL;
2157 size_t linesize = 0;
2161 ask_filename(pw, "Enter file in which the key is");
2162 if (strcmp(identity_file, "-") != 0 && stat(identity_file, &st) == -1)
2163 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
2165 path = identity_file;
2166 if (strcmp(path, "-") == 0) {
2170 } else if ((f = fopen(identity_file, "r")) == NULL)
2171 fatal("fopen %s: %s", identity_file, strerror(errno));
2173 while (getline(&line, &linesize, f) != -1) {
2177 /* Trim leading space and comments */
2178 cp = line + strspn(line, " \t");
2179 if (*cp == '#' || *cp == '\0')
2181 if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2182 fatal("sshkey_new");
2183 if ((r = sshkey_read(key, &cp)) != 0) {
2184 error_r(r, "%s:%lu: invalid key", path, lnum);
2187 if (!sshkey_is_cert(key)) {
2188 error("%s:%lu is not a certificate", path, lnum);
2192 if (!is_stdin && lnum == 1)
2193 printf("%s:\n", path);
2195 printf("%s:%lu:\n", path, lnum);
2205 load_krl(const char *path, struct ssh_krl **krlp)
2207 struct sshbuf *krlbuf;
2210 if ((r = sshbuf_load_file(path, &krlbuf)) != 0)
2211 fatal_r(r, "Unable to load KRL %s", path);
2212 /* XXX check sigs */
2213 if ((r = ssh_krl_from_blob(krlbuf, krlp, NULL, 0)) != 0 ||
2215 fatal_r(r, "Invalid KRL file %s", path);
2216 sshbuf_free(krlbuf);
2220 hash_to_blob(const char *cp, u_char **blobp, size_t *lenp,
2221 const char *file, u_long lnum)
2228 if (strncmp(cp, "SHA256:", 7) != 0)
2229 fatal("%s:%lu: unsupported hash algorithm", file, lnum);
2233 * OpenSSH base64 hashes omit trailing '='
2234 * characters; put them back for decode.
2237 tmp = xmalloc(tlen + 4 + 1);
2238 strlcpy(tmp, cp, tlen + 1);
2239 while ((tlen % 4) != 0) {
2243 if ((b = sshbuf_new()) == NULL)
2244 fatal_f("sshbuf_new failed");
2245 if ((r = sshbuf_b64tod(b, tmp)) != 0)
2246 fatal_r(r, "%s:%lu: decode hash failed", file, lnum);
2248 *lenp = sshbuf_len(b);
2249 *blobp = xmalloc(*lenp);
2250 memcpy(*blobp, sshbuf_ptr(b), *lenp);
2255 update_krl_from_file(struct passwd *pw, const char *file, int wild_ca,
2256 const struct sshkey *ca, struct ssh_krl *krl)
2258 struct sshkey *key = NULL;
2260 char *path, *cp, *ep, *line = NULL;
2261 u_char *blob = NULL;
2262 size_t blen = 0, linesize = 0;
2263 unsigned long long serial, serial2;
2264 int i, was_explicit_key, was_sha1, was_sha256, was_hash, r;
2267 path = tilde_expand_filename(file, pw->pw_uid);
2268 if (strcmp(path, "-") == 0) {
2271 path = xstrdup("(standard input)");
2272 } else if ((krl_spec = fopen(path, "r")) == NULL)
2273 fatal("fopen %s: %s", path, strerror(errno));
2276 printf("Revoking from %s\n", path);
2277 while (getline(&line, &linesize, krl_spec) != -1) {
2279 was_explicit_key = was_sha1 = was_sha256 = was_hash = 0;
2280 cp = line + strspn(line, " \t");
2281 /* Trim trailing space, comments and strip \n */
2282 for (i = 0, r = -1; cp[i] != '\0'; i++) {
2283 if (cp[i] == '#' || cp[i] == '\n') {
2287 if (cp[i] == ' ' || cp[i] == '\t') {
2288 /* Remember the start of a span of whitespace */
2298 if (strncasecmp(cp, "serial:", 7) == 0) {
2299 if (ca == NULL && !wild_ca) {
2300 fatal("revoking certificates by serial number "
2301 "requires specification of a CA key");
2304 cp = cp + strspn(cp, " \t");
2306 serial = strtoull(cp, &ep, 0);
2307 if (*cp == '\0' || (*ep != '\0' && *ep != '-'))
2308 fatal("%s:%lu: invalid serial \"%s\"",
2310 if (errno == ERANGE && serial == ULLONG_MAX)
2311 fatal("%s:%lu: serial out of range",
2317 serial2 = strtoull(cp, &ep, 0);
2318 if (*cp == '\0' || *ep != '\0')
2319 fatal("%s:%lu: invalid serial \"%s\"",
2321 if (errno == ERANGE && serial2 == ULLONG_MAX)
2322 fatal("%s:%lu: serial out of range",
2324 if (serial2 <= serial)
2325 fatal("%s:%lu: invalid serial range "
2326 "%llu:%llu", path, lnum,
2327 (unsigned long long)serial,
2328 (unsigned long long)serial2);
2330 if (ssh_krl_revoke_cert_by_serial_range(krl,
2331 ca, serial, serial2) != 0) {
2332 fatal_f("revoke serial failed");
2334 } else if (strncasecmp(cp, "id:", 3) == 0) {
2335 if (ca == NULL && !wild_ca) {
2336 fatal("revoking certificates by key ID "
2337 "requires specification of a CA key");
2340 cp = cp + strspn(cp, " \t");
2341 if (ssh_krl_revoke_cert_by_key_id(krl, ca, cp) != 0)
2342 fatal_f("revoke key ID failed");
2343 } else if (strncasecmp(cp, "hash:", 5) == 0) {
2345 cp = cp + strspn(cp, " \t");
2346 hash_to_blob(cp, &blob, &blen, file, lnum);
2347 r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2349 fatal_fr(r, "revoke key failed");
2351 if (strncasecmp(cp, "key:", 4) == 0) {
2353 cp = cp + strspn(cp, " \t");
2354 was_explicit_key = 1;
2355 } else if (strncasecmp(cp, "sha1:", 5) == 0) {
2357 cp = cp + strspn(cp, " \t");
2359 } else if (strncasecmp(cp, "sha256:", 7) == 0) {
2361 cp = cp + strspn(cp, " \t");
2364 * Just try to process the line as a key.
2365 * Parsing will fail if it isn't.
2368 if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2369 fatal("sshkey_new");
2370 if ((r = sshkey_read(key, &cp)) != 0)
2371 fatal_r(r, "%s:%lu: invalid key", path, lnum);
2372 if (was_explicit_key)
2373 r = ssh_krl_revoke_key_explicit(krl, key);
2374 else if (was_sha1) {
2375 if (sshkey_fingerprint_raw(key,
2376 SSH_DIGEST_SHA1, &blob, &blen) != 0) {
2377 fatal("%s:%lu: fingerprint failed",
2380 r = ssh_krl_revoke_key_sha1(krl, blob, blen);
2381 } else if (was_sha256) {
2382 if (sshkey_fingerprint_raw(key,
2383 SSH_DIGEST_SHA256, &blob, &blen) != 0) {
2384 fatal("%s:%lu: fingerprint failed",
2387 r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2389 r = ssh_krl_revoke_key(krl, key);
2391 fatal_fr(r, "revoke key failed");
2392 freezero(blob, blen);
2398 if (strcmp(path, "-") != 0)
2405 do_gen_krl(struct passwd *pw, int updating, const char *ca_key_path,
2406 unsigned long long krl_version, const char *krl_comment,
2407 int argc, char **argv)
2409 struct ssh_krl *krl;
2411 struct sshkey *ca = NULL;
2412 int i, r, wild_ca = 0;
2414 struct sshbuf *kbuf;
2416 if (*identity_file == '\0')
2417 fatal("KRL generation requires an output file");
2418 if (stat(identity_file, &sb) == -1) {
2419 if (errno != ENOENT)
2420 fatal("Cannot access KRL \"%s\": %s",
2421 identity_file, strerror(errno));
2423 fatal("KRL \"%s\" does not exist", identity_file);
2425 if (ca_key_path != NULL) {
2426 if (strcasecmp(ca_key_path, "none") == 0)
2429 tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
2430 if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
2431 fatal_r(r, "Cannot load CA public key %s", tmp);
2437 load_krl(identity_file, &krl);
2438 else if ((krl = ssh_krl_init()) == NULL)
2439 fatal("couldn't create KRL");
2441 if (krl_version != 0)
2442 ssh_krl_set_version(krl, krl_version);
2443 if (krl_comment != NULL)
2444 ssh_krl_set_comment(krl, krl_comment);
2446 for (i = 0; i < argc; i++)
2447 update_krl_from_file(pw, argv[i], wild_ca, ca, krl);
2449 if ((kbuf = sshbuf_new()) == NULL)
2450 fatal("sshbuf_new failed");
2451 if (ssh_krl_to_blob(krl, kbuf, NULL, 0) != 0)
2452 fatal("Couldn't generate KRL");
2453 if ((r = sshbuf_write_file(identity_file, kbuf)) != 0)
2454 fatal("write %s: %s", identity_file, strerror(errno));
2461 do_check_krl(struct passwd *pw, int print_krl, int argc, char **argv)
2465 struct ssh_krl *krl;
2468 if (*identity_file == '\0')
2469 fatal("KRL checking requires an input file");
2470 load_krl(identity_file, &krl);
2472 krl_dump(krl, stdout);
2473 for (i = 0; i < argc; i++) {
2474 if ((r = sshkey_load_public(argv[i], &k, &comment)) != 0)
2475 fatal_r(r, "Cannot load public key %s", argv[i]);
2476 r = ssh_krl_check_key(krl, k);
2477 printf("%s%s%s%s: %s\n", argv[i],
2478 *comment ? " (" : "", comment, *comment ? ")" : "",
2479 r == 0 ? "ok" : "REVOKED");
2489 static struct sshkey *
2490 load_sign_key(const char *keypath, const struct sshkey *pubkey)
2492 size_t i, slen, plen = strlen(keypath);
2493 char *privpath = xstrdup(keypath);
2494 static const char * const suffixes[] = { "-cert.pub", ".pub", NULL };
2495 struct sshkey *ret = NULL, *privkey = NULL;
2500 * If passed a public key filename, then try to locate the corresponding
2501 * private key. This lets us specify certificates on the command-line
2502 * and have ssh-keygen find the appropriate private key.
2504 for (i = 0; suffixes[i]; i++) {
2505 slen = strlen(suffixes[i]);
2507 strcmp(privpath + plen - slen, suffixes[i]) != 0)
2509 privpath[plen - slen] = '\0';
2510 debug_f("%s looks like a public key, using private key "
2511 "path %s instead", keypath, privpath);
2514 if (waspub && stat(privpath, &st) != 0 && errno == ENOENT)
2515 fatal("No private key found for public key \"%s\"", keypath);
2516 if ((r = sshkey_load_private(privpath, "", &privkey, NULL)) != 0 &&
2517 (r != SSH_ERR_KEY_WRONG_PASSPHRASE)) {
2518 debug_fr(r, "load private key \"%s\"", privpath);
2519 fatal("No private key found for \"%s\"", privpath);
2520 } else if (privkey == NULL)
2521 privkey = load_identity(privpath, NULL);
2523 if (!sshkey_equal_public(pubkey, privkey)) {
2524 error("Public key %s doesn't match private %s",
2528 if (sshkey_is_cert(pubkey) && !sshkey_is_cert(privkey)) {
2530 * Graft the certificate onto the private key to make
2531 * it capable of signing.
2533 if ((r = sshkey_to_certified(privkey)) != 0) {
2534 error_fr(r, "sshkey_to_certified");
2537 if ((r = sshkey_cert_copy(pubkey, privkey)) != 0) {
2538 error_fr(r, "sshkey_cert_copy");
2546 sshkey_free(privkey);
2552 sign_one(struct sshkey *signkey, const char *filename, int fd,
2553 const char *sig_namespace, const char *hashalg, sshsig_signer *signer,
2556 struct sshbuf *sigbuf = NULL, *abuf = NULL;
2557 int r = SSH_ERR_INTERNAL_ERROR, wfd = -1, oerrno;
2558 char *wfile = NULL, *asig = NULL, *fp = NULL;
2559 char *pin = NULL, *prompt = NULL;
2562 if (fd == STDIN_FILENO)
2563 fprintf(stderr, "Signing data on standard input\n");
2565 fprintf(stderr, "Signing file %s\n", filename);
2567 if (signer == NULL && sshkey_is_sk(signkey)) {
2568 if ((signkey->sk_flags & SSH_SK_USER_VERIFICATION_REQD)) {
2569 xasprintf(&prompt, "Enter PIN for %s key: ",
2570 sshkey_type(signkey));
2571 if ((pin = read_passphrase(prompt,
2572 RP_ALLOW_STDIN)) == NULL)
2573 fatal_f("couldn't read PIN");
2575 if ((signkey->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
2576 if ((fp = sshkey_fingerprint(signkey, fingerprint_hash,
2577 SSH_FP_DEFAULT)) == NULL)
2578 fatal_f("fingerprint failed");
2579 fprintf(stderr, "Confirm user presence for key %s %s\n",
2580 sshkey_type(signkey), fp);
2584 if ((r = sshsig_sign_fd(signkey, hashalg, sk_provider, pin,
2585 fd, sig_namespace, &sigbuf, signer, signer_ctx)) != 0) {
2586 error_r(r, "Signing %s failed", filename);
2589 if ((r = sshsig_armor(sigbuf, &abuf)) != 0) {
2590 error_fr(r, "sshsig_armor");
2593 if ((asig = sshbuf_dup_string(abuf)) == NULL) {
2594 error_f("buffer error");
2595 r = SSH_ERR_ALLOC_FAIL;
2599 if (fd == STDIN_FILENO) {
2600 fputs(asig, stdout);
2603 xasprintf(&wfile, "%s.sig", filename);
2604 if (confirm_overwrite(wfile)) {
2605 if ((wfd = open(wfile, O_WRONLY|O_CREAT|O_TRUNC,
2608 error("Cannot open %s: %s",
2609 wfile, strerror(errno));
2611 r = SSH_ERR_SYSTEM_ERROR;
2614 if (atomicio(vwrite, wfd, asig,
2615 strlen(asig)) != strlen(asig)) {
2617 error("Cannot write to %s: %s",
2618 wfile, strerror(errno));
2620 r = SSH_ERR_SYSTEM_ERROR;
2624 fprintf(stderr, "Write signature to %s\n",
2636 freezero(pin, strlen(pin));
2638 sshbuf_free(sigbuf);
2645 sig_process_opts(char * const *opts, size_t nopts, char **hashalgp,
2646 uint64_t *verify_timep, int *print_pubkey)
2651 if (verify_timep != NULL)
2653 if (print_pubkey != NULL)
2655 if (hashalgp != NULL)
2657 for (i = 0; i < nopts; i++) {
2658 if (hashalgp != NULL &&
2659 strncasecmp(opts[i], "hashalg=", 8) == 0) {
2660 *hashalgp = xstrdup(opts[i] + 8);
2661 } else if (verify_timep &&
2662 strncasecmp(opts[i], "verify-time=", 12) == 0) {
2663 if (parse_absolute_time(opts[i] + 12,
2664 verify_timep) != 0 || *verify_timep == 0) {
2665 error("Invalid \"verify-time\" option");
2666 return SSH_ERR_INVALID_ARGUMENT;
2668 } else if (print_pubkey &&
2669 strcasecmp(opts[i], "print-pubkey") == 0) {
2672 error("Invalid option \"%s\"", opts[i]);
2673 return SSH_ERR_INVALID_ARGUMENT;
2676 if (verify_timep && *verify_timep == 0) {
2677 if ((now = time(NULL)) < 0) {
2678 error("Time is before epoch");
2679 return SSH_ERR_INVALID_ARGUMENT;
2681 *verify_timep = (uint64_t)now;
2688 sig_sign(const char *keypath, const char *sig_namespace, int require_agent,
2689 int argc, char **argv, char * const *opts, size_t nopts)
2691 int i, fd = -1, r, ret = -1;
2693 struct sshkey *pubkey = NULL, *privkey = NULL, *signkey = NULL;
2694 sshsig_signer *signer = NULL;
2695 char *hashalg = NULL;
2697 /* Check file arguments. */
2698 for (i = 0; i < argc; i++) {
2699 if (strcmp(argv[i], "-") != 0)
2701 if (i > 0 || argc > 1)
2702 fatal("Cannot sign mix of paths and standard input");
2705 if (sig_process_opts(opts, nopts, &hashalg, NULL, NULL) != 0)
2706 goto done; /* error already logged */
2708 if ((r = sshkey_load_public(keypath, &pubkey, NULL)) != 0) {
2709 error_r(r, "Couldn't load public key %s", keypath);
2713 if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) {
2715 fatal("Couldn't get agent socket");
2716 debug_r(r, "Couldn't get agent socket");
2718 if ((r = ssh_agent_has_key(agent_fd, pubkey)) == 0)
2719 signer = agent_signer;
2722 fatal("Couldn't find key in agent");
2723 debug_r(r, "Couldn't find key in agent");
2727 if (signer == NULL) {
2728 /* Not using agent - try to load private key */
2729 if ((privkey = load_sign_key(keypath, pubkey)) == NULL)
2733 /* Will use key in agent */
2738 if ((r = sign_one(signkey, "(stdin)", STDIN_FILENO,
2739 sig_namespace, hashalg, signer, &agent_fd)) != 0)
2742 for (i = 0; i < argc; i++) {
2743 if (strcmp(argv[i], "-") == 0)
2745 else if ((fd = open(argv[i], O_RDONLY)) == -1) {
2746 error("Cannot open %s for signing: %s",
2747 argv[i], strerror(errno));
2750 if ((r = sign_one(signkey, argv[i], fd, sig_namespace,
2751 hashalg, signer, &agent_fd)) != 0)
2753 if (fd != STDIN_FILENO)
2761 if (fd != -1 && fd != STDIN_FILENO)
2763 sshkey_free(pubkey);
2764 sshkey_free(privkey);
2770 sig_verify(const char *signature, const char *sig_namespace,
2771 const char *principal, const char *allowed_keys, const char *revoked_keys,
2772 char * const *opts, size_t nopts)
2775 int print_pubkey = 0;
2776 struct sshbuf *sigbuf = NULL, *abuf = NULL;
2777 struct sshkey *sign_key = NULL;
2779 struct sshkey_sig_details *sig_details = NULL;
2780 uint64_t verify_time = 0;
2782 if (sig_process_opts(opts, nopts, NULL, &verify_time,
2783 &print_pubkey) != 0)
2784 goto done; /* error already logged */
2786 memset(&sig_details, 0, sizeof(sig_details));
2787 if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
2788 error_r(r, "Couldn't read signature file");
2792 if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
2793 error_fr(r, "sshsig_armor");
2796 if ((r = sshsig_verify_fd(sigbuf, STDIN_FILENO, sig_namespace,
2797 &sign_key, &sig_details)) != 0)
2798 goto done; /* sshsig_verify() prints error */
2800 if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
2801 SSH_FP_DEFAULT)) == NULL)
2802 fatal_f("sshkey_fingerprint failed");
2803 debug("Valid (unverified) signature from key %s", fp);
2804 if (sig_details != NULL) {
2805 debug2_f("signature details: counter = %u, flags = 0x%02x",
2806 sig_details->sk_counter, sig_details->sk_flags);
2811 if (revoked_keys != NULL) {
2812 if ((r = sshkey_check_revoked(sign_key, revoked_keys)) != 0) {
2813 debug3_fr(r, "sshkey_check_revoked");
2818 if (allowed_keys != NULL && (r = sshsig_check_allowed_keys(allowed_keys,
2819 sign_key, principal, sig_namespace, verify_time)) != 0) {
2820 debug3_fr(r, "sshsig_check_allowed_keys");
2828 if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
2829 SSH_FP_DEFAULT)) == NULL)
2830 fatal_f("sshkey_fingerprint failed");
2831 if (principal == NULL) {
2832 printf("Good \"%s\" signature with %s key %s\n",
2833 sig_namespace, sshkey_type(sign_key), fp);
2836 printf("Good \"%s\" signature for %s with %s key %s\n",
2837 sig_namespace, principal,
2838 sshkey_type(sign_key), fp);
2841 printf("Could not verify signature.\n");
2844 /* Print the signature key if requested */
2845 if (ret == 0 && print_pubkey && sign_key != NULL) {
2846 if ((r = sshkey_write(sign_key, stdout)) == 0)
2847 fputc('\n', stdout);
2849 error_r(r, "Could not print public key.\n");
2853 sshbuf_free(sigbuf);
2855 sshkey_free(sign_key);
2856 sshkey_sig_details_free(sig_details);
2862 sig_find_principals(const char *signature, const char *allowed_keys,
2863 char * const *opts, size_t nopts)
2866 struct sshbuf *sigbuf = NULL, *abuf = NULL;
2867 struct sshkey *sign_key = NULL;
2868 char *principals = NULL, *cp, *tmp;
2869 uint64_t verify_time = 0;
2871 if (sig_process_opts(opts, nopts, NULL, &verify_time, NULL) != 0)
2872 goto done; /* error already logged */
2874 if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
2875 error_r(r, "Couldn't read signature file");
2878 if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
2879 error_fr(r, "sshsig_armor");
2882 if ((r = sshsig_get_pubkey(sigbuf, &sign_key)) != 0) {
2883 error_fr(r, "sshsig_get_pubkey");
2886 if ((r = sshsig_find_principals(allowed_keys, sign_key,
2887 verify_time, &principals)) != 0) {
2888 if (r != SSH_ERR_KEY_NOT_FOUND)
2889 error_fr(r, "sshsig_find_principal");
2895 /* Emit matching principals one per line */
2897 while ((cp = strsep(&tmp, ",")) != NULL && *cp != '\0')
2900 fprintf(stderr, "No principal matched.\n");
2902 sshbuf_free(sigbuf);
2904 sshkey_free(sign_key);
2910 sig_match_principals(const char *allowed_keys, char *principal,
2911 char * const *opts, size_t nopts)
2914 char **principals = NULL;
2915 size_t i, nprincipals = 0;
2917 if ((r = sig_process_opts(opts, nopts, NULL, NULL, NULL)) != 0)
2918 return r; /* error already logged */
2920 if ((r = sshsig_match_principals(allowed_keys, principal,
2921 &principals, &nprincipals)) != 0) {
2922 debug_f("match: %s", ssh_err(r));
2923 fprintf(stderr, "No principal matched.\n");
2926 for (i = 0; i < nprincipals; i++) {
2927 printf("%s\n", principals[i]);
2928 free(principals[i]);
2936 do_moduli_gen(const char *out_file, char **opts, size_t nopts)
2939 /* Moduli generation/screening */
2940 u_int32_t memory = 0;
2941 BIGNUM *start = NULL;
2942 int moduli_bits = 0;
2948 for (i = 0; i < nopts; i++) {
2949 if (strncmp(opts[i], "memory=", 7) == 0) {
2950 memory = (u_int32_t)strtonum(opts[i]+7, 1,
2953 fatal("Memory limit is %s: %s",
2956 } else if (strncmp(opts[i], "start=", 6) == 0) {
2957 /* XXX - also compare length against bits */
2958 if (BN_hex2bn(&start, opts[i]+6) == 0)
2959 fatal("Invalid start point.");
2960 } else if (strncmp(opts[i], "bits=", 5) == 0) {
2961 moduli_bits = (int)strtonum(opts[i]+5, 1,
2964 fatal("Invalid number: %s (%s)",
2965 opts[i]+12, errstr);
2968 fatal("Option \"%s\" is unsupported for moduli "
2969 "generation", opts[i]);
2973 if ((out = fopen(out_file, "w")) == NULL) {
2974 fatal("Couldn't open modulus candidate file \"%s\": %s",
2975 out_file, strerror(errno));
2977 setvbuf(out, NULL, _IOLBF, 0);
2979 if (moduli_bits == 0)
2980 moduli_bits = DEFAULT_BITS;
2981 if (gen_candidates(out, memory, moduli_bits, start) != 0)
2982 fatal("modulus candidate generation failed");
2983 #else /* WITH_OPENSSL */
2984 fatal("Moduli generation is not supported");
2985 #endif /* WITH_OPENSSL */
2989 do_moduli_screen(const char *out_file, char **opts, size_t nopts)
2992 /* Moduli generation/screening */
2993 char *checkpoint = NULL;
2994 u_int32_t generator_wanted = 0;
2995 unsigned long start_lineno = 0, lines_to_process = 0;
2996 int prime_tests = 0;
2997 FILE *out, *in = stdin;
3002 for (i = 0; i < nopts; i++) {
3003 if (strncmp(opts[i], "lines=", 6) == 0) {
3004 lines_to_process = strtoul(opts[i]+6, NULL, 10);
3005 } else if (strncmp(opts[i], "start-line=", 11) == 0) {
3006 start_lineno = strtoul(opts[i]+11, NULL, 10);
3007 } else if (strncmp(opts[i], "checkpoint=", 11) == 0) {
3008 checkpoint = xstrdup(opts[i]+11);
3009 } else if (strncmp(opts[i], "generator=", 10) == 0) {
3010 generator_wanted = (u_int32_t)strtonum(
3011 opts[i]+10, 1, UINT_MAX, &errstr);
3012 if (errstr != NULL) {
3013 fatal("Generator invalid: %s (%s)",
3014 opts[i]+10, errstr);
3016 } else if (strncmp(opts[i], "prime-tests=", 12) == 0) {
3017 prime_tests = (int)strtonum(opts[i]+12, 1,
3020 fatal("Invalid number: %s (%s)",
3021 opts[i]+12, errstr);
3024 fatal("Option \"%s\" is unsupported for moduli "
3025 "screening", opts[i]);
3029 if (have_identity && strcmp(identity_file, "-") != 0) {
3030 if ((in = fopen(identity_file, "r")) == NULL) {
3031 fatal("Couldn't open modulus candidate "
3032 "file \"%s\": %s", identity_file,
3037 if ((out = fopen(out_file, "a")) == NULL) {
3038 fatal("Couldn't open moduli file \"%s\": %s",
3039 out_file, strerror(errno));
3041 setvbuf(out, NULL, _IOLBF, 0);
3042 if (prime_test(in, out, prime_tests == 0 ? 100 : prime_tests,
3043 generator_wanted, checkpoint,
3044 start_lineno, lines_to_process) != 0)
3045 fatal("modulus screening failed");
3046 #else /* WITH_OPENSSL */
3047 fatal("Moduli screening is not supported");
3048 #endif /* WITH_OPENSSL */
3051 /* Read and confirm a passphrase */
3053 read_check_passphrase(const char *prompt1, const char *prompt2,
3054 const char *retry_prompt)
3056 char *passphrase1, *passphrase2;
3059 passphrase1 = read_passphrase(prompt1, RP_ALLOW_STDIN);
3060 passphrase2 = read_passphrase(prompt2, RP_ALLOW_STDIN);
3061 if (strcmp(passphrase1, passphrase2) == 0) {
3062 freezero(passphrase2, strlen(passphrase2));
3065 /* The passphrases do not match. Clear them and retry. */
3066 freezero(passphrase1, strlen(passphrase1));
3067 freezero(passphrase2, strlen(passphrase2));
3068 fputs(retry_prompt, stdout);
3069 fputc('\n', stdout);
3077 private_key_passphrase(void)
3079 if (identity_passphrase)
3080 return xstrdup(identity_passphrase);
3081 if (identity_new_passphrase)
3082 return xstrdup(identity_new_passphrase);
3084 return read_check_passphrase(
3085 "Enter passphrase (empty for no passphrase): ",
3086 "Enter same passphrase again: ",
3087 "Passphrases do not match. Try again.");
3091 sk_suffix(const char *application, const uint8_t *user, size_t userlen)
3096 /* Trim off URL-like preamble */
3097 if (strncmp(application, "ssh://", 6) == 0)
3098 ret = xstrdup(application + 6);
3099 else if (strncmp(application, "ssh:", 4) == 0)
3100 ret = xstrdup(application + 4);
3102 ret = xstrdup(application);
3104 /* Count trailing zeros in user */
3105 for (i = 0; i < userlen; i++) {
3106 if (user[userlen - i - 1] != 0)
3110 return ret; /* user-id was default all-zeros */
3112 /* Append user-id, escaping non-UTF-8 characters */
3114 if (asmprintf(&cp, INT_MAX, NULL, "%.*s", (int)slen, user) == -1)
3115 fatal_f("asmprintf failed");
3116 /* Don't emit a user-id that contains path or control characters */
3117 if (strchr(cp, '/') != NULL || strstr(cp, "..") != NULL ||
3118 strchr(cp, '\\') != NULL) {
3120 cp = tohex(user, slen);
3122 xextendf(&ret, "_", "%s", cp);
3128 do_download_sk(const char *skprovider, const char *device)
3130 struct sshsk_resident_key **srks;
3133 char *fp, *pin = NULL, *pass = NULL, *path, *pubpath;
3137 if (skprovider == NULL)
3138 fatal("Cannot download keys without provider");
3140 pin = read_passphrase("Enter PIN for authenticator: ", RP_ALLOW_STDIN);
3142 printf("You may need to touch your authenticator "
3143 "to authorize key download.\n");
3145 if ((r = sshsk_load_resident(skprovider, device, pin, 0,
3146 &srks, &nsrks)) != 0) {
3148 freezero(pin, strlen(pin));
3149 error_r(r, "Unable to load resident keys");
3153 logit("No keys to download");
3155 freezero(pin, strlen(pin));
3157 for (i = 0; i < nsrks; i++) {
3159 if (key->type != KEY_ECDSA_SK && key->type != KEY_ED25519_SK) {
3160 error("Unsupported key type %s (%d)",
3161 sshkey_type(key), key->type);
3164 if ((fp = sshkey_fingerprint(key, fingerprint_hash,
3165 SSH_FP_DEFAULT)) == NULL)
3166 fatal_f("sshkey_fingerprint failed");
3167 debug_f("key %zu: %s %s %s (flags 0x%02x)", i,
3168 sshkey_type(key), fp, key->sk_application, key->sk_flags);
3169 ext = sk_suffix(key->sk_application,
3170 srks[i]->user_id, srks[i]->user_id_len);
3171 xasprintf(&path, "id_%s_rk%s%s",
3172 key->type == KEY_ECDSA_SK ? "ecdsa_sk" : "ed25519_sk",
3173 *ext == '\0' ? "" : "_", ext);
3175 /* If the file already exists, ask the user to confirm. */
3176 if (!confirm_overwrite(path)) {
3181 /* Save the key with the application string as the comment */
3183 pass = private_key_passphrase();
3184 if ((r = sshkey_save_private(key, path, pass,
3185 key->sk_application, private_key_format,
3186 openssh_format_cipher, rounds)) != 0) {
3187 error_r(r, "Saving key \"%s\" failed", path);
3192 printf("Saved %s key%s%s to %s\n", sshkey_type(key),
3193 *ext != '\0' ? " " : "",
3194 *ext != '\0' ? key->sk_application : "",
3198 /* Save public key too */
3199 xasprintf(&pubpath, "%s.pub", path);
3201 if ((r = sshkey_save_public(key, pubpath,
3202 key->sk_application)) != 0) {
3203 error_r(r, "Saving public key \"%s\" failed", pubpath);
3211 ret = 0; /* success */
3213 freezero(pass, strlen(pass));
3214 sshsk_free_resident_keys(srks, nsrks);
3219 save_attestation(struct sshbuf *attest, const char *path)
3225 return; /* nothing to do */
3226 if (attest == NULL || sshbuf_len(attest) == 0)
3227 fatal("Enrollment did not return attestation data");
3229 r = sshbuf_write_file(path, attest);
3232 fatal_r(r, "Unable to write attestation data \"%s\"", path);
3234 printf("Your FIDO attestation certificate has been saved in "
3239 confirm_sk_overwrite(const char *application, const char *user)
3243 printf("A resident key scoped to '%s' with user id '%s' already "
3244 "exists.\n", application == NULL ? "ssh:" : application,
3245 user == NULL ? "null" : user);
3246 printf("Overwrite key in token (y/n)? ");
3248 if (fgets(yesno, sizeof(yesno), stdin) == NULL)
3250 if (yesno[0] != 'y' && yesno[0] != 'Y')
3259 "usage: ssh-keygen [-q] [-a rounds] [-b bits] [-C comment] [-f output_keyfile]\n"
3260 " [-m format] [-N new_passphrase] [-O option]\n"
3261 " [-t dsa | ecdsa | ecdsa-sk | ed25519 | ed25519-sk | rsa]\n"
3262 " [-w provider] [-Z cipher]\n"
3263 " ssh-keygen -p [-a rounds] [-f keyfile] [-m format] [-N new_passphrase]\n"
3264 " [-P old_passphrase] [-Z cipher]\n"
3266 " ssh-keygen -i [-f input_keyfile] [-m key_format]\n"
3267 " ssh-keygen -e [-f input_keyfile] [-m key_format]\n"
3269 " ssh-keygen -y [-f input_keyfile]\n"
3270 " ssh-keygen -c [-a rounds] [-C comment] [-f keyfile] [-P passphrase]\n"
3271 " ssh-keygen -l [-v] [-E fingerprint_hash] [-f input_keyfile]\n"
3272 " ssh-keygen -B [-f input_keyfile]\n");
3273 #ifdef ENABLE_PKCS11
3275 " ssh-keygen -D pkcs11\n");
3278 " ssh-keygen -F hostname [-lv] [-f known_hosts_file]\n"
3279 " ssh-keygen -H [-f known_hosts_file]\n"
3280 " ssh-keygen -K [-a rounds] [-w provider]\n"
3281 " ssh-keygen -R hostname [-f known_hosts_file]\n"
3282 " ssh-keygen -r hostname [-g] [-f input_keyfile]\n"
3284 " ssh-keygen -M generate [-O option] output_file\n"
3285 " ssh-keygen -M screen [-f input_file] [-O option] output_file\n"
3287 " ssh-keygen -I certificate_identity -s ca_key [-hU] [-D pkcs11_provider]\n"
3288 " [-n principals] [-O option] [-V validity_interval]\n"
3289 " [-z serial_number] file ...\n"
3290 " ssh-keygen -L [-f input_keyfile]\n"
3291 " ssh-keygen -A [-a rounds] [-f prefix_path]\n"
3292 " ssh-keygen -k -f krl_file [-u] [-s ca_public] [-z version_number]\n"
3294 " ssh-keygen -Q [-l] -f krl_file [file ...]\n"
3295 " ssh-keygen -Y find-principals -s signature_file -f allowed_signers_file\n"
3296 " ssh-keygen -Y match-principals -I signer_identity -f allowed_signers_file\n"
3297 " ssh-keygen -Y check-novalidate -n namespace -s signature_file\n"
3298 " ssh-keygen -Y sign -f key_file -n namespace file [-O option] ...\n"
3299 " ssh-keygen -Y verify -f allowed_signers_file -I signer_identity\n"
3300 " -n namespace -s signature_file [-r krl_file] [-O option]\n");
3305 * Main program for key management.
3308 main(int argc, char **argv)
3310 char comment[1024], *passphrase = NULL;
3311 char *rr_hostname = NULL, *ep, *fp, *ra;
3312 struct sshkey *private, *public;
3315 int change_passphrase = 0, change_comment = 0, show_cert = 0;
3316 int find_host = 0, delete_host = 0, hash_hosts = 0;
3317 int gen_all_hostkeys = 0, gen_krl = 0, update_krl = 0, check_krl = 0;
3318 int prefer_agent = 0, convert_to = 0, convert_from = 0;
3319 int print_public = 0, print_generic = 0, cert_serial_autoinc = 0;
3320 int do_gen_candidates = 0, do_screen_candidates = 0, download_sk = 0;
3321 unsigned long long cert_serial = 0;
3322 char *identity_comment = NULL, *ca_key_path = NULL, **opts = NULL;
3323 char *sk_application = NULL, *sk_device = NULL, *sk_user = NULL;
3324 char *sk_attestation_path = NULL;
3325 struct sshbuf *challenge = NULL, *attest = NULL;
3326 size_t i, nopts = 0;
3328 uint8_t sk_flags = SSH_SK_USER_PRESENCE_REQD;
3330 int log_level = SYSLOG_LEVEL_INFO;
3331 char *sign_op = NULL;
3334 extern char *optarg;
3336 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
3339 __progname = ssh_get_progname(argv[0]);
3343 log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
3347 /* we need this for the home * directory. */
3348 pw = getpwuid(getuid());
3350 fatal("No user exists for uid %lu", (u_long)getuid());
3352 if (gethostname(hostname, sizeof(hostname)) == -1)
3353 fatal("gethostname: %s", strerror(errno));
3355 sk_provider = getenv("SSH_SK_PROVIDER");
3357 /* Remaining characters: dGjJSTWx */
3358 while ((opt = getopt(argc, argv, "ABHKLQUXceghiklopquvy"
3359 "C:D:E:F:I:M:N:O:P:R:V:Y:Z:"
3360 "a:b:f:g:m:n:r:s:t:w:z:")) != -1) {
3363 gen_all_hostkeys = 1;
3366 bits = (u_int32_t)strtonum(optarg, 1, UINT32_MAX,
3369 fatal("Bits has bad value %s (%s)",
3373 fingerprint_hash = ssh_digest_alg_by_name(optarg);
3374 if (fingerprint_hash == -1)
3375 fatal("Invalid hash algorithm \"%s\"", optarg);
3379 rr_hostname = optarg;
3385 cert_key_id = optarg;
3389 rr_hostname = optarg;
3395 print_fingerprint = 1;
3398 print_bubblebabble = 1;
3401 if (strcasecmp(optarg, "RFC4716") == 0 ||
3402 strcasecmp(optarg, "ssh2") == 0) {
3403 convert_format = FMT_RFC4716;
3406 if (strcasecmp(optarg, "PKCS8") == 0) {
3407 convert_format = FMT_PKCS8;
3408 private_key_format = SSHKEY_PRIVATE_PKCS8;
3411 if (strcasecmp(optarg, "PEM") == 0) {
3412 convert_format = FMT_PEM;
3413 private_key_format = SSHKEY_PRIVATE_PEM;
3416 fatal("Unsupported conversion format \"%s\"", optarg);
3418 cert_principals = optarg;
3421 /* no-op; new format is already the default */
3424 change_passphrase = 1;
3430 if (strlcpy(identity_file, optarg,
3431 sizeof(identity_file)) >= sizeof(identity_file))
3432 fatal("Identity filename too long");
3442 identity_passphrase = optarg;
3445 identity_new_passphrase = optarg;
3451 opts = xrecallocarray(opts, nopts, nopts + 1,
3453 opts[nopts++] = xstrdup(optarg);
3456 openssh_format_cipher = optarg;
3457 if (cipher_by_name(openssh_format_cipher) == NULL)
3458 fatal("Invalid OpenSSH-format cipher '%s'",
3459 openssh_format_cipher);
3462 identity_comment = optarg;
3472 cert_key_type = SSH2_CERT_TYPE_HOST;
3473 certflags_flags = 0;
3487 ca_key_path = optarg;
3490 key_type_name = optarg;
3493 pkcs11provider = optarg;
3502 if (log_level == SYSLOG_LEVEL_INFO)
3503 log_level = SYSLOG_LEVEL_DEBUG1;
3505 if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
3506 log_level < SYSLOG_LEVEL_DEBUG3)
3511 rr_hostname = optarg;
3514 rounds = (int)strtonum(optarg, 1, INT_MAX, &errstr);
3516 fatal("Invalid number: %s (%s)",
3520 parse_cert_times(optarg);
3526 sk_provider = optarg;
3530 if (*optarg == '+') {
3531 cert_serial_autoinc = 1;
3534 cert_serial = strtoull(optarg, &ep, 10);
3535 if (*optarg < '0' || *optarg > '9' || *ep != '\0' ||
3536 (errno == ERANGE && cert_serial == ULLONG_MAX))
3537 fatal("Invalid serial number \"%s\"", optarg);
3540 if (strcmp(optarg, "generate") == 0)
3541 do_gen_candidates = 1;
3542 else if (strcmp(optarg, "screen") == 0)
3543 do_screen_candidates = 1;
3545 fatal("Unsupported moduli option %s", optarg);
3553 #ifdef ENABLE_SK_INTERNAL
3554 if (sk_provider == NULL)
3555 sk_provider = "internal";
3559 log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
3564 if (sign_op != NULL) {
3565 if (strncmp(sign_op, "find-principals", 15) == 0) {
3566 if (ca_key_path == NULL) {
3567 error("Too few arguments for find-principals:"
3568 "missing signature file");
3571 if (!have_identity) {
3572 error("Too few arguments for find-principals:"
3573 "missing allowed keys file");
3576 return sig_find_principals(ca_key_path, identity_file,
3578 } else if (strncmp(sign_op, "match-principals", 16) == 0) {
3579 if (!have_identity) {
3580 error("Too few arguments for match-principals:"
3581 "missing allowed keys file");
3584 if (cert_key_id == NULL) {
3585 error("Too few arguments for match-principals: "
3586 "missing principal ID");
3589 return sig_match_principals(identity_file, cert_key_id,
3591 } else if (strncmp(sign_op, "sign", 4) == 0) {
3592 /* NB. cert_principals is actually namespace, via -n */
3593 if (cert_principals == NULL ||
3594 *cert_principals == '\0') {
3595 error("Too few arguments for sign: "
3596 "missing namespace");
3599 if (!have_identity) {
3600 error("Too few arguments for sign: "
3604 return sig_sign(identity_file, cert_principals,
3605 prefer_agent, argc, argv, opts, nopts);
3606 } else if (strncmp(sign_op, "check-novalidate", 16) == 0) {
3607 /* NB. cert_principals is actually namespace, via -n */
3608 if (cert_principals == NULL ||
3609 *cert_principals == '\0') {
3610 error("Too few arguments for check-novalidate: "
3611 "missing namespace");
3614 if (ca_key_path == NULL) {
3615 error("Too few arguments for check-novalidate: "
3616 "missing signature file");
3619 return sig_verify(ca_key_path, cert_principals,
3620 NULL, NULL, NULL, opts, nopts);
3621 } else if (strncmp(sign_op, "verify", 6) == 0) {
3622 /* NB. cert_principals is actually namespace, via -n */
3623 if (cert_principals == NULL ||
3624 *cert_principals == '\0') {
3625 error("Too few arguments for verify: "
3626 "missing namespace");
3629 if (ca_key_path == NULL) {
3630 error("Too few arguments for verify: "
3631 "missing signature file");
3634 if (!have_identity) {
3635 error("Too few arguments for sign: "
3636 "missing allowed keys file");
3639 if (cert_key_id == NULL) {
3640 error("Too few arguments for verify: "
3641 "missing principal identity");
3644 return sig_verify(ca_key_path, cert_principals,
3645 cert_key_id, identity_file, rr_hostname,
3648 error("Unsupported operation for -Y: \"%s\"", sign_op);
3653 if (ca_key_path != NULL) {
3654 if (argc < 1 && !gen_krl) {
3655 error("Too few arguments.");
3658 } else if (argc > 0 && !gen_krl && !check_krl &&
3659 !do_gen_candidates && !do_screen_candidates) {
3660 error("Too many arguments.");
3663 if (change_passphrase && change_comment) {
3664 error("Can only have one of -p and -c.");
3667 if (print_fingerprint && (delete_host || hash_hosts)) {
3668 error("Cannot use -l with -H or -R.");
3672 do_gen_krl(pw, update_krl, ca_key_path,
3673 cert_serial, identity_comment, argc, argv);
3677 do_check_krl(pw, print_fingerprint, argc, argv);
3680 if (ca_key_path != NULL) {
3681 if (cert_key_id == NULL)
3682 fatal("Must specify key id (-I) when certifying");
3683 for (i = 0; i < nopts; i++)
3684 add_cert_option(opts[i]);
3685 do_ca_sign(pw, ca_key_path, prefer_agent,
3686 cert_serial, cert_serial_autoinc, argc, argv);
3690 if (delete_host || hash_hosts || find_host) {
3691 do_known_hosts(pw, rr_hostname, find_host,
3692 delete_host, hash_hosts);
3694 if (pkcs11provider != NULL)
3697 for (i = 0; i < nopts; i++) {
3698 if (strncasecmp(opts[i], "device=", 7) == 0) {
3699 sk_device = xstrdup(opts[i] + 7);
3701 fatal("Option \"%s\" is unsupported for "
3702 "FIDO authenticator download", opts[i]);
3705 return do_download_sk(sk_provider, sk_device);
3707 if (print_fingerprint || print_bubblebabble)
3709 if (change_passphrase)
3710 do_change_passphrase(pw);
3712 do_change_comment(pw, identity_comment);
3717 do_convert_from(pw);
3718 #else /* WITH_OPENSSL */
3719 if (convert_to || convert_from)
3720 fatal("key conversion disabled at compile time");
3721 #endif /* WITH_OPENSSL */
3723 do_print_public(pw);
3724 if (rr_hostname != NULL) {
3727 if (have_identity) {
3728 n = do_print_resource_record(pw, identity_file,
3729 rr_hostname, print_generic);
3731 fatal("%s: %s", identity_file, strerror(errno));
3735 n += do_print_resource_record(pw,
3736 _PATH_HOST_RSA_KEY_FILE, rr_hostname,
3738 n += do_print_resource_record(pw,
3739 _PATH_HOST_DSA_KEY_FILE, rr_hostname,
3741 n += do_print_resource_record(pw,
3742 _PATH_HOST_ECDSA_KEY_FILE, rr_hostname,
3744 n += do_print_resource_record(pw,
3745 _PATH_HOST_ED25519_KEY_FILE, rr_hostname,
3747 n += do_print_resource_record(pw,
3748 _PATH_HOST_XMSS_KEY_FILE, rr_hostname,
3751 fatal("no keys found.");
3756 if (do_gen_candidates || do_screen_candidates) {
3758 fatal("No output file specified");
3760 fatal("Too many output files specified");
3762 if (do_gen_candidates) {
3763 do_moduli_gen(argv[0], opts, nopts);
3766 if (do_screen_candidates) {
3767 do_moduli_screen(argv[0], opts, nopts);
3771 if (gen_all_hostkeys) {
3772 do_gen_all_hostkeys(pw);
3776 if (key_type_name == NULL)
3777 key_type_name = DEFAULT_KEY_TYPE_NAME;
3779 type = sshkey_type_from_name(key_type_name);
3780 type_bits_valid(type, key_type_name, &bits);
3783 printf("Generating public/private %s key pair.\n",
3787 case KEY_ED25519_SK:
3788 for (i = 0; i < nopts; i++) {
3789 if (strcasecmp(opts[i], "no-touch-required") == 0) {
3790 sk_flags &= ~SSH_SK_USER_PRESENCE_REQD;
3791 } else if (strcasecmp(opts[i], "verify-required") == 0) {
3792 sk_flags |= SSH_SK_USER_VERIFICATION_REQD;
3793 } else if (strcasecmp(opts[i], "resident") == 0) {
3794 sk_flags |= SSH_SK_RESIDENT_KEY;
3795 } else if (strncasecmp(opts[i], "device=", 7) == 0) {
3796 sk_device = xstrdup(opts[i] + 7);
3797 } else if (strncasecmp(opts[i], "user=", 5) == 0) {
3798 sk_user = xstrdup(opts[i] + 5);
3799 } else if (strncasecmp(opts[i], "challenge=", 10) == 0) {
3800 if ((r = sshbuf_load_file(opts[i] + 10,
3801 &challenge)) != 0) {
3802 fatal_r(r, "Unable to load FIDO "
3803 "enrollment challenge \"%s\"",
3806 } else if (strncasecmp(opts[i],
3807 "write-attestation=", 18) == 0) {
3808 sk_attestation_path = opts[i] + 18;
3809 } else if (strncasecmp(opts[i],
3810 "application=", 12) == 0) {
3811 sk_application = xstrdup(opts[i] + 12);
3812 if (strncmp(sk_application, "ssh:", 4) != 0) {
3813 fatal("FIDO application string must "
3814 "begin with \"ssh:\"");
3817 fatal("Option \"%s\" is unsupported for "
3818 "FIDO authenticator enrollment", opts[i]);
3821 if ((attest = sshbuf_new()) == NULL)
3822 fatal("sshbuf_new failed");
3826 printf("You may need to touch your "
3827 "authenticator%s to authorize key "
3829 r == 0 ? "" : " again");
3832 r = sshsk_enroll(type, sk_provider, sk_device,
3833 sk_application == NULL ? "ssh:" : sk_application,
3834 sk_user, sk_flags, passphrase, challenge,
3838 if (r == SSH_ERR_KEY_BAD_PERMISSIONS &&
3839 (sk_flags & SSH_SK_RESIDENT_KEY) != 0 &&
3840 (sk_flags & SSH_SK_FORCE_OPERATION) == 0 &&
3841 confirm_sk_overwrite(sk_application, sk_user)) {
3842 sk_flags |= SSH_SK_FORCE_OPERATION;
3845 if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
3846 fatal_r(r, "Key enrollment failed");
3847 else if (passphrase != NULL) {
3848 error("PIN incorrect");
3849 freezero(passphrase, strlen(passphrase));
3853 fatal("Too many incorrect PINs");
3854 passphrase = read_passphrase("Enter PIN for "
3855 "authenticator: ", RP_ALLOW_STDIN);
3857 if (passphrase != NULL) {
3858 freezero(passphrase, strlen(passphrase));
3863 if ((r = sshkey_generate(type, bits, &private)) != 0)
3864 fatal("sshkey_generate failed");
3867 if ((r = sshkey_from_private(private, &public)) != 0)
3868 fatal_r(r, "sshkey_from_private");
3871 ask_filename(pw, "Enter file in which to save the key");
3873 /* Create ~/.ssh directory if it doesn't already exist. */
3874 hostfile_create_user_ssh_dir(identity_file, !quiet);
3876 /* If the file already exists, ask the user to confirm. */
3877 if (!confirm_overwrite(identity_file))
3880 /* Determine the passphrase for the private key */
3881 passphrase = private_key_passphrase();
3882 if (identity_comment) {
3883 strlcpy(comment, identity_comment, sizeof(comment));
3885 /* Create default comment field for the passphrase. */
3886 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
3889 /* Save the key with the given passphrase and comment. */
3890 if ((r = sshkey_save_private(private, identity_file, passphrase,
3891 comment, private_key_format, openssh_format_cipher, rounds)) != 0) {
3892 error_r(r, "Saving key \"%s\" failed", identity_file);
3893 freezero(passphrase, strlen(passphrase));
3896 freezero(passphrase, strlen(passphrase));
3897 sshkey_free(private);
3900 printf("Your identification has been saved in %s\n",
3904 strlcat(identity_file, ".pub", sizeof(identity_file));
3905 if ((r = sshkey_save_public(public, identity_file, comment)) != 0)
3906 fatal_r(r, "Unable to save public key to %s", identity_file);
3909 fp = sshkey_fingerprint(public, fingerprint_hash,
3911 ra = sshkey_fingerprint(public, fingerprint_hash,
3913 if (fp == NULL || ra == NULL)
3914 fatal("sshkey_fingerprint failed");
3915 printf("Your public key has been saved in %s\n",
3917 printf("The key fingerprint is:\n");
3918 printf("%s %s\n", fp, comment);
3919 printf("The key's randomart image is:\n");
3925 if (sk_attestation_path != NULL)
3926 save_attestation(attest, sk_attestation_path);
3928 sshbuf_free(attest);
3929 sshkey_free(public);