1 /* $OpenBSD: ssh-keygen.c,v 1.314 2018/03/12 00:52:01 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"
47 #include "pathnames.h"
56 #include "ssh-pkcs11.h"
64 # define DEFAULT_KEY_TYPE_NAME "rsa"
66 # define DEFAULT_KEY_TYPE_NAME "ed25519"
69 /* Number of bits in the RSA/DSA key. This value can be set on the command line. */
70 #define DEFAULT_BITS 2048
71 #define DEFAULT_BITS_DSA 1024
72 #define DEFAULT_BITS_ECDSA 256
76 * Flag indicating that we just want to change the passphrase. This can be
77 * set on the command line.
79 int change_passphrase = 0;
82 * Flag indicating that we just want to change the comment. This can be set
83 * on the command line.
85 int change_comment = 0;
89 int log_level = SYSLOG_LEVEL_INFO;
91 /* Flag indicating that we want to hash a known_hosts file */
93 /* Flag indicating that we want lookup a host in known_hosts file */
95 /* Flag indicating that we want to delete a host from a known_hosts file */
98 /* Flag indicating that we want to show the contents of a certificate */
101 /* Flag indicating that we just want to see the key fingerprint */
102 int print_fingerprint = 0;
103 int print_bubblebabble = 0;
105 /* Hash algorithm to use for fingerprints. */
106 int fingerprint_hash = SSH_FP_HASH_DEFAULT;
108 /* The identity file name, given on the command line or entered by the user. */
109 char identity_file[1024];
110 int have_identity = 0;
112 /* This is set to the passphrase if given on the command line. */
113 char *identity_passphrase = NULL;
115 /* This is set to the new passphrase if given on the command line. */
116 char *identity_new_passphrase = NULL;
118 /* This is set to the new comment if given on the command line. */
119 char *identity_comment = NULL;
121 /* Path to CA key when certifying keys. */
122 char *ca_key_path = NULL;
124 /* Prefer to use agent keys for CA signing */
125 int prefer_agent = 0;
127 /* Certificate serial number */
128 unsigned long long cert_serial = 0;
130 /* Key type when certifying */
131 u_int cert_key_type = SSH2_CERT_TYPE_USER;
133 /* "key ID" of signed key */
134 char *cert_key_id = NULL;
136 /* Comma-separated list of principal names for certifying keys */
137 char *cert_principals = NULL;
139 /* Validity period for certificates */
140 u_int64_t cert_valid_from = 0;
141 u_int64_t cert_valid_to = ~0ULL;
143 /* Certificate options */
144 #define CERTOPT_X_FWD (1)
145 #define CERTOPT_AGENT_FWD (1<<1)
146 #define CERTOPT_PORT_FWD (1<<2)
147 #define CERTOPT_PTY (1<<3)
148 #define CERTOPT_USER_RC (1<<4)
149 #define CERTOPT_DEFAULT (CERTOPT_X_FWD|CERTOPT_AGENT_FWD| \
150 CERTOPT_PORT_FWD|CERTOPT_PTY|CERTOPT_USER_RC)
151 u_int32_t certflags_flags = CERTOPT_DEFAULT;
152 char *certflags_command = NULL;
153 char *certflags_src_addr = NULL;
155 /* Arbitrary extensions specified by user */
156 struct cert_userext {
161 struct cert_userext *cert_userext;
162 size_t ncert_userext;
164 /* Conversion to/from various formats */
166 int convert_from = 0;
171 } convert_format = FMT_RFC4716;
172 int print_public = 0;
173 int print_generic = 0;
175 char *key_type_name = NULL;
177 /* Load key from this PKCS#11 provider */
178 char *pkcs11provider = NULL;
180 /* Use new OpenSSH private key format when writing SSH2 keys instead of PEM */
181 int use_new_format = 0;
183 /* Cipher for new-format private keys */
184 char *new_format_cipher = NULL;
187 * Number of KDF rounds to derive new format keys /
188 * number of primality trials when screening moduli.
193 extern char *__progname;
195 char hostname[NI_MAXHOST];
199 int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
200 int prime_test(FILE *, FILE *, u_int32_t, u_int32_t, char *, unsigned long,
205 type_bits_valid(int type, const char *name, u_int32_t *bitsp)
211 if (type == KEY_UNSPEC)
212 fatal("unknown key type %s", key_type_name);
216 *bitsp = DEFAULT_BITS_DSA;
217 else if (type == KEY_ECDSA) {
219 (nid = sshkey_ecdsa_nid_from_name(name)) > 0)
220 *bitsp = sshkey_curve_nid_to_bits(nid);
222 *bitsp = DEFAULT_BITS_ECDSA;
225 *bitsp = DEFAULT_BITS;
228 maxbits = (type == KEY_DSA) ?
229 OPENSSL_DSA_MAX_MODULUS_BITS : OPENSSL_RSA_MAX_MODULUS_BITS;
230 if (*bitsp > maxbits)
231 fatal("key bits exceeds maximum %d", maxbits);
235 fatal("Invalid DSA key length: must be 1024 bits");
238 if (*bitsp < SSH_RSA_MINIMUM_MODULUS_SIZE)
239 fatal("Invalid RSA key length: minimum is %d bits",
240 SSH_RSA_MINIMUM_MODULUS_SIZE);
243 if (sshkey_ecdsa_bits_to_nid(*bitsp) == -1)
244 fatal("Invalid ECDSA key length: valid lengths are "
245 "256, 384 or 521 bits");
251 ask_filename(struct passwd *pw, const char *prompt)
256 if (key_type_name == NULL)
257 name = _PATH_SSH_CLIENT_ID_RSA;
259 switch (sshkey_type_from_name(key_type_name)) {
262 name = _PATH_SSH_CLIENT_ID_DSA;
264 #ifdef OPENSSL_HAS_ECC
267 name = _PATH_SSH_CLIENT_ID_ECDSA;
272 name = _PATH_SSH_CLIENT_ID_RSA;
275 case KEY_ED25519_CERT:
276 name = _PATH_SSH_CLIENT_ID_ED25519;
280 name = _PATH_SSH_CLIENT_ID_XMSS;
283 fatal("bad key type");
286 snprintf(identity_file, sizeof(identity_file),
287 "%s/%s", pw->pw_dir, name);
288 printf("%s (%s): ", prompt, identity_file);
290 if (fgets(buf, sizeof(buf), stdin) == NULL)
292 buf[strcspn(buf, "\n")] = '\0';
293 if (strcmp(buf, "") != 0)
294 strlcpy(identity_file, buf, sizeof(identity_file));
298 static struct sshkey *
299 load_identity(char *filename)
305 if ((r = sshkey_load_private(filename, "", &prv, NULL)) == 0)
307 if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
308 fatal("Load key \"%s\": %s", filename, ssh_err(r));
309 if (identity_passphrase)
310 pass = xstrdup(identity_passphrase);
312 pass = read_passphrase("Enter passphrase: ", RP_ALLOW_STDIN);
313 r = sshkey_load_private(filename, pass, &prv, NULL);
314 explicit_bzero(pass, strlen(pass));
317 fatal("Load key \"%s\": %s", filename, ssh_err(r));
321 #define SSH_COM_PUBLIC_BEGIN "---- BEGIN SSH2 PUBLIC KEY ----"
322 #define SSH_COM_PUBLIC_END "---- END SSH2 PUBLIC KEY ----"
323 #define SSH_COM_PRIVATE_BEGIN "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
324 #define SSH_COM_PRIVATE_KEY_MAGIC 0x3f6ff9eb
328 do_convert_to_ssh2(struct passwd *pw, struct sshkey *k)
335 if ((r = sshkey_to_blob(k, &blob, &len)) != 0)
336 fatal("key_to_blob failed: %s", ssh_err(r));
337 /* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
338 snprintf(comment, sizeof(comment),
339 "%u-bit %s, converted by %s@%s from OpenSSH",
340 sshkey_size(k), sshkey_type(k),
341 pw->pw_name, hostname);
343 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
344 fprintf(stdout, "Comment: \"%s\"\n", comment);
345 dump_base64(stdout, blob, len);
346 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
353 do_convert_to_pkcs8(struct sshkey *k)
355 switch (sshkey_type_plain(k->type)) {
357 if (!PEM_write_RSA_PUBKEY(stdout, k->rsa))
358 fatal("PEM_write_RSA_PUBKEY failed");
361 if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
362 fatal("PEM_write_DSA_PUBKEY failed");
364 #ifdef OPENSSL_HAS_ECC
366 if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
367 fatal("PEM_write_EC_PUBKEY failed");
371 fatal("%s: unsupported key type %s", __func__, sshkey_type(k));
377 do_convert_to_pem(struct sshkey *k)
379 switch (sshkey_type_plain(k->type)) {
381 if (!PEM_write_RSAPublicKey(stdout, k->rsa))
382 fatal("PEM_write_RSAPublicKey failed");
385 fatal("%s: unsupported key type %s", __func__, sshkey_type(k));
391 do_convert_to(struct passwd *pw)
398 ask_filename(pw, "Enter file in which the key is");
399 if (stat(identity_file, &st) < 0)
400 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
401 if ((r = sshkey_load_public(identity_file, &k, NULL)) != 0)
402 k = load_identity(identity_file);
403 switch (convert_format) {
405 do_convert_to_ssh2(pw, k);
408 do_convert_to_pkcs8(k);
411 do_convert_to_pem(k);
414 fatal("%s: unknown key format %d", __func__, convert_format);
420 * This is almost exactly the bignum1 encoding, but with 32 bit for length
424 buffer_get_bignum_bits(struct sshbuf *b, BIGNUM *value)
426 u_int bytes, bignum_bits;
429 if ((r = sshbuf_get_u32(b, &bignum_bits)) != 0)
430 fatal("%s: buffer error: %s", __func__, ssh_err(r));
431 bytes = (bignum_bits + 7) / 8;
432 if (sshbuf_len(b) < bytes)
433 fatal("%s: input buffer too small: need %d have %zu",
434 __func__, bytes, sshbuf_len(b));
435 if (BN_bin2bn(sshbuf_ptr(b), bytes, value) == NULL)
436 fatal("%s: BN_bin2bn failed", __func__);
437 if ((r = sshbuf_consume(b, bytes)) != 0)
438 fatal("%s: buffer error: %s", __func__, ssh_err(r));
441 static struct sshkey *
442 do_convert_private_ssh2_from_blob(u_char *blob, u_int blen)
445 struct sshkey *key = NULL;
447 u_char e1, e2, e3, *sig = NULL, data[] = "abcde12345";
449 u_int magic, i1, i2, i3, i4;
453 if ((b = sshbuf_from(blob, blen)) == NULL)
454 fatal("%s: sshbuf_from failed", __func__);
455 if ((r = sshbuf_get_u32(b, &magic)) != 0)
456 fatal("%s: buffer error: %s", __func__, ssh_err(r));
458 if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
459 error("bad magic 0x%x != 0x%x", magic,
460 SSH_COM_PRIVATE_KEY_MAGIC);
464 if ((r = sshbuf_get_u32(b, &i1)) != 0 ||
465 (r = sshbuf_get_cstring(b, &type, NULL)) != 0 ||
466 (r = sshbuf_get_cstring(b, &cipher, NULL)) != 0 ||
467 (r = sshbuf_get_u32(b, &i2)) != 0 ||
468 (r = sshbuf_get_u32(b, &i3)) != 0 ||
469 (r = sshbuf_get_u32(b, &i4)) != 0)
470 fatal("%s: buffer error: %s", __func__, ssh_err(r));
471 debug("ignore (%d %d %d %d)", i1, i2, i3, i4);
472 if (strcmp(cipher, "none") != 0) {
473 error("unsupported cipher %s", cipher);
481 if (strstr(type, "dsa")) {
483 } else if (strstr(type, "rsa")) {
490 if ((key = sshkey_new_private(ktype)) == NULL)
491 fatal("sshkey_new_private failed");
497 BIGNUM *p=NULL, *g=NULL, *q=NULL, *pub_key=NULL, *priv_key=NULL;
498 if ((p=BN_new()) == NULL ||
499 (g=BN_new()) == NULL ||
500 (q=BN_new()) == NULL ||
501 (pub_key=BN_new()) == NULL ||
502 (priv_key=BN_new()) == NULL) {
510 buffer_get_bignum_bits(b, p);
511 buffer_get_bignum_bits(b, g);
512 buffer_get_bignum_bits(b, q);
513 buffer_get_bignum_bits(b, pub_key);
514 buffer_get_bignum_bits(b, priv_key);
515 if (DSA_set0_pqg(key->dsa, p, q, g) == 0 ||
516 DSA_set0_key(key->dsa, pub_key, priv_key) == 0) {
517 fatal("failed to set DSA key");
518 BN_free(p); BN_free(g); BN_free(q);
519 BN_free(pub_key); BN_free(priv_key);
525 if ((r = sshbuf_get_u8(b, &e1)) != 0 ||
526 (e1 < 30 && (r = sshbuf_get_u8(b, &e2)) != 0) ||
527 (e1 < 30 && (r = sshbuf_get_u8(b, &e3)) != 0))
528 fatal("%s: buffer error: %s", __func__, ssh_err(r));
540 BIGNUM *rsa_e = NULL;
541 BIGNUM *d=NULL, *n=NULL, *iqmp=NULL, *q=NULL, *p=NULL;
542 BIGNUM *dmp1=NULL, *dmq1=NULL; /* dummy input to set in RSA_set0_crt_params */
544 if (!rsa_e || !BN_set_word(rsa_e, e)) {
545 if (rsa_e) BN_free(rsa_e);
550 if ((d=BN_new()) == NULL ||
551 (n=BN_new()) == NULL ||
552 (iqmp=BN_new()) == NULL ||
553 (q=BN_new()) == NULL ||
554 (p=BN_new()) == NULL ||
555 (dmp1=BN_new()) == NULL ||
556 (dmq1=BN_new()) == NULL) {
557 BN_free(d); BN_free(n); BN_free(iqmp);
558 BN_free(q); BN_free(p);
559 BN_free(dmp1); BN_free(dmq1);
562 BN_clear(dmp1); BN_clear(dmq1);
563 buffer_get_bignum_bits(b, d);
564 buffer_get_bignum_bits(b, n);
565 buffer_get_bignum_bits(b, iqmp);
566 buffer_get_bignum_bits(b, q);
567 buffer_get_bignum_bits(b, p);
568 if (RSA_set0_key(key->rsa, n, rsa_e, d) == 0)
571 if (RSA_set0_factors(key->rsa, p, q) == 0)
574 /* dmp1, dmq1 should not be NULL for initial set0 */
575 if (RSA_set0_crt_params(key->rsa, dmp1, dmq1, iqmp) == 0) {
577 fatal("Failed to set RSA parameters");
578 BN_free(d); BN_free(n); BN_free(iqmp);
579 BN_free(q); BN_free(p);
580 BN_free(dmp1); BN_free(dmq1);
583 dmp1 = dmq1 = iqmp = NULL;
585 if ((r = ssh_rsa_generate_additional_parameters(key)) != 0)
586 fatal("generate RSA parameters failed: %s", ssh_err(r));
589 rlen = sshbuf_len(b);
591 error("do_convert_private_ssh2_from_blob: "
592 "remaining bytes in key blob %d", rlen);
596 if (sshkey_sign(key, &sig, &slen, data, sizeof(data), NULL, 0) != 0 ||
597 sshkey_verify(key, sig, slen, data, sizeof(data), NULL, 0) != 0) {
607 get_line(FILE *fp, char *line, size_t len)
613 while ((c = fgetc(fp)) != EOF) {
615 fatal("input line too long.");
619 if (c != EOF && c != '\n' && ungetc(c, fp) == EOF)
620 fatal("unget: %s", strerror(errno));
633 do_convert_from_ssh2(struct passwd *pw, struct sshkey **k, int *private)
635 int r, blen, escaped = 0;
642 if ((fp = fopen(identity_file, "r")) == NULL)
643 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
645 while ((blen = get_line(fp, line, sizeof(line))) != -1) {
646 if (blen > 0 && line[blen - 1] == '\\')
648 if (strncmp(line, "----", 4) == 0 ||
649 strstr(line, ": ") != NULL) {
650 if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
652 if (strstr(line, " END ") != NULL) {
655 /* fprintf(stderr, "ignore: %s", line); */
660 /* fprintf(stderr, "escaped: %s", line); */
663 strlcat(encoded, line, sizeof(encoded));
665 len = strlen(encoded);
666 if (((len % 4) == 3) &&
667 (encoded[len-1] == '=') &&
668 (encoded[len-2] == '=') &&
669 (encoded[len-3] == '='))
670 encoded[len-3] = '\0';
671 blen = uudecode(encoded, blob, sizeof(blob));
673 fatal("uudecode failed.");
675 *k = do_convert_private_ssh2_from_blob(blob, blen);
676 else if ((r = sshkey_from_blob(blob, blen, k)) != 0)
677 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_type(EVP_PKEY_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_type(EVP_PKEY_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) < 0)
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)
811 ask_filename(pw, "Enter file in which the key is");
812 if (stat(identity_file, &st) < 0)
813 fatal("%s: %s", identity_file, strerror(errno));
814 prv = load_identity(identity_file);
815 if ((r = sshkey_write(prv, stdout)) != 0)
816 error("sshkey_write failed: %s", ssh_err(r));
818 fprintf(stdout, "\n");
823 do_download(struct passwd *pw)
826 struct sshkey **keys = NULL;
828 enum sshkey_fp_rep rep;
832 fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
833 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
836 nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys);
838 fatal("cannot read public key from pkcs11");
839 for (i = 0; i < nkeys; i++) {
840 if (print_fingerprint) {
841 fp = sshkey_fingerprint(keys[i], fptype, rep);
842 ra = sshkey_fingerprint(keys[i], fingerprint_hash,
844 if (fp == NULL || ra == NULL)
845 fatal("%s: sshkey_fingerprint fail", __func__);
846 printf("%u %s %s (PKCS11 key)\n", sshkey_size(keys[i]),
847 fp, sshkey_type(keys[i]));
848 if (log_level >= SYSLOG_LEVEL_VERBOSE)
853 (void) sshkey_write(keys[i], stdout); /* XXX check */
854 fprintf(stdout, "\n");
856 sshkey_free(keys[i]);
862 fatal("no pkcs11 support");
863 #endif /* ENABLE_PKCS11 */
866 static struct sshkey *
867 try_read_key(char **cpp)
872 if ((ret = sshkey_new(KEY_UNSPEC)) == NULL)
873 fatal("sshkey_new failed");
874 if ((r = sshkey_read(ret, cpp)) == 0)
882 fingerprint_one_key(const struct sshkey *public, const char *comment)
884 char *fp = NULL, *ra = NULL;
885 enum sshkey_fp_rep rep;
888 fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
889 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
890 fp = sshkey_fingerprint(public, fptype, rep);
891 ra = sshkey_fingerprint(public, fingerprint_hash, SSH_FP_RANDOMART);
892 if (fp == NULL || ra == NULL)
893 fatal("%s: sshkey_fingerprint failed", __func__);
894 mprintf("%u %s %s (%s)\n", sshkey_size(public), fp,
895 comment ? comment : "no comment", sshkey_type(public));
896 if (log_level >= SYSLOG_LEVEL_VERBOSE)
903 fingerprint_private(const char *path)
906 char *comment = NULL;
907 struct sshkey *public = NULL;
910 if (stat(identity_file, &st) < 0)
911 fatal("%s: %s", path, strerror(errno));
912 if ((r = sshkey_load_public(path, &public, &comment)) != 0) {
913 debug("load public \"%s\": %s", path, ssh_err(r));
914 if ((r = sshkey_load_private(path, NULL,
915 &public, &comment)) != 0) {
916 debug("load private \"%s\": %s", path, ssh_err(r));
917 fatal("%s is not a key file.", path);
921 fingerprint_one_key(public, comment);
927 do_fingerprint(struct passwd *pw)
930 struct sshkey *public = NULL;
931 char *comment = NULL, *cp, *ep, line[SSH_MAX_PUBKEY_BYTES];
937 ask_filename(pw, "Enter file in which the key is");
938 path = identity_file;
940 if (strcmp(identity_file, "-") == 0) {
943 } else if ((f = fopen(path, "r")) == NULL)
944 fatal("%s: %s: %s", __progname, path, strerror(errno));
946 while (read_keyfile_line(f, path, line, sizeof(line), &lnum) == 0) {
948 cp[strcspn(cp, "\n")] = '\0';
949 /* Trim leading space and comments */
950 cp = line + strspn(line, " \t");
951 if (*cp == '#' || *cp == '\0')
955 * Input may be plain keys, private keys, authorized_keys
960 * Try private keys first. Assume a key is private if
961 * "SSH PRIVATE KEY" appears on the first line and we're
962 * not reading from stdin (XXX support private keys on stdin).
964 if (lnum == 1 && strcmp(identity_file, "-") != 0 &&
965 strstr(cp, "PRIVATE KEY") != NULL) {
967 fingerprint_private(path);
972 * If it's not a private key, then this must be prepared to
973 * accept a public key prefixed with a hostname or options.
974 * Try a bare key first, otherwise skip the leading stuff.
976 if ((public = try_read_key(&cp)) == NULL) {
977 i = strtol(cp, &ep, 10);
978 if (i == 0 || ep == NULL ||
979 (*ep != ' ' && *ep != '\t')) {
983 for (; *cp && (quoted || (*cp != ' ' &&
984 *cp != '\t')); cp++) {
985 if (*cp == '\\' && cp[1] == '"')
986 cp++; /* Skip both */
995 /* Retry after parsing leading hostname/key options */
996 if (public == NULL && (public = try_read_key(&cp)) == NULL) {
997 debug("%s:%lu: not a public key", path, lnum);
1001 /* Find trailing comment, if any */
1002 for (; *cp == ' ' || *cp == '\t'; cp++)
1004 if (*cp != '\0' && *cp != '#')
1007 fingerprint_one_key(public, comment);
1008 sshkey_free(public);
1009 invalid = 0; /* One good key in the file is sufficient */
1014 fatal("%s is not a public key file.", path);
1019 do_gen_all_hostkeys(struct passwd *pw)
1023 char *key_type_display;
1027 { "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE },
1028 { "dsa", "DSA", _PATH_HOST_DSA_KEY_FILE },
1029 #ifdef OPENSSL_HAS_ECC
1030 { "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE },
1031 #endif /* OPENSSL_HAS_ECC */
1032 #endif /* WITH_OPENSSL */
1033 { "ed25519", "ED25519",_PATH_HOST_ED25519_KEY_FILE },
1035 { "xmss", "XMSS",_PATH_HOST_XMSS_KEY_FILE },
1036 #endif /* WITH_XMSS */
1037 { NULL, NULL, NULL }
1042 struct sshkey *private, *public;
1043 char comment[1024], *prv_tmp, *pub_tmp, *prv_file, *pub_file;
1047 for (i = 0; key_types[i].key_type; i++) {
1048 public = private = NULL;
1049 prv_tmp = pub_tmp = prv_file = pub_file = NULL;
1051 xasprintf(&prv_file, "%s%s",
1052 identity_file, key_types[i].path);
1054 /* Check whether private key exists and is not zero-length */
1055 if (stat(prv_file, &st) == 0) {
1056 if (st.st_size != 0)
1058 } else if (errno != ENOENT) {
1059 error("Could not stat %s: %s", key_types[i].path,
1065 * Private key doesn't exist or is invalid; proceed with
1068 xasprintf(&prv_tmp, "%s%s.XXXXXXXXXX",
1069 identity_file, key_types[i].path);
1070 xasprintf(&pub_tmp, "%s%s.pub.XXXXXXXXXX",
1071 identity_file, key_types[i].path);
1072 xasprintf(&pub_file, "%s%s.pub",
1073 identity_file, key_types[i].path);
1077 printf("%s: generating new host keys: ", __progname);
1079 printf("%s ", key_types[i].key_type_display);
1081 type = sshkey_type_from_name(key_types[i].key_type);
1082 if ((fd = mkstemp(prv_tmp)) == -1) {
1083 error("Could not save your public key in %s: %s",
1084 prv_tmp, strerror(errno));
1087 close(fd); /* just using mkstemp() to generate/reserve a name */
1089 type_bits_valid(type, NULL, &bits);
1090 if ((r = sshkey_generate(type, bits, &private)) != 0) {
1091 error("sshkey_generate failed: %s", ssh_err(r));
1094 if ((r = sshkey_from_private(private, &public)) != 0)
1095 fatal("sshkey_from_private failed: %s", ssh_err(r));
1096 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name,
1098 if ((r = sshkey_save_private(private, prv_tmp, "",
1099 comment, use_new_format, new_format_cipher, rounds)) != 0) {
1100 error("Saving key \"%s\" failed: %s",
1101 prv_tmp, ssh_err(r));
1104 if ((fd = mkstemp(pub_tmp)) == -1) {
1105 error("Could not save your public key in %s: %s",
1106 pub_tmp, strerror(errno));
1109 (void)fchmod(fd, 0644);
1110 f = fdopen(fd, "w");
1112 error("fdopen %s failed: %s", pub_tmp, strerror(errno));
1116 if ((r = sshkey_write(public, f)) != 0) {
1117 error("write key failed: %s", ssh_err(r));
1121 fprintf(f, " %s\n", comment);
1122 if (ferror(f) != 0) {
1123 error("write key failed: %s", strerror(errno));
1127 if (fclose(f) != 0) {
1128 error("key close failed: %s", strerror(errno));
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 */
1166 known_hosts_hash(struct hostkey_foreach_line *l, void *_ctx)
1168 struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1169 char *hashed, *cp, *hosts, *ohosts;
1170 int has_wild = l->hosts && strcspn(l->hosts, "*?!") != strlen(l->hosts);
1171 int was_hashed = l->hosts && l->hosts[0] == HASH_DELIM;
1173 switch (l->status) {
1175 case HKF_STATUS_MATCHED:
1177 * Don't hash hosts already already hashed, with wildcard
1178 * characters or a CA/revocation marker.
1180 if (was_hashed || has_wild || l->marker != MRK_NONE) {
1181 fprintf(ctx->out, "%s\n", l->line);
1182 if (has_wild && !find_host) {
1183 logit("%s:%lu: ignoring host name "
1184 "with wildcard: %.64s", l->path,
1185 l->linenum, l->hosts);
1190 * Split any comma-separated hostnames from the host list,
1191 * hash and store separately.
1193 ohosts = hosts = xstrdup(l->hosts);
1194 while ((cp = strsep(&hosts, ",")) != NULL && *cp != '\0') {
1196 if ((hashed = host_hash(cp, NULL, 0)) == NULL)
1197 fatal("hash_host failed");
1198 fprintf(ctx->out, "%s %s\n", hashed, l->rawkey);
1199 ctx->has_unhashed = 1;
1203 case HKF_STATUS_INVALID:
1204 /* Retain invalid lines, but mark file as invalid. */
1206 logit("%s:%lu: invalid line", l->path, l->linenum);
1209 fprintf(ctx->out, "%s\n", l->line);
1217 known_hosts_find_delete(struct hostkey_foreach_line *l, void *_ctx)
1219 struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1220 enum sshkey_fp_rep rep;
1224 fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
1225 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1227 if (l->status == HKF_STATUS_MATCHED) {
1229 if (l->marker != MRK_NONE) {
1230 /* Don't remove CA and revocation lines */
1231 fprintf(ctx->out, "%s\n", l->line);
1234 * Hostname matches and has no CA/revoke
1235 * marker, delete it by *not* writing the
1240 printf("# Host %s found: line %lu\n",
1241 ctx->host, l->linenum);
1244 } else if (find_host) {
1247 printf("# Host %s found: line %lu %s\n",
1249 l->linenum, l->marker == MRK_CA ? "CA" :
1250 (l->marker == MRK_REVOKE ? "REVOKED" : ""));
1253 known_hosts_hash(l, ctx);
1254 else if (print_fingerprint) {
1255 fp = sshkey_fingerprint(l->key, fptype, rep);
1256 mprintf("%s %s %s %s\n", ctx->host,
1257 sshkey_type(l->key), fp, l->comment);
1260 fprintf(ctx->out, "%s\n", l->line);
1263 } else if (delete_host) {
1264 /* Retain non-matching hosts when deleting */
1265 if (l->status == HKF_STATUS_INVALID) {
1267 logit("%s:%lu: invalid line", l->path, l->linenum);
1269 fprintf(ctx->out, "%s\n", l->line);
1275 do_known_hosts(struct passwd *pw, const char *name)
1277 char *cp, tmp[PATH_MAX], old[PATH_MAX];
1278 int r, fd, oerrno, inplace = 0;
1279 struct known_hosts_ctx ctx;
1280 u_int foreach_options;
1282 if (!have_identity) {
1283 cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
1284 if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
1285 sizeof(identity_file))
1286 fatal("Specified known hosts path too long");
1291 memset(&ctx, 0, sizeof(ctx));
1296 * Find hosts goes to stdout, hash and deletions happen in-place
1297 * A corner case is ssh-keygen -HF foo, which should go to stdout
1299 if (!find_host && (hash_hosts || delete_host)) {
1300 if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
1301 strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
1302 strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
1303 strlcat(old, ".old", sizeof(old)) >= sizeof(old))
1304 fatal("known_hosts path too long");
1306 if ((fd = mkstemp(tmp)) == -1)
1307 fatal("mkstemp: %s", strerror(errno));
1308 if ((ctx.out = fdopen(fd, "w")) == NULL) {
1311 fatal("fdopen: %s", strerror(oerrno));
1316 /* XXX support identity_file == "-" for stdin */
1317 foreach_options = find_host ? HKF_WANT_MATCH : 0;
1318 foreach_options |= print_fingerprint ? HKF_WANT_PARSE_KEY : 0;
1319 if ((r = hostkeys_foreach(identity_file,
1320 hash_hosts ? known_hosts_hash : known_hosts_find_delete, &ctx,
1321 name, NULL, foreach_options)) != 0) {
1324 fatal("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
1331 error("%s is not a valid known_hosts file.", identity_file);
1333 error("Not replacing existing known_hosts "
1334 "file because of errors");
1338 } else if (delete_host && !ctx.found_key) {
1339 logit("Host %s not found in %s", name, identity_file);
1342 } else if (inplace) {
1343 /* Backup existing file */
1344 if (unlink(old) == -1 && errno != ENOENT)
1345 fatal("unlink %.100s: %s", old, strerror(errno));
1346 if (link(identity_file, old) == -1)
1347 fatal("link %.100s to %.100s: %s", identity_file, old,
1349 /* Move new one into place */
1350 if (rename(tmp, identity_file) == -1) {
1351 error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
1358 printf("%s updated.\n", identity_file);
1359 printf("Original contents retained as %s\n", old);
1360 if (ctx.has_unhashed) {
1361 logit("WARNING: %s contains unhashed entries", old);
1362 logit("Delete this file to ensure privacy "
1367 exit (find_host && !ctx.found_key);
1371 * Perform changing a passphrase. The argument is the passwd structure
1372 * for the current user.
1375 do_change_passphrase(struct passwd *pw)
1378 char *old_passphrase, *passphrase1, *passphrase2;
1380 struct sshkey *private;
1384 ask_filename(pw, "Enter file in which the key is");
1385 if (stat(identity_file, &st) < 0)
1386 fatal("%s: %s", identity_file, strerror(errno));
1387 /* Try to load the file with empty passphrase. */
1388 r = sshkey_load_private(identity_file, "", &private, &comment);
1389 if (r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
1390 if (identity_passphrase)
1391 old_passphrase = xstrdup(identity_passphrase);
1394 read_passphrase("Enter old passphrase: ",
1396 r = sshkey_load_private(identity_file, old_passphrase,
1397 &private, &comment);
1398 explicit_bzero(old_passphrase, strlen(old_passphrase));
1399 free(old_passphrase);
1402 } else if (r != 0) {
1404 fatal("Failed to load key %s: %s", identity_file, ssh_err(r));
1407 mprintf("Key has comment '%s'\n", comment);
1409 /* Ask the new passphrase (twice). */
1410 if (identity_new_passphrase) {
1411 passphrase1 = xstrdup(identity_new_passphrase);
1415 read_passphrase("Enter new passphrase (empty for no "
1416 "passphrase): ", RP_ALLOW_STDIN);
1417 passphrase2 = read_passphrase("Enter same passphrase again: ",
1420 /* Verify that they are the same. */
1421 if (strcmp(passphrase1, passphrase2) != 0) {
1422 explicit_bzero(passphrase1, strlen(passphrase1));
1423 explicit_bzero(passphrase2, strlen(passphrase2));
1426 printf("Pass phrases do not match. Try again.\n");
1429 /* Destroy the other copy. */
1430 explicit_bzero(passphrase2, strlen(passphrase2));
1434 /* Save the file using the new passphrase. */
1435 if ((r = sshkey_save_private(private, identity_file, passphrase1,
1436 comment, use_new_format, new_format_cipher, rounds)) != 0) {
1437 error("Saving key \"%s\" failed: %s.",
1438 identity_file, ssh_err(r));
1439 explicit_bzero(passphrase1, strlen(passphrase1));
1441 sshkey_free(private);
1445 /* Destroy the passphrase and the copy of the key in memory. */
1446 explicit_bzero(passphrase1, strlen(passphrase1));
1448 sshkey_free(private); /* Destroys contents */
1451 printf("Your identification has been saved with the new passphrase.\n");
1456 * Print the SSHFP RR.
1459 do_print_resource_record(struct passwd *pw, char *fname, char *hname)
1461 struct sshkey *public;
1462 char *comment = NULL;
1467 fatal("%s: no filename", __func__);
1468 if (stat(fname, &st) < 0) {
1469 if (errno == ENOENT)
1471 fatal("%s: %s", fname, strerror(errno));
1473 if ((r = sshkey_load_public(fname, &public, &comment)) != 0)
1474 fatal("Failed to read v2 public key from \"%s\": %s.",
1476 export_dns_rr(hname, public, stdout, print_generic);
1477 sshkey_free(public);
1483 * Change the comment of a private key file.
1486 do_change_comment(struct passwd *pw)
1488 char new_comment[1024], *comment, *passphrase;
1489 struct sshkey *private;
1490 struct sshkey *public;
1496 ask_filename(pw, "Enter file in which the key is");
1497 if (stat(identity_file, &st) < 0)
1498 fatal("%s: %s", identity_file, strerror(errno));
1499 if ((r = sshkey_load_private(identity_file, "",
1500 &private, &comment)) == 0)
1501 passphrase = xstrdup("");
1502 else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
1503 fatal("Cannot load private key \"%s\": %s.",
1504 identity_file, ssh_err(r));
1506 if (identity_passphrase)
1507 passphrase = xstrdup(identity_passphrase);
1508 else if (identity_new_passphrase)
1509 passphrase = xstrdup(identity_new_passphrase);
1511 passphrase = read_passphrase("Enter passphrase: ",
1513 /* Try to load using the passphrase. */
1514 if ((r = sshkey_load_private(identity_file, passphrase,
1515 &private, &comment)) != 0) {
1516 explicit_bzero(passphrase, strlen(passphrase));
1518 fatal("Cannot load private key \"%s\": %s.",
1519 identity_file, ssh_err(r));
1523 if (private->type != KEY_ED25519 && private->type != KEY_XMSS &&
1525 error("Comments are only supported for keys stored in "
1526 "the new format (-o).");
1527 explicit_bzero(passphrase, strlen(passphrase));
1528 sshkey_free(private);
1532 printf("Key now has comment '%s'\n", comment);
1534 printf("Key now has no comment\n");
1536 if (identity_comment) {
1537 strlcpy(new_comment, identity_comment, sizeof(new_comment));
1539 printf("Enter new comment: ");
1541 if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1542 explicit_bzero(passphrase, strlen(passphrase));
1543 sshkey_free(private);
1546 new_comment[strcspn(new_comment, "\n")] = '\0';
1549 /* Save the file using the new passphrase. */
1550 if ((r = sshkey_save_private(private, identity_file, passphrase,
1551 new_comment, use_new_format, new_format_cipher, rounds)) != 0) {
1552 error("Saving key \"%s\" failed: %s",
1553 identity_file, ssh_err(r));
1554 explicit_bzero(passphrase, strlen(passphrase));
1556 sshkey_free(private);
1560 explicit_bzero(passphrase, strlen(passphrase));
1562 if ((r = sshkey_from_private(private, &public)) != 0)
1563 fatal("sshkey_from_private failed: %s", ssh_err(r));
1564 sshkey_free(private);
1566 strlcat(identity_file, ".pub", sizeof(identity_file));
1567 fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1569 fatal("Could not save your public key in %s", identity_file);
1570 f = fdopen(fd, "w");
1572 fatal("fdopen %s failed: %s", identity_file, strerror(errno));
1573 if ((r = sshkey_write(public, f)) != 0)
1574 fatal("write key failed: %s", ssh_err(r));
1575 sshkey_free(public);
1576 fprintf(f, " %s\n", new_comment);
1581 printf("The comment in your key file has been changed.\n");
1586 add_flag_option(struct sshbuf *c, const char *name)
1590 debug3("%s: %s", __func__, name);
1591 if ((r = sshbuf_put_cstring(c, name)) != 0 ||
1592 (r = sshbuf_put_string(c, NULL, 0)) != 0)
1593 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1597 add_string_option(struct sshbuf *c, const char *name, const char *value)
1602 debug3("%s: %s=%s", __func__, name, value);
1603 if ((b = sshbuf_new()) == NULL)
1604 fatal("%s: sshbuf_new failed", __func__);
1605 if ((r = sshbuf_put_cstring(b, value)) != 0 ||
1606 (r = sshbuf_put_cstring(c, name)) != 0 ||
1607 (r = sshbuf_put_stringb(c, b)) != 0)
1608 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1613 #define OPTIONS_CRITICAL 1
1614 #define OPTIONS_EXTENSIONS 2
1616 prepare_options_buf(struct sshbuf *c, int which)
1621 if ((which & OPTIONS_CRITICAL) != 0 &&
1622 certflags_command != NULL)
1623 add_string_option(c, "force-command", certflags_command);
1624 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1625 (certflags_flags & CERTOPT_X_FWD) != 0)
1626 add_flag_option(c, "permit-X11-forwarding");
1627 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1628 (certflags_flags & CERTOPT_AGENT_FWD) != 0)
1629 add_flag_option(c, "permit-agent-forwarding");
1630 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1631 (certflags_flags & CERTOPT_PORT_FWD) != 0)
1632 add_flag_option(c, "permit-port-forwarding");
1633 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1634 (certflags_flags & CERTOPT_PTY) != 0)
1635 add_flag_option(c, "permit-pty");
1636 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1637 (certflags_flags & CERTOPT_USER_RC) != 0)
1638 add_flag_option(c, "permit-user-rc");
1639 if ((which & OPTIONS_CRITICAL) != 0 &&
1640 certflags_src_addr != NULL)
1641 add_string_option(c, "source-address", certflags_src_addr);
1642 for (i = 0; i < ncert_userext; i++) {
1643 if ((cert_userext[i].crit && (which & OPTIONS_EXTENSIONS)) ||
1644 (!cert_userext[i].crit && (which & OPTIONS_CRITICAL)))
1646 if (cert_userext[i].val == NULL)
1647 add_flag_option(c, cert_userext[i].key);
1649 add_string_option(c, cert_userext[i].key,
1650 cert_userext[i].val);
1655 static struct sshkey *
1656 load_pkcs11_key(char *path)
1658 #ifdef ENABLE_PKCS11
1659 struct sshkey **keys = NULL, *public, *private = NULL;
1662 if ((r = sshkey_load_public(path, &public, NULL)) != 0)
1663 fatal("Couldn't load CA public key \"%s\": %s",
1666 nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase, &keys);
1667 debug3("%s: %d keys", __func__, nkeys);
1669 fatal("cannot read public key from pkcs11");
1670 for (i = 0; i < nkeys; i++) {
1671 if (sshkey_equal_public(public, keys[i])) {
1675 sshkey_free(keys[i]);
1678 sshkey_free(public);
1681 fatal("no pkcs11 support");
1682 #endif /* ENABLE_PKCS11 */
1685 /* Signer for sshkey_certify_custom that uses the agent */
1687 agent_signer(const struct sshkey *key, u_char **sigp, size_t *lenp,
1688 const u_char *data, size_t datalen,
1689 const char *alg, u_int compat, void *ctx)
1691 int *agent_fdp = (int *)ctx;
1693 return ssh_agent_sign(*agent_fdp, key, sigp, lenp,
1694 data, datalen, alg, compat);
1698 do_ca_sign(struct passwd *pw, int argc, char **argv)
1700 int r, i, fd, found, agent_fd = -1;
1702 struct sshkey *ca, *public;
1703 char valid[64], *otmp, *tmp, *cp, *out, *comment, **plist = NULL;
1705 struct ssh_identitylist *agent_ids;
1708 #ifdef ENABLE_PKCS11
1711 tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
1712 if (pkcs11provider != NULL) {
1713 /* If a PKCS#11 token was specified then try to use it */
1714 if ((ca = load_pkcs11_key(tmp)) == NULL)
1715 fatal("No PKCS#11 key matching %s found", ca_key_path);
1716 } else if (prefer_agent) {
1718 * Agent signature requested. Try to use agent after making
1719 * sure the public key specified is actually present in the
1722 if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
1723 fatal("Cannot load CA public key %s: %s",
1725 if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
1726 fatal("Cannot use public key for CA signature: %s",
1728 if ((r = ssh_fetch_identitylist(agent_fd, &agent_ids)) != 0)
1729 fatal("Retrieve agent key list: %s", ssh_err(r));
1731 for (j = 0; j < agent_ids->nkeys; j++) {
1732 if (sshkey_equal(ca, agent_ids->keys[j])) {
1738 fatal("CA key %s not found in agent", tmp);
1739 ssh_free_identitylist(agent_ids);
1740 ca->flags |= SSHKEY_FLAG_EXT;
1742 /* CA key is assumed to be a private key on the filesystem */
1743 ca = load_identity(tmp);
1747 if (key_type_name != NULL &&
1748 sshkey_type_from_name(key_type_name) != ca->type) {
1749 fatal("CA key type %s doesn't match specified %s",
1750 sshkey_ssh_name(ca), key_type_name);
1753 for (i = 0; i < argc; i++) {
1754 /* Split list of principals */
1756 if (cert_principals != NULL) {
1757 otmp = tmp = xstrdup(cert_principals);
1759 for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1760 plist = xreallocarray(plist, n + 1, sizeof(*plist));
1761 if (*(plist[n] = xstrdup(cp)) == '\0')
1762 fatal("Empty principal name");
1766 if (n > SSHKEY_CERT_MAX_PRINCIPALS)
1767 fatal("Too many certificate principals specified");
1769 tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1770 if ((r = sshkey_load_public(tmp, &public, &comment)) != 0)
1771 fatal("%s: unable to open \"%s\": %s",
1772 __func__, tmp, ssh_err(r));
1773 if (public->type != KEY_RSA && public->type != KEY_DSA &&
1774 public->type != KEY_ECDSA && public->type != KEY_ED25519 &&
1775 public->type != KEY_XMSS)
1776 fatal("%s: key \"%s\" type %s cannot be certified",
1777 __func__, tmp, sshkey_type(public));
1779 /* Prepare certificate to sign */
1780 if ((r = sshkey_to_certified(public)) != 0)
1781 fatal("Could not upgrade key %s to certificate: %s",
1783 public->cert->type = cert_key_type;
1784 public->cert->serial = (u_int64_t)cert_serial;
1785 public->cert->key_id = xstrdup(cert_key_id);
1786 public->cert->nprincipals = n;
1787 public->cert->principals = plist;
1788 public->cert->valid_after = cert_valid_from;
1789 public->cert->valid_before = cert_valid_to;
1790 prepare_options_buf(public->cert->critical, OPTIONS_CRITICAL);
1791 prepare_options_buf(public->cert->extensions,
1792 OPTIONS_EXTENSIONS);
1793 if ((r = sshkey_from_private(ca,
1794 &public->cert->signature_key)) != 0)
1795 fatal("sshkey_from_private (ca key): %s", ssh_err(r));
1797 if (agent_fd != -1 && (ca->flags & SSHKEY_FLAG_EXT) != 0) {
1798 if ((r = sshkey_certify_custom(public, ca,
1799 key_type_name, agent_signer, &agent_fd)) != 0)
1800 fatal("Couldn't certify key %s via agent: %s",
1803 if ((sshkey_certify(public, ca, key_type_name)) != 0)
1804 fatal("Couldn't certify key %s: %s",
1808 if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
1810 xasprintf(&out, "%s-cert.pub", tmp);
1813 if ((fd = open(out, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
1814 fatal("Could not open \"%s\" for writing: %s", out,
1816 if ((f = fdopen(fd, "w")) == NULL)
1817 fatal("%s: fdopen: %s", __func__, strerror(errno));
1818 if ((r = sshkey_write(public, f)) != 0)
1819 fatal("Could not write certified key to %s: %s",
1821 fprintf(f, " %s\n", comment);
1825 sshkey_format_cert_validity(public->cert,
1826 valid, sizeof(valid));
1827 logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1828 "valid %s", sshkey_cert_type(public),
1829 out, public->cert->key_id,
1830 (unsigned long long)public->cert->serial,
1831 cert_principals != NULL ? " for " : "",
1832 cert_principals != NULL ? cert_principals : "",
1836 sshkey_free(public);
1839 #ifdef ENABLE_PKCS11
1846 parse_relative_time(const char *s, time_t now)
1850 mul = *s == '-' ? -1 : 1;
1852 if ((secs = convtime(s + 1)) == -1)
1853 fatal("Invalid relative certificate time %s", s);
1854 if (mul == -1 && secs > now)
1855 fatal("Certificate time %s cannot be represented", s);
1856 return now + (u_int64_t)(secs * mul);
1860 parse_cert_times(char *timespec)
1863 time_t now = time(NULL);
1866 /* +timespec relative to now */
1867 if (*timespec == '+' && strchr(timespec, ':') == NULL) {
1868 if ((secs = convtime(timespec + 1)) == -1)
1869 fatal("Invalid relative certificate life %s", timespec);
1870 cert_valid_to = now + secs;
1872 * Backdate certificate one minute to avoid problems on hosts
1873 * with poorly-synchronised clocks.
1875 cert_valid_from = ((now - 59)/ 60) * 60;
1881 * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "always"
1882 * to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "forever"
1884 from = xstrdup(timespec);
1885 to = strchr(from, ':');
1886 if (to == NULL || from == to || *(to + 1) == '\0')
1887 fatal("Invalid certificate life specification %s", timespec);
1890 if (*from == '-' || *from == '+')
1891 cert_valid_from = parse_relative_time(from, now);
1892 else if (strcmp(from, "always") == 0)
1893 cert_valid_from = 0;
1894 else if (parse_absolute_time(from, &cert_valid_from) != 0)
1895 fatal("Invalid from time \"%s\"", from);
1897 if (*to == '-' || *to == '+')
1898 cert_valid_to = parse_relative_time(to, now);
1899 else if (strcmp(to, "forever") == 0)
1900 cert_valid_to = ~(u_int64_t)0;
1901 else if (parse_absolute_time(to, &cert_valid_to) != 0)
1902 fatal("Invalid to time \"%s\"", to);
1904 if (cert_valid_to <= cert_valid_from)
1905 fatal("Empty certificate validity interval");
1910 add_cert_option(char *opt)
1915 if (strcasecmp(opt, "clear") == 0)
1916 certflags_flags = 0;
1917 else if (strcasecmp(opt, "no-x11-forwarding") == 0)
1918 certflags_flags &= ~CERTOPT_X_FWD;
1919 else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
1920 certflags_flags |= CERTOPT_X_FWD;
1921 else if (strcasecmp(opt, "no-agent-forwarding") == 0)
1922 certflags_flags &= ~CERTOPT_AGENT_FWD;
1923 else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
1924 certflags_flags |= CERTOPT_AGENT_FWD;
1925 else if (strcasecmp(opt, "no-port-forwarding") == 0)
1926 certflags_flags &= ~CERTOPT_PORT_FWD;
1927 else if (strcasecmp(opt, "permit-port-forwarding") == 0)
1928 certflags_flags |= CERTOPT_PORT_FWD;
1929 else if (strcasecmp(opt, "no-pty") == 0)
1930 certflags_flags &= ~CERTOPT_PTY;
1931 else if (strcasecmp(opt, "permit-pty") == 0)
1932 certflags_flags |= CERTOPT_PTY;
1933 else if (strcasecmp(opt, "no-user-rc") == 0)
1934 certflags_flags &= ~CERTOPT_USER_RC;
1935 else if (strcasecmp(opt, "permit-user-rc") == 0)
1936 certflags_flags |= CERTOPT_USER_RC;
1937 else if (strncasecmp(opt, "force-command=", 14) == 0) {
1940 fatal("Empty force-command option");
1941 if (certflags_command != NULL)
1942 fatal("force-command already specified");
1943 certflags_command = xstrdup(val);
1944 } else if (strncasecmp(opt, "source-address=", 15) == 0) {
1947 fatal("Empty source-address option");
1948 if (certflags_src_addr != NULL)
1949 fatal("source-address already specified");
1950 if (addr_match_cidr_list(NULL, val) != 0)
1951 fatal("Invalid source-address list");
1952 certflags_src_addr = xstrdup(val);
1953 } else if (strncasecmp(opt, "extension:", 10) == 0 ||
1954 (iscrit = (strncasecmp(opt, "critical:", 9) == 0))) {
1955 val = xstrdup(strchr(opt, ':') + 1);
1956 if ((cp = strchr(val, '=')) != NULL)
1958 cert_userext = xreallocarray(cert_userext, ncert_userext + 1,
1959 sizeof(*cert_userext));
1960 cert_userext[ncert_userext].key = val;
1961 cert_userext[ncert_userext].val = cp == NULL ?
1963 cert_userext[ncert_userext].crit = iscrit;
1966 fatal("Unsupported certificate option \"%s\"", opt);
1970 show_options(struct sshbuf *optbuf, int in_critical)
1973 struct sshbuf *options, *option = NULL;
1976 if ((options = sshbuf_fromb(optbuf)) == NULL)
1977 fatal("%s: sshbuf_fromb failed", __func__);
1978 while (sshbuf_len(options) != 0) {
1979 sshbuf_free(option);
1981 if ((r = sshbuf_get_cstring(options, &name, NULL)) != 0 ||
1982 (r = sshbuf_froms(options, &option)) != 0)
1983 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1984 printf(" %s", name);
1986 (strcmp(name, "permit-X11-forwarding") == 0 ||
1987 strcmp(name, "permit-agent-forwarding") == 0 ||
1988 strcmp(name, "permit-port-forwarding") == 0 ||
1989 strcmp(name, "permit-pty") == 0 ||
1990 strcmp(name, "permit-user-rc") == 0))
1992 else if (in_critical &&
1993 (strcmp(name, "force-command") == 0 ||
1994 strcmp(name, "source-address") == 0)) {
1995 if ((r = sshbuf_get_cstring(option, &arg, NULL)) != 0)
1996 fatal("%s: buffer error: %s",
1997 __func__, ssh_err(r));
1998 printf(" %s\n", arg);
2001 printf(" UNKNOWN OPTION (len %zu)\n",
2002 sshbuf_len(option));
2003 sshbuf_reset(option);
2006 if (sshbuf_len(option) != 0)
2007 fatal("Option corrupt: extra data at end");
2009 sshbuf_free(option);
2010 sshbuf_free(options);
2014 print_cert(struct sshkey *key)
2016 char valid[64], *key_fp, *ca_fp;
2019 key_fp = sshkey_fingerprint(key, fingerprint_hash, SSH_FP_DEFAULT);
2020 ca_fp = sshkey_fingerprint(key->cert->signature_key,
2021 fingerprint_hash, SSH_FP_DEFAULT);
2022 if (key_fp == NULL || ca_fp == NULL)
2023 fatal("%s: sshkey_fingerprint fail", __func__);
2024 sshkey_format_cert_validity(key->cert, valid, sizeof(valid));
2026 printf(" Type: %s %s certificate\n", sshkey_ssh_name(key),
2027 sshkey_cert_type(key));
2028 printf(" Public key: %s %s\n", sshkey_type(key), key_fp);
2029 printf(" Signing CA: %s %s\n",
2030 sshkey_type(key->cert->signature_key), ca_fp);
2031 printf(" Key ID: \"%s\"\n", key->cert->key_id);
2032 printf(" Serial: %llu\n", (unsigned long long)key->cert->serial);
2033 printf(" Valid: %s\n", valid);
2034 printf(" Principals: ");
2035 if (key->cert->nprincipals == 0)
2038 for (i = 0; i < key->cert->nprincipals; i++)
2040 key->cert->principals[i]);
2043 printf(" Critical Options: ");
2044 if (sshbuf_len(key->cert->critical) == 0)
2048 show_options(key->cert->critical, 1);
2050 printf(" Extensions: ");
2051 if (sshbuf_len(key->cert->extensions) == 0)
2055 show_options(key->cert->extensions, 0);
2060 do_show_cert(struct passwd *pw)
2062 struct sshkey *key = NULL;
2064 int r, is_stdin = 0, ok = 0;
2066 char *cp, line[SSH_MAX_PUBKEY_BYTES];
2071 ask_filename(pw, "Enter file in which the key is");
2072 if (strcmp(identity_file, "-") != 0 && stat(identity_file, &st) < 0)
2073 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
2075 path = identity_file;
2076 if (strcmp(path, "-") == 0) {
2080 } else if ((f = fopen(identity_file, "r")) == NULL)
2081 fatal("fopen %s: %s", identity_file, strerror(errno));
2083 while (read_keyfile_line(f, path, line, sizeof(line), &lnum) == 0) {
2086 /* Trim leading space and comments */
2087 cp = line + strspn(line, " \t");
2088 if (*cp == '#' || *cp == '\0')
2090 if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2091 fatal("sshkey_new");
2092 if ((r = sshkey_read(key, &cp)) != 0) {
2093 error("%s:%lu: invalid key: %s", path,
2097 if (!sshkey_is_cert(key)) {
2098 error("%s:%lu is not a certificate", path, lnum);
2102 if (!is_stdin && lnum == 1)
2103 printf("%s:\n", path);
2105 printf("%s:%lu:\n", path, lnum);
2114 load_krl(const char *path, struct ssh_krl **krlp)
2116 struct sshbuf *krlbuf;
2119 if ((krlbuf = sshbuf_new()) == NULL)
2120 fatal("sshbuf_new failed");
2121 if ((fd = open(path, O_RDONLY)) == -1)
2122 fatal("open %s: %s", path, strerror(errno));
2123 if ((r = sshkey_load_file(fd, krlbuf)) != 0)
2124 fatal("Unable to load KRL: %s", ssh_err(r));
2126 /* XXX check sigs */
2127 if ((r = ssh_krl_from_blob(krlbuf, krlp, NULL, 0)) != 0 ||
2129 fatal("Invalid KRL file: %s", ssh_err(r));
2130 sshbuf_free(krlbuf);
2134 update_krl_from_file(struct passwd *pw, const char *file, int wild_ca,
2135 const struct sshkey *ca, struct ssh_krl *krl)
2137 struct sshkey *key = NULL;
2139 char *path, *cp, *ep, line[SSH_MAX_PUBKEY_BYTES];
2140 unsigned long long serial, serial2;
2141 int i, was_explicit_key, was_sha1, r;
2144 path = tilde_expand_filename(file, pw->pw_uid);
2145 if (strcmp(path, "-") == 0) {
2148 path = xstrdup("(standard input)");
2149 } else if ((krl_spec = fopen(path, "r")) == NULL)
2150 fatal("fopen %s: %s", path, strerror(errno));
2153 printf("Revoking from %s\n", path);
2154 while (read_keyfile_line(krl_spec, path, line, sizeof(line),
2156 was_explicit_key = was_sha1 = 0;
2157 cp = line + strspn(line, " \t");
2158 /* Trim trailing space, comments and strip \n */
2159 for (i = 0, r = -1; cp[i] != '\0'; i++) {
2160 if (cp[i] == '#' || cp[i] == '\n') {
2164 if (cp[i] == ' ' || cp[i] == '\t') {
2165 /* Remember the start of a span of whitespace */
2175 if (strncasecmp(cp, "serial:", 7) == 0) {
2176 if (ca == NULL && !wild_ca) {
2177 fatal("revoking certificates by serial number "
2178 "requires specification of a CA key");
2181 cp = cp + strspn(cp, " \t");
2183 serial = strtoull(cp, &ep, 0);
2184 if (*cp == '\0' || (*ep != '\0' && *ep != '-'))
2185 fatal("%s:%lu: invalid serial \"%s\"",
2187 if (errno == ERANGE && serial == ULLONG_MAX)
2188 fatal("%s:%lu: serial out of range",
2194 serial2 = strtoull(cp, &ep, 0);
2195 if (*cp == '\0' || *ep != '\0')
2196 fatal("%s:%lu: invalid serial \"%s\"",
2198 if (errno == ERANGE && serial2 == ULLONG_MAX)
2199 fatal("%s:%lu: serial out of range",
2201 if (serial2 <= serial)
2202 fatal("%s:%lu: invalid serial range "
2203 "%llu:%llu", path, lnum,
2204 (unsigned long long)serial,
2205 (unsigned long long)serial2);
2207 if (ssh_krl_revoke_cert_by_serial_range(krl,
2208 ca, serial, serial2) != 0) {
2209 fatal("%s: revoke serial failed",
2212 } else if (strncasecmp(cp, "id:", 3) == 0) {
2213 if (ca == NULL && !wild_ca) {
2214 fatal("revoking certificates by key ID "
2215 "requires specification of a CA key");
2218 cp = cp + strspn(cp, " \t");
2219 if (ssh_krl_revoke_cert_by_key_id(krl, ca, cp) != 0)
2220 fatal("%s: revoke key ID failed", __func__);
2222 if (strncasecmp(cp, "key:", 4) == 0) {
2224 cp = cp + strspn(cp, " \t");
2225 was_explicit_key = 1;
2226 } else if (strncasecmp(cp, "sha1:", 5) == 0) {
2228 cp = cp + strspn(cp, " \t");
2232 * Just try to process the line as a key.
2233 * Parsing will fail if it isn't.
2236 if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2237 fatal("sshkey_new");
2238 if ((r = sshkey_read(key, &cp)) != 0)
2239 fatal("%s:%lu: invalid key: %s",
2240 path, lnum, ssh_err(r));
2241 if (was_explicit_key)
2242 r = ssh_krl_revoke_key_explicit(krl, key);
2244 r = ssh_krl_revoke_key_sha1(krl, key);
2246 r = ssh_krl_revoke_key(krl, key);
2248 fatal("%s: revoke key failed: %s",
2249 __func__, ssh_err(r));
2253 if (strcmp(path, "-") != 0)
2259 do_gen_krl(struct passwd *pw, int updating, int argc, char **argv)
2261 struct ssh_krl *krl;
2263 struct sshkey *ca = NULL;
2264 int fd, i, r, wild_ca = 0;
2266 struct sshbuf *kbuf;
2268 if (*identity_file == '\0')
2269 fatal("KRL generation requires an output file");
2270 if (stat(identity_file, &sb) == -1) {
2271 if (errno != ENOENT)
2272 fatal("Cannot access KRL \"%s\": %s",
2273 identity_file, strerror(errno));
2275 fatal("KRL \"%s\" does not exist", identity_file);
2277 if (ca_key_path != NULL) {
2278 if (strcasecmp(ca_key_path, "none") == 0)
2281 tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
2282 if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
2283 fatal("Cannot load CA public key %s: %s",
2290 load_krl(identity_file, &krl);
2291 else if ((krl = ssh_krl_init()) == NULL)
2292 fatal("couldn't create KRL");
2294 if (cert_serial != 0)
2295 ssh_krl_set_version(krl, cert_serial);
2296 if (identity_comment != NULL)
2297 ssh_krl_set_comment(krl, identity_comment);
2299 for (i = 0; i < argc; i++)
2300 update_krl_from_file(pw, argv[i], wild_ca, ca, krl);
2302 if ((kbuf = sshbuf_new()) == NULL)
2303 fatal("sshbuf_new failed");
2304 if (ssh_krl_to_blob(krl, kbuf, NULL, 0) != 0)
2305 fatal("Couldn't generate KRL");
2306 if ((fd = open(identity_file, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
2307 fatal("open %s: %s", identity_file, strerror(errno));
2308 if (atomicio(vwrite, fd, (void *)sshbuf_ptr(kbuf), sshbuf_len(kbuf)) !=
2310 fatal("write %s: %s", identity_file, strerror(errno));
2318 do_check_krl(struct passwd *pw, int argc, char **argv)
2322 struct ssh_krl *krl;
2325 if (*identity_file == '\0')
2326 fatal("KRL checking requires an input file");
2327 load_krl(identity_file, &krl);
2328 for (i = 0; i < argc; i++) {
2329 if ((r = sshkey_load_public(argv[i], &k, &comment)) != 0)
2330 fatal("Cannot load public key %s: %s",
2331 argv[i], ssh_err(r));
2332 r = ssh_krl_check_key(krl, k);
2333 printf("%s%s%s%s: %s\n", argv[i],
2334 *comment ? " (" : "", comment, *comment ? ")" : "",
2335 r == 0 ? "ok" : "REVOKED");
2349 "usage: ssh-keygen [-q] [-b bits] [-t dsa | ecdsa | ed25519 | rsa]\n"
2350 " [-N new_passphrase] [-C comment] [-f output_keyfile]\n"
2351 " ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]\n"
2352 " ssh-keygen -i [-m key_format] [-f input_keyfile]\n"
2353 " ssh-keygen -e [-m key_format] [-f input_keyfile]\n"
2354 " ssh-keygen -y [-f input_keyfile]\n"
2355 " ssh-keygen -c [-P passphrase] [-C comment] [-f keyfile]\n"
2356 " ssh-keygen -l [-v] [-E fingerprint_hash] [-f input_keyfile]\n"
2357 " ssh-keygen -B [-f input_keyfile]\n");
2358 #ifdef ENABLE_PKCS11
2360 " ssh-keygen -D pkcs11\n");
2363 " ssh-keygen -F hostname [-f known_hosts_file] [-l]\n"
2364 " ssh-keygen -H [-f known_hosts_file]\n"
2365 " ssh-keygen -R hostname [-f known_hosts_file]\n"
2366 " ssh-keygen -r hostname [-f input_keyfile] [-g]\n"
2368 " ssh-keygen -G output_file [-v] [-b bits] [-M memory] [-S start_point]\n"
2369 " ssh-keygen -T output_file -f input_file [-v] [-a rounds] [-J num_lines]\n"
2370 " [-j start_line] [-K checkpt] [-W generator]\n"
2372 " ssh-keygen -s ca_key -I certificate_identity [-h] [-U]\n"
2373 " [-D pkcs11_provider] [-n principals] [-O option]\n"
2374 " [-V validity_interval] [-z serial_number] file ...\n"
2375 " ssh-keygen -L [-f input_keyfile]\n"
2377 " ssh-keygen -k -f krl_file [-u] [-s ca_public] [-z version_number]\n"
2379 " ssh-keygen -Q -f krl_file file ...\n");
2384 * Main program for key management.
2387 main(int argc, char **argv)
2389 char dotsshdir[PATH_MAX], comment[1024], *passphrase1, *passphrase2;
2390 char *rr_hostname = NULL, *ep, *fp, *ra;
2391 struct sshkey *private, *public;
2394 int r, opt, type, fd;
2395 int gen_all_hostkeys = 0, gen_krl = 0, update_krl = 0, check_krl = 0;
2399 /* Moduli generation/screening */
2400 char out_file[PATH_MAX], *checkpoint = NULL;
2401 u_int32_t memory = 0, generator_wanted = 0;
2402 int do_gen_candidates = 0, do_screen_candidates = 0;
2403 unsigned long start_lineno = 0, lines_to_process = 0;
2404 BIGNUM *start = NULL;
2408 extern char *optarg;
2410 ssh_malloc_init(); /* must be called before any mallocs */
2411 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
2414 __progname = ssh_get_progname(argv[0]);
2417 OpenSSL_add_all_algorithms();
2419 log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
2425 /* we need this for the home * directory. */
2426 pw = getpwuid(getuid());
2428 fatal("No user exists for uid %lu", (u_long)getuid());
2429 if (gethostname(hostname, sizeof(hostname)) < 0)
2430 fatal("gethostname: %s", strerror(errno));
2432 /* Remaining characters: Ydw */
2433 while ((opt = getopt(argc, argv, "ABHLQUXceghiklopquvxy"
2434 "C:D:E:F:G:I:J:K:M:N:O:P:R:S:T:V:W:Z:"
2435 "a:b:f:g:j:m:n:r:s:t:z:")) != -1) {
2438 gen_all_hostkeys = 1;
2441 bits = (u_int32_t)strtonum(optarg, 10, 32768, &errstr);
2443 fatal("Bits has bad value %s (%s)",
2447 fingerprint_hash = ssh_digest_alg_by_name(optarg);
2448 if (fingerprint_hash == -1)
2449 fatal("Invalid hash algorithm \"%s\"", optarg);
2453 rr_hostname = optarg;
2459 cert_key_id = optarg;
2463 rr_hostname = optarg;
2469 print_fingerprint = 1;
2472 print_bubblebabble = 1;
2475 if (strcasecmp(optarg, "RFC4716") == 0 ||
2476 strcasecmp(optarg, "ssh2") == 0) {
2477 convert_format = FMT_RFC4716;
2480 if (strcasecmp(optarg, "PKCS8") == 0) {
2481 convert_format = FMT_PKCS8;
2484 if (strcasecmp(optarg, "PEM") == 0) {
2485 convert_format = FMT_PEM;
2488 fatal("Unsupported conversion format \"%s\"", optarg);
2490 cert_principals = optarg;
2496 change_passphrase = 1;
2502 if (strlcpy(identity_file, optarg,
2503 sizeof(identity_file)) >= sizeof(identity_file))
2504 fatal("Identity filename too long");
2511 identity_passphrase = optarg;
2514 identity_new_passphrase = optarg;
2520 add_cert_option(optarg);
2523 new_format_cipher = optarg;
2526 identity_comment = optarg;
2537 cert_key_type = SSH2_CERT_TYPE_HOST;
2538 certflags_flags = 0;
2552 ca_key_path = optarg;
2555 key_type_name = optarg;
2558 pkcs11provider = optarg;
2567 if (log_level == SYSLOG_LEVEL_INFO)
2568 log_level = SYSLOG_LEVEL_DEBUG1;
2570 if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
2571 log_level < SYSLOG_LEVEL_DEBUG3)
2576 rr_hostname = optarg;
2579 rounds = (int)strtonum(optarg, 1, INT_MAX, &errstr);
2581 fatal("Invalid number: %s (%s)",
2585 parse_cert_times(optarg);
2589 cert_serial = strtoull(optarg, &ep, 10);
2590 if (*optarg < '0' || *optarg > '9' || *ep != '\0' ||
2591 (errno == ERANGE && cert_serial == ULLONG_MAX))
2592 fatal("Invalid serial number \"%s\"", optarg);
2595 /* Moduli generation/screening */
2597 do_gen_candidates = 1;
2598 if (strlcpy(out_file, optarg, sizeof(out_file)) >=
2600 fatal("Output filename too long");
2603 lines_to_process = strtoul(optarg, NULL, 10);
2606 start_lineno = strtoul(optarg, NULL, 10);
2609 if (strlen(optarg) >= PATH_MAX)
2610 fatal("Checkpoint filename too long");
2611 checkpoint = xstrdup(optarg);
2614 memory = (u_int32_t)strtonum(optarg, 1, UINT_MAX,
2617 fatal("Memory limit is %s: %s", errstr, optarg);
2620 /* XXX - also compare length against bits */
2621 if (BN_hex2bn(&start, optarg) == 0)
2622 fatal("Invalid start point.");
2625 do_screen_candidates = 1;
2626 if (strlcpy(out_file, optarg, sizeof(out_file)) >=
2628 fatal("Output filename too long");
2631 generator_wanted = (u_int32_t)strtonum(optarg, 1,
2634 fatal("Desired generator invalid: %s (%s)",
2637 #endif /* WITH_OPENSSL */
2645 log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
2650 if (ca_key_path != NULL) {
2651 if (argc < 1 && !gen_krl) {
2652 error("Too few arguments.");
2655 } else if (argc > 0 && !gen_krl && !check_krl) {
2656 error("Too many arguments.");
2659 if (change_passphrase && change_comment) {
2660 error("Can only have one of -p and -c.");
2663 if (print_fingerprint && (delete_host || hash_hosts)) {
2664 error("Cannot use -l with -H or -R.");
2668 do_gen_krl(pw, update_krl, argc, argv);
2672 do_check_krl(pw, argc, argv);
2675 if (ca_key_path != NULL) {
2676 if (cert_key_id == NULL)
2677 fatal("Must specify key id (-I) when certifying");
2678 do_ca_sign(pw, argc, argv);
2682 if (delete_host || hash_hosts || find_host)
2683 do_known_hosts(pw, rr_hostname);
2684 if (pkcs11provider != NULL)
2686 if (print_fingerprint || print_bubblebabble)
2688 if (change_passphrase)
2689 do_change_passphrase(pw);
2691 do_change_comment(pw);
2696 do_convert_from(pw);
2699 do_print_public(pw);
2700 if (rr_hostname != NULL) {
2703 if (have_identity) {
2704 n = do_print_resource_record(pw,
2705 identity_file, rr_hostname);
2707 fatal("%s: %s", identity_file, strerror(errno));
2711 n += do_print_resource_record(pw,
2712 _PATH_HOST_RSA_KEY_FILE, rr_hostname);
2713 n += do_print_resource_record(pw,
2714 _PATH_HOST_DSA_KEY_FILE, rr_hostname);
2715 n += do_print_resource_record(pw,
2716 _PATH_HOST_ECDSA_KEY_FILE, rr_hostname);
2717 n += do_print_resource_record(pw,
2718 _PATH_HOST_ED25519_KEY_FILE, rr_hostname);
2719 n += do_print_resource_record(pw,
2720 _PATH_HOST_XMSS_KEY_FILE, rr_hostname);
2722 fatal("no keys found.");
2728 if (do_gen_candidates) {
2729 FILE *out = fopen(out_file, "w");
2732 error("Couldn't open modulus candidate file \"%s\": %s",
2733 out_file, strerror(errno));
2737 bits = DEFAULT_BITS;
2738 if (gen_candidates(out, memory, bits, start) != 0)
2739 fatal("modulus candidate generation failed");
2744 if (do_screen_candidates) {
2746 FILE *out = fopen(out_file, "a");
2748 if (have_identity && strcmp(identity_file, "-") != 0) {
2749 if ((in = fopen(identity_file, "r")) == NULL) {
2750 fatal("Couldn't open modulus candidate "
2751 "file \"%s\": %s", identity_file,
2758 fatal("Couldn't open moduli file \"%s\": %s",
2759 out_file, strerror(errno));
2761 if (prime_test(in, out, rounds == 0 ? 100 : rounds,
2762 generator_wanted, checkpoint,
2763 start_lineno, lines_to_process) != 0)
2764 fatal("modulus screening failed");
2769 if (gen_all_hostkeys) {
2770 do_gen_all_hostkeys(pw);
2774 if (key_type_name == NULL)
2775 key_type_name = DEFAULT_KEY_TYPE_NAME;
2777 type = sshkey_type_from_name(key_type_name);
2778 type_bits_valid(type, key_type_name, &bits);
2781 printf("Generating public/private %s key pair.\n",
2783 if ((r = sshkey_generate(type, bits, &private)) != 0)
2784 fatal("sshkey_generate failed");
2785 if ((r = sshkey_from_private(private, &public)) != 0)
2786 fatal("sshkey_from_private failed: %s\n", ssh_err(r));
2789 ask_filename(pw, "Enter file in which to save the key");
2791 /* Create ~/.ssh directory if it doesn't already exist. */
2792 snprintf(dotsshdir, sizeof dotsshdir, "%s/%s",
2793 pw->pw_dir, _PATH_SSH_USER_DIR);
2794 if (strstr(identity_file, dotsshdir) != NULL) {
2795 if (stat(dotsshdir, &st) < 0) {
2796 if (errno != ENOENT) {
2797 error("Could not stat %s: %s", dotsshdir,
2799 } else if (mkdir(dotsshdir, 0700) < 0) {
2800 error("Could not create directory '%s': %s",
2801 dotsshdir, strerror(errno));
2803 printf("Created directory '%s'.\n", dotsshdir);
2806 /* If the file already exists, ask the user to confirm. */
2807 if (stat(identity_file, &st) >= 0) {
2809 printf("%s already exists.\n", identity_file);
2810 printf("Overwrite (y/n)? ");
2812 if (fgets(yesno, sizeof(yesno), stdin) == NULL)
2814 if (yesno[0] != 'y' && yesno[0] != 'Y')
2817 /* Ask for a passphrase (twice). */
2818 if (identity_passphrase)
2819 passphrase1 = xstrdup(identity_passphrase);
2820 else if (identity_new_passphrase)
2821 passphrase1 = xstrdup(identity_new_passphrase);
2825 read_passphrase("Enter passphrase (empty for no "
2826 "passphrase): ", RP_ALLOW_STDIN);
2827 passphrase2 = read_passphrase("Enter same passphrase again: ",
2829 if (strcmp(passphrase1, passphrase2) != 0) {
2831 * The passphrases do not match. Clear them and
2834 explicit_bzero(passphrase1, strlen(passphrase1));
2835 explicit_bzero(passphrase2, strlen(passphrase2));
2838 printf("Passphrases do not match. Try again.\n");
2839 goto passphrase_again;
2841 /* Clear the other copy of the passphrase. */
2842 explicit_bzero(passphrase2, strlen(passphrase2));
2846 if (identity_comment) {
2847 strlcpy(comment, identity_comment, sizeof(comment));
2849 /* Create default comment field for the passphrase. */
2850 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
2853 /* Save the key with the given passphrase and comment. */
2854 if ((r = sshkey_save_private(private, identity_file, passphrase1,
2855 comment, use_new_format, new_format_cipher, rounds)) != 0) {
2856 error("Saving key \"%s\" failed: %s",
2857 identity_file, ssh_err(r));
2858 explicit_bzero(passphrase1, strlen(passphrase1));
2862 /* Clear the passphrase. */
2863 explicit_bzero(passphrase1, strlen(passphrase1));
2866 /* Clear the private key and the random number generator. */
2867 sshkey_free(private);
2870 printf("Your identification has been saved in %s.\n", identity_file);
2872 strlcat(identity_file, ".pub", sizeof(identity_file));
2873 if ((fd = open(identity_file, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
2874 fatal("Unable to save public key to %s: %s",
2875 identity_file, strerror(errno));
2876 if ((f = fdopen(fd, "w")) == NULL)
2877 fatal("fdopen %s failed: %s", identity_file, strerror(errno));
2878 if ((r = sshkey_write(public, f)) != 0)
2879 error("write key failed: %s", ssh_err(r));
2880 fprintf(f, " %s\n", comment);
2881 if (ferror(f) || fclose(f) != 0)
2882 fatal("write public failed: %s", strerror(errno));
2885 fp = sshkey_fingerprint(public, fingerprint_hash,
2887 ra = sshkey_fingerprint(public, fingerprint_hash,
2889 if (fp == NULL || ra == NULL)
2890 fatal("sshkey_fingerprint failed");
2891 printf("Your public key has been saved in %s.\n",
2893 printf("The key fingerprint is:\n");
2894 printf("%s %s\n", fp, comment);
2895 printf("The key's randomart image is:\n");
2901 sshkey_free(public);