1 /* $OpenBSD: ssh-keygen.c,v 1.409.2.1 2020/05/18 19:02:13 benno 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 */
70 # define DEFAULT_KEY_TYPE_NAME "rsa"
72 # define DEFAULT_KEY_TYPE_NAME "ed25519"
76 * Default number of bits in the RSA, DSA and ECDSA keys. These value can be
77 * overridden on the command line.
79 * These values, with the exception of DSA, provide security equivalent to at
80 * least 128 bits of security according to NIST Special Publication 800-57:
81 * Recommendation for Key Management Part 1 rev 4 section 5.6.1.
82 * For DSA it (and FIPS-186-4 section 4.2) specifies that the only size for
83 * which a 160bit hash is acceptable is 1kbit, and since ssh-dss specifies only
84 * SHA1 we limit the DSA key size 1k bits.
86 #define DEFAULT_BITS 3072
87 #define DEFAULT_BITS_DSA 1024
88 #define DEFAULT_BITS_ECDSA 256
92 /* Flag indicating that we just want to see the key fingerprint */
93 static int print_fingerprint = 0;
94 static int print_bubblebabble = 0;
96 /* Hash algorithm to use for fingerprints. */
97 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
99 /* The identity file name, given on the command line or entered by the user. */
100 static char identity_file[PATH_MAX];
101 static int have_identity = 0;
103 /* This is set to the passphrase if given on the command line. */
104 static char *identity_passphrase = NULL;
106 /* This is set to the new passphrase if given on the command line. */
107 static char *identity_new_passphrase = NULL;
109 /* Key type when certifying */
110 static u_int cert_key_type = SSH2_CERT_TYPE_USER;
112 /* "key ID" of signed key */
113 static char *cert_key_id = NULL;
115 /* Comma-separated list of principal names for certifying keys */
116 static char *cert_principals = NULL;
118 /* Validity period for certificates */
119 static u_int64_t cert_valid_from = 0;
120 static u_int64_t cert_valid_to = ~0ULL;
122 /* Certificate options */
123 #define CERTOPT_X_FWD (1)
124 #define CERTOPT_AGENT_FWD (1<<1)
125 #define CERTOPT_PORT_FWD (1<<2)
126 #define CERTOPT_PTY (1<<3)
127 #define CERTOPT_USER_RC (1<<4)
128 #define CERTOPT_NO_REQUIRE_USER_PRESENCE (1<<5)
129 #define CERTOPT_DEFAULT (CERTOPT_X_FWD|CERTOPT_AGENT_FWD| \
130 CERTOPT_PORT_FWD|CERTOPT_PTY|CERTOPT_USER_RC)
131 static u_int32_t certflags_flags = CERTOPT_DEFAULT;
132 static char *certflags_command = NULL;
133 static char *certflags_src_addr = NULL;
135 /* Arbitrary extensions specified by user */
136 struct cert_userext {
141 static struct cert_userext *cert_userext;
142 static size_t ncert_userext;
144 /* Conversion to/from various formats */
149 } convert_format = FMT_RFC4716;
151 static char *key_type_name = NULL;
153 /* Load key from this PKCS#11 provider */
154 static char *pkcs11provider = NULL;
156 /* FIDO/U2F provider to use */
157 static char *sk_provider = NULL;
159 /* Format for writing private keys */
160 static int private_key_format = SSHKEY_PRIVATE_OPENSSH;
162 /* Cipher for new-format private keys */
163 static char *openssh_format_cipher = NULL;
165 /* Number of KDF rounds to derive new format keys. */
166 static int rounds = 0;
169 extern char *__progname;
171 static char hostname[NI_MAXHOST];
175 int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
176 int prime_test(FILE *, FILE *, u_int32_t, u_int32_t, char *, unsigned long,
181 type_bits_valid(int type, const char *name, u_int32_t *bitsp)
183 if (type == KEY_UNSPEC)
184 fatal("unknown key type %s", key_type_name);
191 *bitsp = DEFAULT_BITS_DSA;
195 (nid = sshkey_ecdsa_nid_from_name(name)) > 0)
196 *bitsp = sshkey_curve_nid_to_bits(nid);
198 *bitsp = DEFAULT_BITS_ECDSA;
201 *bitsp = DEFAULT_BITS;
210 fatal("Invalid DSA key length: must be 1024 bits");
213 if (*bitsp < SSH_RSA_MINIMUM_MODULUS_SIZE)
214 fatal("Invalid RSA key length: minimum is %d bits",
215 SSH_RSA_MINIMUM_MODULUS_SIZE);
216 else if (*bitsp > OPENSSL_RSA_MAX_MODULUS_BITS)
217 fatal("Invalid RSA key length: maximum is %d bits",
218 OPENSSL_RSA_MAX_MODULUS_BITS);
221 if (sshkey_ecdsa_bits_to_nid(*bitsp) == -1)
222 fatal("Invalid ECDSA key length: valid lengths are "
223 #ifdef OPENSSL_HAS_NISTP521
224 "256, 384 or 521 bits");
233 * Checks whether a file exists and, if so, asks the user whether they wish
235 * Returns nonzero if the file does not already exist or if the user agrees to
236 * overwrite, or zero otherwise.
239 confirm_overwrite(const char *filename)
244 if (stat(filename, &st) != 0)
246 printf("%s already exists.\n", filename);
247 printf("Overwrite (y/n)? ");
249 if (fgets(yesno, sizeof(yesno), stdin) == NULL)
251 if (yesno[0] != 'y' && yesno[0] != 'Y')
257 ask_filename(struct passwd *pw, const char *prompt)
262 if (key_type_name == NULL)
263 name = _PATH_SSH_CLIENT_ID_RSA;
265 switch (sshkey_type_from_name(key_type_name)) {
268 name = _PATH_SSH_CLIENT_ID_DSA;
270 #ifdef OPENSSL_HAS_ECC
273 name = _PATH_SSH_CLIENT_ID_ECDSA;
275 case KEY_ECDSA_SK_CERT:
277 name = _PATH_SSH_CLIENT_ID_ECDSA_SK;
282 name = _PATH_SSH_CLIENT_ID_RSA;
285 case KEY_ED25519_CERT:
286 name = _PATH_SSH_CLIENT_ID_ED25519;
289 case KEY_ED25519_SK_CERT:
290 name = _PATH_SSH_CLIENT_ID_ED25519_SK;
294 name = _PATH_SSH_CLIENT_ID_XMSS;
297 fatal("bad key type");
300 snprintf(identity_file, sizeof(identity_file),
301 "%s/%s", pw->pw_dir, name);
302 printf("%s (%s): ", prompt, identity_file);
304 if (fgets(buf, sizeof(buf), stdin) == NULL)
306 buf[strcspn(buf, "\n")] = '\0';
307 if (strcmp(buf, "") != 0)
308 strlcpy(identity_file, buf, sizeof(identity_file));
312 static struct sshkey *
313 load_identity(const char *filename, char **commentp)
319 if (commentp != NULL)
321 if ((r = sshkey_load_private(filename, "", &prv, commentp)) == 0)
323 if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
324 fatal("Load key \"%s\": %s", filename, ssh_err(r));
325 if (identity_passphrase)
326 pass = xstrdup(identity_passphrase);
328 pass = read_passphrase("Enter passphrase: ", RP_ALLOW_STDIN);
329 r = sshkey_load_private(filename, pass, &prv, commentp);
330 freezero(pass, strlen(pass));
332 fatal("Load key \"%s\": %s", filename, ssh_err(r));
336 #define SSH_COM_PUBLIC_BEGIN "---- BEGIN SSH2 PUBLIC KEY ----"
337 #define SSH_COM_PUBLIC_END "---- END SSH2 PUBLIC KEY ----"
338 #define SSH_COM_PRIVATE_BEGIN "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
339 #define SSH_COM_PRIVATE_KEY_MAGIC 0x3f6ff9eb
343 do_convert_to_ssh2(struct passwd *pw, struct sshkey *k)
346 char comment[61], *b64;
349 if ((b = sshbuf_new()) == NULL)
350 fatal("%s: sshbuf_new failed", __func__);
351 if ((r = sshkey_putb(k, b)) != 0)
352 fatal("key_to_blob failed: %s", ssh_err(r));
353 if ((b64 = sshbuf_dtob64_string(b, 1)) == NULL)
354 fatal("%s: sshbuf_dtob64_string failed", __func__);
356 /* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
357 snprintf(comment, sizeof(comment),
358 "%u-bit %s, converted by %s@%s from OpenSSH",
359 sshkey_size(k), sshkey_type(k),
360 pw->pw_name, hostname);
365 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
366 fprintf(stdout, "Comment: \"%s\"\n%s", comment, b64);
367 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
373 do_convert_to_pkcs8(struct sshkey *k)
375 switch (sshkey_type_plain(k->type)) {
377 if (!PEM_write_RSA_PUBKEY(stdout, k->rsa))
378 fatal("PEM_write_RSA_PUBKEY failed");
381 if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
382 fatal("PEM_write_DSA_PUBKEY failed");
384 #ifdef OPENSSL_HAS_ECC
386 if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
387 fatal("PEM_write_EC_PUBKEY failed");
391 fatal("%s: unsupported key type %s", __func__, sshkey_type(k));
397 do_convert_to_pem(struct sshkey *k)
399 switch (sshkey_type_plain(k->type)) {
401 if (!PEM_write_RSAPublicKey(stdout, k->rsa))
402 fatal("PEM_write_RSAPublicKey failed");
405 if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
406 fatal("PEM_write_DSA_PUBKEY failed");
408 #ifdef OPENSSL_HAS_ECC
410 if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
411 fatal("PEM_write_EC_PUBKEY failed");
415 fatal("%s: unsupported key type %s", __func__, sshkey_type(k));
421 do_convert_to(struct passwd *pw)
428 ask_filename(pw, "Enter file in which the key is");
429 if (stat(identity_file, &st) == -1)
430 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
431 if ((r = sshkey_load_public(identity_file, &k, NULL)) != 0)
432 k = load_identity(identity_file, NULL);
433 switch (convert_format) {
435 do_convert_to_ssh2(pw, k);
438 do_convert_to_pkcs8(k);
441 do_convert_to_pem(k);
444 fatal("%s: unknown key format %d", __func__, convert_format);
450 * This is almost exactly the bignum1 encoding, but with 32 bit for length
454 buffer_get_bignum_bits(struct sshbuf *b, BIGNUM *value)
456 u_int bytes, bignum_bits;
459 if ((r = sshbuf_get_u32(b, &bignum_bits)) != 0)
460 fatal("%s: buffer error: %s", __func__, ssh_err(r));
461 bytes = (bignum_bits + 7) / 8;
462 if (sshbuf_len(b) < bytes)
463 fatal("%s: input buffer too small: need %d have %zu",
464 __func__, bytes, sshbuf_len(b));
465 if (BN_bin2bn(sshbuf_ptr(b), bytes, value) == NULL)
466 fatal("%s: BN_bin2bn failed", __func__);
467 if ((r = sshbuf_consume(b, bytes)) != 0)
468 fatal("%s: buffer error: %s", __func__, ssh_err(r));
471 static struct sshkey *
472 do_convert_private_ssh2(struct sshbuf *b)
474 struct sshkey *key = NULL;
476 u_char e1, e2, e3, *sig = NULL, data[] = "abcde12345";
478 u_int magic, i1, i2, i3, i4;
481 BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL;
482 BIGNUM *dsa_pub_key = NULL, *dsa_priv_key = NULL;
483 BIGNUM *rsa_n = NULL, *rsa_e = NULL, *rsa_d = NULL;
484 BIGNUM *rsa_p = NULL, *rsa_q = NULL, *rsa_iqmp = NULL;
486 if ((r = sshbuf_get_u32(b, &magic)) != 0)
487 fatal("%s: buffer error: %s", __func__, ssh_err(r));
489 if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
490 error("bad magic 0x%x != 0x%x", magic,
491 SSH_COM_PRIVATE_KEY_MAGIC);
494 if ((r = sshbuf_get_u32(b, &i1)) != 0 ||
495 (r = sshbuf_get_cstring(b, &type, NULL)) != 0 ||
496 (r = sshbuf_get_cstring(b, &cipher, NULL)) != 0 ||
497 (r = sshbuf_get_u32(b, &i2)) != 0 ||
498 (r = sshbuf_get_u32(b, &i3)) != 0 ||
499 (r = sshbuf_get_u32(b, &i4)) != 0)
500 fatal("%s: buffer error: %s", __func__, ssh_err(r));
501 debug("ignore (%d %d %d %d)", i1, i2, i3, i4);
502 if (strcmp(cipher, "none") != 0) {
503 error("unsupported cipher %s", cipher);
510 if (strstr(type, "dsa")) {
512 } else if (strstr(type, "rsa")) {
518 if ((key = sshkey_new(ktype)) == NULL)
519 fatal("sshkey_new failed");
524 if ((dsa_p = BN_new()) == NULL ||
525 (dsa_q = BN_new()) == NULL ||
526 (dsa_g = BN_new()) == NULL ||
527 (dsa_pub_key = BN_new()) == NULL ||
528 (dsa_priv_key = BN_new()) == NULL)
529 fatal("%s: BN_new", __func__);
530 buffer_get_bignum_bits(b, dsa_p);
531 buffer_get_bignum_bits(b, dsa_g);
532 buffer_get_bignum_bits(b, dsa_q);
533 buffer_get_bignum_bits(b, dsa_pub_key);
534 buffer_get_bignum_bits(b, dsa_priv_key);
535 if (!DSA_set0_pqg(key->dsa, dsa_p, dsa_q, dsa_g))
536 fatal("%s: DSA_set0_pqg failed", __func__);
537 dsa_p = dsa_q = dsa_g = NULL; /* transferred */
538 if (!DSA_set0_key(key->dsa, dsa_pub_key, dsa_priv_key))
539 fatal("%s: DSA_set0_key failed", __func__);
540 dsa_pub_key = dsa_priv_key = NULL; /* transferred */
543 if ((r = sshbuf_get_u8(b, &e1)) != 0 ||
544 (e1 < 30 && (r = sshbuf_get_u8(b, &e2)) != 0) ||
545 (e1 < 30 && (r = sshbuf_get_u8(b, &e3)) != 0))
546 fatal("%s: buffer error: %s", __func__, ssh_err(r));
557 if ((rsa_e = BN_new()) == NULL)
558 fatal("%s: BN_new", __func__);
559 if (!BN_set_word(rsa_e, e)) {
560 BN_clear_free(rsa_e);
564 if ((rsa_n = BN_new()) == NULL ||
565 (rsa_d = BN_new()) == NULL ||
566 (rsa_p = BN_new()) == NULL ||
567 (rsa_q = BN_new()) == NULL ||
568 (rsa_iqmp = BN_new()) == NULL)
569 fatal("%s: BN_new", __func__);
570 buffer_get_bignum_bits(b, rsa_d);
571 buffer_get_bignum_bits(b, rsa_n);
572 buffer_get_bignum_bits(b, rsa_iqmp);
573 buffer_get_bignum_bits(b, rsa_q);
574 buffer_get_bignum_bits(b, rsa_p);
575 if (!RSA_set0_key(key->rsa, rsa_n, rsa_e, rsa_d))
576 fatal("%s: RSA_set0_key failed", __func__);
577 rsa_n = rsa_e = rsa_d = NULL; /* transferred */
578 if (!RSA_set0_factors(key->rsa, rsa_p, rsa_q))
579 fatal("%s: RSA_set0_factors failed", __func__);
580 rsa_p = rsa_q = NULL; /* transferred */
581 if ((r = ssh_rsa_complete_crt_parameters(key, rsa_iqmp)) != 0)
582 fatal("generate RSA parameters failed: %s", ssh_err(r));
583 BN_clear_free(rsa_iqmp);
586 rlen = sshbuf_len(b);
588 error("%s: remaining bytes in key blob %d", __func__, rlen);
591 if (sshkey_sign(key, &sig, &slen, data, sizeof(data),
592 NULL, NULL, 0) != 0 ||
593 sshkey_verify(key, sig, slen, data, sizeof(data),
594 NULL, 0, NULL) != 0) {
604 get_line(FILE *fp, char *line, size_t len)
610 while ((c = fgetc(fp)) != EOF) {
612 fatal("input line too long.");
616 if (c != EOF && c != '\n' && ungetc(c, fp) == EOF)
617 fatal("unget: %s", strerror(errno));
630 do_convert_from_ssh2(struct passwd *pw, struct sshkey **k, int *private)
632 int r, blen, escaped = 0;
639 if ((buf = sshbuf_new()) == NULL)
640 fatal("sshbuf_new failed");
641 if ((fp = fopen(identity_file, "r")) == NULL)
642 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
644 while ((blen = get_line(fp, line, sizeof(line))) != -1) {
645 if (blen > 0 && line[blen - 1] == '\\')
647 if (strncmp(line, "----", 4) == 0 ||
648 strstr(line, ": ") != NULL) {
649 if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
651 if (strstr(line, " END ") != NULL) {
654 /* fprintf(stderr, "ignore: %s", line); */
659 /* fprintf(stderr, "escaped: %s", line); */
662 strlcat(encoded, line, sizeof(encoded));
664 len = strlen(encoded);
665 if (((len % 4) == 3) &&
666 (encoded[len-1] == '=') &&
667 (encoded[len-2] == '=') &&
668 (encoded[len-3] == '='))
669 encoded[len-3] = '\0';
670 if ((r = sshbuf_b64tod(buf, encoded)) != 0)
671 fatal("%s: base64 decoding failed: %s", __func__, ssh_err(r));
673 if ((*k = do_convert_private_ssh2(buf)) == NULL)
674 fatal("%s: private key conversion failed", __func__);
675 } else if ((r = sshkey_fromb(buf, k)) != 0)
676 fatal("decode blob failed: %s", ssh_err(r));
682 do_convert_from_pkcs8(struct sshkey **k, int *private)
687 if ((fp = fopen(identity_file, "r")) == NULL)
688 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
689 if ((pubkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL)) == NULL) {
690 fatal("%s: %s is not a recognised public key format", __func__,
694 switch (EVP_PKEY_base_id(pubkey)) {
696 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
697 fatal("sshkey_new failed");
698 (*k)->type = KEY_RSA;
699 (*k)->rsa = EVP_PKEY_get1_RSA(pubkey);
702 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
703 fatal("sshkey_new failed");
704 (*k)->type = KEY_DSA;
705 (*k)->dsa = EVP_PKEY_get1_DSA(pubkey);
707 #ifdef OPENSSL_HAS_ECC
709 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
710 fatal("sshkey_new failed");
711 (*k)->type = KEY_ECDSA;
712 (*k)->ecdsa = EVP_PKEY_get1_EC_KEY(pubkey);
713 (*k)->ecdsa_nid = sshkey_ecdsa_key_to_nid((*k)->ecdsa);
717 fatal("%s: unsupported pubkey type %d", __func__,
718 EVP_PKEY_base_id(pubkey));
720 EVP_PKEY_free(pubkey);
725 do_convert_from_pem(struct sshkey **k, int *private)
730 if ((fp = fopen(identity_file, "r")) == NULL)
731 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
732 if ((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
733 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
734 fatal("sshkey_new failed");
735 (*k)->type = KEY_RSA;
740 fatal("%s: unrecognised raw private key format", __func__);
744 do_convert_from(struct passwd *pw)
746 struct sshkey *k = NULL;
747 int r, private = 0, ok = 0;
751 ask_filename(pw, "Enter file in which the key is");
752 if (stat(identity_file, &st) == -1)
753 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
755 switch (convert_format) {
757 do_convert_from_ssh2(pw, &k, &private);
760 do_convert_from_pkcs8(&k, &private);
763 do_convert_from_pem(&k, &private);
766 fatal("%s: unknown key format %d", __func__, convert_format);
770 if ((r = sshkey_write(k, stdout)) == 0)
773 fprintf(stdout, "\n");
777 ok = PEM_write_DSAPrivateKey(stdout, k->dsa, NULL,
778 NULL, 0, NULL, NULL);
780 #ifdef OPENSSL_HAS_ECC
782 ok = PEM_write_ECPrivateKey(stdout, k->ecdsa, NULL,
783 NULL, 0, NULL, NULL);
787 ok = PEM_write_RSAPrivateKey(stdout, k->rsa, NULL,
788 NULL, 0, NULL, NULL);
791 fatal("%s: unsupported key type %s", __func__,
797 fatal("key write failed");
804 do_print_public(struct passwd *pw)
809 char *comment = NULL;
812 ask_filename(pw, "Enter file in which the key is");
813 if (stat(identity_file, &st) == -1)
814 fatal("%s: %s", identity_file, strerror(errno));
815 prv = load_identity(identity_file, &comment);
816 if ((r = sshkey_write(prv, stdout)) != 0)
817 error("sshkey_write failed: %s", ssh_err(r));
819 if (comment != NULL && *comment != '\0')
820 fprintf(stdout, " %s", comment);
821 fprintf(stdout, "\n");
827 do_download(struct passwd *pw)
830 struct sshkey **keys = NULL;
832 enum sshkey_fp_rep rep;
834 char *fp, *ra, **comments = NULL;
836 fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
837 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
840 nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys, &comments);
842 fatal("cannot read public key from pkcs11");
843 for (i = 0; i < nkeys; i++) {
844 if (print_fingerprint) {
845 fp = sshkey_fingerprint(keys[i], fptype, rep);
846 ra = sshkey_fingerprint(keys[i], fingerprint_hash,
848 if (fp == NULL || ra == NULL)
849 fatal("%s: sshkey_fingerprint fail", __func__);
850 printf("%u %s %s (PKCS11 key)\n", sshkey_size(keys[i]),
851 fp, sshkey_type(keys[i]));
852 if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
857 (void) sshkey_write(keys[i], stdout); /* XXX check */
858 fprintf(stdout, "%s%s\n",
859 *(comments[i]) == '\0' ? "" : " ", comments[i]);
862 sshkey_free(keys[i]);
869 fatal("no pkcs11 support");
870 #endif /* ENABLE_PKCS11 */
873 static struct sshkey *
874 try_read_key(char **cpp)
879 if ((ret = sshkey_new(KEY_UNSPEC)) == NULL)
880 fatal("sshkey_new failed");
881 if ((r = sshkey_read(ret, cpp)) == 0)
889 fingerprint_one_key(const struct sshkey *public, const char *comment)
891 char *fp = NULL, *ra = NULL;
892 enum sshkey_fp_rep rep;
895 fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
896 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
897 fp = sshkey_fingerprint(public, fptype, rep);
898 ra = sshkey_fingerprint(public, fingerprint_hash, SSH_FP_RANDOMART);
899 if (fp == NULL || ra == NULL)
900 fatal("%s: sshkey_fingerprint failed", __func__);
901 mprintf("%u %s %s (%s)\n", sshkey_size(public), fp,
902 comment ? comment : "no comment", sshkey_type(public));
903 if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
910 fingerprint_private(const char *path)
913 char *comment = NULL;
914 struct sshkey *privkey = NULL, *pubkey = NULL;
917 if (stat(identity_file, &st) == -1)
918 fatal("%s: %s", path, strerror(errno));
919 if ((r = sshkey_load_public(path, &pubkey, &comment)) != 0)
920 debug("load public \"%s\": %s", path, ssh_err(r));
921 if (pubkey == NULL || comment == NULL || *comment == '\0') {
923 if ((r = sshkey_load_private(path, NULL,
924 &privkey, &comment)) != 0)
925 debug("load private \"%s\": %s", path, ssh_err(r));
927 if (pubkey == NULL && privkey == NULL)
928 fatal("%s is not a key file.", path);
930 fingerprint_one_key(pubkey == NULL ? privkey : pubkey, comment);
932 sshkey_free(privkey);
937 do_fingerprint(struct passwd *pw)
940 struct sshkey *public = NULL;
941 char *comment = NULL, *cp, *ep, *line = NULL;
948 ask_filename(pw, "Enter file in which the key is");
949 path = identity_file;
951 if (strcmp(identity_file, "-") == 0) {
954 } else if ((f = fopen(path, "r")) == NULL)
955 fatal("%s: %s: %s", __progname, path, strerror(errno));
957 while (getline(&line, &linesize, f) != -1) {
960 cp[strcspn(cp, "\n")] = '\0';
961 /* Trim leading space and comments */
962 cp = line + strspn(line, " \t");
963 if (*cp == '#' || *cp == '\0')
967 * Input may be plain keys, private keys, authorized_keys
972 * Try private keys first. Assume a key is private if
973 * "SSH PRIVATE KEY" appears on the first line and we're
974 * not reading from stdin (XXX support private keys on stdin).
976 if (lnum == 1 && strcmp(identity_file, "-") != 0 &&
977 strstr(cp, "PRIVATE KEY") != NULL) {
980 fingerprint_private(path);
985 * If it's not a private key, then this must be prepared to
986 * accept a public key prefixed with a hostname or options.
987 * Try a bare key first, otherwise skip the leading stuff.
989 if ((public = try_read_key(&cp)) == NULL) {
990 i = strtol(cp, &ep, 10);
991 if (i == 0 || ep == NULL ||
992 (*ep != ' ' && *ep != '\t')) {
996 for (; *cp && (quoted || (*cp != ' ' &&
997 *cp != '\t')); cp++) {
998 if (*cp == '\\' && cp[1] == '"')
999 cp++; /* Skip both */
1000 else if (*cp == '"')
1008 /* Retry after parsing leading hostname/key options */
1009 if (public == NULL && (public = try_read_key(&cp)) == NULL) {
1010 debug("%s:%lu: not a public key", path, lnum);
1014 /* Find trailing comment, if any */
1015 for (; *cp == ' ' || *cp == '\t'; cp++)
1017 if (*cp != '\0' && *cp != '#')
1020 fingerprint_one_key(public, comment);
1021 sshkey_free(public);
1022 invalid = 0; /* One good key in the file is sufficient */
1028 fatal("%s is not a public key file.", path);
1033 do_gen_all_hostkeys(struct passwd *pw)
1037 char *key_type_display;
1041 { "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE },
1042 { "dsa", "DSA", _PATH_HOST_DSA_KEY_FILE },
1043 #ifdef OPENSSL_HAS_ECC
1044 { "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE },
1045 #endif /* OPENSSL_HAS_ECC */
1046 #endif /* WITH_OPENSSL */
1047 { "ed25519", "ED25519",_PATH_HOST_ED25519_KEY_FILE },
1049 { "xmss", "XMSS",_PATH_HOST_XMSS_KEY_FILE },
1050 #endif /* WITH_XMSS */
1051 { NULL, NULL, NULL }
1057 struct sshkey *private, *public;
1058 char comment[1024], *prv_tmp, *pub_tmp, *prv_file, *pub_file;
1061 for (i = 0; key_types[i].key_type; i++) {
1062 public = private = NULL;
1063 prv_tmp = pub_tmp = prv_file = pub_file = NULL;
1065 xasprintf(&prv_file, "%s%s",
1066 identity_file, key_types[i].path);
1068 /* Check whether private key exists and is not zero-length */
1069 if (stat(prv_file, &st) == 0) {
1070 if (st.st_size != 0)
1072 } else if (errno != ENOENT) {
1073 error("Could not stat %s: %s", key_types[i].path,
1079 * Private key doesn't exist or is invalid; proceed with
1082 xasprintf(&prv_tmp, "%s%s.XXXXXXXXXX",
1083 identity_file, key_types[i].path);
1084 xasprintf(&pub_tmp, "%s%s.pub.XXXXXXXXXX",
1085 identity_file, key_types[i].path);
1086 xasprintf(&pub_file, "%s%s.pub",
1087 identity_file, key_types[i].path);
1091 printf("%s: generating new host keys: ", __progname);
1093 printf("%s ", key_types[i].key_type_display);
1095 type = sshkey_type_from_name(key_types[i].key_type);
1096 if ((fd = mkstemp(prv_tmp)) == -1) {
1097 error("Could not save your private key in %s: %s",
1098 prv_tmp, strerror(errno));
1101 (void)close(fd); /* just using mkstemp() to reserve a name */
1103 type_bits_valid(type, NULL, &bits);
1104 if ((r = sshkey_generate(type, bits, &private)) != 0) {
1105 error("sshkey_generate failed: %s", ssh_err(r));
1108 if ((r = sshkey_from_private(private, &public)) != 0)
1109 fatal("sshkey_from_private failed: %s", ssh_err(r));
1110 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name,
1112 if ((r = sshkey_save_private(private, prv_tmp, "",
1113 comment, private_key_format, openssh_format_cipher,
1115 error("Saving key \"%s\" failed: %s",
1116 prv_tmp, ssh_err(r));
1119 if ((fd = mkstemp(pub_tmp)) == -1) {
1120 error("Could not save your public key in %s: %s",
1121 pub_tmp, strerror(errno));
1124 (void)fchmod(fd, 0644);
1126 if ((r = sshkey_save_public(public, pub_tmp, comment)) != 0) {
1127 fatal("Unable to save public key to %s: %s",
1128 identity_file, ssh_err(r));
1132 /* Rename temporary files to their permanent locations. */
1133 if (rename(pub_tmp, pub_file) != 0) {
1134 error("Unable to move %s into position: %s",
1135 pub_file, strerror(errno));
1138 if (rename(prv_tmp, prv_file) != 0) {
1139 error("Unable to move %s into position: %s",
1140 key_types[i].path, strerror(errno));
1146 sshkey_free(private);
1147 sshkey_free(public);
1157 struct known_hosts_ctx {
1158 const char *host; /* Hostname searched for in find/delete case */
1159 FILE *out; /* Output file, stdout for find_hosts case */
1160 int has_unhashed; /* When hashing, original had unhashed hosts */
1161 int found_key; /* For find/delete, host was found */
1162 int invalid; /* File contained invalid items; don't delete */
1163 int hash_hosts; /* Hash hostnames as we go */
1164 int find_host; /* Search for specific hostname */
1165 int delete_host; /* Delete host from known_hosts */
1169 known_hosts_hash(struct hostkey_foreach_line *l, void *_ctx)
1171 struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1172 char *hashed, *cp, *hosts, *ohosts;
1173 int has_wild = l->hosts && strcspn(l->hosts, "*?!") != strlen(l->hosts);
1174 int was_hashed = l->hosts && l->hosts[0] == HASH_DELIM;
1176 switch (l->status) {
1178 case HKF_STATUS_MATCHED:
1180 * Don't hash hosts already already hashed, with wildcard
1181 * characters or a CA/revocation marker.
1183 if (was_hashed || has_wild || l->marker != MRK_NONE) {
1184 fprintf(ctx->out, "%s\n", l->line);
1185 if (has_wild && !ctx->find_host) {
1186 logit("%s:%lu: ignoring host name "
1187 "with wildcard: %.64s", l->path,
1188 l->linenum, l->hosts);
1193 * Split any comma-separated hostnames from the host list,
1194 * hash and store separately.
1196 ohosts = hosts = xstrdup(l->hosts);
1197 while ((cp = strsep(&hosts, ",")) != NULL && *cp != '\0') {
1199 if ((hashed = host_hash(cp, NULL, 0)) == NULL)
1200 fatal("hash_host failed");
1201 fprintf(ctx->out, "%s %s\n", hashed, l->rawkey);
1202 ctx->has_unhashed = 1;
1206 case HKF_STATUS_INVALID:
1207 /* Retain invalid lines, but mark file as invalid. */
1209 logit("%s:%lu: invalid line", l->path, l->linenum);
1212 fprintf(ctx->out, "%s\n", l->line);
1220 known_hosts_find_delete(struct hostkey_foreach_line *l, void *_ctx)
1222 struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1223 enum sshkey_fp_rep rep;
1225 char *fp = NULL, *ra = NULL;
1227 fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
1228 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1230 if (l->status == HKF_STATUS_MATCHED) {
1231 if (ctx->delete_host) {
1232 if (l->marker != MRK_NONE) {
1233 /* Don't remove CA and revocation lines */
1234 fprintf(ctx->out, "%s\n", l->line);
1237 * Hostname matches and has no CA/revoke
1238 * marker, delete it by *not* writing the
1243 printf("# Host %s found: line %lu\n",
1244 ctx->host, l->linenum);
1247 } else if (ctx->find_host) {
1250 printf("# Host %s found: line %lu %s\n",
1252 l->linenum, l->marker == MRK_CA ? "CA" :
1253 (l->marker == MRK_REVOKE ? "REVOKED" : ""));
1255 if (ctx->hash_hosts)
1256 known_hosts_hash(l, ctx);
1257 else if (print_fingerprint) {
1258 fp = sshkey_fingerprint(l->key, fptype, rep);
1259 ra = sshkey_fingerprint(l->key,
1260 fingerprint_hash, SSH_FP_RANDOMART);
1261 if (fp == NULL || ra == NULL)
1262 fatal("%s: sshkey_fingerprint failed",
1264 mprintf("%s %s %s%s%s\n", ctx->host,
1265 sshkey_type(l->key), fp,
1266 l->comment[0] ? " " : "",
1268 if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
1273 fprintf(ctx->out, "%s\n", l->line);
1276 } else if (ctx->delete_host) {
1277 /* Retain non-matching hosts when deleting */
1278 if (l->status == HKF_STATUS_INVALID) {
1280 logit("%s:%lu: invalid line", l->path, l->linenum);
1282 fprintf(ctx->out, "%s\n", l->line);
1288 do_known_hosts(struct passwd *pw, const char *name, int find_host,
1289 int delete_host, int hash_hosts)
1291 char *cp, tmp[PATH_MAX], old[PATH_MAX];
1292 int r, fd, oerrno, inplace = 0;
1293 struct known_hosts_ctx ctx;
1294 u_int foreach_options;
1296 if (!have_identity) {
1297 cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
1298 if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
1299 sizeof(identity_file))
1300 fatal("Specified known hosts path too long");
1305 memset(&ctx, 0, sizeof(ctx));
1308 ctx.hash_hosts = hash_hosts;
1309 ctx.find_host = find_host;
1310 ctx.delete_host = delete_host;
1313 * Find hosts goes to stdout, hash and deletions happen in-place
1314 * A corner case is ssh-keygen -HF foo, which should go to stdout
1316 if (!find_host && (hash_hosts || delete_host)) {
1317 if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
1318 strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
1319 strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
1320 strlcat(old, ".old", sizeof(old)) >= sizeof(old))
1321 fatal("known_hosts path too long");
1323 if ((fd = mkstemp(tmp)) == -1)
1324 fatal("mkstemp: %s", strerror(errno));
1325 if ((ctx.out = fdopen(fd, "w")) == NULL) {
1328 fatal("fdopen: %s", strerror(oerrno));
1332 /* XXX support identity_file == "-" for stdin */
1333 foreach_options = find_host ? HKF_WANT_MATCH : 0;
1334 foreach_options |= print_fingerprint ? HKF_WANT_PARSE_KEY : 0;
1335 if ((r = hostkeys_foreach(identity_file, (find_host || !hash_hosts) ?
1336 known_hosts_find_delete : known_hosts_hash, &ctx, name, NULL,
1337 foreach_options)) != 0) {
1340 fatal("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
1347 error("%s is not a valid known_hosts file.", identity_file);
1349 error("Not replacing existing known_hosts "
1350 "file because of errors");
1354 } else if (delete_host && !ctx.found_key) {
1355 logit("Host %s not found in %s", name, identity_file);
1358 } else if (inplace) {
1359 /* Backup existing file */
1360 if (unlink(old) == -1 && errno != ENOENT)
1361 fatal("unlink %.100s: %s", old, strerror(errno));
1362 if (link(identity_file, old) == -1)
1363 fatal("link %.100s to %.100s: %s", identity_file, old,
1365 /* Move new one into place */
1366 if (rename(tmp, identity_file) == -1) {
1367 error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
1374 printf("%s updated.\n", identity_file);
1375 printf("Original contents retained as %s\n", old);
1376 if (ctx.has_unhashed) {
1377 logit("WARNING: %s contains unhashed entries", old);
1378 logit("Delete this file to ensure privacy "
1383 exit (find_host && !ctx.found_key);
1387 * Perform changing a passphrase. The argument is the passwd structure
1388 * for the current user.
1391 do_change_passphrase(struct passwd *pw)
1394 char *old_passphrase, *passphrase1, *passphrase2;
1396 struct sshkey *private;
1400 ask_filename(pw, "Enter file in which the key is");
1401 if (stat(identity_file, &st) == -1)
1402 fatal("%s: %s", identity_file, strerror(errno));
1403 /* Try to load the file with empty passphrase. */
1404 r = sshkey_load_private(identity_file, "", &private, &comment);
1405 if (r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
1406 if (identity_passphrase)
1407 old_passphrase = xstrdup(identity_passphrase);
1410 read_passphrase("Enter old passphrase: ",
1412 r = sshkey_load_private(identity_file, old_passphrase,
1413 &private, &comment);
1414 freezero(old_passphrase, strlen(old_passphrase));
1417 } else if (r != 0) {
1419 fatal("Failed to load key %s: %s", identity_file, ssh_err(r));
1422 mprintf("Key has comment '%s'\n", comment);
1424 /* Ask the new passphrase (twice). */
1425 if (identity_new_passphrase) {
1426 passphrase1 = xstrdup(identity_new_passphrase);
1430 read_passphrase("Enter new passphrase (empty for no "
1431 "passphrase): ", RP_ALLOW_STDIN);
1432 passphrase2 = read_passphrase("Enter same passphrase again: ",
1435 /* Verify that they are the same. */
1436 if (strcmp(passphrase1, passphrase2) != 0) {
1437 explicit_bzero(passphrase1, strlen(passphrase1));
1438 explicit_bzero(passphrase2, strlen(passphrase2));
1441 printf("Pass phrases do not match. Try again.\n");
1444 /* Destroy the other copy. */
1445 freezero(passphrase2, strlen(passphrase2));
1448 /* Save the file using the new passphrase. */
1449 if ((r = sshkey_save_private(private, identity_file, passphrase1,
1450 comment, private_key_format, openssh_format_cipher, rounds)) != 0) {
1451 error("Saving key \"%s\" failed: %s.",
1452 identity_file, ssh_err(r));
1453 freezero(passphrase1, strlen(passphrase1));
1454 sshkey_free(private);
1458 /* Destroy the passphrase and the copy of the key in memory. */
1459 freezero(passphrase1, strlen(passphrase1));
1460 sshkey_free(private); /* Destroys contents */
1463 printf("Your identification has been saved with the new passphrase.\n");
1468 * Print the SSHFP RR.
1471 do_print_resource_record(struct passwd *pw, char *fname, char *hname,
1474 struct sshkey *public;
1475 char *comment = NULL;
1480 fatal("%s: no filename", __func__);
1481 if (stat(fname, &st) == -1) {
1482 if (errno == ENOENT)
1484 fatal("%s: %s", fname, strerror(errno));
1486 if ((r = sshkey_load_public(fname, &public, &comment)) != 0)
1487 fatal("Failed to read v2 public key from \"%s\": %s.",
1489 export_dns_rr(hname, public, stdout, print_generic);
1490 sshkey_free(public);
1496 * Change the comment of a private key file.
1499 do_change_comment(struct passwd *pw, const char *identity_comment)
1501 char new_comment[1024], *comment, *passphrase;
1502 struct sshkey *private;
1503 struct sshkey *public;
1508 ask_filename(pw, "Enter file in which the key is");
1509 if (stat(identity_file, &st) == -1)
1510 fatal("%s: %s", identity_file, strerror(errno));
1511 if ((r = sshkey_load_private(identity_file, "",
1512 &private, &comment)) == 0)
1513 passphrase = xstrdup("");
1514 else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
1515 fatal("Cannot load private key \"%s\": %s.",
1516 identity_file, ssh_err(r));
1518 if (identity_passphrase)
1519 passphrase = xstrdup(identity_passphrase);
1520 else if (identity_new_passphrase)
1521 passphrase = xstrdup(identity_new_passphrase);
1523 passphrase = read_passphrase("Enter passphrase: ",
1525 /* Try to load using the passphrase. */
1526 if ((r = sshkey_load_private(identity_file, passphrase,
1527 &private, &comment)) != 0) {
1528 freezero(passphrase, strlen(passphrase));
1529 fatal("Cannot load private key \"%s\": %s.",
1530 identity_file, ssh_err(r));
1534 if (private->type != KEY_ED25519 && private->type != KEY_XMSS &&
1535 private_key_format != SSHKEY_PRIVATE_OPENSSH) {
1536 error("Comments are only supported for keys stored in "
1537 "the new format (-o).");
1538 explicit_bzero(passphrase, strlen(passphrase));
1539 sshkey_free(private);
1543 printf("Old comment: %s\n", comment);
1545 printf("No existing comment\n");
1547 if (identity_comment) {
1548 strlcpy(new_comment, identity_comment, sizeof(new_comment));
1550 printf("New comment: ");
1552 if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1553 explicit_bzero(passphrase, strlen(passphrase));
1554 sshkey_free(private);
1557 new_comment[strcspn(new_comment, "\n")] = '\0';
1559 if (comment != NULL && strcmp(comment, new_comment) == 0) {
1560 printf("No change to comment\n");
1562 sshkey_free(private);
1567 /* Save the file using the new passphrase. */
1568 if ((r = sshkey_save_private(private, identity_file, passphrase,
1569 new_comment, private_key_format, openssh_format_cipher,
1571 error("Saving key \"%s\" failed: %s",
1572 identity_file, ssh_err(r));
1573 freezero(passphrase, strlen(passphrase));
1574 sshkey_free(private);
1578 freezero(passphrase, strlen(passphrase));
1579 if ((r = sshkey_from_private(private, &public)) != 0)
1580 fatal("sshkey_from_private failed: %s", ssh_err(r));
1581 sshkey_free(private);
1583 strlcat(identity_file, ".pub", sizeof(identity_file));
1584 if ((r = sshkey_save_public(public, identity_file, new_comment)) != 0) {
1585 fatal("Unable to save public key to %s: %s",
1586 identity_file, ssh_err(r));
1588 sshkey_free(public);
1591 if (strlen(new_comment) > 0)
1592 printf("Comment '%s' applied\n", new_comment);
1594 printf("Comment removed\n");
1600 add_flag_option(struct sshbuf *c, const char *name)
1604 debug3("%s: %s", __func__, name);
1605 if ((r = sshbuf_put_cstring(c, name)) != 0 ||
1606 (r = sshbuf_put_string(c, NULL, 0)) != 0)
1607 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1611 add_string_option(struct sshbuf *c, const char *name, const char *value)
1616 debug3("%s: %s=%s", __func__, name, value);
1617 if ((b = sshbuf_new()) == NULL)
1618 fatal("%s: sshbuf_new failed", __func__);
1619 if ((r = sshbuf_put_cstring(b, value)) != 0 ||
1620 (r = sshbuf_put_cstring(c, name)) != 0 ||
1621 (r = sshbuf_put_stringb(c, b)) != 0)
1622 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1627 #define OPTIONS_CRITICAL 1
1628 #define OPTIONS_EXTENSIONS 2
1630 prepare_options_buf(struct sshbuf *c, int which)
1635 if ((which & OPTIONS_CRITICAL) != 0 &&
1636 certflags_command != NULL)
1637 add_string_option(c, "force-command", certflags_command);
1638 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1639 (certflags_flags & CERTOPT_X_FWD) != 0)
1640 add_flag_option(c, "permit-X11-forwarding");
1641 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1642 (certflags_flags & CERTOPT_AGENT_FWD) != 0)
1643 add_flag_option(c, "permit-agent-forwarding");
1644 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1645 (certflags_flags & CERTOPT_PORT_FWD) != 0)
1646 add_flag_option(c, "permit-port-forwarding");
1647 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1648 (certflags_flags & CERTOPT_PTY) != 0)
1649 add_flag_option(c, "permit-pty");
1650 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1651 (certflags_flags & CERTOPT_USER_RC) != 0)
1652 add_flag_option(c, "permit-user-rc");
1653 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1654 (certflags_flags & CERTOPT_NO_REQUIRE_USER_PRESENCE) != 0)
1655 add_flag_option(c, "no-touch-required");
1656 if ((which & OPTIONS_CRITICAL) != 0 &&
1657 certflags_src_addr != NULL)
1658 add_string_option(c, "source-address", certflags_src_addr);
1659 for (i = 0; i < ncert_userext; i++) {
1660 if ((cert_userext[i].crit && (which & OPTIONS_EXTENSIONS)) ||
1661 (!cert_userext[i].crit && (which & OPTIONS_CRITICAL)))
1663 if (cert_userext[i].val == NULL)
1664 add_flag_option(c, cert_userext[i].key);
1666 add_string_option(c, cert_userext[i].key,
1667 cert_userext[i].val);
1672 static struct sshkey *
1673 load_pkcs11_key(char *path)
1675 #ifdef ENABLE_PKCS11
1676 struct sshkey **keys = NULL, *public, *private = NULL;
1679 if ((r = sshkey_load_public(path, &public, NULL)) != 0)
1680 fatal("Couldn't load CA public key \"%s\": %s",
1683 nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase,
1685 debug3("%s: %d keys", __func__, nkeys);
1687 fatal("cannot read public key from pkcs11");
1688 for (i = 0; i < nkeys; i++) {
1689 if (sshkey_equal_public(public, keys[i])) {
1693 sshkey_free(keys[i]);
1696 sshkey_free(public);
1699 fatal("no pkcs11 support");
1700 #endif /* ENABLE_PKCS11 */
1703 /* Signer for sshkey_certify_custom that uses the agent */
1705 agent_signer(struct sshkey *key, u_char **sigp, size_t *lenp,
1706 const u_char *data, size_t datalen,
1707 const char *alg, const char *provider, u_int compat, void *ctx)
1709 int *agent_fdp = (int *)ctx;
1711 return ssh_agent_sign(*agent_fdp, key, sigp, lenp,
1712 data, datalen, alg, compat);
1716 do_ca_sign(struct passwd *pw, const char *ca_key_path, int prefer_agent,
1717 unsigned long long cert_serial, int cert_serial_autoinc,
1718 int argc, char **argv)
1720 int r, i, found, agent_fd = -1;
1722 struct sshkey *ca, *public;
1723 char valid[64], *otmp, *tmp, *cp, *out, *comment;
1724 char *ca_fp = NULL, **plist = NULL;
1725 struct ssh_identitylist *agent_ids;
1727 struct notifier_ctx *notifier = NULL;
1729 #ifdef ENABLE_PKCS11
1732 tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
1733 if (pkcs11provider != NULL) {
1734 /* If a PKCS#11 token was specified then try to use it */
1735 if ((ca = load_pkcs11_key(tmp)) == NULL)
1736 fatal("No PKCS#11 key matching %s found", ca_key_path);
1737 } else if (prefer_agent) {
1739 * Agent signature requested. Try to use agent after making
1740 * sure the public key specified is actually present in the
1743 if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
1744 fatal("Cannot load CA public key %s: %s",
1746 if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
1747 fatal("Cannot use public key for CA signature: %s",
1749 if ((r = ssh_fetch_identitylist(agent_fd, &agent_ids)) != 0)
1750 fatal("Retrieve agent key list: %s", ssh_err(r));
1752 for (j = 0; j < agent_ids->nkeys; j++) {
1753 if (sshkey_equal(ca, agent_ids->keys[j])) {
1759 fatal("CA key %s not found in agent", tmp);
1760 ssh_free_identitylist(agent_ids);
1761 ca->flags |= SSHKEY_FLAG_EXT;
1763 /* CA key is assumed to be a private key on the filesystem */
1764 ca = load_identity(tmp, NULL);
1768 if (key_type_name != NULL) {
1769 if (sshkey_type_from_name(key_type_name) != ca->type) {
1770 fatal("CA key type %s doesn't match specified %s",
1771 sshkey_ssh_name(ca), key_type_name);
1773 } else if (ca->type == KEY_RSA) {
1774 /* Default to a good signature algorithm */
1775 key_type_name = "rsa-sha2-512";
1777 ca_fp = sshkey_fingerprint(ca, fingerprint_hash, SSH_FP_DEFAULT);
1779 for (i = 0; i < argc; i++) {
1780 /* Split list of principals */
1782 if (cert_principals != NULL) {
1783 otmp = tmp = xstrdup(cert_principals);
1785 for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1786 plist = xreallocarray(plist, n + 1, sizeof(*plist));
1787 if (*(plist[n] = xstrdup(cp)) == '\0')
1788 fatal("Empty principal name");
1792 if (n > SSHKEY_CERT_MAX_PRINCIPALS)
1793 fatal("Too many certificate principals specified");
1795 tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1796 if ((r = sshkey_load_public(tmp, &public, &comment)) != 0)
1797 fatal("%s: unable to open \"%s\": %s",
1798 __func__, tmp, ssh_err(r));
1799 if (sshkey_is_cert(public))
1800 fatal("%s: key \"%s\" type %s cannot be certified",
1801 __func__, tmp, sshkey_type(public));
1803 /* Prepare certificate to sign */
1804 if ((r = sshkey_to_certified(public)) != 0)
1805 fatal("Could not upgrade key %s to certificate: %s",
1807 public->cert->type = cert_key_type;
1808 public->cert->serial = (u_int64_t)cert_serial;
1809 public->cert->key_id = xstrdup(cert_key_id);
1810 public->cert->nprincipals = n;
1811 public->cert->principals = plist;
1812 public->cert->valid_after = cert_valid_from;
1813 public->cert->valid_before = cert_valid_to;
1814 prepare_options_buf(public->cert->critical, OPTIONS_CRITICAL);
1815 prepare_options_buf(public->cert->extensions,
1816 OPTIONS_EXTENSIONS);
1817 if ((r = sshkey_from_private(ca,
1818 &public->cert->signature_key)) != 0)
1819 fatal("sshkey_from_private (ca key): %s", ssh_err(r));
1821 if (agent_fd != -1 && (ca->flags & SSHKEY_FLAG_EXT) != 0) {
1822 if ((r = sshkey_certify_custom(public, ca,
1823 key_type_name, sk_provider, agent_signer,
1825 fatal("Couldn't certify key %s via agent: %s",
1828 if (sshkey_is_sk(ca) &&
1829 (ca->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
1830 notifier = notify_start(0,
1831 "Confirm user presence for key %s %s",
1832 sshkey_type(ca), ca_fp);
1834 r = sshkey_certify(public, ca, key_type_name,
1836 notify_complete(notifier);
1838 fatal("Couldn't certify key %s: %s",
1842 if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
1844 xasprintf(&out, "%s-cert.pub", tmp);
1847 if ((r = sshkey_save_public(public, out, comment)) != 0) {
1848 fatal("Unable to save public key to %s: %s",
1849 identity_file, ssh_err(r));
1853 sshkey_format_cert_validity(public->cert,
1854 valid, sizeof(valid));
1855 logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1856 "valid %s", sshkey_cert_type(public),
1857 out, public->cert->key_id,
1858 (unsigned long long)public->cert->serial,
1859 cert_principals != NULL ? " for " : "",
1860 cert_principals != NULL ? cert_principals : "",
1864 sshkey_free(public);
1866 if (cert_serial_autoinc)
1870 #ifdef ENABLE_PKCS11
1877 parse_relative_time(const char *s, time_t now)
1881 mul = *s == '-' ? -1 : 1;
1883 if ((secs = convtime(s + 1)) == -1)
1884 fatal("Invalid relative certificate time %s", s);
1885 if (mul == -1 && secs > now)
1886 fatal("Certificate time %s cannot be represented", s);
1887 return now + (u_int64_t)(secs * mul);
1891 parse_cert_times(char *timespec)
1894 time_t now = time(NULL);
1897 /* +timespec relative to now */
1898 if (*timespec == '+' && strchr(timespec, ':') == NULL) {
1899 if ((secs = convtime(timespec + 1)) == -1)
1900 fatal("Invalid relative certificate life %s", timespec);
1901 cert_valid_to = now + secs;
1903 * Backdate certificate one minute to avoid problems on hosts
1904 * with poorly-synchronised clocks.
1906 cert_valid_from = ((now - 59)/ 60) * 60;
1912 * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "always"
1913 * to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "forever"
1915 from = xstrdup(timespec);
1916 to = strchr(from, ':');
1917 if (to == NULL || from == to || *(to + 1) == '\0')
1918 fatal("Invalid certificate life specification %s", timespec);
1921 if (*from == '-' || *from == '+')
1922 cert_valid_from = parse_relative_time(from, now);
1923 else if (strcmp(from, "always") == 0)
1924 cert_valid_from = 0;
1925 else if (parse_absolute_time(from, &cert_valid_from) != 0)
1926 fatal("Invalid from time \"%s\"", from);
1928 if (*to == '-' || *to == '+')
1929 cert_valid_to = parse_relative_time(to, now);
1930 else if (strcmp(to, "forever") == 0)
1931 cert_valid_to = ~(u_int64_t)0;
1932 else if (parse_absolute_time(to, &cert_valid_to) != 0)
1933 fatal("Invalid to time \"%s\"", to);
1935 if (cert_valid_to <= cert_valid_from)
1936 fatal("Empty certificate validity interval");
1941 add_cert_option(char *opt)
1946 if (strcasecmp(opt, "clear") == 0)
1947 certflags_flags = 0;
1948 else if (strcasecmp(opt, "no-x11-forwarding") == 0)
1949 certflags_flags &= ~CERTOPT_X_FWD;
1950 else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
1951 certflags_flags |= CERTOPT_X_FWD;
1952 else if (strcasecmp(opt, "no-agent-forwarding") == 0)
1953 certflags_flags &= ~CERTOPT_AGENT_FWD;
1954 else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
1955 certflags_flags |= CERTOPT_AGENT_FWD;
1956 else if (strcasecmp(opt, "no-port-forwarding") == 0)
1957 certflags_flags &= ~CERTOPT_PORT_FWD;
1958 else if (strcasecmp(opt, "permit-port-forwarding") == 0)
1959 certflags_flags |= CERTOPT_PORT_FWD;
1960 else if (strcasecmp(opt, "no-pty") == 0)
1961 certflags_flags &= ~CERTOPT_PTY;
1962 else if (strcasecmp(opt, "permit-pty") == 0)
1963 certflags_flags |= CERTOPT_PTY;
1964 else if (strcasecmp(opt, "no-user-rc") == 0)
1965 certflags_flags &= ~CERTOPT_USER_RC;
1966 else if (strcasecmp(opt, "permit-user-rc") == 0)
1967 certflags_flags |= CERTOPT_USER_RC;
1968 else if (strcasecmp(opt, "touch-required") == 0)
1969 certflags_flags &= ~CERTOPT_NO_REQUIRE_USER_PRESENCE;
1970 else if (strcasecmp(opt, "no-touch-required") == 0)
1971 certflags_flags |= CERTOPT_NO_REQUIRE_USER_PRESENCE;
1972 else if (strncasecmp(opt, "force-command=", 14) == 0) {
1975 fatal("Empty force-command option");
1976 if (certflags_command != NULL)
1977 fatal("force-command already specified");
1978 certflags_command = xstrdup(val);
1979 } else if (strncasecmp(opt, "source-address=", 15) == 0) {
1982 fatal("Empty source-address option");
1983 if (certflags_src_addr != NULL)
1984 fatal("source-address already specified");
1985 if (addr_match_cidr_list(NULL, val) != 0)
1986 fatal("Invalid source-address list");
1987 certflags_src_addr = xstrdup(val);
1988 } else if (strncasecmp(opt, "extension:", 10) == 0 ||
1989 (iscrit = (strncasecmp(opt, "critical:", 9) == 0))) {
1990 val = xstrdup(strchr(opt, ':') + 1);
1991 if ((cp = strchr(val, '=')) != NULL)
1993 cert_userext = xreallocarray(cert_userext, ncert_userext + 1,
1994 sizeof(*cert_userext));
1995 cert_userext[ncert_userext].key = val;
1996 cert_userext[ncert_userext].val = cp == NULL ?
1998 cert_userext[ncert_userext].crit = iscrit;
2001 fatal("Unsupported certificate option \"%s\"", opt);
2005 show_options(struct sshbuf *optbuf, int in_critical)
2008 struct sshbuf *options, *option = NULL;
2011 if ((options = sshbuf_fromb(optbuf)) == NULL)
2012 fatal("%s: sshbuf_fromb failed", __func__);
2013 while (sshbuf_len(options) != 0) {
2014 sshbuf_free(option);
2016 if ((r = sshbuf_get_cstring(options, &name, NULL)) != 0 ||
2017 (r = sshbuf_froms(options, &option)) != 0)
2018 fatal("%s: buffer error: %s", __func__, ssh_err(r));
2019 printf(" %s", name);
2021 (strcmp(name, "permit-X11-forwarding") == 0 ||
2022 strcmp(name, "permit-agent-forwarding") == 0 ||
2023 strcmp(name, "permit-port-forwarding") == 0 ||
2024 strcmp(name, "permit-pty") == 0 ||
2025 strcmp(name, "permit-user-rc") == 0 ||
2026 strcmp(name, "no-touch-required") == 0)) {
2028 } else if (in_critical &&
2029 (strcmp(name, "force-command") == 0 ||
2030 strcmp(name, "source-address") == 0)) {
2031 if ((r = sshbuf_get_cstring(option, &arg, NULL)) != 0)
2032 fatal("%s: buffer error: %s",
2033 __func__, ssh_err(r));
2034 printf(" %s\n", arg);
2037 printf(" UNKNOWN OPTION (len %zu)\n",
2038 sshbuf_len(option));
2039 sshbuf_reset(option);
2042 if (sshbuf_len(option) != 0)
2043 fatal("Option corrupt: extra data at end");
2045 sshbuf_free(option);
2046 sshbuf_free(options);
2050 print_cert(struct sshkey *key)
2052 char valid[64], *key_fp, *ca_fp;
2055 key_fp = sshkey_fingerprint(key, fingerprint_hash, SSH_FP_DEFAULT);
2056 ca_fp = sshkey_fingerprint(key->cert->signature_key,
2057 fingerprint_hash, SSH_FP_DEFAULT);
2058 if (key_fp == NULL || ca_fp == NULL)
2059 fatal("%s: sshkey_fingerprint fail", __func__);
2060 sshkey_format_cert_validity(key->cert, valid, sizeof(valid));
2062 printf(" Type: %s %s certificate\n", sshkey_ssh_name(key),
2063 sshkey_cert_type(key));
2064 printf(" Public key: %s %s\n", sshkey_type(key), key_fp);
2065 printf(" Signing CA: %s %s (using %s)\n",
2066 sshkey_type(key->cert->signature_key), ca_fp,
2067 key->cert->signature_type);
2068 printf(" Key ID: \"%s\"\n", key->cert->key_id);
2069 printf(" Serial: %llu\n", (unsigned long long)key->cert->serial);
2070 printf(" Valid: %s\n", valid);
2071 printf(" Principals: ");
2072 if (key->cert->nprincipals == 0)
2075 for (i = 0; i < key->cert->nprincipals; i++)
2077 key->cert->principals[i]);
2080 printf(" Critical Options: ");
2081 if (sshbuf_len(key->cert->critical) == 0)
2085 show_options(key->cert->critical, 1);
2087 printf(" Extensions: ");
2088 if (sshbuf_len(key->cert->extensions) == 0)
2092 show_options(key->cert->extensions, 0);
2097 do_show_cert(struct passwd *pw)
2099 struct sshkey *key = NULL;
2101 int r, is_stdin = 0, ok = 0;
2103 char *cp, *line = NULL;
2105 size_t linesize = 0;
2109 ask_filename(pw, "Enter file in which the key is");
2110 if (strcmp(identity_file, "-") != 0 && stat(identity_file, &st) == -1)
2111 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
2113 path = identity_file;
2114 if (strcmp(path, "-") == 0) {
2118 } else if ((f = fopen(identity_file, "r")) == NULL)
2119 fatal("fopen %s: %s", identity_file, strerror(errno));
2121 while (getline(&line, &linesize, f) != -1) {
2125 /* Trim leading space and comments */
2126 cp = line + strspn(line, " \t");
2127 if (*cp == '#' || *cp == '\0')
2129 if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2130 fatal("sshkey_new");
2131 if ((r = sshkey_read(key, &cp)) != 0) {
2132 error("%s:%lu: invalid key: %s", path,
2136 if (!sshkey_is_cert(key)) {
2137 error("%s:%lu is not a certificate", path, lnum);
2141 if (!is_stdin && lnum == 1)
2142 printf("%s:\n", path);
2144 printf("%s:%lu:\n", path, lnum);
2154 load_krl(const char *path, struct ssh_krl **krlp)
2156 struct sshbuf *krlbuf;
2159 if ((r = sshbuf_load_file(path, &krlbuf)) != 0)
2160 fatal("Unable to load KRL: %s", ssh_err(r));
2161 /* XXX check sigs */
2162 if ((r = ssh_krl_from_blob(krlbuf, krlp, NULL, 0)) != 0 ||
2164 fatal("Invalid KRL file: %s", ssh_err(r));
2165 sshbuf_free(krlbuf);
2169 hash_to_blob(const char *cp, u_char **blobp, size_t *lenp,
2170 const char *file, u_long lnum)
2177 if (strncmp(cp, "SHA256:", 7) != 0)
2178 fatal("%s:%lu: unsupported hash algorithm", file, lnum);
2182 * OpenSSH base64 hashes omit trailing '='
2183 * characters; put them back for decode.
2186 tmp = xmalloc(tlen + 4 + 1);
2187 strlcpy(tmp, cp, tlen + 1);
2188 while ((tlen % 4) != 0) {
2192 if ((b = sshbuf_new()) == NULL)
2193 fatal("%s: sshbuf_new failed", __func__);
2194 if ((r = sshbuf_b64tod(b, tmp)) != 0)
2195 fatal("%s:%lu: decode hash failed: %s", file, lnum, ssh_err(r));
2197 *lenp = sshbuf_len(b);
2198 *blobp = xmalloc(*lenp);
2199 memcpy(*blobp, sshbuf_ptr(b), *lenp);
2204 update_krl_from_file(struct passwd *pw, const char *file, int wild_ca,
2205 const struct sshkey *ca, struct ssh_krl *krl)
2207 struct sshkey *key = NULL;
2209 char *path, *cp, *ep, *line = NULL;
2210 u_char *blob = NULL;
2211 size_t blen = 0, linesize = 0;
2212 unsigned long long serial, serial2;
2213 int i, was_explicit_key, was_sha1, was_sha256, was_hash, r;
2216 path = tilde_expand_filename(file, pw->pw_uid);
2217 if (strcmp(path, "-") == 0) {
2220 path = xstrdup("(standard input)");
2221 } else if ((krl_spec = fopen(path, "r")) == NULL)
2222 fatal("fopen %s: %s", path, strerror(errno));
2225 printf("Revoking from %s\n", path);
2226 while (getline(&line, &linesize, krl_spec) != -1) {
2228 was_explicit_key = was_sha1 = was_sha256 = was_hash = 0;
2229 cp = line + strspn(line, " \t");
2230 /* Trim trailing space, comments and strip \n */
2231 for (i = 0, r = -1; cp[i] != '\0'; i++) {
2232 if (cp[i] == '#' || cp[i] == '\n') {
2236 if (cp[i] == ' ' || cp[i] == '\t') {
2237 /* Remember the start of a span of whitespace */
2247 if (strncasecmp(cp, "serial:", 7) == 0) {
2248 if (ca == NULL && !wild_ca) {
2249 fatal("revoking certificates by serial number "
2250 "requires specification of a CA key");
2253 cp = cp + strspn(cp, " \t");
2255 serial = strtoull(cp, &ep, 0);
2256 if (*cp == '\0' || (*ep != '\0' && *ep != '-'))
2257 fatal("%s:%lu: invalid serial \"%s\"",
2259 if (errno == ERANGE && serial == ULLONG_MAX)
2260 fatal("%s:%lu: serial out of range",
2266 serial2 = strtoull(cp, &ep, 0);
2267 if (*cp == '\0' || *ep != '\0')
2268 fatal("%s:%lu: invalid serial \"%s\"",
2270 if (errno == ERANGE && serial2 == ULLONG_MAX)
2271 fatal("%s:%lu: serial out of range",
2273 if (serial2 <= serial)
2274 fatal("%s:%lu: invalid serial range "
2275 "%llu:%llu", path, lnum,
2276 (unsigned long long)serial,
2277 (unsigned long long)serial2);
2279 if (ssh_krl_revoke_cert_by_serial_range(krl,
2280 ca, serial, serial2) != 0) {
2281 fatal("%s: revoke serial failed",
2284 } else if (strncasecmp(cp, "id:", 3) == 0) {
2285 if (ca == NULL && !wild_ca) {
2286 fatal("revoking certificates by key ID "
2287 "requires specification of a CA key");
2290 cp = cp + strspn(cp, " \t");
2291 if (ssh_krl_revoke_cert_by_key_id(krl, ca, cp) != 0)
2292 fatal("%s: revoke key ID failed", __func__);
2293 } else if (strncasecmp(cp, "hash:", 5) == 0) {
2295 cp = cp + strspn(cp, " \t");
2296 hash_to_blob(cp, &blob, &blen, file, lnum);
2297 r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2299 fatal("%s: revoke key failed: %s",
2300 __func__, ssh_err(r));
2302 if (strncasecmp(cp, "key:", 4) == 0) {
2304 cp = cp + strspn(cp, " \t");
2305 was_explicit_key = 1;
2306 } else if (strncasecmp(cp, "sha1:", 5) == 0) {
2308 cp = cp + strspn(cp, " \t");
2310 } else if (strncasecmp(cp, "sha256:", 7) == 0) {
2312 cp = cp + strspn(cp, " \t");
2315 * Just try to process the line as a key.
2316 * Parsing will fail if it isn't.
2319 if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2320 fatal("sshkey_new");
2321 if ((r = sshkey_read(key, &cp)) != 0)
2322 fatal("%s:%lu: invalid key: %s",
2323 path, lnum, ssh_err(r));
2324 if (was_explicit_key)
2325 r = ssh_krl_revoke_key_explicit(krl, key);
2326 else if (was_sha1) {
2327 if (sshkey_fingerprint_raw(key,
2328 SSH_DIGEST_SHA1, &blob, &blen) != 0) {
2329 fatal("%s:%lu: fingerprint failed",
2332 r = ssh_krl_revoke_key_sha1(krl, blob, blen);
2333 } else if (was_sha256) {
2334 if (sshkey_fingerprint_raw(key,
2335 SSH_DIGEST_SHA256, &blob, &blen) != 0) {
2336 fatal("%s:%lu: fingerprint failed",
2339 r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2341 r = ssh_krl_revoke_key(krl, key);
2343 fatal("%s: revoke key failed: %s",
2344 __func__, ssh_err(r));
2345 freezero(blob, blen);
2351 if (strcmp(path, "-") != 0)
2358 do_gen_krl(struct passwd *pw, int updating, const char *ca_key_path,
2359 unsigned long long krl_version, const char *krl_comment,
2360 int argc, char **argv)
2362 struct ssh_krl *krl;
2364 struct sshkey *ca = NULL;
2365 int i, r, wild_ca = 0;
2367 struct sshbuf *kbuf;
2369 if (*identity_file == '\0')
2370 fatal("KRL generation requires an output file");
2371 if (stat(identity_file, &sb) == -1) {
2372 if (errno != ENOENT)
2373 fatal("Cannot access KRL \"%s\": %s",
2374 identity_file, strerror(errno));
2376 fatal("KRL \"%s\" does not exist", identity_file);
2378 if (ca_key_path != NULL) {
2379 if (strcasecmp(ca_key_path, "none") == 0)
2382 tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
2383 if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
2384 fatal("Cannot load CA public key %s: %s",
2391 load_krl(identity_file, &krl);
2392 else if ((krl = ssh_krl_init()) == NULL)
2393 fatal("couldn't create KRL");
2395 if (krl_version != 0)
2396 ssh_krl_set_version(krl, krl_version);
2397 if (krl_comment != NULL)
2398 ssh_krl_set_comment(krl, krl_comment);
2400 for (i = 0; i < argc; i++)
2401 update_krl_from_file(pw, argv[i], wild_ca, ca, krl);
2403 if ((kbuf = sshbuf_new()) == NULL)
2404 fatal("sshbuf_new failed");
2405 if (ssh_krl_to_blob(krl, kbuf, NULL, 0) != 0)
2406 fatal("Couldn't generate KRL");
2407 if ((r = sshbuf_write_file(identity_file, kbuf)) != 0)
2408 fatal("write %s: %s", identity_file, strerror(errno));
2415 do_check_krl(struct passwd *pw, int print_krl, int argc, char **argv)
2419 struct ssh_krl *krl;
2422 if (*identity_file == '\0')
2423 fatal("KRL checking requires an input file");
2424 load_krl(identity_file, &krl);
2426 krl_dump(krl, stdout);
2427 for (i = 0; i < argc; i++) {
2428 if ((r = sshkey_load_public(argv[i], &k, &comment)) != 0)
2429 fatal("Cannot load public key %s: %s",
2430 argv[i], ssh_err(r));
2431 r = ssh_krl_check_key(krl, k);
2432 printf("%s%s%s%s: %s\n", argv[i],
2433 *comment ? " (" : "", comment, *comment ? ")" : "",
2434 r == 0 ? "ok" : "REVOKED");
2444 static struct sshkey *
2445 load_sign_key(const char *keypath, const struct sshkey *pubkey)
2447 size_t i, slen, plen = strlen(keypath);
2448 char *privpath = xstrdup(keypath);
2449 const char *suffixes[] = { "-cert.pub", ".pub", NULL };
2450 struct sshkey *ret = NULL, *privkey = NULL;
2454 * If passed a public key filename, then try to locate the corresponding
2455 * private key. This lets us specify certificates on the command-line
2456 * and have ssh-keygen find the appropriate private key.
2458 for (i = 0; suffixes[i]; i++) {
2459 slen = strlen(suffixes[i]);
2461 strcmp(privpath + plen - slen, suffixes[i]) != 0)
2463 privpath[plen - slen] = '\0';
2464 debug("%s: %s looks like a public key, using private key "
2465 "path %s instead", __func__, keypath, privpath);
2467 if ((privkey = load_identity(privpath, NULL)) == NULL) {
2468 error("Couldn't load identity %s", keypath);
2471 if (!sshkey_equal_public(pubkey, privkey)) {
2472 error("Public key %s doesn't match private %s",
2476 if (sshkey_is_cert(pubkey) && !sshkey_is_cert(privkey)) {
2478 * Graft the certificate onto the private key to make
2479 * it capable of signing.
2481 if ((r = sshkey_to_certified(privkey)) != 0) {
2482 error("%s: sshkey_to_certified: %s", __func__,
2486 if ((r = sshkey_cert_copy(pubkey, privkey)) != 0) {
2487 error("%s: sshkey_cert_copy: %s", __func__, ssh_err(r));
2495 sshkey_free(privkey);
2501 sign_one(struct sshkey *signkey, const char *filename, int fd,
2502 const char *sig_namespace, sshsig_signer *signer, void *signer_ctx)
2504 struct sshbuf *sigbuf = NULL, *abuf = NULL;
2505 int r = SSH_ERR_INTERNAL_ERROR, wfd = -1, oerrno;
2506 char *wfile = NULL, *asig = NULL, *fp = NULL;
2509 if (fd == STDIN_FILENO)
2510 fprintf(stderr, "Signing data on standard input\n");
2512 fprintf(stderr, "Signing file %s\n", filename);
2514 if (signer == NULL && sshkey_is_sk(signkey) &&
2515 (signkey->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
2516 if ((fp = sshkey_fingerprint(signkey, fingerprint_hash,
2517 SSH_FP_DEFAULT)) == NULL)
2518 fatal("%s: sshkey_fingerprint failed", __func__);
2519 fprintf(stderr, "Confirm user presence for key %s %s\n",
2520 sshkey_type(signkey), fp);
2523 if ((r = sshsig_sign_fd(signkey, NULL, sk_provider, fd, sig_namespace,
2524 &sigbuf, signer, signer_ctx)) != 0) {
2525 error("Signing %s failed: %s", filename, ssh_err(r));
2528 if ((r = sshsig_armor(sigbuf, &abuf)) != 0) {
2529 error("%s: sshsig_armor: %s", __func__, ssh_err(r));
2532 if ((asig = sshbuf_dup_string(abuf)) == NULL) {
2533 error("%s: buffer error", __func__);
2534 r = SSH_ERR_ALLOC_FAIL;
2538 if (fd == STDIN_FILENO) {
2539 fputs(asig, stdout);
2542 xasprintf(&wfile, "%s.sig", filename);
2543 if (confirm_overwrite(wfile)) {
2544 if ((wfd = open(wfile, O_WRONLY|O_CREAT|O_TRUNC,
2547 error("Cannot open %s: %s",
2548 wfile, strerror(errno));
2550 r = SSH_ERR_SYSTEM_ERROR;
2553 if (atomicio(vwrite, wfd, asig,
2554 strlen(asig)) != strlen(asig)) {
2556 error("Cannot write to %s: %s",
2557 wfile, strerror(errno));
2559 r = SSH_ERR_SYSTEM_ERROR;
2563 fprintf(stderr, "Write signature to %s\n",
2574 sshbuf_free(sigbuf);
2581 sig_sign(const char *keypath, const char *sig_namespace, int argc, char **argv)
2583 int i, fd = -1, r, ret = -1;
2585 struct sshkey *pubkey = NULL, *privkey = NULL, *signkey = NULL;
2586 sshsig_signer *signer = NULL;
2588 /* Check file arguments. */
2589 for (i = 0; i < argc; i++) {
2590 if (strcmp(argv[i], "-") != 0)
2592 if (i > 0 || argc > 1)
2593 fatal("Cannot sign mix of paths and standard input");
2596 if ((r = sshkey_load_public(keypath, &pubkey, NULL)) != 0) {
2597 error("Couldn't load public key %s: %s", keypath, ssh_err(r));
2601 if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
2602 debug("Couldn't get agent socket: %s", ssh_err(r));
2604 if ((r = ssh_agent_has_key(agent_fd, pubkey)) == 0)
2605 signer = agent_signer;
2607 debug("Couldn't find key in agent: %s", ssh_err(r));
2610 if (signer == NULL) {
2611 /* Not using agent - try to load private key */
2612 if ((privkey = load_sign_key(keypath, pubkey)) == NULL)
2616 /* Will use key in agent */
2621 if ((r = sign_one(signkey, "(stdin)", STDIN_FILENO,
2622 sig_namespace, signer, &agent_fd)) != 0)
2625 for (i = 0; i < argc; i++) {
2626 if (strcmp(argv[i], "-") == 0)
2628 else if ((fd = open(argv[i], O_RDONLY)) == -1) {
2629 error("Cannot open %s for signing: %s",
2630 argv[i], strerror(errno));
2633 if ((r = sign_one(signkey, argv[i], fd, sig_namespace,
2634 signer, &agent_fd)) != 0)
2636 if (fd != STDIN_FILENO)
2644 if (fd != -1 && fd != STDIN_FILENO)
2646 sshkey_free(pubkey);
2647 sshkey_free(privkey);
2652 sig_verify(const char *signature, const char *sig_namespace,
2653 const char *principal, const char *allowed_keys, const char *revoked_keys)
2656 struct sshbuf *sigbuf = NULL, *abuf = NULL;
2657 struct sshkey *sign_key = NULL;
2659 struct sshkey_sig_details *sig_details = NULL;
2661 memset(&sig_details, 0, sizeof(sig_details));
2662 if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
2663 error("Couldn't read signature file: %s", ssh_err(r));
2667 if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
2668 error("%s: sshsig_armor: %s", __func__, ssh_err(r));
2671 if ((r = sshsig_verify_fd(sigbuf, STDIN_FILENO, sig_namespace,
2672 &sign_key, &sig_details)) != 0)
2673 goto done; /* sshsig_verify() prints error */
2675 if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
2676 SSH_FP_DEFAULT)) == NULL)
2677 fatal("%s: sshkey_fingerprint failed", __func__);
2678 debug("Valid (unverified) signature from key %s", fp);
2679 if (sig_details != NULL) {
2680 debug2("%s: signature details: counter = %u, flags = 0x%02x",
2681 __func__, sig_details->sk_counter, sig_details->sk_flags);
2686 if (revoked_keys != NULL) {
2687 if ((r = sshkey_check_revoked(sign_key, revoked_keys)) != 0) {
2688 debug3("sshkey_check_revoked failed: %s", ssh_err(r));
2693 if (allowed_keys != NULL &&
2694 (r = sshsig_check_allowed_keys(allowed_keys, sign_key,
2695 principal, sig_namespace)) != 0) {
2696 debug3("sshsig_check_allowed_keys failed: %s", ssh_err(r));
2704 if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
2705 SSH_FP_DEFAULT)) == NULL) {
2706 fatal("%s: sshkey_fingerprint failed",
2709 if (principal == NULL) {
2710 printf("Good \"%s\" signature with %s key %s\n",
2711 sig_namespace, sshkey_type(sign_key), fp);
2714 printf("Good \"%s\" signature for %s with %s key %s\n",
2715 sig_namespace, principal,
2716 sshkey_type(sign_key), fp);
2719 printf("Could not verify signature.\n");
2722 sshbuf_free(sigbuf);
2724 sshkey_free(sign_key);
2725 sshkey_sig_details_free(sig_details);
2731 sig_find_principals(const char *signature, const char *allowed_keys) {
2733 struct sshbuf *sigbuf = NULL, *abuf = NULL;
2734 struct sshkey *sign_key = NULL;
2735 char *principals = NULL, *cp, *tmp;
2737 if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
2738 error("Couldn't read signature file: %s", ssh_err(r));
2741 if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
2742 error("%s: sshsig_armor: %s", __func__, ssh_err(r));
2745 if ((r = sshsig_get_pubkey(sigbuf, &sign_key)) != 0) {
2746 error("%s: sshsig_get_pubkey: %s",
2747 __func__, ssh_err(r));
2750 if ((r = sshsig_find_principals(allowed_keys, sign_key,
2751 &principals)) != 0) {
2752 error("%s: sshsig_get_principal: %s",
2753 __func__, ssh_err(r));
2759 /* Emit matching principals one per line */
2761 while ((cp = strsep(&tmp, ",")) != NULL && *cp != '\0')
2764 fprintf(stderr, "No principal matched.\n");
2766 sshbuf_free(sigbuf);
2768 sshkey_free(sign_key);
2774 do_moduli_gen(const char *out_file, char **opts, size_t nopts)
2777 /* Moduli generation/screening */
2778 u_int32_t memory = 0;
2779 BIGNUM *start = NULL;
2780 int moduli_bits = 0;
2786 for (i = 0; i < nopts; i++) {
2787 if (strncmp(opts[i], "memory=", 7) == 0) {
2788 memory = (u_int32_t)strtonum(opts[i]+7, 1,
2791 fatal("Memory limit is %s: %s",
2794 } else if (strncmp(opts[i], "start=", 6) == 0) {
2795 /* XXX - also compare length against bits */
2796 if (BN_hex2bn(&start, opts[i]+6) == 0)
2797 fatal("Invalid start point.");
2798 } else if (strncmp(opts[i], "bits=", 5) == 0) {
2799 moduli_bits = (int)strtonum(opts[i]+5, 1,
2802 fatal("Invalid number: %s (%s)",
2803 opts[i]+12, errstr);
2806 fatal("Option \"%s\" is unsupported for moduli "
2807 "generation", opts[i]);
2811 if ((out = fopen(out_file, "w")) == NULL) {
2812 fatal("Couldn't open modulus candidate file \"%s\": %s",
2813 out_file, strerror(errno));
2815 setvbuf(out, NULL, _IOLBF, 0);
2817 if (moduli_bits == 0)
2818 moduli_bits = DEFAULT_BITS;
2819 if (gen_candidates(out, memory, moduli_bits, start) != 0)
2820 fatal("modulus candidate generation failed");
2821 #else /* WITH_OPENSSL */
2822 fatal("Moduli generation is not supported");
2823 #endif /* WITH_OPENSSL */
2827 do_moduli_screen(const char *out_file, char **opts, size_t nopts)
2830 /* Moduli generation/screening */
2831 char *checkpoint = NULL;
2832 u_int32_t generator_wanted = 0;
2833 unsigned long start_lineno = 0, lines_to_process = 0;
2834 int prime_tests = 0;
2835 FILE *out, *in = stdin;
2840 for (i = 0; i < nopts; i++) {
2841 if (strncmp(opts[i], "lines=", 6) == 0) {
2842 lines_to_process = strtoul(opts[i]+6, NULL, 10);
2843 } else if (strncmp(opts[i], "start-line=", 11) == 0) {
2844 start_lineno = strtoul(opts[i]+11, NULL, 10);
2845 } else if (strncmp(opts[i], "checkpoint=", 11) == 0) {
2846 checkpoint = xstrdup(opts[i]+11);
2847 } else if (strncmp(opts[i], "generator=", 10) == 0) {
2848 generator_wanted = (u_int32_t)strtonum(
2849 opts[i]+10, 1, UINT_MAX, &errstr);
2850 if (errstr != NULL) {
2851 fatal("Generator invalid: %s (%s)",
2852 opts[i]+10, errstr);
2854 } else if (strncmp(opts[i], "prime-tests=", 12) == 0) {
2855 prime_tests = (int)strtonum(opts[i]+12, 1,
2858 fatal("Invalid number: %s (%s)",
2859 opts[i]+12, errstr);
2862 fatal("Option \"%s\" is unsupported for moduli "
2863 "screening", opts[i]);
2867 if (have_identity && strcmp(identity_file, "-") != 0) {
2868 if ((in = fopen(identity_file, "r")) == NULL) {
2869 fatal("Couldn't open modulus candidate "
2870 "file \"%s\": %s", identity_file,
2875 if ((out = fopen(out_file, "a")) == NULL) {
2876 fatal("Couldn't open moduli file \"%s\": %s",
2877 out_file, strerror(errno));
2879 setvbuf(out, NULL, _IOLBF, 0);
2880 if (prime_test(in, out, prime_tests == 0 ? 100 : prime_tests,
2881 generator_wanted, checkpoint,
2882 start_lineno, lines_to_process) != 0)
2883 fatal("modulus screening failed");
2884 #else /* WITH_OPENSSL */
2885 fatal("Moduli screening is not supported");
2886 #endif /* WITH_OPENSSL */
2890 private_key_passphrase(void)
2892 char *passphrase1, *passphrase2;
2894 /* Ask for a passphrase (twice). */
2895 if (identity_passphrase)
2896 passphrase1 = xstrdup(identity_passphrase);
2897 else if (identity_new_passphrase)
2898 passphrase1 = xstrdup(identity_new_passphrase);
2902 read_passphrase("Enter passphrase (empty for no "
2903 "passphrase): ", RP_ALLOW_STDIN);
2904 passphrase2 = read_passphrase("Enter same passphrase again: ",
2906 if (strcmp(passphrase1, passphrase2) != 0) {
2908 * The passphrases do not match. Clear them and
2911 freezero(passphrase1, strlen(passphrase1));
2912 freezero(passphrase2, strlen(passphrase2));
2913 printf("Passphrases do not match. Try again.\n");
2914 goto passphrase_again;
2916 /* Clear the other copy of the passphrase. */
2917 freezero(passphrase2, strlen(passphrase2));
2923 skip_ssh_url_preamble(const char *s)
2925 if (strncmp(s, "ssh://", 6) == 0)
2927 else if (strncmp(s, "ssh:", 4) == 0)
2933 do_download_sk(const char *skprovider, const char *device)
2935 struct sshkey **keys;
2938 char *fp, *pin = NULL, *pass = NULL, *path, *pubpath;
2941 if (skprovider == NULL)
2942 fatal("Cannot download keys without provider");
2944 for (i = 0; i < 2; i++) {
2946 pin = read_passphrase("Enter PIN for authenticator: ",
2949 if ((r = sshsk_load_resident(skprovider, device, pin,
2950 &keys, &nkeys)) != 0) {
2951 if (i == 0 && r == SSH_ERR_KEY_WRONG_PASSPHRASE)
2954 freezero(pin, strlen(pin));
2955 error("Unable to load resident keys: %s", ssh_err(r));
2960 logit("No keys to download");
2962 freezero(pin, strlen(pin));
2964 for (i = 0; i < nkeys; i++) {
2965 if (keys[i]->type != KEY_ECDSA_SK &&
2966 keys[i]->type != KEY_ED25519_SK) {
2967 error("Unsupported key type %s (%d)",
2968 sshkey_type(keys[i]), keys[i]->type);
2971 if ((fp = sshkey_fingerprint(keys[i],
2972 fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
2973 fatal("%s: sshkey_fingerprint failed", __func__);
2974 debug("%s: key %zu: %s %s %s (flags 0x%02x)", __func__, i,
2975 sshkey_type(keys[i]), fp, keys[i]->sk_application,
2977 ext = skip_ssh_url_preamble(keys[i]->sk_application);
2978 xasprintf(&path, "id_%s_rk%s%s",
2979 keys[i]->type == KEY_ECDSA_SK ? "ecdsa_sk" : "ed25519_sk",
2980 *ext == '\0' ? "" : "_", ext);
2982 /* If the file already exists, ask the user to confirm. */
2983 if (!confirm_overwrite(path)) {
2988 /* Save the key with the application string as the comment */
2990 pass = private_key_passphrase();
2991 if ((r = sshkey_save_private(keys[i], path, pass,
2992 keys[i]->sk_application, private_key_format,
2993 openssh_format_cipher, rounds)) != 0) {
2994 error("Saving key \"%s\" failed: %s",
3000 printf("Saved %s key%s%s to %s\n",
3001 sshkey_type(keys[i]),
3002 *ext != '\0' ? " " : "",
3003 *ext != '\0' ? keys[i]->sk_application : "",
3007 /* Save public key too */
3008 xasprintf(&pubpath, "%s.pub", path);
3010 if ((r = sshkey_save_public(keys[i], pubpath,
3011 keys[i]->sk_application)) != 0) {
3012 error("Saving public key \"%s\" failed: %s",
3013 pubpath, ssh_err(r));
3021 ok = 0; /* success */
3023 freezero(pass, strlen(pass));
3024 for (i = 0; i < nkeys; i++)
3025 sshkey_free(keys[i]);
3034 "usage: ssh-keygen [-q] [-b bits] [-C comment] [-f output_keyfile] [-m format]\n"
3035 " [-t dsa | ecdsa | ecdsa-sk | ed25519 | ed25519-sk | rsa]\n"
3036 " [-N new_passphrase] [-O option] [-w provider]\n"
3037 " ssh-keygen -p [-f keyfile] [-m format] [-N new_passphrase]\n"
3038 " [-P old_passphrase]\n"
3039 " ssh-keygen -i [-f input_keyfile] [-m key_format]\n"
3040 " ssh-keygen -e [-f input_keyfile] [-m key_format]\n"
3041 " ssh-keygen -y [-f input_keyfile]\n"
3042 " ssh-keygen -c [-C comment] [-f keyfile] [-P passphrase]\n"
3043 " ssh-keygen -l [-v] [-E fingerprint_hash] [-f input_keyfile]\n"
3044 " ssh-keygen -B [-f input_keyfile]\n");
3045 #ifdef ENABLE_PKCS11
3047 " ssh-keygen -D pkcs11\n");
3050 " ssh-keygen -F hostname [-lv] [-f known_hosts_file]\n"
3051 " ssh-keygen -H [-f known_hosts_file]\n"
3052 " ssh-keygen -K [-w provider]\n"
3053 " ssh-keygen -R hostname [-f known_hosts_file]\n"
3054 " ssh-keygen -r hostname [-g] [-f input_keyfile]\n"
3056 " ssh-keygen -M generate [-O option] output_file\n"
3057 " ssh-keygen -M screen [-f input_file] [-O option] output_file\n"
3059 " ssh-keygen -I certificate_identity -s ca_key [-hU] [-D pkcs11_provider]\n"
3060 " [-n principals] [-O option] [-V validity_interval]\n"
3061 " [-z serial_number] file ...\n"
3062 " ssh-keygen -L [-f input_keyfile]\n"
3063 " ssh-keygen -A [-f prefix_path]\n"
3064 " ssh-keygen -k -f krl_file [-u] [-s ca_public] [-z version_number]\n"
3066 " ssh-keygen -Q [-l] -f krl_file [file ...]\n"
3067 " ssh-keygen -Y find-principals -s signature_file -f allowed_signers_file\n"
3068 " ssh-keygen -Y check-novalidate -n namespace -s signature_file\n"
3069 " ssh-keygen -Y sign -f key_file -n namespace file ...\n"
3070 " ssh-keygen -Y verify -f allowed_signers_file -I signer_identity\n"
3071 " -n namespace -s signature_file [-r revocation_file]\n");
3076 * Main program for key management.
3079 main(int argc, char **argv)
3081 char dotsshdir[PATH_MAX], comment[1024], *passphrase;
3082 char *rr_hostname = NULL, *ep, *fp, *ra;
3083 struct sshkey *private, *public;
3087 int change_passphrase = 0, change_comment = 0, show_cert = 0;
3088 int find_host = 0, delete_host = 0, hash_hosts = 0;
3089 int gen_all_hostkeys = 0, gen_krl = 0, update_krl = 0, check_krl = 0;
3090 int prefer_agent = 0, convert_to = 0, convert_from = 0;
3091 int print_public = 0, print_generic = 0, cert_serial_autoinc = 0;
3092 int do_gen_candidates = 0, do_screen_candidates = 0, download_sk = 0;
3093 unsigned long long cert_serial = 0;
3094 char *identity_comment = NULL, *ca_key_path = NULL, **opts = NULL;
3095 char *sk_application = NULL, *sk_device = NULL, *sk_user = NULL;
3096 char *sk_attestaion_path = NULL;
3097 struct sshbuf *challenge = NULL, *attest = NULL;
3098 size_t i, nopts = 0;
3100 uint8_t sk_flags = SSH_SK_USER_PRESENCE_REQD;
3102 int log_level = SYSLOG_LEVEL_INFO;
3103 char *sign_op = NULL;
3106 extern char *optarg;
3108 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
3111 __progname = ssh_get_progname(argv[0]);
3115 log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
3119 /* we need this for the home * directory. */
3120 pw = getpwuid(getuid());
3122 fatal("No user exists for uid %lu", (u_long)getuid());
3123 if (gethostname(hostname, sizeof(hostname)) == -1)
3124 fatal("gethostname: %s", strerror(errno));
3126 sk_provider = getenv("SSH_SK_PROVIDER");
3128 /* Remaining characters: dGjJSTWx */
3129 while ((opt = getopt(argc, argv, "ABHKLQUXceghiklopquvy"
3130 "C:D:E:F:I:M:N:O:P:R:V:Y:Z:"
3131 "a:b:f:g:m:n:r:s:t:w:z:")) != -1) {
3134 gen_all_hostkeys = 1;
3137 bits = (u_int32_t)strtonum(optarg, 1, UINT32_MAX,
3140 fatal("Bits has bad value %s (%s)",
3144 fingerprint_hash = ssh_digest_alg_by_name(optarg);
3145 if (fingerprint_hash == -1)
3146 fatal("Invalid hash algorithm \"%s\"", optarg);
3150 rr_hostname = optarg;
3156 cert_key_id = optarg;
3160 rr_hostname = optarg;
3166 print_fingerprint = 1;
3169 print_bubblebabble = 1;
3172 if (strcasecmp(optarg, "RFC4716") == 0 ||
3173 strcasecmp(optarg, "ssh2") == 0) {
3174 convert_format = FMT_RFC4716;
3177 if (strcasecmp(optarg, "PKCS8") == 0) {
3178 convert_format = FMT_PKCS8;
3179 private_key_format = SSHKEY_PRIVATE_PKCS8;
3182 if (strcasecmp(optarg, "PEM") == 0) {
3183 convert_format = FMT_PEM;
3184 private_key_format = SSHKEY_PRIVATE_PEM;
3187 fatal("Unsupported conversion format \"%s\"", optarg);
3189 cert_principals = optarg;
3192 /* no-op; new format is already the default */
3195 change_passphrase = 1;
3201 if (strlcpy(identity_file, optarg,
3202 sizeof(identity_file)) >= sizeof(identity_file))
3203 fatal("Identity filename too long");
3213 identity_passphrase = optarg;
3216 identity_new_passphrase = optarg;
3222 opts = xrecallocarray(opts, nopts, nopts + 1,
3224 opts[nopts++] = xstrdup(optarg);
3227 openssh_format_cipher = optarg;
3230 identity_comment = optarg;
3240 cert_key_type = SSH2_CERT_TYPE_HOST;
3241 certflags_flags = 0;
3255 ca_key_path = optarg;
3258 key_type_name = optarg;
3261 pkcs11provider = optarg;
3270 if (log_level == SYSLOG_LEVEL_INFO)
3271 log_level = SYSLOG_LEVEL_DEBUG1;
3273 if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
3274 log_level < SYSLOG_LEVEL_DEBUG3)
3279 rr_hostname = optarg;
3282 rounds = (int)strtonum(optarg, 1, INT_MAX, &errstr);
3284 fatal("Invalid number: %s (%s)",
3288 parse_cert_times(optarg);
3294 sk_provider = optarg;
3298 if (*optarg == '+') {
3299 cert_serial_autoinc = 1;
3302 cert_serial = strtoull(optarg, &ep, 10);
3303 if (*optarg < '0' || *optarg > '9' || *ep != '\0' ||
3304 (errno == ERANGE && cert_serial == ULLONG_MAX))
3305 fatal("Invalid serial number \"%s\"", optarg);
3308 if (strcmp(optarg, "generate") == 0)
3309 do_gen_candidates = 1;
3310 else if (strcmp(optarg, "screen") == 0)
3311 do_screen_candidates = 1;
3313 fatal("Unsupported moduli option %s", optarg);
3321 #ifdef ENABLE_SK_INTERNAL
3322 if (sk_provider == NULL)
3323 sk_provider = "internal";
3327 log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
3332 if (sign_op != NULL) {
3333 if (strncmp(sign_op, "find-principals", 15) == 0) {
3334 if (ca_key_path == NULL) {
3335 error("Too few arguments for find-principals:"
3336 "missing signature file");
3339 if (!have_identity) {
3340 error("Too few arguments for find-principals:"
3341 "missing allowed keys file");
3344 return sig_find_principals(ca_key_path, identity_file);
3345 } else if (strncmp(sign_op, "sign", 4) == 0) {
3346 if (cert_principals == NULL ||
3347 *cert_principals == '\0') {
3348 error("Too few arguments for sign: "
3349 "missing namespace");
3352 if (!have_identity) {
3353 error("Too few arguments for sign: "
3357 return sig_sign(identity_file, cert_principals,
3359 } else if (strncmp(sign_op, "check-novalidate", 16) == 0) {
3360 if (ca_key_path == NULL) {
3361 error("Too few arguments for check-novalidate: "
3362 "missing signature file");
3365 return sig_verify(ca_key_path, cert_principals,
3367 } else if (strncmp(sign_op, "verify", 6) == 0) {
3368 if (cert_principals == NULL ||
3369 *cert_principals == '\0') {
3370 error("Too few arguments for verify: "
3371 "missing namespace");
3374 if (ca_key_path == NULL) {
3375 error("Too few arguments for verify: "
3376 "missing signature file");
3379 if (!have_identity) {
3380 error("Too few arguments for sign: "
3381 "missing allowed keys file");
3384 if (cert_key_id == NULL) {
3385 error("Too few arguments for verify: "
3386 "missing principal ID");
3389 return sig_verify(ca_key_path, cert_principals,
3390 cert_key_id, identity_file, rr_hostname);
3392 error("Unsupported operation for -Y: \"%s\"", sign_op);
3397 if (ca_key_path != NULL) {
3398 if (argc < 1 && !gen_krl) {
3399 error("Too few arguments.");
3402 } else if (argc > 0 && !gen_krl && !check_krl &&
3403 !do_gen_candidates && !do_screen_candidates) {
3404 error("Too many arguments.");
3407 if (change_passphrase && change_comment) {
3408 error("Can only have one of -p and -c.");
3411 if (print_fingerprint && (delete_host || hash_hosts)) {
3412 error("Cannot use -l with -H or -R.");
3416 do_gen_krl(pw, update_krl, ca_key_path,
3417 cert_serial, identity_comment, argc, argv);
3421 do_check_krl(pw, print_fingerprint, argc, argv);
3424 if (ca_key_path != NULL) {
3425 if (cert_key_id == NULL)
3426 fatal("Must specify key id (-I) when certifying");
3427 for (i = 0; i < nopts; i++)
3428 add_cert_option(opts[i]);
3429 do_ca_sign(pw, ca_key_path, prefer_agent,
3430 cert_serial, cert_serial_autoinc, argc, argv);
3434 if (delete_host || hash_hosts || find_host) {
3435 do_known_hosts(pw, rr_hostname, find_host,
3436 delete_host, hash_hosts);
3438 if (pkcs11provider != NULL)
3441 for (i = 0; i < nopts; i++) {
3442 if (strncasecmp(opts[i], "device=", 7) == 0) {
3443 sk_device = xstrdup(opts[i] + 7);
3445 fatal("Option \"%s\" is unsupported for "
3446 "FIDO authenticator download", opts[i]);
3449 return do_download_sk(sk_provider, sk_device);
3451 if (print_fingerprint || print_bubblebabble)
3453 if (change_passphrase)
3454 do_change_passphrase(pw);
3456 do_change_comment(pw, identity_comment);
3461 do_convert_from(pw);
3462 #else /* WITH_OPENSSL */
3463 if (convert_to || convert_from)
3464 fatal("key conversion disabled at compile time");
3465 #endif /* WITH_OPENSSL */
3467 do_print_public(pw);
3468 if (rr_hostname != NULL) {
3471 if (have_identity) {
3472 n = do_print_resource_record(pw, identity_file,
3473 rr_hostname, print_generic);
3475 fatal("%s: %s", identity_file, strerror(errno));
3479 n += do_print_resource_record(pw,
3480 _PATH_HOST_RSA_KEY_FILE, rr_hostname,
3482 n += do_print_resource_record(pw,
3483 _PATH_HOST_DSA_KEY_FILE, rr_hostname,
3485 n += do_print_resource_record(pw,
3486 _PATH_HOST_ECDSA_KEY_FILE, rr_hostname,
3488 n += do_print_resource_record(pw,
3489 _PATH_HOST_ED25519_KEY_FILE, rr_hostname,
3491 n += do_print_resource_record(pw,
3492 _PATH_HOST_XMSS_KEY_FILE, rr_hostname,
3495 fatal("no keys found.");
3500 if (do_gen_candidates || do_screen_candidates) {
3502 fatal("No output file specified");
3504 fatal("Too many output files specified");
3506 if (do_gen_candidates) {
3507 do_moduli_gen(argv[0], opts, nopts);
3510 if (do_screen_candidates) {
3511 do_moduli_screen(argv[0], opts, nopts);
3515 if (gen_all_hostkeys) {
3516 do_gen_all_hostkeys(pw);
3520 if (key_type_name == NULL)
3521 key_type_name = DEFAULT_KEY_TYPE_NAME;
3523 type = sshkey_type_from_name(key_type_name);
3524 type_bits_valid(type, key_type_name, &bits);
3527 printf("Generating public/private %s key pair.\n",
3531 case KEY_ED25519_SK:
3532 for (i = 0; i < nopts; i++) {
3533 if (strcasecmp(opts[i], "no-touch-required") == 0) {
3534 sk_flags &= ~SSH_SK_USER_PRESENCE_REQD;
3535 } else if (strcasecmp(opts[i], "resident") == 0) {
3536 sk_flags |= SSH_SK_RESIDENT_KEY;
3537 } else if (strncasecmp(opts[i], "device=", 7) == 0) {
3538 sk_device = xstrdup(opts[i] + 7);
3539 } else if (strncasecmp(opts[i], "user=", 5) == 0) {
3540 sk_user = xstrdup(opts[i] + 5);
3541 } else if (strncasecmp(opts[i], "challenge=", 10) == 0) {
3542 if ((r = sshbuf_load_file(opts[i] + 10,
3543 &challenge)) != 0) {
3544 fatal("Unable to load FIDO enrollment "
3545 "challenge \"%s\": %s",
3546 opts[i] + 10, ssh_err(r));
3548 } else if (strncasecmp(opts[i],
3549 "write-attestation=", 18) == 0) {
3550 sk_attestaion_path = opts[i] + 18;
3551 } else if (strncasecmp(opts[i],
3552 "application=", 12) == 0) {
3553 sk_application = xstrdup(opts[i] + 12);
3554 if (strncmp(sk_application, "ssh:", 4) != 0) {
3555 fatal("FIDO application string must "
3556 "begin with \"ssh:\"");
3559 fatal("Option \"%s\" is unsupported for "
3560 "FIDO authenticator enrollment", opts[i]);
3564 printf("You may need to touch your authenticator "
3565 "to authorize key generation.\n");
3568 if ((attest = sshbuf_new()) == NULL)
3569 fatal("sshbuf_new failed");
3570 for (i = 0 ; ; i++) {
3572 r = sshsk_enroll(type, sk_provider, sk_device,
3573 sk_application == NULL ? "ssh:" : sk_application,
3574 sk_user, sk_flags, passphrase, challenge,
3578 if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
3579 fatal("Key enrollment failed: %s", ssh_err(r));
3581 error("PIN incorrect");
3582 if (passphrase != NULL) {
3583 freezero(passphrase, strlen(passphrase));
3587 fatal("Too many incorrect PINs");
3588 passphrase = read_passphrase("Enter PIN for "
3589 "authenticator: ", RP_ALLOW_STDIN);
3591 if (passphrase != NULL) {
3592 freezero(passphrase, strlen(passphrase));
3597 if ((r = sshkey_generate(type, bits, &private)) != 0)
3598 fatal("sshkey_generate failed");
3601 if ((r = sshkey_from_private(private, &public)) != 0)
3602 fatal("sshkey_from_private failed: %s\n", ssh_err(r));
3605 ask_filename(pw, "Enter file in which to save the key");
3607 /* Create ~/.ssh directory if it doesn't already exist. */
3608 snprintf(dotsshdir, sizeof dotsshdir, "%s/%s",
3609 pw->pw_dir, _PATH_SSH_USER_DIR);
3610 if (strstr(identity_file, dotsshdir) != NULL) {
3611 if (stat(dotsshdir, &st) == -1) {
3612 if (errno != ENOENT) {
3613 error("Could not stat %s: %s", dotsshdir,
3615 } else if (mkdir(dotsshdir, 0700) == -1) {
3616 error("Could not create directory '%s': %s",
3617 dotsshdir, strerror(errno));
3619 printf("Created directory '%s'.\n", dotsshdir);
3622 /* If the file already exists, ask the user to confirm. */
3623 if (!confirm_overwrite(identity_file))
3626 /* Determine the passphrase for the private key */
3627 passphrase = private_key_passphrase();
3628 if (identity_comment) {
3629 strlcpy(comment, identity_comment, sizeof(comment));
3631 /* Create default comment field for the passphrase. */
3632 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
3635 /* Save the key with the given passphrase and comment. */
3636 if ((r = sshkey_save_private(private, identity_file, passphrase,
3637 comment, private_key_format, openssh_format_cipher, rounds)) != 0) {
3638 error("Saving key \"%s\" failed: %s",
3639 identity_file, ssh_err(r));
3640 freezero(passphrase, strlen(passphrase));
3643 freezero(passphrase, strlen(passphrase));
3644 sshkey_free(private);
3647 printf("Your identification has been saved in %s\n",
3651 strlcat(identity_file, ".pub", sizeof(identity_file));
3652 if ((r = sshkey_save_public(public, identity_file, comment)) != 0) {
3653 fatal("Unable to save public key to %s: %s",
3654 identity_file, ssh_err(r));
3658 fp = sshkey_fingerprint(public, fingerprint_hash,
3660 ra = sshkey_fingerprint(public, fingerprint_hash,
3662 if (fp == NULL || ra == NULL)
3663 fatal("sshkey_fingerprint failed");
3664 printf("Your public key has been saved in %s\n",
3666 printf("The key fingerprint is:\n");
3667 printf("%s %s\n", fp, comment);
3668 printf("The key's randomart image is:\n");
3674 if (sk_attestaion_path != NULL) {
3675 if (attest == NULL || sshbuf_len(attest) == 0) {
3676 fatal("Enrollment did not return attestation "
3679 if ((r = sshbuf_write_file(sk_attestaion_path, attest)) != 0) {
3680 fatal("Unable to write attestation certificate "
3681 "\"%s\": %s", sk_attestaion_path, ssh_err(r));
3684 printf("Your FIDO attestation certificate has been "
3685 "saved in %s\n", sk_attestaion_path);
3688 sshbuf_free(attest);
3689 sshkey_free(public);