1 /* $OpenBSD: ssh-keygen.c,v 1.437 2021/09/08 03:23:44 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1994 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * Identity and host key generation and maintenance.
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose. Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
17 #include <sys/types.h>
18 #include <sys/socket.h>
22 #include <openssl/evp.h>
23 #include <openssl/pem.h>
24 #include "openbsd-compat/openssl-compat.h"
50 #include "pathnames.h"
59 #include "ssh-pkcs11.h"
67 #include "sk-api.h" /* XXX for SSH_SK_USER_PRESENCE_REQD; remove */
71 # define DEFAULT_KEY_TYPE_NAME "rsa"
73 # define DEFAULT_KEY_TYPE_NAME "ed25519"
77 * Default number of bits in the RSA, DSA and ECDSA keys. These value can be
78 * overridden on the command line.
80 * These values, with the exception of DSA, provide security equivalent to at
81 * least 128 bits of security according to NIST Special Publication 800-57:
82 * Recommendation for Key Management Part 1 rev 4 section 5.6.1.
83 * For DSA it (and FIPS-186-4 section 4.2) specifies that the only size for
84 * which a 160bit hash is acceptable is 1kbit, and since ssh-dss specifies only
85 * SHA1 we limit the DSA key size 1k bits.
87 #define DEFAULT_BITS 3072
88 #define DEFAULT_BITS_DSA 1024
89 #define DEFAULT_BITS_ECDSA 256
93 /* Flag indicating that we just want to see the key fingerprint */
94 static int print_fingerprint
= 0;
95 static int print_bubblebabble
= 0;
97 /* Hash algorithm to use for fingerprints. */
98 static int fingerprint_hash
= SSH_FP_HASH_DEFAULT
;
100 /* The identity file name, given on the command line or entered by the user. */
101 static char identity_file
[PATH_MAX
];
102 static int have_identity
= 0;
104 /* This is set to the passphrase if given on the command line. */
105 static char *identity_passphrase
= NULL
;
107 /* This is set to the new passphrase if given on the command line. */
108 static char *identity_new_passphrase
= NULL
;
110 /* Key type when certifying */
111 static u_int cert_key_type
= SSH2_CERT_TYPE_USER
;
113 /* "key ID" of signed key */
114 static char *cert_key_id
= NULL
;
116 /* Comma-separated list of principal names for certifying keys */
117 static char *cert_principals
= NULL
;
119 /* Validity period for certificates */
120 static u_int64_t cert_valid_from
= 0;
121 static u_int64_t cert_valid_to
= ~0ULL;
123 /* Certificate options */
124 #define CERTOPT_X_FWD (1)
125 #define CERTOPT_AGENT_FWD (1<<1)
126 #define CERTOPT_PORT_FWD (1<<2)
127 #define CERTOPT_PTY (1<<3)
128 #define CERTOPT_USER_RC (1<<4)
129 #define CERTOPT_NO_REQUIRE_USER_PRESENCE (1<<5)
130 #define CERTOPT_DEFAULT (CERTOPT_X_FWD|CERTOPT_AGENT_FWD| \
131 CERTOPT_PORT_FWD|CERTOPT_PTY|CERTOPT_USER_RC)
132 static u_int32_t certflags_flags
= CERTOPT_DEFAULT
;
133 static char *certflags_command
= NULL
;
134 static char *certflags_src_addr
= NULL
;
136 /* Arbitrary extensions specified by user */
142 static struct cert_ext
*cert_ext
;
143 static size_t ncert_ext
;
145 /* Conversion to/from various formats */
150 } convert_format
= FMT_RFC4716
;
152 static char *key_type_name
= NULL
;
154 /* Load key from this PKCS#11 provider */
155 static char *pkcs11provider
= NULL
;
157 /* FIDO/U2F provider to use */
158 static char *sk_provider
= NULL
;
160 /* Format for writing private keys */
161 static int private_key_format
= SSHKEY_PRIVATE_OPENSSH
;
163 /* Cipher for new-format private keys */
164 static char *openssh_format_cipher
= NULL
;
166 /* Number of KDF rounds to derive new format keys. */
167 static int rounds
= 0;
170 extern char *__progname
;
172 static char hostname
[NI_MAXHOST
];
176 int gen_candidates(FILE *, u_int32_t
, u_int32_t
, BIGNUM
*);
177 int prime_test(FILE *, FILE *, u_int32_t
, u_int32_t
, char *, unsigned long,
182 type_bits_valid(int type
, const char *name
, u_int32_t
*bitsp
)
184 if (type
== KEY_UNSPEC
)
185 fatal("unknown key type %s", key_type_name
);
192 *bitsp
= DEFAULT_BITS_DSA
;
196 (nid
= sshkey_ecdsa_nid_from_name(name
)) > 0)
197 *bitsp
= sshkey_curve_nid_to_bits(nid
);
199 *bitsp
= DEFAULT_BITS_ECDSA
;
202 *bitsp
= DEFAULT_BITS
;
211 fatal("Invalid DSA key length: must be 1024 bits");
214 if (*bitsp
< SSH_RSA_MINIMUM_MODULUS_SIZE
)
215 fatal("Invalid RSA key length: minimum is %d bits",
216 SSH_RSA_MINIMUM_MODULUS_SIZE
);
217 else if (*bitsp
> OPENSSL_RSA_MAX_MODULUS_BITS
)
218 fatal("Invalid RSA key length: maximum is %d bits",
219 OPENSSL_RSA_MAX_MODULUS_BITS
);
222 if (sshkey_ecdsa_bits_to_nid(*bitsp
) == -1)
223 #ifdef OPENSSL_HAS_NISTP521
224 fatal("Invalid ECDSA key length: valid lengths are "
225 "256, 384 or 521 bits");
227 fatal("Invalid ECDSA key length: valid lengths are "
235 * Checks whether a file exists and, if so, asks the user whether they wish
237 * Returns nonzero if the file does not already exist or if the user agrees to
238 * overwrite, or zero otherwise.
241 confirm_overwrite(const char *filename
)
246 if (stat(filename
, &st
) != 0)
248 printf("%s already exists.\n", filename
);
249 printf("Overwrite (y/n)? ");
251 if (fgets(yesno
, sizeof(yesno
), stdin
) == NULL
)
253 if (yesno
[0] != 'y' && yesno
[0] != 'Y')
259 ask_filename(struct passwd
*pw
, const char *prompt
)
264 if (key_type_name
== NULL
)
265 name
= _PATH_SSH_CLIENT_ID_RSA
;
267 switch (sshkey_type_from_name(key_type_name
)) {
270 name
= _PATH_SSH_CLIENT_ID_DSA
;
272 #ifdef OPENSSL_HAS_ECC
275 name
= _PATH_SSH_CLIENT_ID_ECDSA
;
277 case KEY_ECDSA_SK_CERT
:
279 name
= _PATH_SSH_CLIENT_ID_ECDSA_SK
;
284 name
= _PATH_SSH_CLIENT_ID_RSA
;
287 case KEY_ED25519_CERT
:
288 name
= _PATH_SSH_CLIENT_ID_ED25519
;
291 case KEY_ED25519_SK_CERT
:
292 name
= _PATH_SSH_CLIENT_ID_ED25519_SK
;
296 name
= _PATH_SSH_CLIENT_ID_XMSS
;
299 fatal("bad key type");
302 snprintf(identity_file
, sizeof(identity_file
),
303 "%s/%s", pw
->pw_dir
, name
);
304 printf("%s (%s): ", prompt
, identity_file
);
306 if (fgets(buf
, sizeof(buf
), stdin
) == NULL
)
308 buf
[strcspn(buf
, "\n")] = '\0';
309 if (strcmp(buf
, "") != 0)
310 strlcpy(identity_file
, buf
, sizeof(identity_file
));
314 static struct sshkey
*
315 load_identity(const char *filename
, char **commentp
)
321 if (commentp
!= NULL
)
323 if ((r
= sshkey_load_private(filename
, "", &prv
, commentp
)) == 0)
325 if (r
!= SSH_ERR_KEY_WRONG_PASSPHRASE
)
326 fatal_r(r
, "Load key \"%s\"", filename
);
327 if (identity_passphrase
)
328 pass
= xstrdup(identity_passphrase
);
330 pass
= read_passphrase("Enter passphrase: ", RP_ALLOW_STDIN
);
331 r
= sshkey_load_private(filename
, pass
, &prv
, commentp
);
332 freezero(pass
, strlen(pass
));
334 fatal_r(r
, "Load key \"%s\"", filename
);
338 #define SSH_COM_PUBLIC_BEGIN "---- BEGIN SSH2 PUBLIC KEY ----"
339 #define SSH_COM_PUBLIC_END "---- END SSH2 PUBLIC KEY ----"
340 #define SSH_COM_PRIVATE_BEGIN "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
341 #define SSH_COM_PRIVATE_KEY_MAGIC 0x3f6ff9eb
345 do_convert_to_ssh2(struct passwd
*pw
, struct sshkey
*k
)
348 char comment
[61], *b64
;
351 if ((b
= sshbuf_new()) == NULL
)
352 fatal_f("sshbuf_new failed");
353 if ((r
= sshkey_putb(k
, b
)) != 0)
354 fatal_fr(r
, "put key");
355 if ((b64
= sshbuf_dtob64_string(b
, 1)) == NULL
)
356 fatal_f("sshbuf_dtob64_string failed");
358 /* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
359 snprintf(comment
, sizeof(comment
),
360 "%u-bit %s, converted by %s@%s from OpenSSH",
361 sshkey_size(k
), sshkey_type(k
),
362 pw
->pw_name
, hostname
);
367 fprintf(stdout
, "%s\n", SSH_COM_PUBLIC_BEGIN
);
368 fprintf(stdout
, "Comment: \"%s\"\n%s", comment
, b64
);
369 fprintf(stdout
, "%s\n", SSH_COM_PUBLIC_END
);
375 do_convert_to_pkcs8(struct sshkey
*k
)
377 switch (sshkey_type_plain(k
->type
)) {
379 if (!PEM_write_RSA_PUBKEY(stdout
, k
->rsa
))
380 fatal("PEM_write_RSA_PUBKEY failed");
383 if (!PEM_write_DSA_PUBKEY(stdout
, k
->dsa
))
384 fatal("PEM_write_DSA_PUBKEY failed");
386 #ifdef OPENSSL_HAS_ECC
388 if (!PEM_write_EC_PUBKEY(stdout
, k
->ecdsa
))
389 fatal("PEM_write_EC_PUBKEY failed");
393 fatal_f("unsupported key type %s", sshkey_type(k
));
399 do_convert_to_pem(struct sshkey
*k
)
401 switch (sshkey_type_plain(k
->type
)) {
403 if (!PEM_write_RSAPublicKey(stdout
, k
->rsa
))
404 fatal("PEM_write_RSAPublicKey failed");
407 if (!PEM_write_DSA_PUBKEY(stdout
, k
->dsa
))
408 fatal("PEM_write_DSA_PUBKEY failed");
410 #ifdef OPENSSL_HAS_ECC
412 if (!PEM_write_EC_PUBKEY(stdout
, k
->ecdsa
))
413 fatal("PEM_write_EC_PUBKEY failed");
417 fatal_f("unsupported key type %s", sshkey_type(k
));
423 do_convert_to(struct passwd
*pw
)
430 ask_filename(pw
, "Enter file in which the key is");
431 if (stat(identity_file
, &st
) == -1)
432 fatal("%s: %s: %s", __progname
, identity_file
, strerror(errno
));
433 if ((r
= sshkey_load_public(identity_file
, &k
, NULL
)) != 0)
434 k
= load_identity(identity_file
, NULL
);
435 switch (convert_format
) {
437 do_convert_to_ssh2(pw
, k
);
440 do_convert_to_pkcs8(k
);
443 do_convert_to_pem(k
);
446 fatal_f("unknown key format %d", convert_format
);
452 * This is almost exactly the bignum1 encoding, but with 32 bit for length
456 buffer_get_bignum_bits(struct sshbuf
*b
, BIGNUM
*value
)
458 u_int bytes
, bignum_bits
;
461 if ((r
= sshbuf_get_u32(b
, &bignum_bits
)) != 0)
462 fatal_fr(r
, "parse");
463 bytes
= (bignum_bits
+ 7) / 8;
464 if (sshbuf_len(b
) < bytes
)
465 fatal_f("input buffer too small: need %d have %zu",
466 bytes
, sshbuf_len(b
));
467 if (BN_bin2bn(sshbuf_ptr(b
), bytes
, value
) == NULL
)
468 fatal_f("BN_bin2bn failed");
469 if ((r
= sshbuf_consume(b
, bytes
)) != 0)
470 fatal_fr(r
, "consume");
473 static struct sshkey
*
474 do_convert_private_ssh2(struct sshbuf
*b
)
476 struct sshkey
*key
= NULL
;
478 u_char e1
, e2
, e3
, *sig
= NULL
, data
[] = "abcde12345";
480 u_int magic
, i1
, i2
, i3
, i4
;
483 BIGNUM
*dsa_p
= NULL
, *dsa_q
= NULL
, *dsa_g
= NULL
;
484 BIGNUM
*dsa_pub_key
= NULL
, *dsa_priv_key
= NULL
;
485 BIGNUM
*rsa_n
= NULL
, *rsa_e
= NULL
, *rsa_d
= NULL
;
486 BIGNUM
*rsa_p
= NULL
, *rsa_q
= NULL
, *rsa_iqmp
= NULL
;
488 if ((r
= sshbuf_get_u32(b
, &magic
)) != 0)
489 fatal_fr(r
, "parse magic");
491 if (magic
!= SSH_COM_PRIVATE_KEY_MAGIC
) {
492 error("bad magic 0x%x != 0x%x", magic
,
493 SSH_COM_PRIVATE_KEY_MAGIC
);
496 if ((r
= sshbuf_get_u32(b
, &i1
)) != 0 ||
497 (r
= sshbuf_get_cstring(b
, &type
, NULL
)) != 0 ||
498 (r
= sshbuf_get_cstring(b
, &cipher
, NULL
)) != 0 ||
499 (r
= sshbuf_get_u32(b
, &i2
)) != 0 ||
500 (r
= sshbuf_get_u32(b
, &i3
)) != 0 ||
501 (r
= sshbuf_get_u32(b
, &i4
)) != 0)
502 fatal_fr(r
, "parse");
503 debug("ignore (%d %d %d %d)", i1
, i2
, i3
, i4
);
504 if (strcmp(cipher
, "none") != 0) {
505 error("unsupported cipher %s", cipher
);
512 if (strstr(type
, "dsa")) {
514 } else if (strstr(type
, "rsa")) {
520 if ((key
= sshkey_new(ktype
)) == NULL
)
521 fatal("sshkey_new failed");
526 if ((dsa_p
= BN_new()) == NULL
||
527 (dsa_q
= BN_new()) == NULL
||
528 (dsa_g
= BN_new()) == NULL
||
529 (dsa_pub_key
= BN_new()) == NULL
||
530 (dsa_priv_key
= BN_new()) == NULL
)
532 buffer_get_bignum_bits(b
, dsa_p
);
533 buffer_get_bignum_bits(b
, dsa_g
);
534 buffer_get_bignum_bits(b
, dsa_q
);
535 buffer_get_bignum_bits(b
, dsa_pub_key
);
536 buffer_get_bignum_bits(b
, dsa_priv_key
);
537 if (!DSA_set0_pqg(key
->dsa
, dsa_p
, dsa_q
, dsa_g
))
538 fatal_f("DSA_set0_pqg failed");
539 dsa_p
= dsa_q
= dsa_g
= NULL
; /* transferred */
540 if (!DSA_set0_key(key
->dsa
, dsa_pub_key
, dsa_priv_key
))
541 fatal_f("DSA_set0_key failed");
542 dsa_pub_key
= dsa_priv_key
= NULL
; /* transferred */
545 if ((r
= sshbuf_get_u8(b
, &e1
)) != 0 ||
546 (e1
< 30 && (r
= sshbuf_get_u8(b
, &e2
)) != 0) ||
547 (e1
< 30 && (r
= sshbuf_get_u8(b
, &e3
)) != 0))
548 fatal_fr(r
, "parse RSA");
559 if ((rsa_e
= BN_new()) == NULL
)
561 if (!BN_set_word(rsa_e
, e
)) {
562 BN_clear_free(rsa_e
);
566 if ((rsa_n
= BN_new()) == NULL
||
567 (rsa_d
= BN_new()) == NULL
||
568 (rsa_p
= BN_new()) == NULL
||
569 (rsa_q
= BN_new()) == NULL
||
570 (rsa_iqmp
= BN_new()) == NULL
)
572 buffer_get_bignum_bits(b
, rsa_d
);
573 buffer_get_bignum_bits(b
, rsa_n
);
574 buffer_get_bignum_bits(b
, rsa_iqmp
);
575 buffer_get_bignum_bits(b
, rsa_q
);
576 buffer_get_bignum_bits(b
, rsa_p
);
577 if (!RSA_set0_key(key
->rsa
, rsa_n
, rsa_e
, rsa_d
))
578 fatal_f("RSA_set0_key failed");
579 rsa_n
= rsa_e
= rsa_d
= NULL
; /* transferred */
580 if (!RSA_set0_factors(key
->rsa
, rsa_p
, rsa_q
))
581 fatal_f("RSA_set0_factors failed");
582 rsa_p
= rsa_q
= NULL
; /* transferred */
583 if ((r
= ssh_rsa_complete_crt_parameters(key
, rsa_iqmp
)) != 0)
584 fatal_fr(r
, "generate RSA parameters");
585 BN_clear_free(rsa_iqmp
);
588 rlen
= sshbuf_len(b
);
590 error_f("remaining bytes in key blob %d", rlen
);
593 if (sshkey_sign(key
, &sig
, &slen
, data
, sizeof(data
),
594 NULL
, NULL
, NULL
, 0) != 0 ||
595 sshkey_verify(key
, sig
, slen
, data
, sizeof(data
),
596 NULL
, 0, NULL
) != 0) {
606 get_line(FILE *fp
, char *line
, size_t len
)
612 while ((c
= fgetc(fp
)) != EOF
) {
614 fatal("input line too long.");
618 if (c
!= EOF
&& c
!= '\n' && ungetc(c
, fp
) == EOF
)
619 fatal("unget: %s", strerror(errno
));
632 do_convert_from_ssh2(struct passwd
*pw
, struct sshkey
**k
, int *private)
634 int r
, blen
, escaped
= 0;
641 if ((buf
= sshbuf_new()) == NULL
)
642 fatal("sshbuf_new failed");
643 if ((fp
= fopen(identity_file
, "r")) == NULL
)
644 fatal("%s: %s: %s", __progname
, identity_file
, strerror(errno
));
646 while ((blen
= get_line(fp
, line
, sizeof(line
))) != -1) {
647 if (blen
> 0 && line
[blen
- 1] == '\\')
649 if (strncmp(line
, "----", 4) == 0 ||
650 strstr(line
, ": ") != NULL
) {
651 if (strstr(line
, SSH_COM_PRIVATE_BEGIN
) != NULL
)
653 if (strstr(line
, " END ") != NULL
) {
656 /* fprintf(stderr, "ignore: %s", line); */
661 /* fprintf(stderr, "escaped: %s", line); */
664 strlcat(encoded
, line
, sizeof(encoded
));
666 len
= strlen(encoded
);
667 if (((len
% 4) == 3) &&
668 (encoded
[len
-1] == '=') &&
669 (encoded
[len
-2] == '=') &&
670 (encoded
[len
-3] == '='))
671 encoded
[len
-3] = '\0';
672 if ((r
= sshbuf_b64tod(buf
, encoded
)) != 0)
673 fatal_fr(r
, "base64 decode");
675 if ((*k
= do_convert_private_ssh2(buf
)) == NULL
)
676 fatal_f("private key conversion failed");
677 } else if ((r
= sshkey_fromb(buf
, k
)) != 0)
678 fatal_fr(r
, "parse key");
684 do_convert_from_pkcs8(struct sshkey
**k
, int *private)
689 if ((fp
= fopen(identity_file
, "r")) == NULL
)
690 fatal("%s: %s: %s", __progname
, identity_file
, strerror(errno
));
691 if ((pubkey
= PEM_read_PUBKEY(fp
, NULL
, NULL
, NULL
)) == NULL
) {
692 fatal_f("%s is not a recognised public key format",
696 switch (EVP_PKEY_base_id(pubkey
)) {
698 if ((*k
= sshkey_new(KEY_UNSPEC
)) == NULL
)
699 fatal("sshkey_new failed");
700 (*k
)->type
= KEY_RSA
;
701 (*k
)->rsa
= EVP_PKEY_get1_RSA(pubkey
);
704 if ((*k
= sshkey_new(KEY_UNSPEC
)) == NULL
)
705 fatal("sshkey_new failed");
706 (*k
)->type
= KEY_DSA
;
707 (*k
)->dsa
= EVP_PKEY_get1_DSA(pubkey
);
709 #ifdef OPENSSL_HAS_ECC
711 if ((*k
= sshkey_new(KEY_UNSPEC
)) == NULL
)
712 fatal("sshkey_new failed");
713 (*k
)->type
= KEY_ECDSA
;
714 (*k
)->ecdsa
= EVP_PKEY_get1_EC_KEY(pubkey
);
715 (*k
)->ecdsa_nid
= sshkey_ecdsa_key_to_nid((*k
)->ecdsa
);
719 fatal_f("unsupported pubkey type %d",
720 EVP_PKEY_base_id(pubkey
));
722 EVP_PKEY_free(pubkey
);
727 do_convert_from_pem(struct sshkey
**k
, int *private)
732 if ((fp
= fopen(identity_file
, "r")) == NULL
)
733 fatal("%s: %s: %s", __progname
, identity_file
, strerror(errno
));
734 if ((rsa
= PEM_read_RSAPublicKey(fp
, NULL
, NULL
, NULL
)) != NULL
) {
735 if ((*k
= sshkey_new(KEY_UNSPEC
)) == NULL
)
736 fatal("sshkey_new failed");
737 (*k
)->type
= KEY_RSA
;
742 fatal_f("unrecognised raw private key format");
746 do_convert_from(struct passwd
*pw
)
748 struct sshkey
*k
= NULL
;
749 int r
, private = 0, ok
= 0;
753 ask_filename(pw
, "Enter file in which the key is");
754 if (stat(identity_file
, &st
) == -1)
755 fatal("%s: %s: %s", __progname
, identity_file
, strerror(errno
));
757 switch (convert_format
) {
759 do_convert_from_ssh2(pw
, &k
, &private);
762 do_convert_from_pkcs8(&k
, &private);
765 do_convert_from_pem(&k
, &private);
768 fatal_f("unknown key format %d", convert_format
);
772 if ((r
= sshkey_write(k
, stdout
)) == 0)
775 fprintf(stdout
, "\n");
779 ok
= PEM_write_DSAPrivateKey(stdout
, k
->dsa
, NULL
,
780 NULL
, 0, NULL
, NULL
);
782 #ifdef OPENSSL_HAS_ECC
784 ok
= PEM_write_ECPrivateKey(stdout
, k
->ecdsa
, NULL
,
785 NULL
, 0, NULL
, NULL
);
789 ok
= PEM_write_RSAPrivateKey(stdout
, k
->rsa
, NULL
,
790 NULL
, 0, NULL
, NULL
);
793 fatal_f("unsupported key type %s", sshkey_type(k
));
798 fatal("key write failed");
805 do_print_public(struct passwd
*pw
)
810 char *comment
= NULL
;
813 ask_filename(pw
, "Enter file in which the key is");
814 if (stat(identity_file
, &st
) == -1)
815 fatal("%s: %s", identity_file
, strerror(errno
));
816 prv
= load_identity(identity_file
, &comment
);
817 if ((r
= sshkey_write(prv
, stdout
)) != 0)
818 fatal_fr(r
, "write key");
819 if (comment
!= NULL
&& *comment
!= '\0')
820 fprintf(stdout
, " %s", comment
);
821 fprintf(stdout
, "\n");
822 if (sshkey_is_sk(prv
)) {
823 debug("sk_application: \"%s\", sk_flags 0x%02x",
824 prv
->sk_application
, prv
->sk_flags
);
832 do_download(struct passwd
*pw
)
835 struct sshkey
**keys
= NULL
;
837 enum sshkey_fp_rep rep
;
839 char *fp
, *ra
, **comments
= NULL
;
841 fptype
= print_bubblebabble
? SSH_DIGEST_SHA1
: fingerprint_hash
;
842 rep
= print_bubblebabble
? SSH_FP_BUBBLEBABBLE
: SSH_FP_DEFAULT
;
845 nkeys
= pkcs11_add_provider(pkcs11provider
, NULL
, &keys
, &comments
);
847 fatal("cannot read public key from pkcs11");
848 for (i
= 0; i
< nkeys
; i
++) {
849 if (print_fingerprint
) {
850 fp
= sshkey_fingerprint(keys
[i
], fptype
, rep
);
851 ra
= sshkey_fingerprint(keys
[i
], fingerprint_hash
,
853 if (fp
== NULL
|| ra
== NULL
)
854 fatal_f("sshkey_fingerprint fail");
855 printf("%u %s %s (PKCS11 key)\n", sshkey_size(keys
[i
]),
856 fp
, sshkey_type(keys
[i
]));
857 if (log_level_get() >= SYSLOG_LEVEL_VERBOSE
)
862 (void) sshkey_write(keys
[i
], stdout
); /* XXX check */
863 fprintf(stdout
, "%s%s\n",
864 *(comments
[i
]) == '\0' ? "" : " ", comments
[i
]);
867 sshkey_free(keys
[i
]);
874 fatal("no pkcs11 support");
875 #endif /* ENABLE_PKCS11 */
878 static struct sshkey
*
879 try_read_key(char **cpp
)
884 if ((ret
= sshkey_new(KEY_UNSPEC
)) == NULL
)
885 fatal("sshkey_new failed");
886 if ((r
= sshkey_read(ret
, cpp
)) == 0)
894 fingerprint_one_key(const struct sshkey
*public, const char *comment
)
896 char *fp
= NULL
, *ra
= NULL
;
897 enum sshkey_fp_rep rep
;
900 fptype
= print_bubblebabble
? SSH_DIGEST_SHA1
: fingerprint_hash
;
901 rep
= print_bubblebabble
? SSH_FP_BUBBLEBABBLE
: SSH_FP_DEFAULT
;
902 fp
= sshkey_fingerprint(public, fptype
, rep
);
903 ra
= sshkey_fingerprint(public, fingerprint_hash
, SSH_FP_RANDOMART
);
904 if (fp
== NULL
|| ra
== NULL
)
905 fatal_f("sshkey_fingerprint failed");
906 mprintf("%u %s %s (%s)\n", sshkey_size(public), fp
,
907 comment
? comment
: "no comment", sshkey_type(public));
908 if (log_level_get() >= SYSLOG_LEVEL_VERBOSE
)
915 fingerprint_private(const char *path
)
918 char *comment
= NULL
;
919 struct sshkey
*privkey
= NULL
, *pubkey
= NULL
;
922 if (stat(identity_file
, &st
) == -1)
923 fatal("%s: %s", path
, strerror(errno
));
924 if ((r
= sshkey_load_public(path
, &pubkey
, &comment
)) != 0)
925 debug_r(r
, "load public \"%s\"", path
);
926 if (pubkey
== NULL
|| comment
== NULL
|| *comment
== '\0') {
928 if ((r
= sshkey_load_private(path
, NULL
,
929 &privkey
, &comment
)) != 0)
930 debug_r(r
, "load private \"%s\"", path
);
932 if (pubkey
== NULL
&& privkey
== NULL
)
933 fatal("%s is not a key file.", path
);
935 fingerprint_one_key(pubkey
== NULL
? privkey
: pubkey
, comment
);
937 sshkey_free(privkey
);
942 do_fingerprint(struct passwd
*pw
)
945 struct sshkey
*public = NULL
;
946 char *comment
= NULL
, *cp
, *ep
, *line
= NULL
;
953 ask_filename(pw
, "Enter file in which the key is");
954 path
= identity_file
;
956 if (strcmp(identity_file
, "-") == 0) {
959 } else if ((f
= fopen(path
, "r")) == NULL
)
960 fatal("%s: %s: %s", __progname
, path
, strerror(errno
));
962 while (getline(&line
, &linesize
, f
) != -1) {
965 cp
[strcspn(cp
, "\n")] = '\0';
966 /* Trim leading space and comments */
967 cp
= line
+ strspn(line
, " \t");
968 if (*cp
== '#' || *cp
== '\0')
972 * Input may be plain keys, private keys, authorized_keys
977 * Try private keys first. Assume a key is private if
978 * "SSH PRIVATE KEY" appears on the first line and we're
979 * not reading from stdin (XXX support private keys on stdin).
981 if (lnum
== 1 && strcmp(identity_file
, "-") != 0 &&
982 strstr(cp
, "PRIVATE KEY") != NULL
) {
985 fingerprint_private(path
);
990 * If it's not a private key, then this must be prepared to
991 * accept a public key prefixed with a hostname or options.
992 * Try a bare key first, otherwise skip the leading stuff.
994 if ((public = try_read_key(&cp
)) == NULL
) {
995 i
= strtol(cp
, &ep
, 10);
996 if (i
== 0 || ep
== NULL
||
997 (*ep
!= ' ' && *ep
!= '\t')) {
1001 for (; *cp
&& (quoted
|| (*cp
!= ' ' &&
1002 *cp
!= '\t')); cp
++) {
1003 if (*cp
== '\\' && cp
[1] == '"')
1004 cp
++; /* Skip both */
1005 else if (*cp
== '"')
1013 /* Retry after parsing leading hostname/key options */
1014 if (public == NULL
&& (public = try_read_key(&cp
)) == NULL
) {
1015 debug("%s:%lu: not a public key", path
, lnum
);
1019 /* Find trailing comment, if any */
1020 for (; *cp
== ' ' || *cp
== '\t'; cp
++)
1022 if (*cp
!= '\0' && *cp
!= '#')
1025 fingerprint_one_key(public, comment
);
1026 sshkey_free(public);
1027 invalid
= 0; /* One good key in the file is sufficient */
1033 fatal("%s is not a public key file.", path
);
1038 do_gen_all_hostkeys(struct passwd
*pw
)
1042 char *key_type_display
;
1046 { "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE
},
1047 { "dsa", "DSA", _PATH_HOST_DSA_KEY_FILE
},
1048 #ifdef OPENSSL_HAS_ECC
1049 { "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE
},
1050 #endif /* OPENSSL_HAS_ECC */
1051 #endif /* WITH_OPENSSL */
1052 { "ed25519", "ED25519",_PATH_HOST_ED25519_KEY_FILE
},
1054 { "xmss", "XMSS",_PATH_HOST_XMSS_KEY_FILE
},
1055 #endif /* WITH_XMSS */
1056 { NULL
, NULL
, NULL
}
1062 struct sshkey
*private, *public;
1063 char comment
[1024], *prv_tmp
, *pub_tmp
, *prv_file
, *pub_file
;
1066 for (i
= 0; key_types
[i
].key_type
; i
++) {
1067 public = private = NULL
;
1068 prv_tmp
= pub_tmp
= prv_file
= pub_file
= NULL
;
1070 xasprintf(&prv_file
, "%s%s",
1071 identity_file
, key_types
[i
].path
);
1073 /* Check whether private key exists and is not zero-length */
1074 if (stat(prv_file
, &st
) == 0) {
1075 if (st
.st_size
!= 0)
1077 } else if (errno
!= ENOENT
) {
1078 error("Could not stat %s: %s", key_types
[i
].path
,
1084 * Private key doesn't exist or is invalid; proceed with
1087 xasprintf(&prv_tmp
, "%s%s.XXXXXXXXXX",
1088 identity_file
, key_types
[i
].path
);
1089 xasprintf(&pub_tmp
, "%s%s.pub.XXXXXXXXXX",
1090 identity_file
, key_types
[i
].path
);
1091 xasprintf(&pub_file
, "%s%s.pub",
1092 identity_file
, key_types
[i
].path
);
1096 printf("%s: generating new host keys: ", __progname
);
1098 printf("%s ", key_types
[i
].key_type_display
);
1100 type
= sshkey_type_from_name(key_types
[i
].key_type
);
1101 if ((fd
= mkstemp(prv_tmp
)) == -1) {
1102 error("Could not save your private key in %s: %s",
1103 prv_tmp
, strerror(errno
));
1106 (void)close(fd
); /* just using mkstemp() to reserve a name */
1108 type_bits_valid(type
, NULL
, &bits
);
1109 if ((r
= sshkey_generate(type
, bits
, &private)) != 0) {
1110 error_r(r
, "sshkey_generate failed");
1113 if ((r
= sshkey_from_private(private, &public)) != 0)
1114 fatal_fr(r
, "sshkey_from_private");
1115 snprintf(comment
, sizeof comment
, "%s@%s", pw
->pw_name
,
1117 if ((r
= sshkey_save_private(private, prv_tmp
, "",
1118 comment
, private_key_format
, openssh_format_cipher
,
1120 error_r(r
, "Saving key \"%s\" failed", prv_tmp
);
1123 if ((fd
= mkstemp(pub_tmp
)) == -1) {
1124 error("Could not save your public key in %s: %s",
1125 pub_tmp
, strerror(errno
));
1128 (void)fchmod(fd
, 0644);
1130 if ((r
= sshkey_save_public(public, pub_tmp
, comment
)) != 0) {
1131 error_r(r
, "Unable to save public key to %s",
1136 /* Rename temporary files to their permanent locations. */
1137 if (rename(pub_tmp
, pub_file
) != 0) {
1138 error("Unable to move %s into position: %s",
1139 pub_file
, strerror(errno
));
1142 if (rename(prv_tmp
, prv_file
) != 0) {
1143 error("Unable to move %s into position: %s",
1144 key_types
[i
].path
, strerror(errno
));
1150 sshkey_free(private);
1151 sshkey_free(public);
1161 struct known_hosts_ctx
{
1162 const char *host
; /* Hostname searched for in find/delete case */
1163 FILE *out
; /* Output file, stdout for find_hosts case */
1164 int has_unhashed
; /* When hashing, original had unhashed hosts */
1165 int found_key
; /* For find/delete, host was found */
1166 int invalid
; /* File contained invalid items; don't delete */
1167 int hash_hosts
; /* Hash hostnames as we go */
1168 int find_host
; /* Search for specific hostname */
1169 int delete_host
; /* Delete host from known_hosts */
1173 known_hosts_hash(struct hostkey_foreach_line
*l
, void *_ctx
)
1175 struct known_hosts_ctx
*ctx
= (struct known_hosts_ctx
*)_ctx
;
1176 char *hashed
, *cp
, *hosts
, *ohosts
;
1177 int has_wild
= l
->hosts
&& strcspn(l
->hosts
, "*?!") != strlen(l
->hosts
);
1178 int was_hashed
= l
->hosts
&& l
->hosts
[0] == HASH_DELIM
;
1180 switch (l
->status
) {
1182 case HKF_STATUS_MATCHED
:
1184 * Don't hash hosts already already hashed, with wildcard
1185 * characters or a CA/revocation marker.
1187 if (was_hashed
|| has_wild
|| l
->marker
!= MRK_NONE
) {
1188 fprintf(ctx
->out
, "%s\n", l
->line
);
1189 if (has_wild
&& !ctx
->find_host
) {
1190 logit("%s:%lu: ignoring host name "
1191 "with wildcard: %.64s", l
->path
,
1192 l
->linenum
, l
->hosts
);
1197 * Split any comma-separated hostnames from the host list,
1198 * hash and store separately.
1200 ohosts
= hosts
= xstrdup(l
->hosts
);
1201 while ((cp
= strsep(&hosts
, ",")) != NULL
&& *cp
!= '\0') {
1203 if ((hashed
= host_hash(cp
, NULL
, 0)) == NULL
)
1204 fatal("hash_host failed");
1205 fprintf(ctx
->out
, "%s %s\n", hashed
, l
->rawkey
);
1206 ctx
->has_unhashed
= 1;
1210 case HKF_STATUS_INVALID
:
1211 /* Retain invalid lines, but mark file as invalid. */
1213 logit("%s:%lu: invalid line", l
->path
, l
->linenum
);
1216 fprintf(ctx
->out
, "%s\n", l
->line
);
1224 known_hosts_find_delete(struct hostkey_foreach_line
*l
, void *_ctx
)
1226 struct known_hosts_ctx
*ctx
= (struct known_hosts_ctx
*)_ctx
;
1227 enum sshkey_fp_rep rep
;
1229 char *fp
= NULL
, *ra
= NULL
;
1231 fptype
= print_bubblebabble
? SSH_DIGEST_SHA1
: fingerprint_hash
;
1232 rep
= print_bubblebabble
? SSH_FP_BUBBLEBABBLE
: SSH_FP_DEFAULT
;
1234 if (l
->status
== HKF_STATUS_MATCHED
) {
1235 if (ctx
->delete_host
) {
1236 if (l
->marker
!= MRK_NONE
) {
1237 /* Don't remove CA and revocation lines */
1238 fprintf(ctx
->out
, "%s\n", l
->line
);
1241 * Hostname matches and has no CA/revoke
1242 * marker, delete it by *not* writing the
1247 printf("# Host %s found: line %lu\n",
1248 ctx
->host
, l
->linenum
);
1251 } else if (ctx
->find_host
) {
1254 printf("# Host %s found: line %lu %s\n",
1256 l
->linenum
, l
->marker
== MRK_CA
? "CA" :
1257 (l
->marker
== MRK_REVOKE
? "REVOKED" : ""));
1259 if (ctx
->hash_hosts
)
1260 known_hosts_hash(l
, ctx
);
1261 else if (print_fingerprint
) {
1262 fp
= sshkey_fingerprint(l
->key
, fptype
, rep
);
1263 ra
= sshkey_fingerprint(l
->key
,
1264 fingerprint_hash
, SSH_FP_RANDOMART
);
1265 if (fp
== NULL
|| ra
== NULL
)
1266 fatal_f("sshkey_fingerprint failed");
1267 mprintf("%s %s %s%s%s\n", ctx
->host
,
1268 sshkey_type(l
->key
), fp
,
1269 l
->comment
[0] ? " " : "",
1271 if (log_level_get() >= SYSLOG_LEVEL_VERBOSE
)
1276 fprintf(ctx
->out
, "%s\n", l
->line
);
1279 } else if (ctx
->delete_host
) {
1280 /* Retain non-matching hosts when deleting */
1281 if (l
->status
== HKF_STATUS_INVALID
) {
1283 logit("%s:%lu: invalid line", l
->path
, l
->linenum
);
1285 fprintf(ctx
->out
, "%s\n", l
->line
);
1291 do_known_hosts(struct passwd
*pw
, const char *name
, int find_host
,
1292 int delete_host
, int hash_hosts
)
1294 char *cp
, tmp
[PATH_MAX
], old
[PATH_MAX
];
1295 int r
, fd
, oerrno
, inplace
= 0;
1296 struct known_hosts_ctx ctx
;
1297 u_int foreach_options
;
1300 if (!have_identity
) {
1301 cp
= tilde_expand_filename(_PATH_SSH_USER_HOSTFILE
, pw
->pw_uid
);
1302 if (strlcpy(identity_file
, cp
, sizeof(identity_file
)) >=
1303 sizeof(identity_file
))
1304 fatal("Specified known hosts path too long");
1308 if (stat(identity_file
, &sb
) != 0)
1309 fatal("Cannot stat %s: %s", identity_file
, strerror(errno
));
1311 memset(&ctx
, 0, sizeof(ctx
));
1314 ctx
.hash_hosts
= hash_hosts
;
1315 ctx
.find_host
= find_host
;
1316 ctx
.delete_host
= delete_host
;
1319 * Find hosts goes to stdout, hash and deletions happen in-place
1320 * A corner case is ssh-keygen -HF foo, which should go to stdout
1322 if (!find_host
&& (hash_hosts
|| delete_host
)) {
1323 if (strlcpy(tmp
, identity_file
, sizeof(tmp
)) >= sizeof(tmp
) ||
1324 strlcat(tmp
, ".XXXXXXXXXX", sizeof(tmp
)) >= sizeof(tmp
) ||
1325 strlcpy(old
, identity_file
, sizeof(old
)) >= sizeof(old
) ||
1326 strlcat(old
, ".old", sizeof(old
)) >= sizeof(old
))
1327 fatal("known_hosts path too long");
1329 if ((fd
= mkstemp(tmp
)) == -1)
1330 fatal("mkstemp: %s", strerror(errno
));
1331 if ((ctx
.out
= fdopen(fd
, "w")) == NULL
) {
1334 fatal("fdopen: %s", strerror(oerrno
));
1336 fchmod(fd
, sb
.st_mode
& 0644);
1339 /* XXX support identity_file == "-" for stdin */
1340 foreach_options
= find_host
? HKF_WANT_MATCH
: 0;
1341 foreach_options
|= print_fingerprint
? HKF_WANT_PARSE_KEY
: 0;
1342 if ((r
= hostkeys_foreach(identity_file
, (find_host
|| !hash_hosts
) ?
1343 known_hosts_find_delete
: known_hosts_hash
, &ctx
, name
, NULL
,
1344 foreach_options
, 0)) != 0) {
1347 fatal_fr(r
, "hostkeys_foreach");
1354 error("%s is not a valid known_hosts file.", identity_file
);
1356 error("Not replacing existing known_hosts "
1357 "file because of errors");
1361 } else if (delete_host
&& !ctx
.found_key
) {
1362 logit("Host %s not found in %s", name
, identity_file
);
1365 } else if (inplace
) {
1366 /* Backup existing file */
1367 if (unlink(old
) == -1 && errno
!= ENOENT
)
1368 fatal("unlink %.100s: %s", old
, strerror(errno
));
1369 if (link(identity_file
, old
) == -1)
1370 fatal("link %.100s to %.100s: %s", identity_file
, old
,
1372 /* Move new one into place */
1373 if (rename(tmp
, identity_file
) == -1) {
1374 error("rename\"%s\" to \"%s\": %s", tmp
, identity_file
,
1381 printf("%s updated.\n", identity_file
);
1382 printf("Original contents retained as %s\n", old
);
1383 if (ctx
.has_unhashed
) {
1384 logit("WARNING: %s contains unhashed entries", old
);
1385 logit("Delete this file to ensure privacy "
1390 exit (find_host
&& !ctx
.found_key
);
1394 * Perform changing a passphrase. The argument is the passwd structure
1395 * for the current user.
1398 do_change_passphrase(struct passwd
*pw
)
1401 char *old_passphrase
, *passphrase1
, *passphrase2
;
1403 struct sshkey
*private;
1407 ask_filename(pw
, "Enter file in which the key is");
1408 if (stat(identity_file
, &st
) == -1)
1409 fatal("%s: %s", identity_file
, strerror(errno
));
1410 /* Try to load the file with empty passphrase. */
1411 r
= sshkey_load_private(identity_file
, "", &private, &comment
);
1412 if (r
== SSH_ERR_KEY_WRONG_PASSPHRASE
) {
1413 if (identity_passphrase
)
1414 old_passphrase
= xstrdup(identity_passphrase
);
1417 read_passphrase("Enter old passphrase: ",
1419 r
= sshkey_load_private(identity_file
, old_passphrase
,
1420 &private, &comment
);
1421 freezero(old_passphrase
, strlen(old_passphrase
));
1424 } else if (r
!= 0) {
1426 fatal_r(r
, "Failed to load key %s", identity_file
);
1429 mprintf("Key has comment '%s'\n", comment
);
1431 /* Ask the new passphrase (twice). */
1432 if (identity_new_passphrase
) {
1433 passphrase1
= xstrdup(identity_new_passphrase
);
1437 read_passphrase("Enter new passphrase (empty for no "
1438 "passphrase): ", RP_ALLOW_STDIN
);
1439 passphrase2
= read_passphrase("Enter same passphrase again: ",
1442 /* Verify that they are the same. */
1443 if (strcmp(passphrase1
, passphrase2
) != 0) {
1444 explicit_bzero(passphrase1
, strlen(passphrase1
));
1445 explicit_bzero(passphrase2
, strlen(passphrase2
));
1448 printf("Pass phrases do not match. Try again.\n");
1451 /* Destroy the other copy. */
1452 freezero(passphrase2
, strlen(passphrase2
));
1455 /* Save the file using the new passphrase. */
1456 if ((r
= sshkey_save_private(private, identity_file
, passphrase1
,
1457 comment
, private_key_format
, openssh_format_cipher
, rounds
)) != 0) {
1458 error_r(r
, "Saving key \"%s\" failed", identity_file
);
1459 freezero(passphrase1
, strlen(passphrase1
));
1460 sshkey_free(private);
1464 /* Destroy the passphrase and the copy of the key in memory. */
1465 freezero(passphrase1
, strlen(passphrase1
));
1466 sshkey_free(private); /* Destroys contents */
1469 printf("Your identification has been saved with the new passphrase.\n");
1474 * Print the SSHFP RR.
1477 do_print_resource_record(struct passwd
*pw
, char *fname
, char *hname
,
1480 struct sshkey
*public;
1481 char *comment
= NULL
;
1486 fatal_f("no filename");
1487 if (stat(fname
, &st
) == -1) {
1488 if (errno
== ENOENT
)
1490 fatal("%s: %s", fname
, strerror(errno
));
1492 if ((r
= sshkey_load_public(fname
, &public, &comment
)) != 0)
1493 fatal_r(r
, "Failed to read v2 public key from \"%s\"", fname
);
1494 export_dns_rr(hname
, public, stdout
, print_generic
);
1495 sshkey_free(public);
1501 * Change the comment of a private key file.
1504 do_change_comment(struct passwd
*pw
, const char *identity_comment
)
1506 char new_comment
[1024], *comment
, *passphrase
;
1507 struct sshkey
*private;
1508 struct sshkey
*public;
1513 ask_filename(pw
, "Enter file in which the key is");
1514 if (stat(identity_file
, &st
) == -1)
1515 fatal("%s: %s", identity_file
, strerror(errno
));
1516 if ((r
= sshkey_load_private(identity_file
, "",
1517 &private, &comment
)) == 0)
1518 passphrase
= xstrdup("");
1519 else if (r
!= SSH_ERR_KEY_WRONG_PASSPHRASE
)
1520 fatal_r(r
, "Cannot load private key \"%s\"", identity_file
);
1522 if (identity_passphrase
)
1523 passphrase
= xstrdup(identity_passphrase
);
1524 else if (identity_new_passphrase
)
1525 passphrase
= xstrdup(identity_new_passphrase
);
1527 passphrase
= read_passphrase("Enter passphrase: ",
1529 /* Try to load using the passphrase. */
1530 if ((r
= sshkey_load_private(identity_file
, passphrase
,
1531 &private, &comment
)) != 0) {
1532 freezero(passphrase
, strlen(passphrase
));
1533 fatal_r(r
, "Cannot load private key \"%s\"",
1538 if (private->type
!= KEY_ED25519
&& private->type
!= KEY_XMSS
&&
1539 private_key_format
!= SSHKEY_PRIVATE_OPENSSH
) {
1540 error("Comments are only supported for keys stored in "
1541 "the new format (-o).");
1542 explicit_bzero(passphrase
, strlen(passphrase
));
1543 sshkey_free(private);
1547 printf("Old comment: %s\n", comment
);
1549 printf("No existing comment\n");
1551 if (identity_comment
) {
1552 strlcpy(new_comment
, identity_comment
, sizeof(new_comment
));
1554 printf("New comment: ");
1556 if (!fgets(new_comment
, sizeof(new_comment
), stdin
)) {
1557 explicit_bzero(passphrase
, strlen(passphrase
));
1558 sshkey_free(private);
1561 new_comment
[strcspn(new_comment
, "\n")] = '\0';
1563 if (comment
!= NULL
&& strcmp(comment
, new_comment
) == 0) {
1564 printf("No change to comment\n");
1566 sshkey_free(private);
1571 /* Save the file using the new passphrase. */
1572 if ((r
= sshkey_save_private(private, identity_file
, passphrase
,
1573 new_comment
, private_key_format
, openssh_format_cipher
,
1575 error_r(r
, "Saving key \"%s\" failed", identity_file
);
1576 freezero(passphrase
, strlen(passphrase
));
1577 sshkey_free(private);
1581 freezero(passphrase
, strlen(passphrase
));
1582 if ((r
= sshkey_from_private(private, &public)) != 0)
1583 fatal_fr(r
, "sshkey_from_private");
1584 sshkey_free(private);
1586 strlcat(identity_file
, ".pub", sizeof(identity_file
));
1587 if ((r
= sshkey_save_public(public, identity_file
, new_comment
)) != 0)
1588 fatal_r(r
, "Unable to save public key to %s", identity_file
);
1589 sshkey_free(public);
1592 if (strlen(new_comment
) > 0)
1593 printf("Comment '%s' applied\n", new_comment
);
1595 printf("Comment removed\n");
1601 cert_ext_add(const char *key
, const char *value
, int iscrit
)
1603 cert_ext
= xreallocarray(cert_ext
, ncert_ext
+ 1, sizeof(*cert_ext
));
1604 cert_ext
[ncert_ext
].key
= xstrdup(key
);
1605 cert_ext
[ncert_ext
].val
= value
== NULL
? NULL
: xstrdup(value
);
1606 cert_ext
[ncert_ext
].crit
= iscrit
;
1610 /* qsort(3) comparison function for certificate extensions */
1612 cert_ext_cmp(const void *_a
, const void *_b
)
1614 const struct cert_ext
*a
= (const struct cert_ext
*)_a
;
1615 const struct cert_ext
*b
= (const struct cert_ext
*)_b
;
1618 if (a
->crit
!= b
->crit
)
1619 return (a
->crit
< b
->crit
) ? -1 : 1;
1620 if ((r
= strcmp(a
->key
, b
->key
)) != 0)
1622 if ((a
->val
== NULL
) != (b
->val
== NULL
))
1623 return (a
->val
== NULL
) ? -1 : 1;
1624 if (a
->val
!= NULL
&& (r
= strcmp(a
->val
, b
->val
)) != 0)
1629 #define OPTIONS_CRITICAL 1
1630 #define OPTIONS_EXTENSIONS 2
1632 prepare_options_buf(struct sshbuf
*c
, int which
)
1637 const struct cert_ext
*ext
;
1639 if ((b
= sshbuf_new()) == NULL
)
1640 fatal_f("sshbuf_new failed");
1642 for (i
= 0; i
< ncert_ext
; i
++) {
1644 if ((ext
->crit
&& (which
& OPTIONS_EXTENSIONS
)) ||
1645 (!ext
->crit
&& (which
& OPTIONS_CRITICAL
)))
1647 if (ext
->val
== NULL
) {
1649 debug3_f("%s", ext
->key
);
1650 if ((r
= sshbuf_put_cstring(c
, ext
->key
)) != 0 ||
1651 (r
= sshbuf_put_string(c
, NULL
, 0)) != 0)
1652 fatal_fr(r
, "prepare flag");
1654 /* key/value option */
1655 debug3_f("%s=%s", ext
->key
, ext
->val
);
1657 if ((r
= sshbuf_put_cstring(c
, ext
->key
)) != 0 ||
1658 (r
= sshbuf_put_cstring(b
, ext
->val
)) != 0 ||
1659 (r
= sshbuf_put_stringb(c
, b
)) != 0)
1660 fatal_fr(r
, "prepare k/v");
1667 finalise_cert_exts(void)
1669 /* critical options */
1670 if (certflags_command
!= NULL
)
1671 cert_ext_add("force-command", certflags_command
, 1);
1672 if (certflags_src_addr
!= NULL
)
1673 cert_ext_add("source-address", certflags_src_addr
, 1);
1675 if ((certflags_flags
& CERTOPT_X_FWD
) != 0)
1676 cert_ext_add("permit-X11-forwarding", NULL
, 0);
1677 if ((certflags_flags
& CERTOPT_AGENT_FWD
) != 0)
1678 cert_ext_add("permit-agent-forwarding", NULL
, 0);
1679 if ((certflags_flags
& CERTOPT_PORT_FWD
) != 0)
1680 cert_ext_add("permit-port-forwarding", NULL
, 0);
1681 if ((certflags_flags
& CERTOPT_PTY
) != 0)
1682 cert_ext_add("permit-pty", NULL
, 0);
1683 if ((certflags_flags
& CERTOPT_USER_RC
) != 0)
1684 cert_ext_add("permit-user-rc", NULL
, 0);
1685 if ((certflags_flags
& CERTOPT_NO_REQUIRE_USER_PRESENCE
) != 0)
1686 cert_ext_add("no-touch-required", NULL
, 0);
1687 /* order lexically by key */
1689 qsort(cert_ext
, ncert_ext
, sizeof(*cert_ext
), cert_ext_cmp
);
1692 static struct sshkey
*
1693 load_pkcs11_key(char *path
)
1695 #ifdef ENABLE_PKCS11
1696 struct sshkey
**keys
= NULL
, *public, *private = NULL
;
1699 if ((r
= sshkey_load_public(path
, &public, NULL
)) != 0)
1700 fatal_r(r
, "Couldn't load CA public key \"%s\"", path
);
1702 nkeys
= pkcs11_add_provider(pkcs11provider
, identity_passphrase
,
1704 debug3_f("%d keys", nkeys
);
1706 fatal("cannot read public key from pkcs11");
1707 for (i
= 0; i
< nkeys
; i
++) {
1708 if (sshkey_equal_public(public, keys
[i
])) {
1712 sshkey_free(keys
[i
]);
1715 sshkey_free(public);
1718 fatal("no pkcs11 support");
1719 #endif /* ENABLE_PKCS11 */
1722 /* Signer for sshkey_certify_custom that uses the agent */
1724 agent_signer(struct sshkey
*key
, u_char
**sigp
, size_t *lenp
,
1725 const u_char
*data
, size_t datalen
,
1726 const char *alg
, const char *provider
, const char *pin
,
1727 u_int compat
, void *ctx
)
1729 int *agent_fdp
= (int *)ctx
;
1731 return ssh_agent_sign(*agent_fdp
, key
, sigp
, lenp
,
1732 data
, datalen
, alg
, compat
);
1736 do_ca_sign(struct passwd
*pw
, const char *ca_key_path
, int prefer_agent
,
1737 unsigned long long cert_serial
, int cert_serial_autoinc
,
1738 int argc
, char **argv
)
1740 int r
, i
, found
, agent_fd
= -1;
1742 struct sshkey
*ca
, *public;
1743 char valid
[64], *otmp
, *tmp
, *cp
, *out
, *comment
;
1744 char *ca_fp
= NULL
, **plist
= NULL
, *pin
= NULL
;
1745 struct ssh_identitylist
*agent_ids
;
1747 struct notifier_ctx
*notifier
= NULL
;
1749 #ifdef ENABLE_PKCS11
1752 tmp
= tilde_expand_filename(ca_key_path
, pw
->pw_uid
);
1753 if (pkcs11provider
!= NULL
) {
1754 /* If a PKCS#11 token was specified then try to use it */
1755 if ((ca
= load_pkcs11_key(tmp
)) == NULL
)
1756 fatal("No PKCS#11 key matching %s found", ca_key_path
);
1757 } else if (prefer_agent
) {
1759 * Agent signature requested. Try to use agent after making
1760 * sure the public key specified is actually present in the
1763 if ((r
= sshkey_load_public(tmp
, &ca
, NULL
)) != 0)
1764 fatal_r(r
, "Cannot load CA public key %s", tmp
);
1765 if ((r
= ssh_get_authentication_socket(&agent_fd
)) != 0)
1766 fatal_r(r
, "Cannot use public key for CA signature");
1767 if ((r
= ssh_fetch_identitylist(agent_fd
, &agent_ids
)) != 0)
1768 fatal_r(r
, "Retrieve agent key list");
1770 for (j
= 0; j
< agent_ids
->nkeys
; j
++) {
1771 if (sshkey_equal(ca
, agent_ids
->keys
[j
])) {
1777 fatal("CA key %s not found in agent", tmp
);
1778 ssh_free_identitylist(agent_ids
);
1779 ca
->flags
|= SSHKEY_FLAG_EXT
;
1781 /* CA key is assumed to be a private key on the filesystem */
1782 ca
= load_identity(tmp
, NULL
);
1783 if (sshkey_is_sk(ca
) &&
1784 (ca
->sk_flags
& SSH_SK_USER_VERIFICATION_REQD
)) {
1785 if ((pin
= read_passphrase("Enter PIN for CA key: ",
1786 RP_ALLOW_STDIN
)) == NULL
)
1787 fatal_f("couldn't read PIN");
1792 if (key_type_name
!= NULL
) {
1793 if (sshkey_type_from_name(key_type_name
) != ca
->type
) {
1794 fatal("CA key type %s doesn't match specified %s",
1795 sshkey_ssh_name(ca
), key_type_name
);
1797 } else if (ca
->type
== KEY_RSA
) {
1798 /* Default to a good signature algorithm */
1799 key_type_name
= "rsa-sha2-512";
1801 ca_fp
= sshkey_fingerprint(ca
, fingerprint_hash
, SSH_FP_DEFAULT
);
1803 finalise_cert_exts();
1804 for (i
= 0; i
< argc
; i
++) {
1805 /* Split list of principals */
1807 if (cert_principals
!= NULL
) {
1808 otmp
= tmp
= xstrdup(cert_principals
);
1810 for (; (cp
= strsep(&tmp
, ",")) != NULL
; n
++) {
1811 plist
= xreallocarray(plist
, n
+ 1, sizeof(*plist
));
1812 if (*(plist
[n
] = xstrdup(cp
)) == '\0')
1813 fatal("Empty principal name");
1817 if (n
> SSHKEY_CERT_MAX_PRINCIPALS
)
1818 fatal("Too many certificate principals specified");
1820 tmp
= tilde_expand_filename(argv
[i
], pw
->pw_uid
);
1821 if ((r
= sshkey_load_public(tmp
, &public, &comment
)) != 0)
1822 fatal_r(r
, "load pubkey \"%s\"", tmp
);
1823 if (sshkey_is_cert(public))
1824 fatal_f("key \"%s\" type %s cannot be certified",
1825 tmp
, sshkey_type(public));
1827 /* Prepare certificate to sign */
1828 if ((r
= sshkey_to_certified(public)) != 0)
1829 fatal_r(r
, "Could not upgrade key %s to certificate", tmp
);
1830 public->cert
->type
= cert_key_type
;
1831 public->cert
->serial
= (u_int64_t
)cert_serial
;
1832 public->cert
->key_id
= xstrdup(cert_key_id
);
1833 public->cert
->nprincipals
= n
;
1834 public->cert
->principals
= plist
;
1835 public->cert
->valid_after
= cert_valid_from
;
1836 public->cert
->valid_before
= cert_valid_to
;
1837 prepare_options_buf(public->cert
->critical
, OPTIONS_CRITICAL
);
1838 prepare_options_buf(public->cert
->extensions
,
1839 OPTIONS_EXTENSIONS
);
1840 if ((r
= sshkey_from_private(ca
,
1841 &public->cert
->signature_key
)) != 0)
1842 fatal_r(r
, "sshkey_from_private (ca key)");
1844 if (agent_fd
!= -1 && (ca
->flags
& SSHKEY_FLAG_EXT
) != 0) {
1845 if ((r
= sshkey_certify_custom(public, ca
,
1846 key_type_name
, sk_provider
, NULL
, agent_signer
,
1848 fatal_r(r
, "Couldn't certify %s via agent", tmp
);
1850 if (sshkey_is_sk(ca
) &&
1851 (ca
->sk_flags
& SSH_SK_USER_PRESENCE_REQD
)) {
1852 notifier
= notify_start(0,
1853 "Confirm user presence for key %s %s",
1854 sshkey_type(ca
), ca_fp
);
1856 r
= sshkey_certify(public, ca
, key_type_name
,
1858 notify_complete(notifier
, "User presence confirmed");
1860 fatal_r(r
, "Couldn't certify key %s", tmp
);
1863 if ((cp
= strrchr(tmp
, '.')) != NULL
&& strcmp(cp
, ".pub") == 0)
1865 xasprintf(&out
, "%s-cert.pub", tmp
);
1868 if ((r
= sshkey_save_public(public, out
, comment
)) != 0) {
1869 fatal_r(r
, "Unable to save public key to %s",
1874 sshkey_format_cert_validity(public->cert
,
1875 valid
, sizeof(valid
));
1876 logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1877 "valid %s", sshkey_cert_type(public),
1878 out
, public->cert
->key_id
,
1879 (unsigned long long)public->cert
->serial
,
1880 cert_principals
!= NULL
? " for " : "",
1881 cert_principals
!= NULL
? cert_principals
: "",
1885 sshkey_free(public);
1887 if (cert_serial_autoinc
)
1891 freezero(pin
, strlen(pin
));
1893 #ifdef ENABLE_PKCS11
1900 parse_relative_time(const char *s
, time_t now
)
1904 mul
= *s
== '-' ? -1 : 1;
1906 if ((secs
= convtime(s
+ 1)) == -1)
1907 fatal("Invalid relative certificate time %s", s
);
1908 if (mul
== -1 && secs
> now
)
1909 fatal("Certificate time %s cannot be represented", s
);
1910 return now
+ (u_int64_t
)(secs
* mul
);
1914 parse_cert_times(char *timespec
)
1917 time_t now
= time(NULL
);
1920 /* +timespec relative to now */
1921 if (*timespec
== '+' && strchr(timespec
, ':') == NULL
) {
1922 if ((secs
= convtime(timespec
+ 1)) == -1)
1923 fatal("Invalid relative certificate life %s", timespec
);
1924 cert_valid_to
= now
+ secs
;
1926 * Backdate certificate one minute to avoid problems on hosts
1927 * with poorly-synchronised clocks.
1929 cert_valid_from
= ((now
- 59)/ 60) * 60;
1935 * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "always"
1936 * to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "forever"
1938 from
= xstrdup(timespec
);
1939 to
= strchr(from
, ':');
1940 if (to
== NULL
|| from
== to
|| *(to
+ 1) == '\0')
1941 fatal("Invalid certificate life specification %s", timespec
);
1944 if (*from
== '-' || *from
== '+')
1945 cert_valid_from
= parse_relative_time(from
, now
);
1946 else if (strcmp(from
, "always") == 0)
1947 cert_valid_from
= 0;
1948 else if (parse_absolute_time(from
, &cert_valid_from
) != 0)
1949 fatal("Invalid from time \"%s\"", from
);
1951 if (*to
== '-' || *to
== '+')
1952 cert_valid_to
= parse_relative_time(to
, now
);
1953 else if (strcmp(to
, "forever") == 0)
1954 cert_valid_to
= ~(u_int64_t
)0;
1955 else if (parse_absolute_time(to
, &cert_valid_to
) != 0)
1956 fatal("Invalid to time \"%s\"", to
);
1958 if (cert_valid_to
<= cert_valid_from
)
1959 fatal("Empty certificate validity interval");
1964 add_cert_option(char *opt
)
1969 if (strcasecmp(opt
, "clear") == 0)
1970 certflags_flags
= 0;
1971 else if (strcasecmp(opt
, "no-x11-forwarding") == 0)
1972 certflags_flags
&= ~CERTOPT_X_FWD
;
1973 else if (strcasecmp(opt
, "permit-x11-forwarding") == 0)
1974 certflags_flags
|= CERTOPT_X_FWD
;
1975 else if (strcasecmp(opt
, "no-agent-forwarding") == 0)
1976 certflags_flags
&= ~CERTOPT_AGENT_FWD
;
1977 else if (strcasecmp(opt
, "permit-agent-forwarding") == 0)
1978 certflags_flags
|= CERTOPT_AGENT_FWD
;
1979 else if (strcasecmp(opt
, "no-port-forwarding") == 0)
1980 certflags_flags
&= ~CERTOPT_PORT_FWD
;
1981 else if (strcasecmp(opt
, "permit-port-forwarding") == 0)
1982 certflags_flags
|= CERTOPT_PORT_FWD
;
1983 else if (strcasecmp(opt
, "no-pty") == 0)
1984 certflags_flags
&= ~CERTOPT_PTY
;
1985 else if (strcasecmp(opt
, "permit-pty") == 0)
1986 certflags_flags
|= CERTOPT_PTY
;
1987 else if (strcasecmp(opt
, "no-user-rc") == 0)
1988 certflags_flags
&= ~CERTOPT_USER_RC
;
1989 else if (strcasecmp(opt
, "permit-user-rc") == 0)
1990 certflags_flags
|= CERTOPT_USER_RC
;
1991 else if (strcasecmp(opt
, "touch-required") == 0)
1992 certflags_flags
&= ~CERTOPT_NO_REQUIRE_USER_PRESENCE
;
1993 else if (strcasecmp(opt
, "no-touch-required") == 0)
1994 certflags_flags
|= CERTOPT_NO_REQUIRE_USER_PRESENCE
;
1995 else if (strncasecmp(opt
, "force-command=", 14) == 0) {
1998 fatal("Empty force-command option");
1999 if (certflags_command
!= NULL
)
2000 fatal("force-command already specified");
2001 certflags_command
= xstrdup(val
);
2002 } else if (strncasecmp(opt
, "source-address=", 15) == 0) {
2005 fatal("Empty source-address option");
2006 if (certflags_src_addr
!= NULL
)
2007 fatal("source-address already specified");
2008 if (addr_match_cidr_list(NULL
, val
) != 0)
2009 fatal("Invalid source-address list");
2010 certflags_src_addr
= xstrdup(val
);
2011 } else if (strncasecmp(opt
, "extension:", 10) == 0 ||
2012 (iscrit
= (strncasecmp(opt
, "critical:", 9) == 0))) {
2013 val
= xstrdup(strchr(opt
, ':') + 1);
2014 if ((cp
= strchr(val
, '=')) != NULL
)
2016 cert_ext_add(val
, cp
, iscrit
);
2019 fatal("Unsupported certificate option \"%s\"", opt
);
2023 show_options(struct sshbuf
*optbuf
, int in_critical
)
2025 char *name
, *arg
, *hex
;
2026 struct sshbuf
*options
, *option
= NULL
;
2029 if ((options
= sshbuf_fromb(optbuf
)) == NULL
)
2030 fatal_f("sshbuf_fromb failed");
2031 while (sshbuf_len(options
) != 0) {
2032 sshbuf_free(option
);
2034 if ((r
= sshbuf_get_cstring(options
, &name
, NULL
)) != 0 ||
2035 (r
= sshbuf_froms(options
, &option
)) != 0)
2036 fatal_fr(r
, "parse option");
2037 printf(" %s", name
);
2039 (strcmp(name
, "permit-X11-forwarding") == 0 ||
2040 strcmp(name
, "permit-agent-forwarding") == 0 ||
2041 strcmp(name
, "permit-port-forwarding") == 0 ||
2042 strcmp(name
, "permit-pty") == 0 ||
2043 strcmp(name
, "permit-user-rc") == 0 ||
2044 strcmp(name
, "no-touch-required") == 0)) {
2046 } else if (in_critical
&&
2047 (strcmp(name
, "force-command") == 0 ||
2048 strcmp(name
, "source-address") == 0)) {
2049 if ((r
= sshbuf_get_cstring(option
, &arg
, NULL
)) != 0)
2050 fatal_fr(r
, "parse critical");
2051 printf(" %s\n", arg
);
2053 } else if (sshbuf_len(option
) > 0) {
2054 hex
= sshbuf_dtob16(option
);
2055 printf(" UNKNOWN OPTION: %s (len %zu)\n",
2056 hex
, sshbuf_len(option
));
2057 sshbuf_reset(option
);
2060 printf(" UNKNOWN FLAG OPTION\n");
2062 if (sshbuf_len(option
) != 0)
2063 fatal("Option corrupt: extra data at end");
2065 sshbuf_free(option
);
2066 sshbuf_free(options
);
2070 print_cert(struct sshkey
*key
)
2072 char valid
[64], *key_fp
, *ca_fp
;
2075 key_fp
= sshkey_fingerprint(key
, fingerprint_hash
, SSH_FP_DEFAULT
);
2076 ca_fp
= sshkey_fingerprint(key
->cert
->signature_key
,
2077 fingerprint_hash
, SSH_FP_DEFAULT
);
2078 if (key_fp
== NULL
|| ca_fp
== NULL
)
2079 fatal_f("sshkey_fingerprint fail");
2080 sshkey_format_cert_validity(key
->cert
, valid
, sizeof(valid
));
2082 printf(" Type: %s %s certificate\n", sshkey_ssh_name(key
),
2083 sshkey_cert_type(key
));
2084 printf(" Public key: %s %s\n", sshkey_type(key
), key_fp
);
2085 printf(" Signing CA: %s %s (using %s)\n",
2086 sshkey_type(key
->cert
->signature_key
), ca_fp
,
2087 key
->cert
->signature_type
);
2088 printf(" Key ID: \"%s\"\n", key
->cert
->key_id
);
2089 printf(" Serial: %llu\n", (unsigned long long)key
->cert
->serial
);
2090 printf(" Valid: %s\n", valid
);
2091 printf(" Principals: ");
2092 if (key
->cert
->nprincipals
== 0)
2095 for (i
= 0; i
< key
->cert
->nprincipals
; i
++)
2097 key
->cert
->principals
[i
]);
2100 printf(" Critical Options: ");
2101 if (sshbuf_len(key
->cert
->critical
) == 0)
2105 show_options(key
->cert
->critical
, 1);
2107 printf(" Extensions: ");
2108 if (sshbuf_len(key
->cert
->extensions
) == 0)
2112 show_options(key
->cert
->extensions
, 0);
2117 do_show_cert(struct passwd
*pw
)
2119 struct sshkey
*key
= NULL
;
2121 int r
, is_stdin
= 0, ok
= 0;
2123 char *cp
, *line
= NULL
;
2125 size_t linesize
= 0;
2129 ask_filename(pw
, "Enter file in which the key is");
2130 if (strcmp(identity_file
, "-") != 0 && stat(identity_file
, &st
) == -1)
2131 fatal("%s: %s: %s", __progname
, identity_file
, strerror(errno
));
2133 path
= identity_file
;
2134 if (strcmp(path
, "-") == 0) {
2138 } else if ((f
= fopen(identity_file
, "r")) == NULL
)
2139 fatal("fopen %s: %s", identity_file
, strerror(errno
));
2141 while (getline(&line
, &linesize
, f
) != -1) {
2145 /* Trim leading space and comments */
2146 cp
= line
+ strspn(line
, " \t");
2147 if (*cp
== '#' || *cp
== '\0')
2149 if ((key
= sshkey_new(KEY_UNSPEC
)) == NULL
)
2150 fatal("sshkey_new");
2151 if ((r
= sshkey_read(key
, &cp
)) != 0) {
2152 error_r(r
, "%s:%lu: invalid key", path
, lnum
);
2155 if (!sshkey_is_cert(key
)) {
2156 error("%s:%lu is not a certificate", path
, lnum
);
2160 if (!is_stdin
&& lnum
== 1)
2161 printf("%s:\n", path
);
2163 printf("%s:%lu:\n", path
, lnum
);
2173 load_krl(const char *path
, struct ssh_krl
**krlp
)
2175 struct sshbuf
*krlbuf
;
2178 if ((r
= sshbuf_load_file(path
, &krlbuf
)) != 0)
2179 fatal_r(r
, "Unable to load KRL %s", path
);
2180 /* XXX check sigs */
2181 if ((r
= ssh_krl_from_blob(krlbuf
, krlp
, NULL
, 0)) != 0 ||
2183 fatal_r(r
, "Invalid KRL file %s", path
);
2184 sshbuf_free(krlbuf
);
2188 hash_to_blob(const char *cp
, u_char
**blobp
, size_t *lenp
,
2189 const char *file
, u_long lnum
)
2196 if (strncmp(cp
, "SHA256:", 7) != 0)
2197 fatal("%s:%lu: unsupported hash algorithm", file
, lnum
);
2201 * OpenSSH base64 hashes omit trailing '='
2202 * characters; put them back for decode.
2205 tmp
= xmalloc(tlen
+ 4 + 1);
2206 strlcpy(tmp
, cp
, tlen
+ 1);
2207 while ((tlen
% 4) != 0) {
2211 if ((b
= sshbuf_new()) == NULL
)
2212 fatal_f("sshbuf_new failed");
2213 if ((r
= sshbuf_b64tod(b
, tmp
)) != 0)
2214 fatal_r(r
, "%s:%lu: decode hash failed", file
, lnum
);
2216 *lenp
= sshbuf_len(b
);
2217 *blobp
= xmalloc(*lenp
);
2218 memcpy(*blobp
, sshbuf_ptr(b
), *lenp
);
2223 update_krl_from_file(struct passwd
*pw
, const char *file
, int wild_ca
,
2224 const struct sshkey
*ca
, struct ssh_krl
*krl
)
2226 struct sshkey
*key
= NULL
;
2228 char *path
, *cp
, *ep
, *line
= NULL
;
2229 u_char
*blob
= NULL
;
2230 size_t blen
= 0, linesize
= 0;
2231 unsigned long long serial
, serial2
;
2232 int i
, was_explicit_key
, was_sha1
, was_sha256
, was_hash
, r
;
2235 path
= tilde_expand_filename(file
, pw
->pw_uid
);
2236 if (strcmp(path
, "-") == 0) {
2239 path
= xstrdup("(standard input)");
2240 } else if ((krl_spec
= fopen(path
, "r")) == NULL
)
2241 fatal("fopen %s: %s", path
, strerror(errno
));
2244 printf("Revoking from %s\n", path
);
2245 while (getline(&line
, &linesize
, krl_spec
) != -1) {
2247 was_explicit_key
= was_sha1
= was_sha256
= was_hash
= 0;
2248 cp
= line
+ strspn(line
, " \t");
2249 /* Trim trailing space, comments and strip \n */
2250 for (i
= 0, r
= -1; cp
[i
] != '\0'; i
++) {
2251 if (cp
[i
] == '#' || cp
[i
] == '\n') {
2255 if (cp
[i
] == ' ' || cp
[i
] == '\t') {
2256 /* Remember the start of a span of whitespace */
2266 if (strncasecmp(cp
, "serial:", 7) == 0) {
2267 if (ca
== NULL
&& !wild_ca
) {
2268 fatal("revoking certificates by serial number "
2269 "requires specification of a CA key");
2272 cp
= cp
+ strspn(cp
, " \t");
2274 serial
= strtoull(cp
, &ep
, 0);
2275 if (*cp
== '\0' || (*ep
!= '\0' && *ep
!= '-'))
2276 fatal("%s:%lu: invalid serial \"%s\"",
2278 if (errno
== ERANGE
&& serial
== ULLONG_MAX
)
2279 fatal("%s:%lu: serial out of range",
2285 serial2
= strtoull(cp
, &ep
, 0);
2286 if (*cp
== '\0' || *ep
!= '\0')
2287 fatal("%s:%lu: invalid serial \"%s\"",
2289 if (errno
== ERANGE
&& serial2
== ULLONG_MAX
)
2290 fatal("%s:%lu: serial out of range",
2292 if (serial2
<= serial
)
2293 fatal("%s:%lu: invalid serial range "
2294 "%llu:%llu", path
, lnum
,
2295 (unsigned long long)serial
,
2296 (unsigned long long)serial2
);
2298 if (ssh_krl_revoke_cert_by_serial_range(krl
,
2299 ca
, serial
, serial2
) != 0) {
2300 fatal_f("revoke serial failed");
2302 } else if (strncasecmp(cp
, "id:", 3) == 0) {
2303 if (ca
== NULL
&& !wild_ca
) {
2304 fatal("revoking certificates by key ID "
2305 "requires specification of a CA key");
2308 cp
= cp
+ strspn(cp
, " \t");
2309 if (ssh_krl_revoke_cert_by_key_id(krl
, ca
, cp
) != 0)
2310 fatal_f("revoke key ID failed");
2311 } else if (strncasecmp(cp
, "hash:", 5) == 0) {
2313 cp
= cp
+ strspn(cp
, " \t");
2314 hash_to_blob(cp
, &blob
, &blen
, file
, lnum
);
2315 r
= ssh_krl_revoke_key_sha256(krl
, blob
, blen
);
2317 fatal_fr(r
, "revoke key failed");
2319 if (strncasecmp(cp
, "key:", 4) == 0) {
2321 cp
= cp
+ strspn(cp
, " \t");
2322 was_explicit_key
= 1;
2323 } else if (strncasecmp(cp
, "sha1:", 5) == 0) {
2325 cp
= cp
+ strspn(cp
, " \t");
2327 } else if (strncasecmp(cp
, "sha256:", 7) == 0) {
2329 cp
= cp
+ strspn(cp
, " \t");
2332 * Just try to process the line as a key.
2333 * Parsing will fail if it isn't.
2336 if ((key
= sshkey_new(KEY_UNSPEC
)) == NULL
)
2337 fatal("sshkey_new");
2338 if ((r
= sshkey_read(key
, &cp
)) != 0)
2339 fatal_r(r
, "%s:%lu: invalid key", path
, lnum
);
2340 if (was_explicit_key
)
2341 r
= ssh_krl_revoke_key_explicit(krl
, key
);
2342 else if (was_sha1
) {
2343 if (sshkey_fingerprint_raw(key
,
2344 SSH_DIGEST_SHA1
, &blob
, &blen
) != 0) {
2345 fatal("%s:%lu: fingerprint failed",
2348 r
= ssh_krl_revoke_key_sha1(krl
, blob
, blen
);
2349 } else if (was_sha256
) {
2350 if (sshkey_fingerprint_raw(key
,
2351 SSH_DIGEST_SHA256
, &blob
, &blen
) != 0) {
2352 fatal("%s:%lu: fingerprint failed",
2355 r
= ssh_krl_revoke_key_sha256(krl
, blob
, blen
);
2357 r
= ssh_krl_revoke_key(krl
, key
);
2359 fatal_fr(r
, "revoke key failed");
2360 freezero(blob
, blen
);
2366 if (strcmp(path
, "-") != 0)
2373 do_gen_krl(struct passwd
*pw
, int updating
, const char *ca_key_path
,
2374 unsigned long long krl_version
, const char *krl_comment
,
2375 int argc
, char **argv
)
2377 struct ssh_krl
*krl
;
2379 struct sshkey
*ca
= NULL
;
2380 int i
, r
, wild_ca
= 0;
2382 struct sshbuf
*kbuf
;
2384 if (*identity_file
== '\0')
2385 fatal("KRL generation requires an output file");
2386 if (stat(identity_file
, &sb
) == -1) {
2387 if (errno
!= ENOENT
)
2388 fatal("Cannot access KRL \"%s\": %s",
2389 identity_file
, strerror(errno
));
2391 fatal("KRL \"%s\" does not exist", identity_file
);
2393 if (ca_key_path
!= NULL
) {
2394 if (strcasecmp(ca_key_path
, "none") == 0)
2397 tmp
= tilde_expand_filename(ca_key_path
, pw
->pw_uid
);
2398 if ((r
= sshkey_load_public(tmp
, &ca
, NULL
)) != 0)
2399 fatal_r(r
, "Cannot load CA public key %s", tmp
);
2405 load_krl(identity_file
, &krl
);
2406 else if ((krl
= ssh_krl_init()) == NULL
)
2407 fatal("couldn't create KRL");
2409 if (krl_version
!= 0)
2410 ssh_krl_set_version(krl
, krl_version
);
2411 if (krl_comment
!= NULL
)
2412 ssh_krl_set_comment(krl
, krl_comment
);
2414 for (i
= 0; i
< argc
; i
++)
2415 update_krl_from_file(pw
, argv
[i
], wild_ca
, ca
, krl
);
2417 if ((kbuf
= sshbuf_new()) == NULL
)
2418 fatal("sshbuf_new failed");
2419 if (ssh_krl_to_blob(krl
, kbuf
, NULL
, 0) != 0)
2420 fatal("Couldn't generate KRL");
2421 if ((r
= sshbuf_write_file(identity_file
, kbuf
)) != 0)
2422 fatal("write %s: %s", identity_file
, strerror(errno
));
2429 do_check_krl(struct passwd
*pw
, int print_krl
, int argc
, char **argv
)
2433 struct ssh_krl
*krl
;
2436 if (*identity_file
== '\0')
2437 fatal("KRL checking requires an input file");
2438 load_krl(identity_file
, &krl
);
2440 krl_dump(krl
, stdout
);
2441 for (i
= 0; i
< argc
; i
++) {
2442 if ((r
= sshkey_load_public(argv
[i
], &k
, &comment
)) != 0)
2443 fatal_r(r
, "Cannot load public key %s", argv
[i
]);
2444 r
= ssh_krl_check_key(krl
, k
);
2445 printf("%s%s%s%s: %s\n", argv
[i
],
2446 *comment
? " (" : "", comment
, *comment
? ")" : "",
2447 r
== 0 ? "ok" : "REVOKED");
2457 static struct sshkey
*
2458 load_sign_key(const char *keypath
, const struct sshkey
*pubkey
)
2460 size_t i
, slen
, plen
= strlen(keypath
);
2461 char *privpath
= xstrdup(keypath
);
2462 const char *suffixes
[] = { "-cert.pub", ".pub", NULL
};
2463 struct sshkey
*ret
= NULL
, *privkey
= NULL
;
2467 * If passed a public key filename, then try to locate the corresponding
2468 * private key. This lets us specify certificates on the command-line
2469 * and have ssh-keygen find the appropriate private key.
2471 for (i
= 0; suffixes
[i
]; i
++) {
2472 slen
= strlen(suffixes
[i
]);
2474 strcmp(privpath
+ plen
- slen
, suffixes
[i
]) != 0)
2476 privpath
[plen
- slen
] = '\0';
2477 debug_f("%s looks like a public key, using private key "
2478 "path %s instead", keypath
, privpath
);
2480 if ((privkey
= load_identity(privpath
, NULL
)) == NULL
) {
2481 error("Couldn't load identity %s", keypath
);
2484 if (!sshkey_equal_public(pubkey
, privkey
)) {
2485 error("Public key %s doesn't match private %s",
2489 if (sshkey_is_cert(pubkey
) && !sshkey_is_cert(privkey
)) {
2491 * Graft the certificate onto the private key to make
2492 * it capable of signing.
2494 if ((r
= sshkey_to_certified(privkey
)) != 0) {
2495 error_fr(r
, "sshkey_to_certified");
2498 if ((r
= sshkey_cert_copy(pubkey
, privkey
)) != 0) {
2499 error_fr(r
, "sshkey_cert_copy");
2507 sshkey_free(privkey
);
2513 sign_one(struct sshkey
*signkey
, const char *filename
, int fd
,
2514 const char *sig_namespace
, sshsig_signer
*signer
, void *signer_ctx
)
2516 struct sshbuf
*sigbuf
= NULL
, *abuf
= NULL
;
2517 int r
= SSH_ERR_INTERNAL_ERROR
, wfd
= -1, oerrno
;
2518 char *wfile
= NULL
, *asig
= NULL
, *fp
= NULL
;
2519 char *pin
= NULL
, *prompt
= NULL
;
2522 if (fd
== STDIN_FILENO
)
2523 fprintf(stderr
, "Signing data on standard input\n");
2525 fprintf(stderr
, "Signing file %s\n", filename
);
2527 if (signer
== NULL
&& sshkey_is_sk(signkey
)) {
2528 if ((signkey
->sk_flags
& SSH_SK_USER_VERIFICATION_REQD
)) {
2529 xasprintf(&prompt
, "Enter PIN for %s key: ",
2530 sshkey_type(signkey
));
2531 if ((pin
= read_passphrase(prompt
,
2532 RP_ALLOW_STDIN
)) == NULL
)
2533 fatal_f("couldn't read PIN");
2535 if ((signkey
->sk_flags
& SSH_SK_USER_PRESENCE_REQD
)) {
2536 if ((fp
= sshkey_fingerprint(signkey
, fingerprint_hash
,
2537 SSH_FP_DEFAULT
)) == NULL
)
2538 fatal_f("fingerprint failed");
2539 fprintf(stderr
, "Confirm user presence for key %s %s\n",
2540 sshkey_type(signkey
), fp
);
2544 if ((r
= sshsig_sign_fd(signkey
, NULL
, sk_provider
, pin
,
2545 fd
, sig_namespace
, &sigbuf
, signer
, signer_ctx
)) != 0) {
2546 error_r(r
, "Signing %s failed", filename
);
2549 if ((r
= sshsig_armor(sigbuf
, &abuf
)) != 0) {
2550 error_fr(r
, "sshsig_armor");
2553 if ((asig
= sshbuf_dup_string(abuf
)) == NULL
) {
2554 error_f("buffer error");
2555 r
= SSH_ERR_ALLOC_FAIL
;
2559 if (fd
== STDIN_FILENO
) {
2560 fputs(asig
, stdout
);
2563 xasprintf(&wfile
, "%s.sig", filename
);
2564 if (confirm_overwrite(wfile
)) {
2565 if ((wfd
= open(wfile
, O_WRONLY
|O_CREAT
|O_TRUNC
,
2568 error("Cannot open %s: %s",
2569 wfile
, strerror(errno
));
2571 r
= SSH_ERR_SYSTEM_ERROR
;
2574 if (atomicio(vwrite
, wfd
, asig
,
2575 strlen(asig
)) != strlen(asig
)) {
2577 error("Cannot write to %s: %s",
2578 wfile
, strerror(errno
));
2580 r
= SSH_ERR_SYSTEM_ERROR
;
2584 fprintf(stderr
, "Write signature to %s\n",
2596 freezero(pin
, strlen(pin
));
2598 sshbuf_free(sigbuf
);
2605 sig_sign(const char *keypath
, const char *sig_namespace
, int argc
, char **argv
)
2607 int i
, fd
= -1, r
, ret
= -1;
2609 struct sshkey
*pubkey
= NULL
, *privkey
= NULL
, *signkey
= NULL
;
2610 sshsig_signer
*signer
= NULL
;
2612 /* Check file arguments. */
2613 for (i
= 0; i
< argc
; i
++) {
2614 if (strcmp(argv
[i
], "-") != 0)
2616 if (i
> 0 || argc
> 1)
2617 fatal("Cannot sign mix of paths and standard input");
2620 if ((r
= sshkey_load_public(keypath
, &pubkey
, NULL
)) != 0) {
2621 error_r(r
, "Couldn't load public key %s", keypath
);
2625 if ((r
= ssh_get_authentication_socket(&agent_fd
)) != 0)
2626 debug_r(r
, "Couldn't get agent socket");
2628 if ((r
= ssh_agent_has_key(agent_fd
, pubkey
)) == 0)
2629 signer
= agent_signer
;
2631 debug_r(r
, "Couldn't find key in agent");
2634 if (signer
== NULL
) {
2635 /* Not using agent - try to load private key */
2636 if ((privkey
= load_sign_key(keypath
, pubkey
)) == NULL
)
2640 /* Will use key in agent */
2645 if ((r
= sign_one(signkey
, "(stdin)", STDIN_FILENO
,
2646 sig_namespace
, signer
, &agent_fd
)) != 0)
2649 for (i
= 0; i
< argc
; i
++) {
2650 if (strcmp(argv
[i
], "-") == 0)
2652 else if ((fd
= open(argv
[i
], O_RDONLY
)) == -1) {
2653 error("Cannot open %s for signing: %s",
2654 argv
[i
], strerror(errno
));
2657 if ((r
= sign_one(signkey
, argv
[i
], fd
, sig_namespace
,
2658 signer
, &agent_fd
)) != 0)
2660 if (fd
!= STDIN_FILENO
)
2668 if (fd
!= -1 && fd
!= STDIN_FILENO
)
2670 sshkey_free(pubkey
);
2671 sshkey_free(privkey
);
2676 sig_process_opts(char * const *opts
, size_t nopts
, uint64_t *verify_timep
,
2683 if (print_pubkey
!= NULL
)
2685 for (i
= 0; i
< nopts
; i
++) {
2686 if (strncasecmp(opts
[i
], "verify-time=", 12) == 0) {
2687 if (parse_absolute_time(opts
[i
] + 12,
2688 verify_timep
) != 0 || *verify_timep
== 0) {
2689 error("Invalid \"verify-time\" option");
2690 return SSH_ERR_INVALID_ARGUMENT
;
2692 } else if (print_pubkey
&&
2693 strcasecmp(opts
[i
], "print-pubkey") == 0) {
2696 error("Invalid option \"%s\"", opts
[i
]);
2697 return SSH_ERR_INVALID_ARGUMENT
;
2700 if (*verify_timep
== 0) {
2701 if ((now
= time(NULL
)) < 0) {
2702 error("Time is before epoch");
2703 return SSH_ERR_INVALID_ARGUMENT
;
2705 *verify_timep
= (uint64_t)now
;
2711 sig_verify(const char *signature
, const char *sig_namespace
,
2712 const char *principal
, const char *allowed_keys
, const char *revoked_keys
,
2713 char * const *opts
, size_t nopts
)
2716 int print_pubkey
= 0;
2717 struct sshbuf
*sigbuf
= NULL
, *abuf
= NULL
;
2718 struct sshkey
*sign_key
= NULL
;
2720 struct sshkey_sig_details
*sig_details
= NULL
;
2721 uint64_t verify_time
= 0;
2723 if (sig_process_opts(opts
, nopts
, &verify_time
, &print_pubkey
) != 0)
2724 goto done
; /* error already logged */
2726 memset(&sig_details
, 0, sizeof(sig_details
));
2727 if ((r
= sshbuf_load_file(signature
, &abuf
)) != 0) {
2728 error_r(r
, "Couldn't read signature file");
2732 if ((r
= sshsig_dearmor(abuf
, &sigbuf
)) != 0) {
2733 error_fr(r
, "sshsig_armor");
2736 if ((r
= sshsig_verify_fd(sigbuf
, STDIN_FILENO
, sig_namespace
,
2737 &sign_key
, &sig_details
)) != 0)
2738 goto done
; /* sshsig_verify() prints error */
2740 if ((fp
= sshkey_fingerprint(sign_key
, fingerprint_hash
,
2741 SSH_FP_DEFAULT
)) == NULL
)
2742 fatal_f("sshkey_fingerprint failed");
2743 debug("Valid (unverified) signature from key %s", fp
);
2744 if (sig_details
!= NULL
) {
2745 debug2_f("signature details: counter = %u, flags = 0x%02x",
2746 sig_details
->sk_counter
, sig_details
->sk_flags
);
2751 if (revoked_keys
!= NULL
) {
2752 if ((r
= sshkey_check_revoked(sign_key
, revoked_keys
)) != 0) {
2753 debug3_fr(r
, "sshkey_check_revoked");
2758 if (allowed_keys
!= NULL
&& (r
= sshsig_check_allowed_keys(allowed_keys
,
2759 sign_key
, principal
, sig_namespace
, verify_time
)) != 0) {
2760 debug3_fr(r
, "sshsig_check_allowed_keys");
2768 if ((fp
= sshkey_fingerprint(sign_key
, fingerprint_hash
,
2769 SSH_FP_DEFAULT
)) == NULL
)
2770 fatal_f("sshkey_fingerprint failed");
2771 if (principal
== NULL
) {
2772 printf("Good \"%s\" signature with %s key %s\n",
2773 sig_namespace
, sshkey_type(sign_key
), fp
);
2776 printf("Good \"%s\" signature for %s with %s key %s\n",
2777 sig_namespace
, principal
,
2778 sshkey_type(sign_key
), fp
);
2781 printf("Could not verify signature.\n");
2784 /* Print the signature key if requested */
2785 if (ret
== 0 && print_pubkey
&& sign_key
!= NULL
) {
2786 if ((r
= sshkey_write(sign_key
, stdout
)) == 0)
2787 fputc('\n', stdout
);
2789 error_r(r
, "Could not print public key.\n");
2793 sshbuf_free(sigbuf
);
2795 sshkey_free(sign_key
);
2796 sshkey_sig_details_free(sig_details
);
2802 sig_find_principals(const char *signature
, const char *allowed_keys
,
2803 char * const *opts
, size_t nopts
)
2806 struct sshbuf
*sigbuf
= NULL
, *abuf
= NULL
;
2807 struct sshkey
*sign_key
= NULL
;
2808 char *principals
= NULL
, *cp
, *tmp
;
2809 uint64_t verify_time
= 0;
2811 if (sig_process_opts(opts
, nopts
, &verify_time
, NULL
) != 0)
2812 goto done
; /* error already logged */
2814 if ((r
= sshbuf_load_file(signature
, &abuf
)) != 0) {
2815 error_r(r
, "Couldn't read signature file");
2818 if ((r
= sshsig_dearmor(abuf
, &sigbuf
)) != 0) {
2819 error_fr(r
, "sshsig_armor");
2822 if ((r
= sshsig_get_pubkey(sigbuf
, &sign_key
)) != 0) {
2823 error_fr(r
, "sshsig_get_pubkey");
2826 if ((r
= sshsig_find_principals(allowed_keys
, sign_key
,
2827 verify_time
, &principals
)) != 0) {
2828 if (r
!= SSH_ERR_KEY_NOT_FOUND
)
2829 error_fr(r
, "sshsig_find_principal");
2835 /* Emit matching principals one per line */
2837 while ((cp
= strsep(&tmp
, ",")) != NULL
&& *cp
!= '\0')
2840 fprintf(stderr
, "No principal matched.\n");
2842 sshbuf_free(sigbuf
);
2844 sshkey_free(sign_key
);
2850 do_moduli_gen(const char *out_file
, char **opts
, size_t nopts
)
2853 /* Moduli generation/screening */
2854 u_int32_t memory
= 0;
2855 BIGNUM
*start
= NULL
;
2856 int moduli_bits
= 0;
2862 for (i
= 0; i
< nopts
; i
++) {
2863 if (strncmp(opts
[i
], "memory=", 7) == 0) {
2864 memory
= (u_int32_t
)strtonum(opts
[i
]+7, 1,
2867 fatal("Memory limit is %s: %s",
2870 } else if (strncmp(opts
[i
], "start=", 6) == 0) {
2871 /* XXX - also compare length against bits */
2872 if (BN_hex2bn(&start
, opts
[i
]+6) == 0)
2873 fatal("Invalid start point.");
2874 } else if (strncmp(opts
[i
], "bits=", 5) == 0) {
2875 moduli_bits
= (int)strtonum(opts
[i
]+5, 1,
2878 fatal("Invalid number: %s (%s)",
2879 opts
[i
]+12, errstr
);
2882 fatal("Option \"%s\" is unsupported for moduli "
2883 "generation", opts
[i
]);
2887 if ((out
= fopen(out_file
, "w")) == NULL
) {
2888 fatal("Couldn't open modulus candidate file \"%s\": %s",
2889 out_file
, strerror(errno
));
2891 setvbuf(out
, NULL
, _IOLBF
, 0);
2893 if (moduli_bits
== 0)
2894 moduli_bits
= DEFAULT_BITS
;
2895 if (gen_candidates(out
, memory
, moduli_bits
, start
) != 0)
2896 fatal("modulus candidate generation failed");
2897 #else /* WITH_OPENSSL */
2898 fatal("Moduli generation is not supported");
2899 #endif /* WITH_OPENSSL */
2903 do_moduli_screen(const char *out_file
, char **opts
, size_t nopts
)
2906 /* Moduli generation/screening */
2907 char *checkpoint
= NULL
;
2908 u_int32_t generator_wanted
= 0;
2909 unsigned long start_lineno
= 0, lines_to_process
= 0;
2910 int prime_tests
= 0;
2911 FILE *out
, *in
= stdin
;
2916 for (i
= 0; i
< nopts
; i
++) {
2917 if (strncmp(opts
[i
], "lines=", 6) == 0) {
2918 lines_to_process
= strtoul(opts
[i
]+6, NULL
, 10);
2919 } else if (strncmp(opts
[i
], "start-line=", 11) == 0) {
2920 start_lineno
= strtoul(opts
[i
]+11, NULL
, 10);
2921 } else if (strncmp(opts
[i
], "checkpoint=", 11) == 0) {
2922 checkpoint
= xstrdup(opts
[i
]+11);
2923 } else if (strncmp(opts
[i
], "generator=", 10) == 0) {
2924 generator_wanted
= (u_int32_t
)strtonum(
2925 opts
[i
]+10, 1, UINT_MAX
, &errstr
);
2926 if (errstr
!= NULL
) {
2927 fatal("Generator invalid: %s (%s)",
2928 opts
[i
]+10, errstr
);
2930 } else if (strncmp(opts
[i
], "prime-tests=", 12) == 0) {
2931 prime_tests
= (int)strtonum(opts
[i
]+12, 1,
2934 fatal("Invalid number: %s (%s)",
2935 opts
[i
]+12, errstr
);
2938 fatal("Option \"%s\" is unsupported for moduli "
2939 "screening", opts
[i
]);
2943 if (have_identity
&& strcmp(identity_file
, "-") != 0) {
2944 if ((in
= fopen(identity_file
, "r")) == NULL
) {
2945 fatal("Couldn't open modulus candidate "
2946 "file \"%s\": %s", identity_file
,
2951 if ((out
= fopen(out_file
, "a")) == NULL
) {
2952 fatal("Couldn't open moduli file \"%s\": %s",
2953 out_file
, strerror(errno
));
2955 setvbuf(out
, NULL
, _IOLBF
, 0);
2956 if (prime_test(in
, out
, prime_tests
== 0 ? 100 : prime_tests
,
2957 generator_wanted
, checkpoint
,
2958 start_lineno
, lines_to_process
) != 0)
2959 fatal("modulus screening failed");
2960 #else /* WITH_OPENSSL */
2961 fatal("Moduli screening is not supported");
2962 #endif /* WITH_OPENSSL */
2966 private_key_passphrase(void)
2968 char *passphrase1
, *passphrase2
;
2970 /* Ask for a passphrase (twice). */
2971 if (identity_passphrase
)
2972 passphrase1
= xstrdup(identity_passphrase
);
2973 else if (identity_new_passphrase
)
2974 passphrase1
= xstrdup(identity_new_passphrase
);
2978 read_passphrase("Enter passphrase (empty for no "
2979 "passphrase): ", RP_ALLOW_STDIN
);
2980 passphrase2
= read_passphrase("Enter same passphrase again: ",
2982 if (strcmp(passphrase1
, passphrase2
) != 0) {
2984 * The passphrases do not match. Clear them and
2987 freezero(passphrase1
, strlen(passphrase1
));
2988 freezero(passphrase2
, strlen(passphrase2
));
2989 printf("Passphrases do not match. Try again.\n");
2990 goto passphrase_again
;
2992 /* Clear the other copy of the passphrase. */
2993 freezero(passphrase2
, strlen(passphrase2
));
2999 skip_ssh_url_preamble(const char *s
)
3001 if (strncmp(s
, "ssh://", 6) == 0)
3003 else if (strncmp(s
, "ssh:", 4) == 0)
3009 do_download_sk(const char *skprovider
, const char *device
)
3011 struct sshkey
**keys
;
3014 char *fp
, *pin
= NULL
, *pass
= NULL
, *path
, *pubpath
;
3017 if (skprovider
== NULL
)
3018 fatal("Cannot download keys without provider");
3020 pin
= read_passphrase("Enter PIN for authenticator: ", RP_ALLOW_STDIN
);
3022 printf("You may need to touch your authenticator "
3023 "to authorize key download.\n");
3025 if ((r
= sshsk_load_resident(skprovider
, device
, pin
,
3026 &keys
, &nkeys
)) != 0) {
3028 freezero(pin
, strlen(pin
));
3029 error_r(r
, "Unable to load resident keys");
3033 logit("No keys to download");
3035 freezero(pin
, strlen(pin
));
3037 for (i
= 0; i
< nkeys
; i
++) {
3038 if (keys
[i
]->type
!= KEY_ECDSA_SK
&&
3039 keys
[i
]->type
!= KEY_ED25519_SK
) {
3040 error("Unsupported key type %s (%d)",
3041 sshkey_type(keys
[i
]), keys
[i
]->type
);
3044 if ((fp
= sshkey_fingerprint(keys
[i
],
3045 fingerprint_hash
, SSH_FP_DEFAULT
)) == NULL
)
3046 fatal_f("sshkey_fingerprint failed");
3047 debug_f("key %zu: %s %s %s (flags 0x%02x)", i
,
3048 sshkey_type(keys
[i
]), fp
, keys
[i
]->sk_application
,
3050 ext
= skip_ssh_url_preamble(keys
[i
]->sk_application
);
3051 xasprintf(&path
, "id_%s_rk%s%s",
3052 keys
[i
]->type
== KEY_ECDSA_SK
? "ecdsa_sk" : "ed25519_sk",
3053 *ext
== '\0' ? "" : "_", ext
);
3055 /* If the file already exists, ask the user to confirm. */
3056 if (!confirm_overwrite(path
)) {
3061 /* Save the key with the application string as the comment */
3063 pass
= private_key_passphrase();
3064 if ((r
= sshkey_save_private(keys
[i
], path
, pass
,
3065 keys
[i
]->sk_application
, private_key_format
,
3066 openssh_format_cipher
, rounds
)) != 0) {
3067 error_r(r
, "Saving key \"%s\" failed", path
);
3072 printf("Saved %s key%s%s to %s\n",
3073 sshkey_type(keys
[i
]),
3074 *ext
!= '\0' ? " " : "",
3075 *ext
!= '\0' ? keys
[i
]->sk_application
: "",
3079 /* Save public key too */
3080 xasprintf(&pubpath
, "%s.pub", path
);
3082 if ((r
= sshkey_save_public(keys
[i
], pubpath
,
3083 keys
[i
]->sk_application
)) != 0) {
3084 error_r(r
, "Saving public key \"%s\" failed", pubpath
);
3092 ret
= 0; /* success */
3094 freezero(pass
, strlen(pass
));
3095 for (i
= 0; i
< nkeys
; i
++)
3096 sshkey_free(keys
[i
]);
3102 save_attestation(struct sshbuf
*attest
, const char *path
)
3108 return; /* nothing to do */
3109 if (attest
== NULL
|| sshbuf_len(attest
) == 0)
3110 fatal("Enrollment did not return attestation data");
3112 r
= sshbuf_write_file(path
, attest
);
3115 fatal_r(r
, "Unable to write attestation data \"%s\"", path
);
3117 printf("Your FIDO attestation certificate has been saved in "
3125 "usage: ssh-keygen [-q] [-a rounds] [-b bits] [-C comment] [-f output_keyfile]\n"
3126 " [-m format] [-N new_passphrase] [-O option]\n"
3127 " [-t dsa | ecdsa | ecdsa-sk | ed25519 | ed25519-sk | rsa]\n"
3128 " [-w provider] [-Z cipher]\n"
3129 " ssh-keygen -p [-a rounds] [-f keyfile] [-m format] [-N new_passphrase]\n"
3130 " [-P old_passphrase] [-Z cipher]\n"
3132 " ssh-keygen -i [-f input_keyfile] [-m key_format]\n"
3133 " ssh-keygen -e [-f input_keyfile] [-m key_format]\n"
3135 " ssh-keygen -y [-f input_keyfile]\n"
3136 " ssh-keygen -c [-a rounds] [-C comment] [-f keyfile] [-P passphrase]\n"
3137 " ssh-keygen -l [-v] [-E fingerprint_hash] [-f input_keyfile]\n"
3138 " ssh-keygen -B [-f input_keyfile]\n");
3139 #ifdef ENABLE_PKCS11
3141 " ssh-keygen -D pkcs11\n");
3144 " ssh-keygen -F hostname [-lv] [-f known_hosts_file]\n"
3145 " ssh-keygen -H [-f known_hosts_file]\n"
3146 " ssh-keygen -K [-a rounds] [-w provider]\n"
3147 " ssh-keygen -R hostname [-f known_hosts_file]\n"
3148 " ssh-keygen -r hostname [-g] [-f input_keyfile]\n"
3150 " ssh-keygen -M generate [-O option] output_file\n"
3151 " ssh-keygen -M screen [-f input_file] [-O option] output_file\n"
3153 " ssh-keygen -I certificate_identity -s ca_key [-hU] [-D pkcs11_provider]\n"
3154 " [-n principals] [-O option] [-V validity_interval]\n"
3155 " [-z serial_number] file ...\n"
3156 " ssh-keygen -L [-f input_keyfile]\n"
3157 " ssh-keygen -A [-a rounds] [-f prefix_path]\n"
3158 " ssh-keygen -k -f krl_file [-u] [-s ca_public] [-z version_number]\n"
3160 " ssh-keygen -Q [-l] -f krl_file [file ...]\n"
3161 " ssh-keygen -Y find-principals -s signature_file -f allowed_signers_file\n"
3162 " ssh-keygen -Y check-novalidate -n namespace -s signature_file\n"
3163 " ssh-keygen -Y sign -f key_file -n namespace file ...\n"
3164 " ssh-keygen -Y verify -f allowed_signers_file -I signer_identity\n"
3165 " -n namespace -s signature_file [-r revocation_file]\n");
3170 * Main program for key management.
3173 main(int argc
, char **argv
)
3175 char comment
[1024], *passphrase
;
3176 char *rr_hostname
= NULL
, *ep
, *fp
, *ra
;
3177 struct sshkey
*private, *public;
3180 int change_passphrase
= 0, change_comment
= 0, show_cert
= 0;
3181 int find_host
= 0, delete_host
= 0, hash_hosts
= 0;
3182 int gen_all_hostkeys
= 0, gen_krl
= 0, update_krl
= 0, check_krl
= 0;
3183 int prefer_agent
= 0, convert_to
= 0, convert_from
= 0;
3184 int print_public
= 0, print_generic
= 0, cert_serial_autoinc
= 0;
3185 int do_gen_candidates
= 0, do_screen_candidates
= 0, download_sk
= 0;
3186 unsigned long long cert_serial
= 0;
3187 char *identity_comment
= NULL
, *ca_key_path
= NULL
, **opts
= NULL
;
3188 char *sk_application
= NULL
, *sk_device
= NULL
, *sk_user
= NULL
;
3189 char *sk_attestation_path
= NULL
;
3190 struct sshbuf
*challenge
= NULL
, *attest
= NULL
;
3191 size_t i
, nopts
= 0;
3193 uint8_t sk_flags
= SSH_SK_USER_PRESENCE_REQD
;
3195 int log_level
= SYSLOG_LEVEL_INFO
;
3196 char *sign_op
= NULL
;
3199 extern char *optarg
;
3201 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
3204 __progname
= ssh_get_progname(argv
[0]);
3208 log_init(argv
[0], SYSLOG_LEVEL_INFO
, SYSLOG_FACILITY_USER
, 1);
3212 /* we need this for the home * directory. */
3213 pw
= getpwuid(getuid());
3215 fatal("No user exists for uid %lu", (u_long
)getuid());
3217 if (gethostname(hostname
, sizeof(hostname
)) == -1)
3218 fatal("gethostname: %s", strerror(errno
));
3220 sk_provider
= getenv("SSH_SK_PROVIDER");
3222 /* Remaining characters: dGjJSTWx */
3223 while ((opt
= getopt(argc
, argv
, "ABHKLQUXceghiklopquvy"
3224 "C:D:E:F:I:M:N:O:P:R:V:Y:Z:"
3225 "a:b:f:g:m:n:r:s:t:w:z:")) != -1) {
3228 gen_all_hostkeys
= 1;
3231 bits
= (u_int32_t
)strtonum(optarg
, 1, UINT32_MAX
,
3234 fatal("Bits has bad value %s (%s)",
3238 fingerprint_hash
= ssh_digest_alg_by_name(optarg
);
3239 if (fingerprint_hash
== -1)
3240 fatal("Invalid hash algorithm \"%s\"", optarg
);
3244 rr_hostname
= optarg
;
3250 cert_key_id
= optarg
;
3254 rr_hostname
= optarg
;
3260 print_fingerprint
= 1;
3263 print_bubblebabble
= 1;
3266 if (strcasecmp(optarg
, "RFC4716") == 0 ||
3267 strcasecmp(optarg
, "ssh2") == 0) {
3268 convert_format
= FMT_RFC4716
;
3271 if (strcasecmp(optarg
, "PKCS8") == 0) {
3272 convert_format
= FMT_PKCS8
;
3273 private_key_format
= SSHKEY_PRIVATE_PKCS8
;
3276 if (strcasecmp(optarg
, "PEM") == 0) {
3277 convert_format
= FMT_PEM
;
3278 private_key_format
= SSHKEY_PRIVATE_PEM
;
3281 fatal("Unsupported conversion format \"%s\"", optarg
);
3283 cert_principals
= optarg
;
3286 /* no-op; new format is already the default */
3289 change_passphrase
= 1;
3295 if (strlcpy(identity_file
, optarg
,
3296 sizeof(identity_file
)) >= sizeof(identity_file
))
3297 fatal("Identity filename too long");
3307 identity_passphrase
= optarg
;
3310 identity_new_passphrase
= optarg
;
3316 opts
= xrecallocarray(opts
, nopts
, nopts
+ 1,
3318 opts
[nopts
++] = xstrdup(optarg
);
3321 openssh_format_cipher
= optarg
;
3322 if (cipher_by_name(openssh_format_cipher
) == NULL
)
3323 fatal("Invalid OpenSSH-format cipher '%s'",
3324 openssh_format_cipher
);
3327 identity_comment
= optarg
;
3337 cert_key_type
= SSH2_CERT_TYPE_HOST
;
3338 certflags_flags
= 0;
3352 ca_key_path
= optarg
;
3355 key_type_name
= optarg
;
3358 pkcs11provider
= optarg
;
3367 if (log_level
== SYSLOG_LEVEL_INFO
)
3368 log_level
= SYSLOG_LEVEL_DEBUG1
;
3370 if (log_level
>= SYSLOG_LEVEL_DEBUG1
&&
3371 log_level
< SYSLOG_LEVEL_DEBUG3
)
3376 rr_hostname
= optarg
;
3379 rounds
= (int)strtonum(optarg
, 1, INT_MAX
, &errstr
);
3381 fatal("Invalid number: %s (%s)",
3385 parse_cert_times(optarg
);
3391 sk_provider
= optarg
;
3395 if (*optarg
== '+') {
3396 cert_serial_autoinc
= 1;
3399 cert_serial
= strtoull(optarg
, &ep
, 10);
3400 if (*optarg
< '0' || *optarg
> '9' || *ep
!= '\0' ||
3401 (errno
== ERANGE
&& cert_serial
== ULLONG_MAX
))
3402 fatal("Invalid serial number \"%s\"", optarg
);
3405 if (strcmp(optarg
, "generate") == 0)
3406 do_gen_candidates
= 1;
3407 else if (strcmp(optarg
, "screen") == 0)
3408 do_screen_candidates
= 1;
3410 fatal("Unsupported moduli option %s", optarg
);
3418 #ifdef ENABLE_SK_INTERNAL
3419 if (sk_provider
== NULL
)
3420 sk_provider
= "internal";
3424 log_init(argv
[0], log_level
, SYSLOG_FACILITY_USER
, 1);
3429 if (sign_op
!= NULL
) {
3430 if (strncmp(sign_op
, "find-principals", 15) == 0) {
3431 if (ca_key_path
== NULL
) {
3432 error("Too few arguments for find-principals:"
3433 "missing signature file");
3436 if (!have_identity
) {
3437 error("Too few arguments for find-principals:"
3438 "missing allowed keys file");
3441 return sig_find_principals(ca_key_path
, identity_file
,
3443 } else if (strncmp(sign_op
, "sign", 4) == 0) {
3444 if (cert_principals
== NULL
||
3445 *cert_principals
== '\0') {
3446 error("Too few arguments for sign: "
3447 "missing namespace");
3450 if (!have_identity
) {
3451 error("Too few arguments for sign: "
3455 return sig_sign(identity_file
, cert_principals
,
3457 } else if (strncmp(sign_op
, "check-novalidate", 16) == 0) {
3458 if (ca_key_path
== NULL
) {
3459 error("Too few arguments for check-novalidate: "
3460 "missing signature file");
3463 return sig_verify(ca_key_path
, cert_principals
,
3464 NULL
, NULL
, NULL
, opts
, nopts
);
3465 } else if (strncmp(sign_op
, "verify", 6) == 0) {
3466 if (cert_principals
== NULL
||
3467 *cert_principals
== '\0') {
3468 error("Too few arguments for verify: "
3469 "missing namespace");
3472 if (ca_key_path
== NULL
) {
3473 error("Too few arguments for verify: "
3474 "missing signature file");
3477 if (!have_identity
) {
3478 error("Too few arguments for sign: "
3479 "missing allowed keys file");
3482 if (cert_key_id
== NULL
) {
3483 error("Too few arguments for verify: "
3484 "missing principal ID");
3487 return sig_verify(ca_key_path
, cert_principals
,
3488 cert_key_id
, identity_file
, rr_hostname
,
3491 error("Unsupported operation for -Y: \"%s\"", sign_op
);
3496 if (ca_key_path
!= NULL
) {
3497 if (argc
< 1 && !gen_krl
) {
3498 error("Too few arguments.");
3501 } else if (argc
> 0 && !gen_krl
&& !check_krl
&&
3502 !do_gen_candidates
&& !do_screen_candidates
) {
3503 error("Too many arguments.");
3506 if (change_passphrase
&& change_comment
) {
3507 error("Can only have one of -p and -c.");
3510 if (print_fingerprint
&& (delete_host
|| hash_hosts
)) {
3511 error("Cannot use -l with -H or -R.");
3515 do_gen_krl(pw
, update_krl
, ca_key_path
,
3516 cert_serial
, identity_comment
, argc
, argv
);
3520 do_check_krl(pw
, print_fingerprint
, argc
, argv
);
3523 if (ca_key_path
!= NULL
) {
3524 if (cert_key_id
== NULL
)
3525 fatal("Must specify key id (-I) when certifying");
3526 for (i
= 0; i
< nopts
; i
++)
3527 add_cert_option(opts
[i
]);
3528 do_ca_sign(pw
, ca_key_path
, prefer_agent
,
3529 cert_serial
, cert_serial_autoinc
, argc
, argv
);
3533 if (delete_host
|| hash_hosts
|| find_host
) {
3534 do_known_hosts(pw
, rr_hostname
, find_host
,
3535 delete_host
, hash_hosts
);
3537 if (pkcs11provider
!= NULL
)
3540 for (i
= 0; i
< nopts
; i
++) {
3541 if (strncasecmp(opts
[i
], "device=", 7) == 0) {
3542 sk_device
= xstrdup(opts
[i
] + 7);
3544 fatal("Option \"%s\" is unsupported for "
3545 "FIDO authenticator download", opts
[i
]);
3548 return do_download_sk(sk_provider
, sk_device
);
3550 if (print_fingerprint
|| print_bubblebabble
)
3552 if (change_passphrase
)
3553 do_change_passphrase(pw
);
3555 do_change_comment(pw
, identity_comment
);
3560 do_convert_from(pw
);
3561 #else /* WITH_OPENSSL */
3562 if (convert_to
|| convert_from
)
3563 fatal("key conversion disabled at compile time");
3564 #endif /* WITH_OPENSSL */
3566 do_print_public(pw
);
3567 if (rr_hostname
!= NULL
) {
3570 if (have_identity
) {
3571 n
= do_print_resource_record(pw
, identity_file
,
3572 rr_hostname
, print_generic
);
3574 fatal("%s: %s", identity_file
, strerror(errno
));
3578 n
+= do_print_resource_record(pw
,
3579 _PATH_HOST_RSA_KEY_FILE
, rr_hostname
,
3581 n
+= do_print_resource_record(pw
,
3582 _PATH_HOST_DSA_KEY_FILE
, rr_hostname
,
3584 n
+= do_print_resource_record(pw
,
3585 _PATH_HOST_ECDSA_KEY_FILE
, rr_hostname
,
3587 n
+= do_print_resource_record(pw
,
3588 _PATH_HOST_ED25519_KEY_FILE
, rr_hostname
,
3590 n
+= do_print_resource_record(pw
,
3591 _PATH_HOST_XMSS_KEY_FILE
, rr_hostname
,
3594 fatal("no keys found.");
3599 if (do_gen_candidates
|| do_screen_candidates
) {
3601 fatal("No output file specified");
3603 fatal("Too many output files specified");
3605 if (do_gen_candidates
) {
3606 do_moduli_gen(argv
[0], opts
, nopts
);
3609 if (do_screen_candidates
) {
3610 do_moduli_screen(argv
[0], opts
, nopts
);
3614 if (gen_all_hostkeys
) {
3615 do_gen_all_hostkeys(pw
);
3619 if (key_type_name
== NULL
)
3620 key_type_name
= DEFAULT_KEY_TYPE_NAME
;
3622 type
= sshkey_type_from_name(key_type_name
);
3623 type_bits_valid(type
, key_type_name
, &bits
);
3626 printf("Generating public/private %s key pair.\n",
3630 case KEY_ED25519_SK
:
3631 for (i
= 0; i
< nopts
; i
++) {
3632 if (strcasecmp(opts
[i
], "no-touch-required") == 0) {
3633 sk_flags
&= ~SSH_SK_USER_PRESENCE_REQD
;
3634 } else if (strcasecmp(opts
[i
], "verify-required") == 0) {
3635 sk_flags
|= SSH_SK_USER_VERIFICATION_REQD
;
3636 } else if (strcasecmp(opts
[i
], "resident") == 0) {
3637 sk_flags
|= SSH_SK_RESIDENT_KEY
;
3638 } else if (strncasecmp(opts
[i
], "device=", 7) == 0) {
3639 sk_device
= xstrdup(opts
[i
] + 7);
3640 } else if (strncasecmp(opts
[i
], "user=", 5) == 0) {
3641 sk_user
= xstrdup(opts
[i
] + 5);
3642 } else if (strncasecmp(opts
[i
], "challenge=", 10) == 0) {
3643 if ((r
= sshbuf_load_file(opts
[i
] + 10,
3644 &challenge
)) != 0) {
3645 fatal_r(r
, "Unable to load FIDO "
3646 "enrollment challenge \"%s\"",
3649 } else if (strncasecmp(opts
[i
],
3650 "write-attestation=", 18) == 0) {
3651 sk_attestation_path
= opts
[i
] + 18;
3652 } else if (strncasecmp(opts
[i
],
3653 "application=", 12) == 0) {
3654 sk_application
= xstrdup(opts
[i
] + 12);
3655 if (strncmp(sk_application
, "ssh:", 4) != 0) {
3656 fatal("FIDO application string must "
3657 "begin with \"ssh:\"");
3660 fatal("Option \"%s\" is unsupported for "
3661 "FIDO authenticator enrollment", opts
[i
]);
3665 printf("You may need to touch your authenticator "
3666 "to authorize key generation.\n");
3668 if ((attest
= sshbuf_new()) == NULL
)
3669 fatal("sshbuf_new failed");
3671 (SSH_SK_USER_VERIFICATION_REQD
|SSH_SK_RESIDENT_KEY
))) {
3672 passphrase
= read_passphrase("Enter PIN for "
3673 "authenticator: ", RP_ALLOW_STDIN
);
3677 for (i
= 0 ; ; i
++) {
3679 r
= sshsk_enroll(type
, sk_provider
, sk_device
,
3680 sk_application
== NULL
? "ssh:" : sk_application
,
3681 sk_user
, sk_flags
, passphrase
, challenge
,
3685 if (r
!= SSH_ERR_KEY_WRONG_PASSPHRASE
)
3686 fatal_r(r
, "Key enrollment failed");
3687 else if (passphrase
!= NULL
) {
3688 error("PIN incorrect");
3689 freezero(passphrase
, strlen(passphrase
));
3693 fatal("Too many incorrect PINs");
3694 passphrase
= read_passphrase("Enter PIN for "
3695 "authenticator: ", RP_ALLOW_STDIN
);
3697 printf("You may need to touch your "
3698 "authenticator (again) to authorize "
3699 "key generation.\n");
3702 if (passphrase
!= NULL
) {
3703 freezero(passphrase
, strlen(passphrase
));
3708 if ((r
= sshkey_generate(type
, bits
, &private)) != 0)
3709 fatal("sshkey_generate failed");
3712 if ((r
= sshkey_from_private(private, &public)) != 0)
3713 fatal_r(r
, "sshkey_from_private");
3716 ask_filename(pw
, "Enter file in which to save the key");
3718 /* Create ~/.ssh directory if it doesn't already exist. */
3719 hostfile_create_user_ssh_dir(identity_file
, !quiet
);
3721 /* If the file already exists, ask the user to confirm. */
3722 if (!confirm_overwrite(identity_file
))
3725 /* Determine the passphrase for the private key */
3726 passphrase
= private_key_passphrase();
3727 if (identity_comment
) {
3728 strlcpy(comment
, identity_comment
, sizeof(comment
));
3730 /* Create default comment field for the passphrase. */
3731 snprintf(comment
, sizeof comment
, "%s@%s", pw
->pw_name
, hostname
);
3734 /* Save the key with the given passphrase and comment. */
3735 if ((r
= sshkey_save_private(private, identity_file
, passphrase
,
3736 comment
, private_key_format
, openssh_format_cipher
, rounds
)) != 0) {
3737 error_r(r
, "Saving key \"%s\" failed", identity_file
);
3738 freezero(passphrase
, strlen(passphrase
));
3741 freezero(passphrase
, strlen(passphrase
));
3742 sshkey_free(private);
3745 printf("Your identification has been saved in %s\n",
3749 strlcat(identity_file
, ".pub", sizeof(identity_file
));
3750 if ((r
= sshkey_save_public(public, identity_file
, comment
)) != 0)
3751 fatal_r(r
, "Unable to save public key to %s", identity_file
);
3754 fp
= sshkey_fingerprint(public, fingerprint_hash
,
3756 ra
= sshkey_fingerprint(public, fingerprint_hash
,
3758 if (fp
== NULL
|| ra
== NULL
)
3759 fatal("sshkey_fingerprint failed");
3760 printf("Your public key has been saved in %s\n",
3762 printf("The key fingerprint is:\n");
3763 printf("%s %s\n", fp
, comment
);
3764 printf("The key's randomart image is:\n");
3770 if (sk_attestation_path
!= NULL
)
3771 save_attestation(attest
, sk_attestation_path
);
3773 sshbuf_free(attest
);
3774 sshkey_free(public);