1 /* $OpenBSD: ssh-keygen.c,v 1.466 2023/03/08 00:05:37 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 const char *alg = NULL;
480 u_char e1, e2, e3, *sig = NULL, data[] = "abcde12345";
482 u_int magic, i1, i2, i3, i4;
485 BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL;
486 BIGNUM *dsa_pub_key = NULL, *dsa_priv_key = NULL;
487 BIGNUM *rsa_n = NULL, *rsa_e = NULL, *rsa_d = NULL;
488 BIGNUM *rsa_p = NULL, *rsa_q = NULL, *rsa_iqmp = NULL;
490 if ((r = sshbuf_get_u32(b, &magic)) != 0)
491 fatal_fr(r, "parse magic");
493 if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
494 error("bad magic 0x%x != 0x%x", magic,
495 SSH_COM_PRIVATE_KEY_MAGIC);
498 if ((r = sshbuf_get_u32(b, &i1)) != 0 ||
499 (r = sshbuf_get_cstring(b, &type, NULL)) != 0 ||
500 (r = sshbuf_get_cstring(b, &cipher, NULL)) != 0 ||
501 (r = sshbuf_get_u32(b, &i2)) != 0 ||
502 (r = sshbuf_get_u32(b, &i3)) != 0 ||
503 (r = sshbuf_get_u32(b, &i4)) != 0)
504 fatal_fr(r, "parse");
505 debug("ignore (%d %d %d %d)", i1, i2, i3, i4);
506 if (strcmp(cipher, "none") != 0) {
507 error("unsupported cipher %s", cipher);
514 if (strstr(type, "dsa")) {
516 } else if (strstr(type, "rsa")) {
522 if ((key = sshkey_new(ktype)) == NULL)
523 fatal("sshkey_new failed");
528 if ((dsa_p = BN_new()) == NULL ||
529 (dsa_q = BN_new()) == NULL ||
530 (dsa_g = BN_new()) == NULL ||
531 (dsa_pub_key = BN_new()) == NULL ||
532 (dsa_priv_key = BN_new()) == NULL)
534 buffer_get_bignum_bits(b, dsa_p);
535 buffer_get_bignum_bits(b, dsa_g);
536 buffer_get_bignum_bits(b, dsa_q);
537 buffer_get_bignum_bits(b, dsa_pub_key);
538 buffer_get_bignum_bits(b, dsa_priv_key);
539 if (!DSA_set0_pqg(key->dsa, dsa_p, dsa_q, dsa_g))
540 fatal_f("DSA_set0_pqg failed");
541 dsa_p = dsa_q = dsa_g = NULL; /* transferred */
542 if (!DSA_set0_key(key->dsa, dsa_pub_key, dsa_priv_key))
543 fatal_f("DSA_set0_key failed");
544 dsa_pub_key = dsa_priv_key = NULL; /* transferred */
547 if ((r = sshbuf_get_u8(b, &e1)) != 0 ||
548 (e1 < 30 && (r = sshbuf_get_u8(b, &e2)) != 0) ||
549 (e1 < 30 && (r = sshbuf_get_u8(b, &e3)) != 0))
550 fatal_fr(r, "parse RSA");
561 if ((rsa_e = BN_new()) == NULL)
563 if (!BN_set_word(rsa_e, e)) {
564 BN_clear_free(rsa_e);
568 if ((rsa_n = BN_new()) == NULL ||
569 (rsa_d = BN_new()) == NULL ||
570 (rsa_p = BN_new()) == NULL ||
571 (rsa_q = BN_new()) == NULL ||
572 (rsa_iqmp = BN_new()) == NULL)
574 buffer_get_bignum_bits(b, rsa_d);
575 buffer_get_bignum_bits(b, rsa_n);
576 buffer_get_bignum_bits(b, rsa_iqmp);
577 buffer_get_bignum_bits(b, rsa_q);
578 buffer_get_bignum_bits(b, rsa_p);
579 if (!RSA_set0_key(key->rsa, rsa_n, rsa_e, rsa_d))
580 fatal_f("RSA_set0_key failed");
581 rsa_n = rsa_e = rsa_d = NULL; /* transferred */
582 if (!RSA_set0_factors(key->rsa, rsa_p, rsa_q))
583 fatal_f("RSA_set0_factors failed");
584 rsa_p = rsa_q = NULL; /* transferred */
585 if ((r = ssh_rsa_complete_crt_parameters(key, rsa_iqmp)) != 0)
586 fatal_fr(r, "generate RSA parameters");
587 BN_clear_free(rsa_iqmp);
588 alg = "rsa-sha2-256";
591 rlen = sshbuf_len(b);
593 error_f("remaining bytes in key blob %d", rlen);
596 if ((r = sshkey_sign(key, &sig, &slen, data, sizeof(data),
597 alg, NULL, NULL, 0)) != 0)
598 error_fr(r, "signing with converted key failed");
599 else if ((r = sshkey_verify(key, sig, slen, data, sizeof(data),
601 error_fr(r, "verification with converted key failed");
612 get_line(FILE *fp, char *line, size_t len)
618 while ((c = fgetc(fp)) != EOF) {
620 fatal("input line too long.");
624 if (c != EOF && c != '\n' && ungetc(c, fp) == EOF)
625 fatal("unget: %s", strerror(errno));
638 do_convert_from_ssh2(struct passwd *pw, struct sshkey **k, int *private)
640 int r, blen, escaped = 0;
647 if ((buf = sshbuf_new()) == NULL)
648 fatal("sshbuf_new failed");
649 if ((fp = fopen(identity_file, "r")) == NULL)
650 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
652 while ((blen = get_line(fp, line, sizeof(line))) != -1) {
653 if (blen > 0 && line[blen - 1] == '\\')
655 if (strncmp(line, "----", 4) == 0 ||
656 strstr(line, ": ") != NULL) {
657 if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
659 if (strstr(line, " END ") != NULL) {
662 /* fprintf(stderr, "ignore: %s", line); */
667 /* fprintf(stderr, "escaped: %s", line); */
670 strlcat(encoded, line, sizeof(encoded));
672 len = strlen(encoded);
673 if (((len % 4) == 3) &&
674 (encoded[len-1] == '=') &&
675 (encoded[len-2] == '=') &&
676 (encoded[len-3] == '='))
677 encoded[len-3] = '\0';
678 if ((r = sshbuf_b64tod(buf, encoded)) != 0)
679 fatal_fr(r, "base64 decode");
681 if ((*k = do_convert_private_ssh2(buf)) == NULL)
682 fatal_f("private key conversion failed");
683 } else if ((r = sshkey_fromb(buf, k)) != 0)
684 fatal_fr(r, "parse key");
690 do_convert_from_pkcs8(struct sshkey **k, int *private)
695 if ((fp = fopen(identity_file, "r")) == NULL)
696 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
697 if ((pubkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL)) == NULL) {
698 fatal_f("%s is not a recognised public key format",
702 switch (EVP_PKEY_base_id(pubkey)) {
704 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
705 fatal("sshkey_new failed");
706 (*k)->type = KEY_RSA;
707 (*k)->rsa = EVP_PKEY_get1_RSA(pubkey);
710 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
711 fatal("sshkey_new failed");
712 (*k)->type = KEY_DSA;
713 (*k)->dsa = EVP_PKEY_get1_DSA(pubkey);
715 #ifdef OPENSSL_HAS_ECC
717 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
718 fatal("sshkey_new failed");
719 (*k)->type = KEY_ECDSA;
720 (*k)->ecdsa = EVP_PKEY_get1_EC_KEY(pubkey);
721 (*k)->ecdsa_nid = sshkey_ecdsa_key_to_nid((*k)->ecdsa);
725 fatal_f("unsupported pubkey type %d",
726 EVP_PKEY_base_id(pubkey));
728 EVP_PKEY_free(pubkey);
733 do_convert_from_pem(struct sshkey **k, int *private)
738 if ((fp = fopen(identity_file, "r")) == NULL)
739 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
740 if ((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
741 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
742 fatal("sshkey_new failed");
743 (*k)->type = KEY_RSA;
748 fatal_f("unrecognised raw private key format");
752 do_convert_from(struct passwd *pw)
754 struct sshkey *k = NULL;
755 int r, private = 0, ok = 0;
759 ask_filename(pw, "Enter file in which the key is");
760 if (stat(identity_file, &st) == -1)
761 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
763 switch (convert_format) {
765 do_convert_from_ssh2(pw, &k, &private);
768 do_convert_from_pkcs8(&k, &private);
771 do_convert_from_pem(&k, &private);
774 fatal_f("unknown key format %d", convert_format);
778 if ((r = sshkey_write(k, stdout)) == 0)
781 fprintf(stdout, "\n");
785 ok = PEM_write_DSAPrivateKey(stdout, k->dsa, NULL,
786 NULL, 0, NULL, NULL);
788 #ifdef OPENSSL_HAS_ECC
790 ok = PEM_write_ECPrivateKey(stdout, k->ecdsa, NULL,
791 NULL, 0, NULL, NULL);
795 ok = PEM_write_RSAPrivateKey(stdout, k->rsa, NULL,
796 NULL, 0, NULL, NULL);
799 fatal_f("unsupported key type %s", sshkey_type(k));
804 fatal("key write failed");
811 do_print_public(struct passwd *pw)
816 char *comment = NULL;
819 ask_filename(pw, "Enter file in which the key is");
820 if (stat(identity_file, &st) == -1)
821 fatal("%s: %s", identity_file, strerror(errno));
822 prv = load_identity(identity_file, &comment);
823 if ((r = sshkey_write(prv, stdout)) != 0)
824 fatal_fr(r, "write key");
825 if (comment != NULL && *comment != '\0')
826 fprintf(stdout, " %s", comment);
827 fprintf(stdout, "\n");
828 if (sshkey_is_sk(prv)) {
829 debug("sk_application: \"%s\", sk_flags 0x%02x",
830 prv->sk_application, prv->sk_flags);
838 do_download(struct passwd *pw)
841 struct sshkey **keys = NULL;
843 enum sshkey_fp_rep rep;
845 char *fp, *ra, **comments = NULL;
847 fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
848 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
851 nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys, &comments);
853 fatal("cannot read public key from pkcs11");
854 for (i = 0; i < nkeys; i++) {
855 if (print_fingerprint) {
856 fp = sshkey_fingerprint(keys[i], fptype, rep);
857 ra = sshkey_fingerprint(keys[i], fingerprint_hash,
859 if (fp == NULL || ra == NULL)
860 fatal_f("sshkey_fingerprint fail");
861 printf("%u %s %s (PKCS11 key)\n", sshkey_size(keys[i]),
862 fp, sshkey_type(keys[i]));
863 if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
868 (void) sshkey_write(keys[i], stdout); /* XXX check */
869 fprintf(stdout, "%s%s\n",
870 *(comments[i]) == '\0' ? "" : " ", comments[i]);
873 sshkey_free(keys[i]);
880 fatal("no pkcs11 support");
881 #endif /* ENABLE_PKCS11 */
884 static struct sshkey *
885 try_read_key(char **cpp)
890 if ((ret = sshkey_new(KEY_UNSPEC)) == NULL)
891 fatal("sshkey_new failed");
892 if ((r = sshkey_read(ret, cpp)) == 0)
900 fingerprint_one_key(const struct sshkey *public, const char *comment)
902 char *fp = NULL, *ra = NULL;
903 enum sshkey_fp_rep rep;
906 fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
907 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
908 fp = sshkey_fingerprint(public, fptype, rep);
909 ra = sshkey_fingerprint(public, fingerprint_hash, SSH_FP_RANDOMART);
910 if (fp == NULL || ra == NULL)
911 fatal_f("sshkey_fingerprint failed");
912 mprintf("%u %s %s (%s)\n", sshkey_size(public), fp,
913 comment ? comment : "no comment", sshkey_type(public));
914 if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
921 fingerprint_private(const char *path)
924 char *comment = NULL;
925 struct sshkey *privkey = NULL, *pubkey = NULL;
928 if (stat(identity_file, &st) == -1)
929 fatal("%s: %s", path, strerror(errno));
930 if ((r = sshkey_load_public(path, &pubkey, &comment)) != 0)
931 debug_r(r, "load public \"%s\"", path);
932 if (pubkey == NULL || comment == NULL || *comment == '\0') {
934 if ((r = sshkey_load_private(path, NULL,
935 &privkey, &comment)) != 0)
936 debug_r(r, "load private \"%s\"", path);
938 if (pubkey == NULL && privkey == NULL)
939 fatal("%s is not a key file.", path);
941 fingerprint_one_key(pubkey == NULL ? privkey : pubkey, comment);
943 sshkey_free(privkey);
948 do_fingerprint(struct passwd *pw)
951 struct sshkey *public = NULL;
952 char *comment = NULL, *cp, *ep, *line = NULL;
959 ask_filename(pw, "Enter file in which the key is");
960 path = identity_file;
962 if (strcmp(identity_file, "-") == 0) {
965 } else if ((f = fopen(path, "r")) == NULL)
966 fatal("%s: %s: %s", __progname, path, strerror(errno));
968 while (getline(&line, &linesize, f) != -1) {
971 cp[strcspn(cp, "\n")] = '\0';
972 /* Trim leading space and comments */
973 cp = line + strspn(line, " \t");
974 if (*cp == '#' || *cp == '\0')
978 * Input may be plain keys, private keys, authorized_keys
983 * Try private keys first. Assume a key is private if
984 * "SSH PRIVATE KEY" appears on the first line and we're
985 * not reading from stdin (XXX support private keys on stdin).
987 if (lnum == 1 && strcmp(identity_file, "-") != 0 &&
988 strstr(cp, "PRIVATE KEY") != NULL) {
991 fingerprint_private(path);
996 * If it's not a private key, then this must be prepared to
997 * accept a public key prefixed with a hostname or options.
998 * Try a bare key first, otherwise skip the leading stuff.
1000 if ((public = try_read_key(&cp)) == NULL) {
1001 i = strtol(cp, &ep, 10);
1002 if (i == 0 || ep == NULL ||
1003 (*ep != ' ' && *ep != '\t')) {
1007 for (; *cp && (quoted || (*cp != ' ' &&
1008 *cp != '\t')); cp++) {
1009 if (*cp == '\\' && cp[1] == '"')
1010 cp++; /* Skip both */
1011 else if (*cp == '"')
1019 /* Retry after parsing leading hostname/key options */
1020 if (public == NULL && (public = try_read_key(&cp)) == NULL) {
1021 debug("%s:%lu: not a public key", path, lnum);
1025 /* Find trailing comment, if any */
1026 for (; *cp == ' ' || *cp == '\t'; cp++)
1028 if (*cp != '\0' && *cp != '#')
1031 fingerprint_one_key(public, comment);
1032 sshkey_free(public);
1033 invalid = 0; /* One good key in the file is sufficient */
1039 fatal("%s is not a public key file.", path);
1044 do_gen_all_hostkeys(struct passwd *pw)
1048 char *key_type_display;
1052 { "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE },
1053 #ifdef OPENSSL_HAS_ECC
1054 { "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE },
1055 #endif /* OPENSSL_HAS_ECC */
1056 #endif /* WITH_OPENSSL */
1057 { "ed25519", "ED25519",_PATH_HOST_ED25519_KEY_FILE },
1059 { "xmss", "XMSS",_PATH_HOST_XMSS_KEY_FILE },
1060 #endif /* WITH_XMSS */
1061 { NULL, NULL, NULL }
1067 struct sshkey *private, *public;
1068 char comment[1024], *prv_tmp, *pub_tmp, *prv_file, *pub_file;
1071 for (i = 0; key_types[i].key_type; i++) {
1072 public = private = NULL;
1073 prv_tmp = pub_tmp = prv_file = pub_file = NULL;
1075 xasprintf(&prv_file, "%s%s",
1076 identity_file, key_types[i].path);
1078 /* Check whether private key exists and is not zero-length */
1079 if (stat(prv_file, &st) == 0) {
1080 if (st.st_size != 0)
1082 } else if (errno != ENOENT) {
1083 error("Could not stat %s: %s", key_types[i].path,
1089 * Private key doesn't exist or is invalid; proceed with
1092 xasprintf(&prv_tmp, "%s%s.XXXXXXXXXX",
1093 identity_file, key_types[i].path);
1094 xasprintf(&pub_tmp, "%s%s.pub.XXXXXXXXXX",
1095 identity_file, key_types[i].path);
1096 xasprintf(&pub_file, "%s%s.pub",
1097 identity_file, key_types[i].path);
1101 printf("%s: generating new host keys: ", __progname);
1103 printf("%s ", key_types[i].key_type_display);
1105 type = sshkey_type_from_name(key_types[i].key_type);
1106 if ((fd = mkstemp(prv_tmp)) == -1) {
1107 error("Could not save your private key in %s: %s",
1108 prv_tmp, strerror(errno));
1111 (void)close(fd); /* just using mkstemp() to reserve a name */
1113 type_bits_valid(type, NULL, &bits);
1114 if ((r = sshkey_generate(type, bits, &private)) != 0) {
1115 error_r(r, "sshkey_generate failed");
1118 if ((r = sshkey_from_private(private, &public)) != 0)
1119 fatal_fr(r, "sshkey_from_private");
1120 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name,
1122 if ((r = sshkey_save_private(private, prv_tmp, "",
1123 comment, private_key_format, openssh_format_cipher,
1125 error_r(r, "Saving key \"%s\" failed", prv_tmp);
1128 if ((fd = mkstemp(pub_tmp)) == -1) {
1129 error("Could not save your public key in %s: %s",
1130 pub_tmp, strerror(errno));
1133 (void)fchmod(fd, 0644);
1135 if ((r = sshkey_save_public(public, pub_tmp, comment)) != 0) {
1136 error_r(r, "Unable to save public key to %s",
1141 /* Rename temporary files to their permanent locations. */
1142 if (rename(pub_tmp, pub_file) != 0) {
1143 error("Unable to move %s into position: %s",
1144 pub_file, strerror(errno));
1147 if (rename(prv_tmp, prv_file) != 0) {
1148 error("Unable to move %s into position: %s",
1149 key_types[i].path, strerror(errno));
1155 sshkey_free(private);
1156 sshkey_free(public);
1166 struct known_hosts_ctx {
1167 const char *host; /* Hostname searched for in find/delete case */
1168 FILE *out; /* Output file, stdout for find_hosts case */
1169 int has_unhashed; /* When hashing, original had unhashed hosts */
1170 int found_key; /* For find/delete, host was found */
1171 int invalid; /* File contained invalid items; don't delete */
1172 int hash_hosts; /* Hash hostnames as we go */
1173 int find_host; /* Search for specific hostname */
1174 int delete_host; /* Delete host from known_hosts */
1178 known_hosts_hash(struct hostkey_foreach_line *l, void *_ctx)
1180 struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1181 char *hashed, *cp, *hosts, *ohosts;
1182 int has_wild = l->hosts && strcspn(l->hosts, "*?!") != strlen(l->hosts);
1183 int was_hashed = l->hosts && l->hosts[0] == HASH_DELIM;
1185 switch (l->status) {
1187 case HKF_STATUS_MATCHED:
1189 * Don't hash hosts already already hashed, with wildcard
1190 * characters or a CA/revocation marker.
1192 if (was_hashed || has_wild || l->marker != MRK_NONE) {
1193 fprintf(ctx->out, "%s\n", l->line);
1194 if (has_wild && !ctx->find_host) {
1195 logit("%s:%lu: ignoring host name "
1196 "with wildcard: %.64s", l->path,
1197 l->linenum, l->hosts);
1202 * Split any comma-separated hostnames from the host list,
1203 * hash and store separately.
1205 ohosts = hosts = xstrdup(l->hosts);
1206 while ((cp = strsep(&hosts, ",")) != NULL && *cp != '\0') {
1208 if ((hashed = host_hash(cp, NULL, 0)) == NULL)
1209 fatal("hash_host failed");
1210 fprintf(ctx->out, "%s %s\n", hashed, l->rawkey);
1212 ctx->has_unhashed = 1;
1216 case HKF_STATUS_INVALID:
1217 /* Retain invalid lines, but mark file as invalid. */
1219 logit("%s:%lu: invalid line", l->path, l->linenum);
1222 fprintf(ctx->out, "%s\n", l->line);
1230 known_hosts_find_delete(struct hostkey_foreach_line *l, void *_ctx)
1232 struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1233 enum sshkey_fp_rep rep;
1235 char *fp = NULL, *ra = NULL;
1237 fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
1238 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1240 if (l->status == HKF_STATUS_MATCHED) {
1241 if (ctx->delete_host) {
1242 if (l->marker != MRK_NONE) {
1243 /* Don't remove CA and revocation lines */
1244 fprintf(ctx->out, "%s\n", l->line);
1247 * Hostname matches and has no CA/revoke
1248 * marker, delete it by *not* writing the
1253 printf("# Host %s found: line %lu\n",
1254 ctx->host, l->linenum);
1257 } else if (ctx->find_host) {
1260 printf("# Host %s found: line %lu %s\n",
1262 l->linenum, l->marker == MRK_CA ? "CA" :
1263 (l->marker == MRK_REVOKE ? "REVOKED" : ""));
1265 if (ctx->hash_hosts)
1266 known_hosts_hash(l, ctx);
1267 else if (print_fingerprint) {
1268 fp = sshkey_fingerprint(l->key, fptype, rep);
1269 ra = sshkey_fingerprint(l->key,
1270 fingerprint_hash, SSH_FP_RANDOMART);
1271 if (fp == NULL || ra == NULL)
1272 fatal_f("sshkey_fingerprint failed");
1273 mprintf("%s %s %s%s%s\n", ctx->host,
1274 sshkey_type(l->key), fp,
1275 l->comment[0] ? " " : "",
1277 if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
1282 fprintf(ctx->out, "%s\n", l->line);
1285 } else if (ctx->delete_host) {
1286 /* Retain non-matching hosts when deleting */
1287 if (l->status == HKF_STATUS_INVALID) {
1289 logit("%s:%lu: invalid line", l->path, l->linenum);
1291 fprintf(ctx->out, "%s\n", l->line);
1297 do_known_hosts(struct passwd *pw, const char *name, int find_host,
1298 int delete_host, int hash_hosts)
1300 char *cp, tmp[PATH_MAX], old[PATH_MAX];
1301 int r, fd, oerrno, inplace = 0;
1302 struct known_hosts_ctx ctx;
1303 u_int foreach_options;
1306 if (!have_identity) {
1307 cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
1308 if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
1309 sizeof(identity_file))
1310 fatal("Specified known hosts path too long");
1314 if (stat(identity_file, &sb) != 0)
1315 fatal("Cannot stat %s: %s", identity_file, strerror(errno));
1317 memset(&ctx, 0, sizeof(ctx));
1320 ctx.hash_hosts = hash_hosts;
1321 ctx.find_host = find_host;
1322 ctx.delete_host = delete_host;
1325 * Find hosts goes to stdout, hash and deletions happen in-place
1326 * A corner case is ssh-keygen -HF foo, which should go to stdout
1328 if (!find_host && (hash_hosts || delete_host)) {
1329 if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
1330 strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
1331 strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
1332 strlcat(old, ".old", sizeof(old)) >= sizeof(old))
1333 fatal("known_hosts path too long");
1335 if ((fd = mkstemp(tmp)) == -1)
1336 fatal("mkstemp: %s", strerror(errno));
1337 if ((ctx.out = fdopen(fd, "w")) == NULL) {
1340 fatal("fdopen: %s", strerror(oerrno));
1342 (void)fchmod(fd, sb.st_mode & 0644);
1345 /* XXX support identity_file == "-" for stdin */
1346 foreach_options = find_host ? HKF_WANT_MATCH : 0;
1347 foreach_options |= print_fingerprint ? HKF_WANT_PARSE_KEY : 0;
1348 if ((r = hostkeys_foreach(identity_file, (find_host || !hash_hosts) ?
1349 known_hosts_find_delete : known_hosts_hash, &ctx, name, NULL,
1350 foreach_options, 0)) != 0) {
1353 fatal_fr(r, "hostkeys_foreach");
1360 error("%s is not a valid known_hosts file.", identity_file);
1362 error("Not replacing existing known_hosts "
1363 "file because of errors");
1367 } else if (delete_host && !ctx.found_key) {
1368 logit("Host %s not found in %s", name, identity_file);
1371 } else if (inplace) {
1372 /* Backup existing file */
1373 if (unlink(old) == -1 && errno != ENOENT)
1374 fatal("unlink %.100s: %s", old, strerror(errno));
1375 if (link(identity_file, old) == -1)
1376 fatal("link %.100s to %.100s: %s", identity_file, old,
1378 /* Move new one into place */
1379 if (rename(tmp, identity_file) == -1) {
1380 error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
1387 printf("%s updated.\n", identity_file);
1388 printf("Original contents retained as %s\n", old);
1389 if (ctx.has_unhashed) {
1390 logit("WARNING: %s contains unhashed entries", old);
1391 logit("Delete this file to ensure privacy "
1396 exit (find_host && !ctx.found_key);
1400 * Perform changing a passphrase. The argument is the passwd structure
1401 * for the current user.
1404 do_change_passphrase(struct passwd *pw)
1407 char *old_passphrase, *passphrase1, *passphrase2;
1409 struct sshkey *private;
1413 ask_filename(pw, "Enter file in which the key is");
1414 if (stat(identity_file, &st) == -1)
1415 fatal("%s: %s", identity_file, strerror(errno));
1416 /* Try to load the file with empty passphrase. */
1417 r = sshkey_load_private(identity_file, "", &private, &comment);
1418 if (r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
1419 if (identity_passphrase)
1420 old_passphrase = xstrdup(identity_passphrase);
1423 read_passphrase("Enter old passphrase: ",
1425 r = sshkey_load_private(identity_file, old_passphrase,
1426 &private, &comment);
1427 freezero(old_passphrase, strlen(old_passphrase));
1430 } else if (r != 0) {
1432 fatal_r(r, "Failed to load key %s", identity_file);
1435 mprintf("Key has comment '%s'\n", comment);
1437 /* Ask the new passphrase (twice). */
1438 if (identity_new_passphrase) {
1439 passphrase1 = xstrdup(identity_new_passphrase);
1443 read_passphrase("Enter new passphrase (empty for no "
1444 "passphrase): ", RP_ALLOW_STDIN);
1445 passphrase2 = read_passphrase("Enter same passphrase again: ",
1448 /* Verify that they are the same. */
1449 if (strcmp(passphrase1, passphrase2) != 0) {
1450 explicit_bzero(passphrase1, strlen(passphrase1));
1451 explicit_bzero(passphrase2, strlen(passphrase2));
1454 printf("Pass phrases do not match. Try again.\n");
1457 /* Destroy the other copy. */
1458 freezero(passphrase2, strlen(passphrase2));
1461 /* Save the file using the new passphrase. */
1462 if ((r = sshkey_save_private(private, identity_file, passphrase1,
1463 comment, private_key_format, openssh_format_cipher, rounds)) != 0) {
1464 error_r(r, "Saving key \"%s\" failed", identity_file);
1465 freezero(passphrase1, strlen(passphrase1));
1466 sshkey_free(private);
1470 /* Destroy the passphrase and the copy of the key in memory. */
1471 freezero(passphrase1, strlen(passphrase1));
1472 sshkey_free(private); /* Destroys contents */
1475 printf("Your identification has been saved with the new passphrase.\n");
1480 * Print the SSHFP RR.
1483 do_print_resource_record(struct passwd *pw, char *fname, char *hname,
1484 int print_generic, char * const *opts, size_t nopts)
1486 struct sshkey *public;
1487 char *comment = NULL;
1492 for (i = 0; i < nopts; i++) {
1493 if (strncasecmp(opts[i], "hashalg=", 8) == 0) {
1494 if ((hash = ssh_digest_alg_by_name(opts[i] + 8)) == -1)
1495 fatal("Unsupported hash algorithm");
1497 error("Invalid option \"%s\"", opts[i]);
1498 return SSH_ERR_INVALID_ARGUMENT;
1502 fatal_f("no filename");
1503 if (stat(fname, &st) == -1) {
1504 if (errno == ENOENT)
1506 fatal("%s: %s", fname, strerror(errno));
1508 if ((r = sshkey_load_public(fname, &public, &comment)) != 0)
1509 fatal_r(r, "Failed to read v2 public key from \"%s\"", fname);
1510 export_dns_rr(hname, public, stdout, print_generic, hash);
1511 sshkey_free(public);
1517 * Change the comment of a private key file.
1520 do_change_comment(struct passwd *pw, const char *identity_comment)
1522 char new_comment[1024], *comment, *passphrase;
1523 struct sshkey *private;
1524 struct sshkey *public;
1529 ask_filename(pw, "Enter file in which the key is");
1530 if (stat(identity_file, &st) == -1)
1531 fatal("%s: %s", identity_file, strerror(errno));
1532 if ((r = sshkey_load_private(identity_file, "",
1533 &private, &comment)) == 0)
1534 passphrase = xstrdup("");
1535 else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
1536 fatal_r(r, "Cannot load private key \"%s\"", identity_file);
1538 if (identity_passphrase)
1539 passphrase = xstrdup(identity_passphrase);
1540 else if (identity_new_passphrase)
1541 passphrase = xstrdup(identity_new_passphrase);
1543 passphrase = read_passphrase("Enter passphrase: ",
1545 /* Try to load using the passphrase. */
1546 if ((r = sshkey_load_private(identity_file, passphrase,
1547 &private, &comment)) != 0) {
1548 freezero(passphrase, strlen(passphrase));
1549 fatal_r(r, "Cannot load private key \"%s\"",
1554 if (private->type != KEY_ED25519 && private->type != KEY_XMSS &&
1555 private_key_format != SSHKEY_PRIVATE_OPENSSH) {
1556 error("Comments are only supported for keys stored in "
1557 "the new format (-o).");
1558 explicit_bzero(passphrase, strlen(passphrase));
1559 sshkey_free(private);
1563 printf("Old comment: %s\n", comment);
1565 printf("No existing comment\n");
1567 if (identity_comment) {
1568 strlcpy(new_comment, identity_comment, sizeof(new_comment));
1570 printf("New comment: ");
1572 if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1573 explicit_bzero(passphrase, strlen(passphrase));
1574 sshkey_free(private);
1577 new_comment[strcspn(new_comment, "\n")] = '\0';
1579 if (comment != NULL && strcmp(comment, new_comment) == 0) {
1580 printf("No change to comment\n");
1582 sshkey_free(private);
1587 /* Save the file using the new passphrase. */
1588 if ((r = sshkey_save_private(private, identity_file, passphrase,
1589 new_comment, private_key_format, openssh_format_cipher,
1591 error_r(r, "Saving key \"%s\" failed", identity_file);
1592 freezero(passphrase, strlen(passphrase));
1593 sshkey_free(private);
1597 freezero(passphrase, strlen(passphrase));
1598 if ((r = sshkey_from_private(private, &public)) != 0)
1599 fatal_fr(r, "sshkey_from_private");
1600 sshkey_free(private);
1602 strlcat(identity_file, ".pub", sizeof(identity_file));
1603 if ((r = sshkey_save_public(public, identity_file, new_comment)) != 0)
1604 fatal_r(r, "Unable to save public key to %s", identity_file);
1605 sshkey_free(public);
1608 if (strlen(new_comment) > 0)
1609 printf("Comment '%s' applied\n", new_comment);
1611 printf("Comment removed\n");
1617 cert_ext_add(const char *key, const char *value, int iscrit)
1619 cert_ext = xreallocarray(cert_ext, ncert_ext + 1, sizeof(*cert_ext));
1620 cert_ext[ncert_ext].key = xstrdup(key);
1621 cert_ext[ncert_ext].val = value == NULL ? NULL : xstrdup(value);
1622 cert_ext[ncert_ext].crit = iscrit;
1626 /* qsort(3) comparison function for certificate extensions */
1628 cert_ext_cmp(const void *_a, const void *_b)
1630 const struct cert_ext *a = (const struct cert_ext *)_a;
1631 const struct cert_ext *b = (const struct cert_ext *)_b;
1634 if (a->crit != b->crit)
1635 return (a->crit < b->crit) ? -1 : 1;
1636 if ((r = strcmp(a->key, b->key)) != 0)
1638 if ((a->val == NULL) != (b->val == NULL))
1639 return (a->val == NULL) ? -1 : 1;
1640 if (a->val != NULL && (r = strcmp(a->val, b->val)) != 0)
1645 #define OPTIONS_CRITICAL 1
1646 #define OPTIONS_EXTENSIONS 2
1648 prepare_options_buf(struct sshbuf *c, int which)
1653 const struct cert_ext *ext;
1655 if ((b = sshbuf_new()) == NULL)
1656 fatal_f("sshbuf_new failed");
1658 for (i = 0; i < ncert_ext; i++) {
1660 if ((ext->crit && (which & OPTIONS_EXTENSIONS)) ||
1661 (!ext->crit && (which & OPTIONS_CRITICAL)))
1663 if (ext->val == NULL) {
1665 debug3_f("%s", ext->key);
1666 if ((r = sshbuf_put_cstring(c, ext->key)) != 0 ||
1667 (r = sshbuf_put_string(c, NULL, 0)) != 0)
1668 fatal_fr(r, "prepare flag");
1670 /* key/value option */
1671 debug3_f("%s=%s", ext->key, ext->val);
1673 if ((r = sshbuf_put_cstring(c, ext->key)) != 0 ||
1674 (r = sshbuf_put_cstring(b, ext->val)) != 0 ||
1675 (r = sshbuf_put_stringb(c, b)) != 0)
1676 fatal_fr(r, "prepare k/v");
1683 finalise_cert_exts(void)
1685 /* critical options */
1686 if (certflags_command != NULL)
1687 cert_ext_add("force-command", certflags_command, 1);
1688 if (certflags_src_addr != NULL)
1689 cert_ext_add("source-address", certflags_src_addr, 1);
1690 if ((certflags_flags & CERTOPT_REQUIRE_VERIFY) != 0)
1691 cert_ext_add("verify-required", NULL, 1);
1693 if ((certflags_flags & CERTOPT_X_FWD) != 0)
1694 cert_ext_add("permit-X11-forwarding", NULL, 0);
1695 if ((certflags_flags & CERTOPT_AGENT_FWD) != 0)
1696 cert_ext_add("permit-agent-forwarding", NULL, 0);
1697 if ((certflags_flags & CERTOPT_PORT_FWD) != 0)
1698 cert_ext_add("permit-port-forwarding", NULL, 0);
1699 if ((certflags_flags & CERTOPT_PTY) != 0)
1700 cert_ext_add("permit-pty", NULL, 0);
1701 if ((certflags_flags & CERTOPT_USER_RC) != 0)
1702 cert_ext_add("permit-user-rc", NULL, 0);
1703 if ((certflags_flags & CERTOPT_NO_REQUIRE_USER_PRESENCE) != 0)
1704 cert_ext_add("no-touch-required", NULL, 0);
1705 /* order lexically by key */
1707 qsort(cert_ext, ncert_ext, sizeof(*cert_ext), cert_ext_cmp);
1710 static struct sshkey *
1711 load_pkcs11_key(char *path)
1713 #ifdef ENABLE_PKCS11
1714 struct sshkey **keys = NULL, *public, *private = NULL;
1717 if ((r = sshkey_load_public(path, &public, NULL)) != 0)
1718 fatal_r(r, "Couldn't load CA public key \"%s\"", path);
1720 nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase,
1722 debug3_f("%d keys", nkeys);
1724 fatal("cannot read public key from pkcs11");
1725 for (i = 0; i < nkeys; i++) {
1726 if (sshkey_equal_public(public, keys[i])) {
1730 sshkey_free(keys[i]);
1733 sshkey_free(public);
1736 fatal("no pkcs11 support");
1737 #endif /* ENABLE_PKCS11 */
1740 /* Signer for sshkey_certify_custom that uses the agent */
1742 agent_signer(struct sshkey *key, u_char **sigp, size_t *lenp,
1743 const u_char *data, size_t datalen,
1744 const char *alg, const char *provider, const char *pin,
1745 u_int compat, void *ctx)
1747 int *agent_fdp = (int *)ctx;
1749 return ssh_agent_sign(*agent_fdp, key, sigp, lenp,
1750 data, datalen, alg, compat);
1754 do_ca_sign(struct passwd *pw, const char *ca_key_path, int prefer_agent,
1755 unsigned long long cert_serial, int cert_serial_autoinc,
1756 int argc, char **argv)
1758 int r, i, found, agent_fd = -1;
1760 struct sshkey *ca, *public;
1761 char valid[64], *otmp, *tmp, *cp, *out, *comment;
1762 char *ca_fp = NULL, **plist = NULL, *pin = NULL;
1763 struct ssh_identitylist *agent_ids;
1765 struct notifier_ctx *notifier = NULL;
1767 #ifdef ENABLE_PKCS11
1770 tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
1771 if (pkcs11provider != NULL) {
1772 /* If a PKCS#11 token was specified then try to use it */
1773 if ((ca = load_pkcs11_key(tmp)) == NULL)
1774 fatal("No PKCS#11 key matching %s found", ca_key_path);
1775 } else if (prefer_agent) {
1777 * Agent signature requested. Try to use agent after making
1778 * sure the public key specified is actually present in the
1781 if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
1782 fatal_r(r, "Cannot load CA public key %s", tmp);
1783 if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
1784 fatal_r(r, "Cannot use public key for CA signature");
1785 if ((r = ssh_fetch_identitylist(agent_fd, &agent_ids)) != 0)
1786 fatal_r(r, "Retrieve agent key list");
1788 for (j = 0; j < agent_ids->nkeys; j++) {
1789 if (sshkey_equal(ca, agent_ids->keys[j])) {
1795 fatal("CA key %s not found in agent", tmp);
1796 ssh_free_identitylist(agent_ids);
1797 ca->flags |= SSHKEY_FLAG_EXT;
1799 /* CA key is assumed to be a private key on the filesystem */
1800 ca = load_identity(tmp, NULL);
1801 if (sshkey_is_sk(ca) &&
1802 (ca->sk_flags & SSH_SK_USER_VERIFICATION_REQD)) {
1803 if ((pin = read_passphrase("Enter PIN for CA key: ",
1804 RP_ALLOW_STDIN)) == NULL)
1805 fatal_f("couldn't read PIN");
1810 if (key_type_name != NULL) {
1811 if (sshkey_type_from_name(key_type_name) != ca->type) {
1812 fatal("CA key type %s doesn't match specified %s",
1813 sshkey_ssh_name(ca), key_type_name);
1815 } else if (ca->type == KEY_RSA) {
1816 /* Default to a good signature algorithm */
1817 key_type_name = "rsa-sha2-512";
1819 ca_fp = sshkey_fingerprint(ca, fingerprint_hash, SSH_FP_DEFAULT);
1821 finalise_cert_exts();
1822 for (i = 0; i < argc; i++) {
1823 /* Split list of principals */
1825 if (cert_principals != NULL) {
1826 otmp = tmp = xstrdup(cert_principals);
1828 for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1829 plist = xreallocarray(plist, n + 1, sizeof(*plist));
1830 if (*(plist[n] = xstrdup(cp)) == '\0')
1831 fatal("Empty principal name");
1835 if (n > SSHKEY_CERT_MAX_PRINCIPALS)
1836 fatal("Too many certificate principals specified");
1838 tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1839 if ((r = sshkey_load_public(tmp, &public, &comment)) != 0)
1840 fatal_r(r, "load pubkey \"%s\"", tmp);
1841 if (sshkey_is_cert(public))
1842 fatal_f("key \"%s\" type %s cannot be certified",
1843 tmp, sshkey_type(public));
1845 /* Prepare certificate to sign */
1846 if ((r = sshkey_to_certified(public)) != 0)
1847 fatal_r(r, "Could not upgrade key %s to certificate", tmp);
1848 public->cert->type = cert_key_type;
1849 public->cert->serial = (u_int64_t)cert_serial;
1850 public->cert->key_id = xstrdup(cert_key_id);
1851 public->cert->nprincipals = n;
1852 public->cert->principals = plist;
1853 public->cert->valid_after = cert_valid_from;
1854 public->cert->valid_before = cert_valid_to;
1855 prepare_options_buf(public->cert->critical, OPTIONS_CRITICAL);
1856 prepare_options_buf(public->cert->extensions,
1857 OPTIONS_EXTENSIONS);
1858 if ((r = sshkey_from_private(ca,
1859 &public->cert->signature_key)) != 0)
1860 fatal_r(r, "sshkey_from_private (ca key)");
1862 if (agent_fd != -1 && (ca->flags & SSHKEY_FLAG_EXT) != 0) {
1863 if ((r = sshkey_certify_custom(public, ca,
1864 key_type_name, sk_provider, NULL, agent_signer,
1866 fatal_r(r, "Couldn't certify %s via agent", tmp);
1868 if (sshkey_is_sk(ca) &&
1869 (ca->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
1870 notifier = notify_start(0,
1871 "Confirm user presence for key %s %s",
1872 sshkey_type(ca), ca_fp);
1874 r = sshkey_certify(public, ca, key_type_name,
1876 notify_complete(notifier, "User presence confirmed");
1878 fatal_r(r, "Couldn't certify key %s", tmp);
1881 if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
1883 xasprintf(&out, "%s-cert.pub", tmp);
1886 if ((r = sshkey_save_public(public, out, comment)) != 0) {
1887 fatal_r(r, "Unable to save public key to %s",
1892 sshkey_format_cert_validity(public->cert,
1893 valid, sizeof(valid));
1894 logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1895 "valid %s", sshkey_cert_type(public),
1896 out, public->cert->key_id,
1897 (unsigned long long)public->cert->serial,
1898 cert_principals != NULL ? " for " : "",
1899 cert_principals != NULL ? cert_principals : "",
1903 sshkey_free(public);
1905 if (cert_serial_autoinc)
1909 freezero(pin, strlen(pin));
1911 #ifdef ENABLE_PKCS11
1918 parse_relative_time(const char *s, time_t now)
1922 mul = *s == '-' ? -1 : 1;
1924 if ((secs = convtime(s + 1)) == -1)
1925 fatal("Invalid relative certificate time %s", s);
1926 if (mul == -1 && secs > now)
1927 fatal("Certificate time %s cannot be represented", s);
1928 return now + (u_int64_t)(secs * mul);
1932 parse_hex_u64(const char *s, uint64_t *up)
1935 unsigned long long ull;
1938 ull = strtoull(s, &ep, 16);
1939 if (*s == '\0' || *ep != '\0')
1940 fatal("Invalid certificate time: not a number");
1941 if (errno == ERANGE && ull == ULONG_MAX)
1942 fatal_fr(SSH_ERR_SYSTEM_ERROR, "Invalid certificate time");
1943 *up = (uint64_t)ull;
1947 parse_cert_times(char *timespec)
1950 time_t now = time(NULL);
1953 /* +timespec relative to now */
1954 if (*timespec == '+' && strchr(timespec, ':') == NULL) {
1955 if ((secs = convtime(timespec + 1)) == -1)
1956 fatal("Invalid relative certificate life %s", timespec);
1957 cert_valid_to = now + secs;
1959 * Backdate certificate one minute to avoid problems on hosts
1960 * with poorly-synchronised clocks.
1962 cert_valid_from = ((now - 59)/ 60) * 60;
1968 * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | 0x... | "always"
1969 * to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | 0x... | "forever"
1971 from = xstrdup(timespec);
1972 to = strchr(from, ':');
1973 if (to == NULL || from == to || *(to + 1) == '\0')
1974 fatal("Invalid certificate life specification %s", timespec);
1977 if (*from == '-' || *from == '+')
1978 cert_valid_from = parse_relative_time(from, now);
1979 else if (strcmp(from, "always") == 0)
1980 cert_valid_from = 0;
1981 else if (strncmp(from, "0x", 2) == 0)
1982 parse_hex_u64(from, &cert_valid_from);
1983 else if (parse_absolute_time(from, &cert_valid_from) != 0)
1984 fatal("Invalid from time \"%s\"", from);
1986 if (*to == '-' || *to == '+')
1987 cert_valid_to = parse_relative_time(to, now);
1988 else if (strcmp(to, "forever") == 0)
1989 cert_valid_to = ~(u_int64_t)0;
1990 else if (strncmp(to, "0x", 2) == 0)
1991 parse_hex_u64(to, &cert_valid_to);
1992 else if (parse_absolute_time(to, &cert_valid_to) != 0)
1993 fatal("Invalid to time \"%s\"", to);
1995 if (cert_valid_to <= cert_valid_from)
1996 fatal("Empty certificate validity interval");
2001 add_cert_option(char *opt)
2006 if (strcasecmp(opt, "clear") == 0)
2007 certflags_flags = 0;
2008 else if (strcasecmp(opt, "no-x11-forwarding") == 0)
2009 certflags_flags &= ~CERTOPT_X_FWD;
2010 else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
2011 certflags_flags |= CERTOPT_X_FWD;
2012 else if (strcasecmp(opt, "no-agent-forwarding") == 0)
2013 certflags_flags &= ~CERTOPT_AGENT_FWD;
2014 else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
2015 certflags_flags |= CERTOPT_AGENT_FWD;
2016 else if (strcasecmp(opt, "no-port-forwarding") == 0)
2017 certflags_flags &= ~CERTOPT_PORT_FWD;
2018 else if (strcasecmp(opt, "permit-port-forwarding") == 0)
2019 certflags_flags |= CERTOPT_PORT_FWD;
2020 else if (strcasecmp(opt, "no-pty") == 0)
2021 certflags_flags &= ~CERTOPT_PTY;
2022 else if (strcasecmp(opt, "permit-pty") == 0)
2023 certflags_flags |= CERTOPT_PTY;
2024 else if (strcasecmp(opt, "no-user-rc") == 0)
2025 certflags_flags &= ~CERTOPT_USER_RC;
2026 else if (strcasecmp(opt, "permit-user-rc") == 0)
2027 certflags_flags |= CERTOPT_USER_RC;
2028 else if (strcasecmp(opt, "touch-required") == 0)
2029 certflags_flags &= ~CERTOPT_NO_REQUIRE_USER_PRESENCE;
2030 else if (strcasecmp(opt, "no-touch-required") == 0)
2031 certflags_flags |= CERTOPT_NO_REQUIRE_USER_PRESENCE;
2032 else if (strcasecmp(opt, "no-verify-required") == 0)
2033 certflags_flags &= ~CERTOPT_REQUIRE_VERIFY;
2034 else if (strcasecmp(opt, "verify-required") == 0)
2035 certflags_flags |= CERTOPT_REQUIRE_VERIFY;
2036 else if (strncasecmp(opt, "force-command=", 14) == 0) {
2039 fatal("Empty force-command option");
2040 if (certflags_command != NULL)
2041 fatal("force-command already specified");
2042 certflags_command = xstrdup(val);
2043 } else if (strncasecmp(opt, "source-address=", 15) == 0) {
2046 fatal("Empty source-address option");
2047 if (certflags_src_addr != NULL)
2048 fatal("source-address already specified");
2049 if (addr_match_cidr_list(NULL, val) != 0)
2050 fatal("Invalid source-address list");
2051 certflags_src_addr = xstrdup(val);
2052 } else if (strncasecmp(opt, "extension:", 10) == 0 ||
2053 (iscrit = (strncasecmp(opt, "critical:", 9) == 0))) {
2054 val = xstrdup(strchr(opt, ':') + 1);
2055 if ((cp = strchr(val, '=')) != NULL)
2057 cert_ext_add(val, cp, iscrit);
2060 fatal("Unsupported certificate option \"%s\"", opt);
2064 show_options(struct sshbuf *optbuf, int in_critical)
2066 char *name, *arg, *hex;
2067 struct sshbuf *options, *option = NULL;
2070 if ((options = sshbuf_fromb(optbuf)) == NULL)
2071 fatal_f("sshbuf_fromb failed");
2072 while (sshbuf_len(options) != 0) {
2073 sshbuf_free(option);
2075 if ((r = sshbuf_get_cstring(options, &name, NULL)) != 0 ||
2076 (r = sshbuf_froms(options, &option)) != 0)
2077 fatal_fr(r, "parse option");
2078 printf(" %s", name);
2080 (strcmp(name, "permit-X11-forwarding") == 0 ||
2081 strcmp(name, "permit-agent-forwarding") == 0 ||
2082 strcmp(name, "permit-port-forwarding") == 0 ||
2083 strcmp(name, "permit-pty") == 0 ||
2084 strcmp(name, "permit-user-rc") == 0 ||
2085 strcmp(name, "no-touch-required") == 0)) {
2087 } else if (in_critical &&
2088 (strcmp(name, "force-command") == 0 ||
2089 strcmp(name, "source-address") == 0)) {
2090 if ((r = sshbuf_get_cstring(option, &arg, NULL)) != 0)
2091 fatal_fr(r, "parse critical");
2092 printf(" %s\n", arg);
2094 } else if (in_critical &&
2095 strcmp(name, "verify-required") == 0) {
2097 } else if (sshbuf_len(option) > 0) {
2098 hex = sshbuf_dtob16(option);
2099 printf(" UNKNOWN OPTION: %s (len %zu)\n",
2100 hex, sshbuf_len(option));
2101 sshbuf_reset(option);
2104 printf(" UNKNOWN FLAG OPTION\n");
2106 if (sshbuf_len(option) != 0)
2107 fatal("Option corrupt: extra data at end");
2109 sshbuf_free(option);
2110 sshbuf_free(options);
2114 print_cert(struct sshkey *key)
2116 char valid[64], *key_fp, *ca_fp;
2119 key_fp = sshkey_fingerprint(key, fingerprint_hash, SSH_FP_DEFAULT);
2120 ca_fp = sshkey_fingerprint(key->cert->signature_key,
2121 fingerprint_hash, SSH_FP_DEFAULT);
2122 if (key_fp == NULL || ca_fp == NULL)
2123 fatal_f("sshkey_fingerprint fail");
2124 sshkey_format_cert_validity(key->cert, valid, sizeof(valid));
2126 printf(" Type: %s %s certificate\n", sshkey_ssh_name(key),
2127 sshkey_cert_type(key));
2128 printf(" Public key: %s %s\n", sshkey_type(key), key_fp);
2129 printf(" Signing CA: %s %s (using %s)\n",
2130 sshkey_type(key->cert->signature_key), ca_fp,
2131 key->cert->signature_type);
2132 printf(" Key ID: \"%s\"\n", key->cert->key_id);
2133 printf(" Serial: %llu\n", (unsigned long long)key->cert->serial);
2134 printf(" Valid: %s\n", valid);
2135 printf(" Principals: ");
2136 if (key->cert->nprincipals == 0)
2139 for (i = 0; i < key->cert->nprincipals; i++)
2141 key->cert->principals[i]);
2144 printf(" Critical Options: ");
2145 if (sshbuf_len(key->cert->critical) == 0)
2149 show_options(key->cert->critical, 1);
2151 printf(" Extensions: ");
2152 if (sshbuf_len(key->cert->extensions) == 0)
2156 show_options(key->cert->extensions, 0);
2161 do_show_cert(struct passwd *pw)
2163 struct sshkey *key = NULL;
2165 int r, is_stdin = 0, ok = 0;
2167 char *cp, *line = NULL;
2169 size_t linesize = 0;
2173 ask_filename(pw, "Enter file in which the key is");
2174 if (strcmp(identity_file, "-") != 0 && stat(identity_file, &st) == -1)
2175 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
2177 path = identity_file;
2178 if (strcmp(path, "-") == 0) {
2182 } else if ((f = fopen(identity_file, "r")) == NULL)
2183 fatal("fopen %s: %s", identity_file, strerror(errno));
2185 while (getline(&line, &linesize, f) != -1) {
2189 /* Trim leading space and comments */
2190 cp = line + strspn(line, " \t");
2191 if (*cp == '#' || *cp == '\0')
2193 if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2194 fatal("sshkey_new");
2195 if ((r = sshkey_read(key, &cp)) != 0) {
2196 error_r(r, "%s:%lu: invalid key", path, lnum);
2199 if (!sshkey_is_cert(key)) {
2200 error("%s:%lu is not a certificate", path, lnum);
2204 if (!is_stdin && lnum == 1)
2205 printf("%s:\n", path);
2207 printf("%s:%lu:\n", path, lnum);
2217 load_krl(const char *path, struct ssh_krl **krlp)
2219 struct sshbuf *krlbuf;
2222 if ((r = sshbuf_load_file(path, &krlbuf)) != 0)
2223 fatal_r(r, "Unable to load KRL %s", path);
2224 /* XXX check sigs */
2225 if ((r = ssh_krl_from_blob(krlbuf, krlp, NULL, 0)) != 0 ||
2227 fatal_r(r, "Invalid KRL file %s", path);
2228 sshbuf_free(krlbuf);
2232 hash_to_blob(const char *cp, u_char **blobp, size_t *lenp,
2233 const char *file, u_long lnum)
2240 if (strncmp(cp, "SHA256:", 7) != 0)
2241 fatal("%s:%lu: unsupported hash algorithm", file, lnum);
2245 * OpenSSH base64 hashes omit trailing '='
2246 * characters; put them back for decode.
2249 tmp = xmalloc(tlen + 4 + 1);
2250 strlcpy(tmp, cp, tlen + 1);
2251 while ((tlen % 4) != 0) {
2255 if ((b = sshbuf_new()) == NULL)
2256 fatal_f("sshbuf_new failed");
2257 if ((r = sshbuf_b64tod(b, tmp)) != 0)
2258 fatal_r(r, "%s:%lu: decode hash failed", file, lnum);
2260 *lenp = sshbuf_len(b);
2261 *blobp = xmalloc(*lenp);
2262 memcpy(*blobp, sshbuf_ptr(b), *lenp);
2267 update_krl_from_file(struct passwd *pw, const char *file, int wild_ca,
2268 const struct sshkey *ca, struct ssh_krl *krl)
2270 struct sshkey *key = NULL;
2272 char *path, *cp, *ep, *line = NULL;
2273 u_char *blob = NULL;
2274 size_t blen = 0, linesize = 0;
2275 unsigned long long serial, serial2;
2276 int i, was_explicit_key, was_sha1, was_sha256, was_hash, r;
2279 path = tilde_expand_filename(file, pw->pw_uid);
2280 if (strcmp(path, "-") == 0) {
2283 path = xstrdup("(standard input)");
2284 } else if ((krl_spec = fopen(path, "r")) == NULL)
2285 fatal("fopen %s: %s", path, strerror(errno));
2288 printf("Revoking from %s\n", path);
2289 while (getline(&line, &linesize, krl_spec) != -1) {
2291 was_explicit_key = was_sha1 = was_sha256 = was_hash = 0;
2292 cp = line + strspn(line, " \t");
2293 /* Trim trailing space, comments and strip \n */
2294 for (i = 0, r = -1; cp[i] != '\0'; i++) {
2295 if (cp[i] == '#' || cp[i] == '\n') {
2299 if (cp[i] == ' ' || cp[i] == '\t') {
2300 /* Remember the start of a span of whitespace */
2310 if (strncasecmp(cp, "serial:", 7) == 0) {
2311 if (ca == NULL && !wild_ca) {
2312 fatal("revoking certificates by serial number "
2313 "requires specification of a CA key");
2316 cp = cp + strspn(cp, " \t");
2318 serial = strtoull(cp, &ep, 0);
2319 if (*cp == '\0' || (*ep != '\0' && *ep != '-'))
2320 fatal("%s:%lu: invalid serial \"%s\"",
2322 if (errno == ERANGE && serial == ULLONG_MAX)
2323 fatal("%s:%lu: serial out of range",
2329 serial2 = strtoull(cp, &ep, 0);
2330 if (*cp == '\0' || *ep != '\0')
2331 fatal("%s:%lu: invalid serial \"%s\"",
2333 if (errno == ERANGE && serial2 == ULLONG_MAX)
2334 fatal("%s:%lu: serial out of range",
2336 if (serial2 <= serial)
2337 fatal("%s:%lu: invalid serial range "
2338 "%llu:%llu", path, lnum,
2339 (unsigned long long)serial,
2340 (unsigned long long)serial2);
2342 if (ssh_krl_revoke_cert_by_serial_range(krl,
2343 ca, serial, serial2) != 0) {
2344 fatal_f("revoke serial failed");
2346 } else if (strncasecmp(cp, "id:", 3) == 0) {
2347 if (ca == NULL && !wild_ca) {
2348 fatal("revoking certificates by key ID "
2349 "requires specification of a CA key");
2352 cp = cp + strspn(cp, " \t");
2353 if (ssh_krl_revoke_cert_by_key_id(krl, ca, cp) != 0)
2354 fatal_f("revoke key ID failed");
2355 } else if (strncasecmp(cp, "hash:", 5) == 0) {
2357 cp = cp + strspn(cp, " \t");
2358 hash_to_blob(cp, &blob, &blen, file, lnum);
2359 r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2361 fatal_fr(r, "revoke key failed");
2363 if (strncasecmp(cp, "key:", 4) == 0) {
2365 cp = cp + strspn(cp, " \t");
2366 was_explicit_key = 1;
2367 } else if (strncasecmp(cp, "sha1:", 5) == 0) {
2369 cp = cp + strspn(cp, " \t");
2371 } else if (strncasecmp(cp, "sha256:", 7) == 0) {
2373 cp = cp + strspn(cp, " \t");
2376 * Just try to process the line as a key.
2377 * Parsing will fail if it isn't.
2380 if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2381 fatal("sshkey_new");
2382 if ((r = sshkey_read(key, &cp)) != 0)
2383 fatal_r(r, "%s:%lu: invalid key", path, lnum);
2384 if (was_explicit_key)
2385 r = ssh_krl_revoke_key_explicit(krl, key);
2386 else if (was_sha1) {
2387 if (sshkey_fingerprint_raw(key,
2388 SSH_DIGEST_SHA1, &blob, &blen) != 0) {
2389 fatal("%s:%lu: fingerprint failed",
2392 r = ssh_krl_revoke_key_sha1(krl, blob, blen);
2393 } else if (was_sha256) {
2394 if (sshkey_fingerprint_raw(key,
2395 SSH_DIGEST_SHA256, &blob, &blen) != 0) {
2396 fatal("%s:%lu: fingerprint failed",
2399 r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2401 r = ssh_krl_revoke_key(krl, key);
2403 fatal_fr(r, "revoke key failed");
2404 freezero(blob, blen);
2410 if (strcmp(path, "-") != 0)
2417 do_gen_krl(struct passwd *pw, int updating, const char *ca_key_path,
2418 unsigned long long krl_version, const char *krl_comment,
2419 int argc, char **argv)
2421 struct ssh_krl *krl;
2423 struct sshkey *ca = NULL;
2424 int i, r, wild_ca = 0;
2426 struct sshbuf *kbuf;
2428 if (*identity_file == '\0')
2429 fatal("KRL generation requires an output file");
2430 if (stat(identity_file, &sb) == -1) {
2431 if (errno != ENOENT)
2432 fatal("Cannot access KRL \"%s\": %s",
2433 identity_file, strerror(errno));
2435 fatal("KRL \"%s\" does not exist", identity_file);
2437 if (ca_key_path != NULL) {
2438 if (strcasecmp(ca_key_path, "none") == 0)
2441 tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
2442 if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
2443 fatal_r(r, "Cannot load CA public key %s", tmp);
2449 load_krl(identity_file, &krl);
2450 else if ((krl = ssh_krl_init()) == NULL)
2451 fatal("couldn't create KRL");
2453 if (krl_version != 0)
2454 ssh_krl_set_version(krl, krl_version);
2455 if (krl_comment != NULL)
2456 ssh_krl_set_comment(krl, krl_comment);
2458 for (i = 0; i < argc; i++)
2459 update_krl_from_file(pw, argv[i], wild_ca, ca, krl);
2461 if ((kbuf = sshbuf_new()) == NULL)
2462 fatal("sshbuf_new failed");
2463 if (ssh_krl_to_blob(krl, kbuf, NULL, 0) != 0)
2464 fatal("Couldn't generate KRL");
2465 if ((r = sshbuf_write_file(identity_file, kbuf)) != 0)
2466 fatal("write %s: %s", identity_file, strerror(errno));
2473 do_check_krl(struct passwd *pw, int print_krl, int argc, char **argv)
2477 struct ssh_krl *krl;
2480 if (*identity_file == '\0')
2481 fatal("KRL checking requires an input file");
2482 load_krl(identity_file, &krl);
2484 krl_dump(krl, stdout);
2485 for (i = 0; i < argc; i++) {
2486 if ((r = sshkey_load_public(argv[i], &k, &comment)) != 0)
2487 fatal_r(r, "Cannot load public key %s", argv[i]);
2488 r = ssh_krl_check_key(krl, k);
2489 printf("%s%s%s%s: %s\n", argv[i],
2490 *comment ? " (" : "", comment, *comment ? ")" : "",
2491 r == 0 ? "ok" : "REVOKED");
2501 static struct sshkey *
2502 load_sign_key(const char *keypath, const struct sshkey *pubkey)
2504 size_t i, slen, plen = strlen(keypath);
2505 char *privpath = xstrdup(keypath);
2506 static const char * const suffixes[] = { "-cert.pub", ".pub", NULL };
2507 struct sshkey *ret = NULL, *privkey = NULL;
2512 * If passed a public key filename, then try to locate the corresponding
2513 * private key. This lets us specify certificates on the command-line
2514 * and have ssh-keygen find the appropriate private key.
2516 for (i = 0; suffixes[i]; i++) {
2517 slen = strlen(suffixes[i]);
2519 strcmp(privpath + plen - slen, suffixes[i]) != 0)
2521 privpath[plen - slen] = '\0';
2522 debug_f("%s looks like a public key, using private key "
2523 "path %s instead", keypath, privpath);
2526 if (waspub && stat(privpath, &st) != 0 && errno == ENOENT)
2527 fatal("No private key found for public key \"%s\"", keypath);
2528 if ((r = sshkey_load_private(privpath, "", &privkey, NULL)) != 0 &&
2529 (r != SSH_ERR_KEY_WRONG_PASSPHRASE)) {
2530 debug_fr(r, "load private key \"%s\"", privpath);
2531 fatal("No private key found for \"%s\"", privpath);
2532 } else if (privkey == NULL)
2533 privkey = load_identity(privpath, NULL);
2535 if (!sshkey_equal_public(pubkey, privkey)) {
2536 error("Public key %s doesn't match private %s",
2540 if (sshkey_is_cert(pubkey) && !sshkey_is_cert(privkey)) {
2542 * Graft the certificate onto the private key to make
2543 * it capable of signing.
2545 if ((r = sshkey_to_certified(privkey)) != 0) {
2546 error_fr(r, "sshkey_to_certified");
2549 if ((r = sshkey_cert_copy(pubkey, privkey)) != 0) {
2550 error_fr(r, "sshkey_cert_copy");
2558 sshkey_free(privkey);
2564 sign_one(struct sshkey *signkey, const char *filename, int fd,
2565 const char *sig_namespace, const char *hashalg, sshsig_signer *signer,
2568 struct sshbuf *sigbuf = NULL, *abuf = NULL;
2569 int r = SSH_ERR_INTERNAL_ERROR, wfd = -1, oerrno;
2570 char *wfile = NULL, *asig = NULL, *fp = NULL;
2571 char *pin = NULL, *prompt = NULL;
2574 if (fd == STDIN_FILENO)
2575 fprintf(stderr, "Signing data on standard input\n");
2577 fprintf(stderr, "Signing file %s\n", filename);
2579 if (signer == NULL && sshkey_is_sk(signkey)) {
2580 if ((signkey->sk_flags & SSH_SK_USER_VERIFICATION_REQD)) {
2581 xasprintf(&prompt, "Enter PIN for %s key: ",
2582 sshkey_type(signkey));
2583 if ((pin = read_passphrase(prompt,
2584 RP_ALLOW_STDIN)) == NULL)
2585 fatal_f("couldn't read PIN");
2587 if ((signkey->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
2588 if ((fp = sshkey_fingerprint(signkey, fingerprint_hash,
2589 SSH_FP_DEFAULT)) == NULL)
2590 fatal_f("fingerprint failed");
2591 fprintf(stderr, "Confirm user presence for key %s %s\n",
2592 sshkey_type(signkey), fp);
2596 if ((r = sshsig_sign_fd(signkey, hashalg, sk_provider, pin,
2597 fd, sig_namespace, &sigbuf, signer, signer_ctx)) != 0) {
2598 error_r(r, "Signing %s failed", filename);
2601 if ((r = sshsig_armor(sigbuf, &abuf)) != 0) {
2602 error_fr(r, "sshsig_armor");
2605 if ((asig = sshbuf_dup_string(abuf)) == NULL) {
2606 error_f("buffer error");
2607 r = SSH_ERR_ALLOC_FAIL;
2611 if (fd == STDIN_FILENO) {
2612 fputs(asig, stdout);
2615 xasprintf(&wfile, "%s.sig", filename);
2616 if (confirm_overwrite(wfile)) {
2617 if ((wfd = open(wfile, O_WRONLY|O_CREAT|O_TRUNC,
2620 error("Cannot open %s: %s",
2621 wfile, strerror(errno));
2623 r = SSH_ERR_SYSTEM_ERROR;
2626 if (atomicio(vwrite, wfd, asig,
2627 strlen(asig)) != strlen(asig)) {
2629 error("Cannot write to %s: %s",
2630 wfile, strerror(errno));
2632 r = SSH_ERR_SYSTEM_ERROR;
2636 fprintf(stderr, "Write signature to %s\n",
2648 freezero(pin, strlen(pin));
2650 sshbuf_free(sigbuf);
2657 sig_process_opts(char * const *opts, size_t nopts, char **hashalgp,
2658 uint64_t *verify_timep, int *print_pubkey)
2663 if (verify_timep != NULL)
2665 if (print_pubkey != NULL)
2667 if (hashalgp != NULL)
2669 for (i = 0; i < nopts; i++) {
2670 if (hashalgp != NULL &&
2671 strncasecmp(opts[i], "hashalg=", 8) == 0) {
2672 *hashalgp = xstrdup(opts[i] + 8);
2673 } else if (verify_timep &&
2674 strncasecmp(opts[i], "verify-time=", 12) == 0) {
2675 if (parse_absolute_time(opts[i] + 12,
2676 verify_timep) != 0 || *verify_timep == 0) {
2677 error("Invalid \"verify-time\" option");
2678 return SSH_ERR_INVALID_ARGUMENT;
2680 } else if (print_pubkey &&
2681 strcasecmp(opts[i], "print-pubkey") == 0) {
2684 error("Invalid option \"%s\"", opts[i]);
2685 return SSH_ERR_INVALID_ARGUMENT;
2688 if (verify_timep && *verify_timep == 0) {
2689 if ((now = time(NULL)) < 0) {
2690 error("Time is before epoch");
2691 return SSH_ERR_INVALID_ARGUMENT;
2693 *verify_timep = (uint64_t)now;
2700 sig_sign(const char *keypath, const char *sig_namespace, int require_agent,
2701 int argc, char **argv, char * const *opts, size_t nopts)
2703 int i, fd = -1, r, ret = -1;
2705 struct sshkey *pubkey = NULL, *privkey = NULL, *signkey = NULL;
2706 sshsig_signer *signer = NULL;
2707 char *hashalg = NULL;
2709 /* Check file arguments. */
2710 for (i = 0; i < argc; i++) {
2711 if (strcmp(argv[i], "-") != 0)
2713 if (i > 0 || argc > 1)
2714 fatal("Cannot sign mix of paths and standard input");
2717 if (sig_process_opts(opts, nopts, &hashalg, NULL, NULL) != 0)
2718 goto done; /* error already logged */
2720 if ((r = sshkey_load_public(keypath, &pubkey, NULL)) != 0) {
2721 error_r(r, "Couldn't load public key %s", keypath);
2725 if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) {
2727 fatal("Couldn't get agent socket");
2728 debug_r(r, "Couldn't get agent socket");
2730 if ((r = ssh_agent_has_key(agent_fd, pubkey)) == 0)
2731 signer = agent_signer;
2734 fatal("Couldn't find key in agent");
2735 debug_r(r, "Couldn't find key in agent");
2739 if (signer == NULL) {
2740 /* Not using agent - try to load private key */
2741 if ((privkey = load_sign_key(keypath, pubkey)) == NULL)
2745 /* Will use key in agent */
2750 if ((r = sign_one(signkey, "(stdin)", STDIN_FILENO,
2751 sig_namespace, hashalg, signer, &agent_fd)) != 0)
2754 for (i = 0; i < argc; i++) {
2755 if (strcmp(argv[i], "-") == 0)
2757 else if ((fd = open(argv[i], O_RDONLY)) == -1) {
2758 error("Cannot open %s for signing: %s",
2759 argv[i], strerror(errno));
2762 if ((r = sign_one(signkey, argv[i], fd, sig_namespace,
2763 hashalg, signer, &agent_fd)) != 0)
2765 if (fd != STDIN_FILENO)
2773 if (fd != -1 && fd != STDIN_FILENO)
2775 sshkey_free(pubkey);
2776 sshkey_free(privkey);
2782 sig_verify(const char *signature, const char *sig_namespace,
2783 const char *principal, const char *allowed_keys, const char *revoked_keys,
2784 char * const *opts, size_t nopts)
2787 int print_pubkey = 0;
2788 struct sshbuf *sigbuf = NULL, *abuf = NULL;
2789 struct sshkey *sign_key = NULL;
2791 struct sshkey_sig_details *sig_details = NULL;
2792 uint64_t verify_time = 0;
2794 if (sig_process_opts(opts, nopts, NULL, &verify_time,
2795 &print_pubkey) != 0)
2796 goto done; /* error already logged */
2798 memset(&sig_details, 0, sizeof(sig_details));
2799 if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
2800 error_r(r, "Couldn't read signature file");
2804 if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
2805 error_fr(r, "sshsig_armor");
2808 if ((r = sshsig_verify_fd(sigbuf, STDIN_FILENO, sig_namespace,
2809 &sign_key, &sig_details)) != 0)
2810 goto done; /* sshsig_verify() prints error */
2812 if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
2813 SSH_FP_DEFAULT)) == NULL)
2814 fatal_f("sshkey_fingerprint failed");
2815 debug("Valid (unverified) signature from key %s", fp);
2816 if (sig_details != NULL) {
2817 debug2_f("signature details: counter = %u, flags = 0x%02x",
2818 sig_details->sk_counter, sig_details->sk_flags);
2823 if (revoked_keys != NULL) {
2824 if ((r = sshkey_check_revoked(sign_key, revoked_keys)) != 0) {
2825 debug3_fr(r, "sshkey_check_revoked");
2830 if (allowed_keys != NULL && (r = sshsig_check_allowed_keys(allowed_keys,
2831 sign_key, principal, sig_namespace, verify_time)) != 0) {
2832 debug3_fr(r, "sshsig_check_allowed_keys");
2840 if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
2841 SSH_FP_DEFAULT)) == NULL)
2842 fatal_f("sshkey_fingerprint failed");
2843 if (principal == NULL) {
2844 printf("Good \"%s\" signature with %s key %s\n",
2845 sig_namespace, sshkey_type(sign_key), fp);
2848 printf("Good \"%s\" signature for %s with %s key %s\n",
2849 sig_namespace, principal,
2850 sshkey_type(sign_key), fp);
2853 printf("Could not verify signature.\n");
2856 /* Print the signature key if requested */
2857 if (ret == 0 && print_pubkey && sign_key != NULL) {
2858 if ((r = sshkey_write(sign_key, stdout)) == 0)
2859 fputc('\n', stdout);
2861 error_r(r, "Could not print public key.\n");
2865 sshbuf_free(sigbuf);
2867 sshkey_free(sign_key);
2868 sshkey_sig_details_free(sig_details);
2874 sig_find_principals(const char *signature, const char *allowed_keys,
2875 char * const *opts, size_t nopts)
2878 struct sshbuf *sigbuf = NULL, *abuf = NULL;
2879 struct sshkey *sign_key = NULL;
2880 char *principals = NULL, *cp, *tmp;
2881 uint64_t verify_time = 0;
2883 if (sig_process_opts(opts, nopts, NULL, &verify_time, NULL) != 0)
2884 goto done; /* error already logged */
2886 if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
2887 error_r(r, "Couldn't read signature file");
2890 if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
2891 error_fr(r, "sshsig_armor");
2894 if ((r = sshsig_get_pubkey(sigbuf, &sign_key)) != 0) {
2895 error_fr(r, "sshsig_get_pubkey");
2898 if ((r = sshsig_find_principals(allowed_keys, sign_key,
2899 verify_time, &principals)) != 0) {
2900 if (r != SSH_ERR_KEY_NOT_FOUND)
2901 error_fr(r, "sshsig_find_principal");
2907 /* Emit matching principals one per line */
2909 while ((cp = strsep(&tmp, ",")) != NULL && *cp != '\0')
2912 fprintf(stderr, "No principal matched.\n");
2914 sshbuf_free(sigbuf);
2916 sshkey_free(sign_key);
2922 sig_match_principals(const char *allowed_keys, char *principal,
2923 char * const *opts, size_t nopts)
2926 char **principals = NULL;
2927 size_t i, nprincipals = 0;
2929 if ((r = sig_process_opts(opts, nopts, NULL, NULL, NULL)) != 0)
2930 return r; /* error already logged */
2932 if ((r = sshsig_match_principals(allowed_keys, principal,
2933 &principals, &nprincipals)) != 0) {
2934 debug_f("match: %s", ssh_err(r));
2935 fprintf(stderr, "No principal matched.\n");
2938 for (i = 0; i < nprincipals; i++) {
2939 printf("%s\n", principals[i]);
2940 free(principals[i]);
2948 do_moduli_gen(const char *out_file, char **opts, size_t nopts)
2951 /* Moduli generation/screening */
2952 u_int32_t memory = 0;
2953 BIGNUM *start = NULL;
2954 int moduli_bits = 0;
2960 for (i = 0; i < nopts; i++) {
2961 if (strncmp(opts[i], "memory=", 7) == 0) {
2962 memory = (u_int32_t)strtonum(opts[i]+7, 1,
2965 fatal("Memory limit is %s: %s",
2968 } else if (strncmp(opts[i], "start=", 6) == 0) {
2969 /* XXX - also compare length against bits */
2970 if (BN_hex2bn(&start, opts[i]+6) == 0)
2971 fatal("Invalid start point.");
2972 } else if (strncmp(opts[i], "bits=", 5) == 0) {
2973 moduli_bits = (int)strtonum(opts[i]+5, 1,
2976 fatal("Invalid number: %s (%s)",
2977 opts[i]+12, errstr);
2980 fatal("Option \"%s\" is unsupported for moduli "
2981 "generation", opts[i]);
2985 if ((out = fopen(out_file, "w")) == NULL) {
2986 fatal("Couldn't open modulus candidate file \"%s\": %s",
2987 out_file, strerror(errno));
2989 setvbuf(out, NULL, _IOLBF, 0);
2991 if (moduli_bits == 0)
2992 moduli_bits = DEFAULT_BITS;
2993 if (gen_candidates(out, memory, moduli_bits, start) != 0)
2994 fatal("modulus candidate generation failed");
2995 #else /* WITH_OPENSSL */
2996 fatal("Moduli generation is not supported");
2997 #endif /* WITH_OPENSSL */
3001 do_moduli_screen(const char *out_file, char **opts, size_t nopts)
3004 /* Moduli generation/screening */
3005 char *checkpoint = NULL;
3006 u_int32_t generator_wanted = 0;
3007 unsigned long start_lineno = 0, lines_to_process = 0;
3008 int prime_tests = 0;
3009 FILE *out, *in = stdin;
3014 for (i = 0; i < nopts; i++) {
3015 if (strncmp(opts[i], "lines=", 6) == 0) {
3016 lines_to_process = strtoul(opts[i]+6, NULL, 10);
3017 } else if (strncmp(opts[i], "start-line=", 11) == 0) {
3018 start_lineno = strtoul(opts[i]+11, NULL, 10);
3019 } else if (strncmp(opts[i], "checkpoint=", 11) == 0) {
3021 checkpoint = xstrdup(opts[i]+11);
3022 } else if (strncmp(opts[i], "generator=", 10) == 0) {
3023 generator_wanted = (u_int32_t)strtonum(
3024 opts[i]+10, 1, UINT_MAX, &errstr);
3025 if (errstr != NULL) {
3026 fatal("Generator invalid: %s (%s)",
3027 opts[i]+10, errstr);
3029 } else if (strncmp(opts[i], "prime-tests=", 12) == 0) {
3030 prime_tests = (int)strtonum(opts[i]+12, 1,
3033 fatal("Invalid number: %s (%s)",
3034 opts[i]+12, errstr);
3037 fatal("Option \"%s\" is unsupported for moduli "
3038 "screening", opts[i]);
3042 if (have_identity && strcmp(identity_file, "-") != 0) {
3043 if ((in = fopen(identity_file, "r")) == NULL) {
3044 fatal("Couldn't open modulus candidate "
3045 "file \"%s\": %s", identity_file,
3050 if ((out = fopen(out_file, "a")) == NULL) {
3051 fatal("Couldn't open moduli file \"%s\": %s",
3052 out_file, strerror(errno));
3054 setvbuf(out, NULL, _IOLBF, 0);
3055 if (prime_test(in, out, prime_tests == 0 ? 100 : prime_tests,
3056 generator_wanted, checkpoint,
3057 start_lineno, lines_to_process) != 0)
3058 fatal("modulus screening failed");
3062 #else /* WITH_OPENSSL */
3063 fatal("Moduli screening is not supported");
3064 #endif /* WITH_OPENSSL */
3067 /* Read and confirm a passphrase */
3069 read_check_passphrase(const char *prompt1, const char *prompt2,
3070 const char *retry_prompt)
3072 char *passphrase1, *passphrase2;
3075 passphrase1 = read_passphrase(prompt1, RP_ALLOW_STDIN);
3076 passphrase2 = read_passphrase(prompt2, RP_ALLOW_STDIN);
3077 if (strcmp(passphrase1, passphrase2) == 0) {
3078 freezero(passphrase2, strlen(passphrase2));
3081 /* The passphrases do not match. Clear them and retry. */
3082 freezero(passphrase1, strlen(passphrase1));
3083 freezero(passphrase2, strlen(passphrase2));
3084 fputs(retry_prompt, stdout);
3085 fputc('\n', stdout);
3093 private_key_passphrase(void)
3095 if (identity_passphrase)
3096 return xstrdup(identity_passphrase);
3097 if (identity_new_passphrase)
3098 return xstrdup(identity_new_passphrase);
3100 return read_check_passphrase(
3101 "Enter passphrase (empty for no passphrase): ",
3102 "Enter same passphrase again: ",
3103 "Passphrases do not match. Try again.");
3107 sk_suffix(const char *application, const uint8_t *user, size_t userlen)
3112 /* Trim off URL-like preamble */
3113 if (strncmp(application, "ssh://", 6) == 0)
3114 ret = xstrdup(application + 6);
3115 else if (strncmp(application, "ssh:", 4) == 0)
3116 ret = xstrdup(application + 4);
3118 ret = xstrdup(application);
3120 /* Count trailing zeros in user */
3121 for (i = 0; i < userlen; i++) {
3122 if (user[userlen - i - 1] != 0)
3126 return ret; /* user-id was default all-zeros */
3128 /* Append user-id, escaping non-UTF-8 characters */
3130 if (asmprintf(&cp, INT_MAX, NULL, "%.*s", (int)slen, user) == -1)
3131 fatal_f("asmprintf failed");
3132 /* Don't emit a user-id that contains path or control characters */
3133 if (strchr(cp, '/') != NULL || strstr(cp, "..") != NULL ||
3134 strchr(cp, '\\') != NULL) {
3136 cp = tohex(user, slen);
3138 xextendf(&ret, "_", "%s", cp);
3144 do_download_sk(const char *skprovider, const char *device)
3146 struct sshsk_resident_key **srks;
3149 char *fp, *pin = NULL, *pass = NULL, *path, *pubpath;
3153 if (skprovider == NULL)
3154 fatal("Cannot download keys without provider");
3156 pin = read_passphrase("Enter PIN for authenticator: ", RP_ALLOW_STDIN);
3158 printf("You may need to touch your authenticator "
3159 "to authorize key download.\n");
3161 if ((r = sshsk_load_resident(skprovider, device, pin, 0,
3162 &srks, &nsrks)) != 0) {
3164 freezero(pin, strlen(pin));
3165 error_r(r, "Unable to load resident keys");
3169 logit("No keys to download");
3171 freezero(pin, strlen(pin));
3173 for (i = 0; i < nsrks; i++) {
3175 if (key->type != KEY_ECDSA_SK && key->type != KEY_ED25519_SK) {
3176 error("Unsupported key type %s (%d)",
3177 sshkey_type(key), key->type);
3180 if ((fp = sshkey_fingerprint(key, fingerprint_hash,
3181 SSH_FP_DEFAULT)) == NULL)
3182 fatal_f("sshkey_fingerprint failed");
3183 debug_f("key %zu: %s %s %s (flags 0x%02x)", i,
3184 sshkey_type(key), fp, key->sk_application, key->sk_flags);
3185 ext = sk_suffix(key->sk_application,
3186 srks[i]->user_id, srks[i]->user_id_len);
3187 xasprintf(&path, "id_%s_rk%s%s",
3188 key->type == KEY_ECDSA_SK ? "ecdsa_sk" : "ed25519_sk",
3189 *ext == '\0' ? "" : "_", ext);
3191 /* If the file already exists, ask the user to confirm. */
3192 if (!confirm_overwrite(path)) {
3197 /* Save the key with the application string as the comment */
3199 pass = private_key_passphrase();
3200 if ((r = sshkey_save_private(key, path, pass,
3201 key->sk_application, private_key_format,
3202 openssh_format_cipher, rounds)) != 0) {
3203 error_r(r, "Saving key \"%s\" failed", path);
3208 printf("Saved %s key%s%s to %s\n", sshkey_type(key),
3209 *ext != '\0' ? " " : "",
3210 *ext != '\0' ? key->sk_application : "",
3214 /* Save public key too */
3215 xasprintf(&pubpath, "%s.pub", path);
3217 if ((r = sshkey_save_public(key, pubpath,
3218 key->sk_application)) != 0) {
3219 error_r(r, "Saving public key \"%s\" failed", pubpath);
3227 ret = 0; /* success */
3229 freezero(pass, strlen(pass));
3230 sshsk_free_resident_keys(srks, nsrks);
3235 save_attestation(struct sshbuf *attest, const char *path)
3241 return; /* nothing to do */
3242 if (attest == NULL || sshbuf_len(attest) == 0)
3243 fatal("Enrollment did not return attestation data");
3245 r = sshbuf_write_file(path, attest);
3248 fatal_r(r, "Unable to write attestation data \"%s\"", path);
3250 printf("Your FIDO attestation certificate has been saved in "
3255 confirm_sk_overwrite(const char *application, const char *user)
3259 printf("A resident key scoped to '%s' with user id '%s' already "
3260 "exists.\n", application == NULL ? "ssh:" : application,
3261 user == NULL ? "null" : user);
3262 printf("Overwrite key in token (y/n)? ");
3264 if (fgets(yesno, sizeof(yesno), stdin) == NULL)
3266 if (yesno[0] != 'y' && yesno[0] != 'Y')
3275 "usage: ssh-keygen [-q] [-a rounds] [-b bits] [-C comment] [-f output_keyfile]\n"
3276 " [-m format] [-N new_passphrase] [-O option]\n"
3277 " [-t dsa | ecdsa | ecdsa-sk | ed25519 | ed25519-sk | rsa]\n"
3278 " [-w provider] [-Z cipher]\n"
3279 " ssh-keygen -p [-a rounds] [-f keyfile] [-m format] [-N new_passphrase]\n"
3280 " [-P old_passphrase] [-Z cipher]\n"
3282 " ssh-keygen -i [-f input_keyfile] [-m key_format]\n"
3283 " ssh-keygen -e [-f input_keyfile] [-m key_format]\n"
3285 " ssh-keygen -y [-f input_keyfile]\n"
3286 " ssh-keygen -c [-a rounds] [-C comment] [-f keyfile] [-P passphrase]\n"
3287 " ssh-keygen -l [-v] [-E fingerprint_hash] [-f input_keyfile]\n"
3288 " ssh-keygen -B [-f input_keyfile]\n");
3289 #ifdef ENABLE_PKCS11
3291 " ssh-keygen -D pkcs11\n");
3294 " ssh-keygen -F hostname [-lv] [-f known_hosts_file]\n"
3295 " ssh-keygen -H [-f known_hosts_file]\n"
3296 " ssh-keygen -K [-a rounds] [-w provider]\n"
3297 " ssh-keygen -R hostname [-f known_hosts_file]\n"
3298 " ssh-keygen -r hostname [-g] [-f input_keyfile]\n"
3300 " ssh-keygen -M generate [-O option] output_file\n"
3301 " ssh-keygen -M screen [-f input_file] [-O option] output_file\n"
3303 " ssh-keygen -I certificate_identity -s ca_key [-hU] [-D pkcs11_provider]\n"
3304 " [-n principals] [-O option] [-V validity_interval]\n"
3305 " [-z serial_number] file ...\n"
3306 " ssh-keygen -L [-f input_keyfile]\n"
3307 " ssh-keygen -A [-a rounds] [-f prefix_path]\n"
3308 " ssh-keygen -k -f krl_file [-u] [-s ca_public] [-z version_number]\n"
3310 " ssh-keygen -Q [-l] -f krl_file [file ...]\n"
3311 " ssh-keygen -Y find-principals -s signature_file -f allowed_signers_file\n"
3312 " ssh-keygen -Y match-principals -I signer_identity -f allowed_signers_file\n"
3313 " ssh-keygen -Y check-novalidate -n namespace -s signature_file\n"
3314 " ssh-keygen -Y sign -f key_file -n namespace file [-O option] ...\n"
3315 " ssh-keygen -Y verify -f allowed_signers_file -I signer_identity\n"
3316 " -n namespace -s signature_file [-r krl_file] [-O option]\n");
3321 * Main program for key management.
3324 main(int argc, char **argv)
3326 char comment[1024], *passphrase = NULL;
3327 char *rr_hostname = NULL, *ep, *fp, *ra;
3328 struct sshkey *private, *public;
3331 int change_passphrase = 0, change_comment = 0, show_cert = 0;
3332 int find_host = 0, delete_host = 0, hash_hosts = 0;
3333 int gen_all_hostkeys = 0, gen_krl = 0, update_krl = 0, check_krl = 0;
3334 int prefer_agent = 0, convert_to = 0, convert_from = 0;
3335 int print_public = 0, print_generic = 0, cert_serial_autoinc = 0;
3336 int do_gen_candidates = 0, do_screen_candidates = 0, download_sk = 0;
3337 unsigned long long cert_serial = 0;
3338 char *identity_comment = NULL, *ca_key_path = NULL, **opts = NULL;
3339 char *sk_application = NULL, *sk_device = NULL, *sk_user = NULL;
3340 char *sk_attestation_path = NULL;
3341 struct sshbuf *challenge = NULL, *attest = NULL;
3342 size_t i, nopts = 0;
3344 uint8_t sk_flags = SSH_SK_USER_PRESENCE_REQD;
3346 int log_level = SYSLOG_LEVEL_INFO;
3347 char *sign_op = NULL;
3350 extern char *optarg;
3352 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
3355 __progname = ssh_get_progname(argv[0]);
3359 log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
3363 /* we need this for the home * directory. */
3364 pw = getpwuid(getuid());
3366 fatal("No user exists for uid %lu", (u_long)getuid());
3368 if (gethostname(hostname, sizeof(hostname)) == -1)
3369 fatal("gethostname: %s", strerror(errno));
3371 sk_provider = getenv("SSH_SK_PROVIDER");
3373 /* Remaining characters: dGjJSTWx */
3374 while ((opt = getopt(argc, argv, "ABHKLQUXceghiklopquvy"
3375 "C:D:E:F:I:M:N:O:P:R:V:Y:Z:"
3376 "a:b:f:g:m:n:r:s:t:w:z:")) != -1) {
3379 gen_all_hostkeys = 1;
3382 bits = (u_int32_t)strtonum(optarg, 1, UINT32_MAX,
3385 fatal("Bits has bad value %s (%s)",
3389 fingerprint_hash = ssh_digest_alg_by_name(optarg);
3390 if (fingerprint_hash == -1)
3391 fatal("Invalid hash algorithm \"%s\"", optarg);
3395 rr_hostname = optarg;
3401 cert_key_id = optarg;
3405 rr_hostname = optarg;
3411 print_fingerprint = 1;
3414 print_bubblebabble = 1;
3417 if (strcasecmp(optarg, "RFC4716") == 0 ||
3418 strcasecmp(optarg, "ssh2") == 0) {
3419 convert_format = FMT_RFC4716;
3422 if (strcasecmp(optarg, "PKCS8") == 0) {
3423 convert_format = FMT_PKCS8;
3424 private_key_format = SSHKEY_PRIVATE_PKCS8;
3427 if (strcasecmp(optarg, "PEM") == 0) {
3428 convert_format = FMT_PEM;
3429 private_key_format = SSHKEY_PRIVATE_PEM;
3432 fatal("Unsupported conversion format \"%s\"", optarg);
3434 cert_principals = optarg;
3437 /* no-op; new format is already the default */
3440 change_passphrase = 1;
3446 if (strlcpy(identity_file, optarg,
3447 sizeof(identity_file)) >= sizeof(identity_file))
3448 fatal("Identity filename too long");
3458 identity_passphrase = optarg;
3461 identity_new_passphrase = optarg;
3467 opts = xrecallocarray(opts, nopts, nopts + 1,
3469 opts[nopts++] = xstrdup(optarg);
3472 openssh_format_cipher = optarg;
3473 if (cipher_by_name(openssh_format_cipher) == NULL)
3474 fatal("Invalid OpenSSH-format cipher '%s'",
3475 openssh_format_cipher);
3478 identity_comment = optarg;
3488 cert_key_type = SSH2_CERT_TYPE_HOST;
3489 certflags_flags = 0;
3503 ca_key_path = optarg;
3506 key_type_name = optarg;
3509 pkcs11provider = optarg;
3518 if (log_level == SYSLOG_LEVEL_INFO)
3519 log_level = SYSLOG_LEVEL_DEBUG1;
3521 if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
3522 log_level < SYSLOG_LEVEL_DEBUG3)
3527 rr_hostname = optarg;
3530 rounds = (int)strtonum(optarg, 1, INT_MAX, &errstr);
3532 fatal("Invalid number: %s (%s)",
3536 parse_cert_times(optarg);
3542 sk_provider = optarg;
3546 if (*optarg == '+') {
3547 cert_serial_autoinc = 1;
3550 cert_serial = strtoull(optarg, &ep, 10);
3551 if (*optarg < '0' || *optarg > '9' || *ep != '\0' ||
3552 (errno == ERANGE && cert_serial == ULLONG_MAX))
3553 fatal("Invalid serial number \"%s\"", optarg);
3556 if (strcmp(optarg, "generate") == 0)
3557 do_gen_candidates = 1;
3558 else if (strcmp(optarg, "screen") == 0)
3559 do_screen_candidates = 1;
3561 fatal("Unsupported moduli option %s", optarg);
3568 #ifdef ENABLE_SK_INTERNAL
3569 if (sk_provider == NULL)
3570 sk_provider = "internal";
3574 log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
3579 if (sign_op != NULL) {
3580 if (strncmp(sign_op, "find-principals", 15) == 0) {
3581 if (ca_key_path == NULL) {
3582 error("Too few arguments for find-principals:"
3583 "missing signature file");
3586 if (!have_identity) {
3587 error("Too few arguments for find-principals:"
3588 "missing allowed keys file");
3591 return sig_find_principals(ca_key_path, identity_file,
3593 } else if (strncmp(sign_op, "match-principals", 16) == 0) {
3594 if (!have_identity) {
3595 error("Too few arguments for match-principals:"
3596 "missing allowed keys file");
3599 if (cert_key_id == NULL) {
3600 error("Too few arguments for match-principals: "
3601 "missing principal ID");
3604 return sig_match_principals(identity_file, cert_key_id,
3606 } else if (strncmp(sign_op, "sign", 4) == 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 sign: "
3611 "missing namespace");
3614 if (!have_identity) {
3615 error("Too few arguments for sign: "
3619 return sig_sign(identity_file, cert_principals,
3620 prefer_agent, argc, argv, opts, nopts);
3621 } else if (strncmp(sign_op, "check-novalidate", 16) == 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 check-novalidate: "
3626 "missing namespace");
3629 if (ca_key_path == NULL) {
3630 error("Too few arguments for check-novalidate: "
3631 "missing signature file");
3634 return sig_verify(ca_key_path, cert_principals,
3635 NULL, NULL, NULL, opts, nopts);
3636 } else if (strncmp(sign_op, "verify", 6) == 0) {
3637 /* NB. cert_principals is actually namespace, via -n */
3638 if (cert_principals == NULL ||
3639 *cert_principals == '\0') {
3640 error("Too few arguments for verify: "
3641 "missing namespace");
3644 if (ca_key_path == NULL) {
3645 error("Too few arguments for verify: "
3646 "missing signature file");
3649 if (!have_identity) {
3650 error("Too few arguments for sign: "
3651 "missing allowed keys file");
3654 if (cert_key_id == NULL) {
3655 error("Too few arguments for verify: "
3656 "missing principal identity");
3659 return sig_verify(ca_key_path, cert_principals,
3660 cert_key_id, identity_file, rr_hostname,
3663 error("Unsupported operation for -Y: \"%s\"", sign_op);
3668 if (ca_key_path != NULL) {
3669 if (argc < 1 && !gen_krl) {
3670 error("Too few arguments.");
3673 } else if (argc > 0 && !gen_krl && !check_krl &&
3674 !do_gen_candidates && !do_screen_candidates) {
3675 error("Too many arguments.");
3678 if (change_passphrase && change_comment) {
3679 error("Can only have one of -p and -c.");
3682 if (print_fingerprint && (delete_host || hash_hosts)) {
3683 error("Cannot use -l with -H or -R.");
3687 do_gen_krl(pw, update_krl, ca_key_path,
3688 cert_serial, identity_comment, argc, argv);
3692 do_check_krl(pw, print_fingerprint, argc, argv);
3695 if (ca_key_path != NULL) {
3696 if (cert_key_id == NULL)
3697 fatal("Must specify key id (-I) when certifying");
3698 for (i = 0; i < nopts; i++)
3699 add_cert_option(opts[i]);
3700 do_ca_sign(pw, ca_key_path, prefer_agent,
3701 cert_serial, cert_serial_autoinc, argc, argv);
3705 if (delete_host || hash_hosts || find_host) {
3706 do_known_hosts(pw, rr_hostname, find_host,
3707 delete_host, hash_hosts);
3709 if (pkcs11provider != NULL)
3712 for (i = 0; i < nopts; i++) {
3713 if (strncasecmp(opts[i], "device=", 7) == 0) {
3714 sk_device = xstrdup(opts[i] + 7);
3716 fatal("Option \"%s\" is unsupported for "
3717 "FIDO authenticator download", opts[i]);
3720 return do_download_sk(sk_provider, sk_device);
3722 if (print_fingerprint || print_bubblebabble)
3724 if (change_passphrase)
3725 do_change_passphrase(pw);
3727 do_change_comment(pw, identity_comment);
3732 do_convert_from(pw);
3733 #else /* WITH_OPENSSL */
3734 if (convert_to || convert_from)
3735 fatal("key conversion disabled at compile time");
3736 #endif /* WITH_OPENSSL */
3738 do_print_public(pw);
3739 if (rr_hostname != NULL) {
3742 if (have_identity) {
3743 n = do_print_resource_record(pw, identity_file,
3744 rr_hostname, print_generic, opts, nopts);
3746 fatal("%s: %s", identity_file, strerror(errno));
3750 n += do_print_resource_record(pw,
3751 _PATH_HOST_RSA_KEY_FILE, rr_hostname,
3752 print_generic, opts, nopts);
3753 n += do_print_resource_record(pw,
3754 _PATH_HOST_DSA_KEY_FILE, rr_hostname,
3755 print_generic, opts, nopts);
3756 n += do_print_resource_record(pw,
3757 _PATH_HOST_ECDSA_KEY_FILE, rr_hostname,
3758 print_generic, opts, nopts);
3759 n += do_print_resource_record(pw,
3760 _PATH_HOST_ED25519_KEY_FILE, rr_hostname,
3761 print_generic, opts, nopts);
3762 n += do_print_resource_record(pw,
3763 _PATH_HOST_XMSS_KEY_FILE, rr_hostname,
3764 print_generic, opts, nopts);
3766 fatal("no keys found.");
3771 if (do_gen_candidates || do_screen_candidates) {
3773 fatal("No output file specified");
3775 fatal("Too many output files specified");
3777 if (do_gen_candidates) {
3778 do_moduli_gen(argv[0], opts, nopts);
3781 if (do_screen_candidates) {
3782 do_moduli_screen(argv[0], opts, nopts);
3786 if (gen_all_hostkeys) {
3787 do_gen_all_hostkeys(pw);
3791 if (key_type_name == NULL)
3792 key_type_name = DEFAULT_KEY_TYPE_NAME;
3794 type = sshkey_type_from_name(key_type_name);
3795 type_bits_valid(type, key_type_name, &bits);
3798 printf("Generating public/private %s key pair.\n",
3802 case KEY_ED25519_SK:
3803 for (i = 0; i < nopts; i++) {
3804 if (strcasecmp(opts[i], "no-touch-required") == 0) {
3805 sk_flags &= ~SSH_SK_USER_PRESENCE_REQD;
3806 } else if (strcasecmp(opts[i], "verify-required") == 0) {
3807 sk_flags |= SSH_SK_USER_VERIFICATION_REQD;
3808 } else if (strcasecmp(opts[i], "resident") == 0) {
3809 sk_flags |= SSH_SK_RESIDENT_KEY;
3810 } else if (strncasecmp(opts[i], "device=", 7) == 0) {
3811 sk_device = xstrdup(opts[i] + 7);
3812 } else if (strncasecmp(opts[i], "user=", 5) == 0) {
3813 sk_user = xstrdup(opts[i] + 5);
3814 } else if (strncasecmp(opts[i], "challenge=", 10) == 0) {
3815 if ((r = sshbuf_load_file(opts[i] + 10,
3816 &challenge)) != 0) {
3817 fatal_r(r, "Unable to load FIDO "
3818 "enrollment challenge \"%s\"",
3821 } else if (strncasecmp(opts[i],
3822 "write-attestation=", 18) == 0) {
3823 sk_attestation_path = opts[i] + 18;
3824 } else if (strncasecmp(opts[i],
3825 "application=", 12) == 0) {
3826 sk_application = xstrdup(opts[i] + 12);
3827 if (strncmp(sk_application, "ssh:", 4) != 0) {
3828 fatal("FIDO application string must "
3829 "begin with \"ssh:\"");
3832 fatal("Option \"%s\" is unsupported for "
3833 "FIDO authenticator enrollment", opts[i]);
3836 if ((attest = sshbuf_new()) == NULL)
3837 fatal("sshbuf_new failed");
3841 printf("You may need to touch your "
3842 "authenticator%s to authorize key "
3844 r == 0 ? "" : " again");
3847 r = sshsk_enroll(type, sk_provider, sk_device,
3848 sk_application == NULL ? "ssh:" : sk_application,
3849 sk_user, sk_flags, passphrase, challenge,
3853 if (r == SSH_ERR_KEY_BAD_PERMISSIONS &&
3854 (sk_flags & SSH_SK_RESIDENT_KEY) != 0 &&
3855 (sk_flags & SSH_SK_FORCE_OPERATION) == 0 &&
3856 confirm_sk_overwrite(sk_application, sk_user)) {
3857 sk_flags |= SSH_SK_FORCE_OPERATION;
3860 if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
3861 fatal_r(r, "Key enrollment failed");
3862 else if (passphrase != NULL) {
3863 error("PIN incorrect");
3864 freezero(passphrase, strlen(passphrase));
3868 fatal("Too many incorrect PINs");
3869 passphrase = read_passphrase("Enter PIN for "
3870 "authenticator: ", RP_ALLOW_STDIN);
3872 if (passphrase != NULL) {
3873 freezero(passphrase, strlen(passphrase));
3878 if ((r = sshkey_generate(type, bits, &private)) != 0)
3879 fatal("sshkey_generate failed");
3882 if ((r = sshkey_from_private(private, &public)) != 0)
3883 fatal_r(r, "sshkey_from_private");
3886 ask_filename(pw, "Enter file in which to save the key");
3888 /* Create ~/.ssh directory if it doesn't already exist. */
3889 hostfile_create_user_ssh_dir(identity_file, !quiet);
3891 /* If the file already exists, ask the user to confirm. */
3892 if (!confirm_overwrite(identity_file))
3895 /* Determine the passphrase for the private key */
3896 passphrase = private_key_passphrase();
3897 if (identity_comment) {
3898 strlcpy(comment, identity_comment, sizeof(comment));
3900 /* Create default comment field for the passphrase. */
3901 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
3904 /* Save the key with the given passphrase and comment. */
3905 if ((r = sshkey_save_private(private, identity_file, passphrase,
3906 comment, private_key_format, openssh_format_cipher, rounds)) != 0) {
3907 error_r(r, "Saving key \"%s\" failed", identity_file);
3908 freezero(passphrase, strlen(passphrase));
3911 freezero(passphrase, strlen(passphrase));
3912 sshkey_free(private);
3915 printf("Your identification has been saved in %s\n",
3919 strlcat(identity_file, ".pub", sizeof(identity_file));
3920 if ((r = sshkey_save_public(public, identity_file, comment)) != 0)
3921 fatal_r(r, "Unable to save public key to %s", identity_file);
3924 fp = sshkey_fingerprint(public, fingerprint_hash,
3926 ra = sshkey_fingerprint(public, fingerprint_hash,
3928 if (fp == NULL || ra == NULL)
3929 fatal("sshkey_fingerprint failed");
3930 printf("Your public key has been saved in %s\n",
3932 printf("The key fingerprint is:\n");
3933 printf("%s %s\n", fp, comment);
3934 printf("The key's randomart image is:\n");
3940 if (sk_attestation_path != NULL)
3941 save_attestation(attest, sk_attestation_path);
3943 sshbuf_free(attest);
3944 sshkey_free(public);