1 /* $OpenBSD: ssh-keygen.c,v 1.472 2024/01/11 01:45:36 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 */
70 #define DEFAULT_KEY_TYPE_NAME "ed25519"
73 * Default number of bits in the RSA, DSA and ECDSA keys. These value can be
74 * overridden on the command line.
76 * These values, with the exception of DSA, provide security equivalent to at
77 * least 128 bits of security according to NIST Special Publication 800-57:
78 * Recommendation for Key Management Part 1 rev 4 section 5.6.1.
79 * For DSA it (and FIPS-186-4 section 4.2) specifies that the only size for
80 * which a 160bit hash is acceptable is 1kbit, and since ssh-dss specifies only
81 * SHA1 we limit the DSA key size 1k bits.
83 #define DEFAULT_BITS 3072
84 #define DEFAULT_BITS_DSA 1024
85 #define DEFAULT_BITS_ECDSA 256
89 /* Flag indicating that we just want to see the key fingerprint */
90 static int print_fingerprint
= 0;
91 static int print_bubblebabble
= 0;
93 /* Hash algorithm to use for fingerprints. */
94 static int fingerprint_hash
= SSH_FP_HASH_DEFAULT
;
96 /* The identity file name, given on the command line or entered by the user. */
97 static char identity_file
[PATH_MAX
];
98 static int have_identity
= 0;
100 /* This is set to the passphrase if given on the command line. */
101 static char *identity_passphrase
= NULL
;
103 /* This is set to the new passphrase if given on the command line. */
104 static char *identity_new_passphrase
= NULL
;
106 /* Key type when certifying */
107 static u_int cert_key_type
= SSH2_CERT_TYPE_USER
;
109 /* "key ID" of signed key */
110 static char *cert_key_id
= NULL
;
112 /* Comma-separated list of principal names for certifying keys */
113 static char *cert_principals
= NULL
;
115 /* Validity period for certificates */
116 static u_int64_t cert_valid_from
= 0;
117 static u_int64_t cert_valid_to
= ~0ULL;
119 /* Certificate options */
120 #define CERTOPT_X_FWD (1)
121 #define CERTOPT_AGENT_FWD (1<<1)
122 #define CERTOPT_PORT_FWD (1<<2)
123 #define CERTOPT_PTY (1<<3)
124 #define CERTOPT_USER_RC (1<<4)
125 #define CERTOPT_NO_REQUIRE_USER_PRESENCE (1<<5)
126 #define CERTOPT_REQUIRE_VERIFY (1<<6)
127 #define CERTOPT_DEFAULT (CERTOPT_X_FWD|CERTOPT_AGENT_FWD| \
128 CERTOPT_PORT_FWD|CERTOPT_PTY|CERTOPT_USER_RC)
129 static u_int32_t certflags_flags
= CERTOPT_DEFAULT
;
130 static char *certflags_command
= NULL
;
131 static char *certflags_src_addr
= NULL
;
133 /* Arbitrary extensions specified by user */
139 static struct cert_ext
*cert_ext
;
140 static size_t ncert_ext
;
142 /* Conversion to/from various formats */
147 } convert_format
= FMT_RFC4716
;
149 static char *key_type_name
= NULL
;
151 /* Load key from this PKCS#11 provider */
152 static char *pkcs11provider
= NULL
;
154 /* FIDO/U2F provider to use */
155 static char *sk_provider
= NULL
;
157 /* Format for writing private keys */
158 static int private_key_format
= SSHKEY_PRIVATE_OPENSSH
;
160 /* Cipher for new-format private keys */
161 static char *openssh_format_cipher
= NULL
;
163 /* Number of KDF rounds to derive new format keys. */
164 static int rounds
= 0;
167 extern char *__progname
;
169 static char hostname
[NI_MAXHOST
];
173 int gen_candidates(FILE *, u_int32_t
, u_int32_t
, BIGNUM
*);
174 int prime_test(FILE *, FILE *, u_int32_t
, u_int32_t
, char *, unsigned long,
179 type_bits_valid(int type
, const char *name
, u_int32_t
*bitsp
)
181 if (type
== KEY_UNSPEC
)
182 fatal("unknown key type %s", key_type_name
);
189 *bitsp
= DEFAULT_BITS_DSA
;
193 (nid
= sshkey_ecdsa_nid_from_name(name
)) > 0)
194 *bitsp
= sshkey_curve_nid_to_bits(nid
);
196 *bitsp
= DEFAULT_BITS_ECDSA
;
199 *bitsp
= DEFAULT_BITS
;
208 fatal("Invalid DSA key length: must be 1024 bits");
211 if (*bitsp
< SSH_RSA_MINIMUM_MODULUS_SIZE
)
212 fatal("Invalid RSA key length: minimum is %d bits",
213 SSH_RSA_MINIMUM_MODULUS_SIZE
);
214 else if (*bitsp
> OPENSSL_RSA_MAX_MODULUS_BITS
)
215 fatal("Invalid RSA key length: maximum is %d bits",
216 OPENSSL_RSA_MAX_MODULUS_BITS
);
219 if (sshkey_ecdsa_bits_to_nid(*bitsp
) == -1)
220 #ifdef OPENSSL_HAS_NISTP521
221 fatal("Invalid ECDSA key length: valid lengths are "
222 "256, 384 or 521 bits");
224 fatal("Invalid ECDSA key length: valid lengths are "
232 * Checks whether a file exists and, if so, asks the user whether they wish
234 * Returns nonzero if the file does not already exist or if the user agrees to
235 * overwrite, or zero otherwise.
238 confirm_overwrite(const char *filename
)
243 if (stat(filename
, &st
) != 0)
245 printf("%s already exists.\n", filename
);
246 printf("Overwrite (y/n)? ");
248 if (fgets(yesno
, sizeof(yesno
), stdin
) == NULL
)
250 if (yesno
[0] != 'y' && yesno
[0] != 'Y')
256 ask_filename(struct passwd
*pw
, const char *prompt
)
261 if (key_type_name
== NULL
)
262 name
= _PATH_SSH_CLIENT_ID_ED25519
;
264 switch (sshkey_type_from_name(key_type_name
)) {
268 name
= _PATH_SSH_CLIENT_ID_DSA
;
271 #ifdef OPENSSL_HAS_ECC
274 name
= _PATH_SSH_CLIENT_ID_ECDSA
;
276 case KEY_ECDSA_SK_CERT
:
278 name
= _PATH_SSH_CLIENT_ID_ECDSA_SK
;
283 name
= _PATH_SSH_CLIENT_ID_RSA
;
286 case KEY_ED25519_CERT
:
287 name
= _PATH_SSH_CLIENT_ID_ED25519
;
290 case KEY_ED25519_SK_CERT
:
291 name
= _PATH_SSH_CLIENT_ID_ED25519_SK
;
295 name
= _PATH_SSH_CLIENT_ID_XMSS
;
298 fatal("bad key type");
301 snprintf(identity_file
, sizeof(identity_file
),
302 "%s/%s", pw
->pw_dir
, name
);
303 printf("%s (%s): ", prompt
, identity_file
);
305 if (fgets(buf
, sizeof(buf
), stdin
) == NULL
)
307 buf
[strcspn(buf
, "\n")] = '\0';
308 if (strcmp(buf
, "") != 0)
309 strlcpy(identity_file
, buf
, sizeof(identity_file
));
313 static struct sshkey
*
314 load_identity(const char *filename
, char **commentp
)
320 if (commentp
!= NULL
)
322 if ((r
= sshkey_load_private(filename
, "", &prv
, commentp
)) == 0)
324 if (r
!= SSH_ERR_KEY_WRONG_PASSPHRASE
)
325 fatal_r(r
, "Load key \"%s\"", filename
);
326 if (identity_passphrase
)
327 pass
= xstrdup(identity_passphrase
);
329 pass
= read_passphrase("Enter passphrase: ", RP_ALLOW_STDIN
);
330 r
= sshkey_load_private(filename
, pass
, &prv
, commentp
);
331 freezero(pass
, strlen(pass
));
333 fatal_r(r
, "Load key \"%s\"", filename
);
337 #define SSH_COM_PUBLIC_BEGIN "---- BEGIN SSH2 PUBLIC KEY ----"
338 #define SSH_COM_PUBLIC_END "---- END SSH2 PUBLIC KEY ----"
339 #define SSH_COM_PRIVATE_BEGIN "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
340 #define SSH_COM_PRIVATE_KEY_MAGIC 0x3f6ff9eb
344 do_convert_to_ssh2(struct passwd
*pw
, struct sshkey
*k
)
347 char comment
[61], *b64
;
350 if ((b
= sshbuf_new()) == NULL
)
351 fatal_f("sshbuf_new failed");
352 if ((r
= sshkey_putb(k
, b
)) != 0)
353 fatal_fr(r
, "put key");
354 if ((b64
= sshbuf_dtob64_string(b
, 1)) == NULL
)
355 fatal_f("sshbuf_dtob64_string failed");
357 /* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
358 snprintf(comment
, sizeof(comment
),
359 "%u-bit %s, converted by %s@%s from OpenSSH",
360 sshkey_size(k
), sshkey_type(k
),
361 pw
->pw_name
, hostname
);
366 fprintf(stdout
, "%s\n", SSH_COM_PUBLIC_BEGIN
);
367 fprintf(stdout
, "Comment: \"%s\"\n%s", comment
, b64
);
368 fprintf(stdout
, "%s\n", SSH_COM_PUBLIC_END
);
374 do_convert_to_pkcs8(struct sshkey
*k
)
376 switch (sshkey_type_plain(k
->type
)) {
378 if (!PEM_write_RSA_PUBKEY(stdout
, k
->rsa
))
379 fatal("PEM_write_RSA_PUBKEY failed");
383 if (!PEM_write_DSA_PUBKEY(stdout
, k
->dsa
))
384 fatal("PEM_write_DSA_PUBKEY failed");
387 #ifdef OPENSSL_HAS_ECC
389 if (!PEM_write_EC_PUBKEY(stdout
, k
->ecdsa
))
390 fatal("PEM_write_EC_PUBKEY failed");
394 fatal_f("unsupported key type %s", sshkey_type(k
));
400 do_convert_to_pem(struct sshkey
*k
)
402 switch (sshkey_type_plain(k
->type
)) {
404 if (!PEM_write_RSAPublicKey(stdout
, k
->rsa
))
405 fatal("PEM_write_RSAPublicKey failed");
409 if (!PEM_write_DSA_PUBKEY(stdout
, k
->dsa
))
410 fatal("PEM_write_DSA_PUBKEY failed");
413 #ifdef OPENSSL_HAS_ECC
415 if (!PEM_write_EC_PUBKEY(stdout
, k
->ecdsa
))
416 fatal("PEM_write_EC_PUBKEY failed");
420 fatal_f("unsupported key type %s", sshkey_type(k
));
426 do_convert_to(struct passwd
*pw
)
433 ask_filename(pw
, "Enter file in which the key is");
434 if (stat(identity_file
, &st
) == -1)
435 fatal("%s: %s: %s", __progname
, identity_file
, strerror(errno
));
436 if ((r
= sshkey_load_public(identity_file
, &k
, NULL
)) != 0)
437 k
= load_identity(identity_file
, NULL
);
438 switch (convert_format
) {
440 do_convert_to_ssh2(pw
, k
);
443 do_convert_to_pkcs8(k
);
446 do_convert_to_pem(k
);
449 fatal_f("unknown key format %d", convert_format
);
455 * This is almost exactly the bignum1 encoding, but with 32 bit for length
459 buffer_get_bignum_bits(struct sshbuf
*b
, BIGNUM
*value
)
461 u_int bytes
, bignum_bits
;
464 if ((r
= sshbuf_get_u32(b
, &bignum_bits
)) != 0)
465 fatal_fr(r
, "parse");
466 bytes
= (bignum_bits
+ 7) / 8;
467 if (sshbuf_len(b
) < bytes
)
468 fatal_f("input buffer too small: need %d have %zu",
469 bytes
, sshbuf_len(b
));
470 if (BN_bin2bn(sshbuf_ptr(b
), bytes
, value
) == NULL
)
471 fatal_f("BN_bin2bn failed");
472 if ((r
= sshbuf_consume(b
, bytes
)) != 0)
473 fatal_fr(r
, "consume");
476 static struct sshkey
*
477 do_convert_private_ssh2(struct sshbuf
*b
)
479 struct sshkey
*key
= NULL
;
481 const char *alg
= NULL
;
482 u_char e1
, e2
, e3
, *sig
= NULL
, data
[] = "abcde12345";
484 u_int magic
, i1
, i2
, i3
, i4
;
488 BIGNUM
*dsa_p
= NULL
, *dsa_q
= NULL
, *dsa_g
= NULL
;
489 BIGNUM
*dsa_pub_key
= NULL
, *dsa_priv_key
= NULL
;
491 BIGNUM
*rsa_n
= NULL
, *rsa_e
= NULL
, *rsa_d
= NULL
;
492 BIGNUM
*rsa_p
= NULL
, *rsa_q
= NULL
, *rsa_iqmp
= NULL
;
494 if ((r
= sshbuf_get_u32(b
, &magic
)) != 0)
495 fatal_fr(r
, "parse magic");
497 if (magic
!= SSH_COM_PRIVATE_KEY_MAGIC
) {
498 error("bad magic 0x%x != 0x%x", magic
,
499 SSH_COM_PRIVATE_KEY_MAGIC
);
502 if ((r
= sshbuf_get_u32(b
, &i1
)) != 0 ||
503 (r
= sshbuf_get_cstring(b
, &type
, NULL
)) != 0 ||
504 (r
= sshbuf_get_cstring(b
, &cipher
, NULL
)) != 0 ||
505 (r
= sshbuf_get_u32(b
, &i2
)) != 0 ||
506 (r
= sshbuf_get_u32(b
, &i3
)) != 0 ||
507 (r
= sshbuf_get_u32(b
, &i4
)) != 0)
508 fatal_fr(r
, "parse");
509 debug("ignore (%d %d %d %d)", i1
, i2
, i3
, i4
);
510 if (strcmp(cipher
, "none") != 0) {
511 error("unsupported cipher %s", cipher
);
518 if (strstr(type
, "rsa")) {
521 } else if (strstr(type
, "dsa")) {
528 if ((key
= sshkey_new(ktype
)) == NULL
)
529 fatal("sshkey_new failed");
535 if ((dsa_p
= BN_new()) == NULL
||
536 (dsa_q
= BN_new()) == NULL
||
537 (dsa_g
= BN_new()) == NULL
||
538 (dsa_pub_key
= BN_new()) == NULL
||
539 (dsa_priv_key
= BN_new()) == NULL
)
541 buffer_get_bignum_bits(b
, dsa_p
);
542 buffer_get_bignum_bits(b
, dsa_g
);
543 buffer_get_bignum_bits(b
, dsa_q
);
544 buffer_get_bignum_bits(b
, dsa_pub_key
);
545 buffer_get_bignum_bits(b
, dsa_priv_key
);
546 if (!DSA_set0_pqg(key
->dsa
, dsa_p
, dsa_q
, dsa_g
))
547 fatal_f("DSA_set0_pqg failed");
548 dsa_p
= dsa_q
= dsa_g
= NULL
; /* transferred */
549 if (!DSA_set0_key(key
->dsa
, dsa_pub_key
, dsa_priv_key
))
550 fatal_f("DSA_set0_key failed");
551 dsa_pub_key
= dsa_priv_key
= NULL
; /* transferred */
555 if ((r
= sshbuf_get_u8(b
, &e1
)) != 0 ||
556 (e1
< 30 && (r
= sshbuf_get_u8(b
, &e2
)) != 0) ||
557 (e1
< 30 && (r
= sshbuf_get_u8(b
, &e3
)) != 0))
558 fatal_fr(r
, "parse RSA");
569 if ((rsa_e
= BN_new()) == NULL
)
571 if (!BN_set_word(rsa_e
, e
)) {
572 BN_clear_free(rsa_e
);
576 if ((rsa_n
= BN_new()) == NULL
||
577 (rsa_d
= BN_new()) == NULL
||
578 (rsa_p
= BN_new()) == NULL
||
579 (rsa_q
= BN_new()) == NULL
||
580 (rsa_iqmp
= BN_new()) == NULL
)
582 buffer_get_bignum_bits(b
, rsa_d
);
583 buffer_get_bignum_bits(b
, rsa_n
);
584 buffer_get_bignum_bits(b
, rsa_iqmp
);
585 buffer_get_bignum_bits(b
, rsa_q
);
586 buffer_get_bignum_bits(b
, rsa_p
);
587 if (!RSA_set0_key(key
->rsa
, rsa_n
, rsa_e
, rsa_d
))
588 fatal_f("RSA_set0_key failed");
589 rsa_n
= rsa_e
= rsa_d
= NULL
; /* transferred */
590 if (!RSA_set0_factors(key
->rsa
, rsa_p
, rsa_q
))
591 fatal_f("RSA_set0_factors failed");
592 rsa_p
= rsa_q
= NULL
; /* transferred */
593 if ((r
= ssh_rsa_complete_crt_parameters(key
, rsa_iqmp
)) != 0)
594 fatal_fr(r
, "generate RSA parameters");
595 BN_clear_free(rsa_iqmp
);
596 alg
= "rsa-sha2-256";
599 rlen
= sshbuf_len(b
);
601 error_f("remaining bytes in key blob %d", rlen
);
604 if ((r
= sshkey_sign(key
, &sig
, &slen
, data
, sizeof(data
),
605 alg
, NULL
, NULL
, 0)) != 0)
606 error_fr(r
, "signing with converted key failed");
607 else if ((r
= sshkey_verify(key
, sig
, slen
, data
, sizeof(data
),
609 error_fr(r
, "verification with converted key failed");
620 get_line(FILE *fp
, char *line
, size_t len
)
626 while ((c
= fgetc(fp
)) != EOF
) {
628 fatal("input line too long.");
632 if (c
!= EOF
&& c
!= '\n' && ungetc(c
, fp
) == EOF
)
633 fatal("unget: %s", strerror(errno
));
646 do_convert_from_ssh2(struct passwd
*pw
, struct sshkey
**k
, int *private)
648 int r
, blen
, escaped
= 0;
655 if ((buf
= sshbuf_new()) == NULL
)
656 fatal("sshbuf_new failed");
657 if ((fp
= fopen(identity_file
, "r")) == NULL
)
658 fatal("%s: %s: %s", __progname
, identity_file
, strerror(errno
));
660 while ((blen
= get_line(fp
, line
, sizeof(line
))) != -1) {
661 if (blen
> 0 && line
[blen
- 1] == '\\')
663 if (strncmp(line
, "----", 4) == 0 ||
664 strstr(line
, ": ") != NULL
) {
665 if (strstr(line
, SSH_COM_PRIVATE_BEGIN
) != NULL
)
667 if (strstr(line
, " END ") != NULL
) {
670 /* fprintf(stderr, "ignore: %s", line); */
675 /* fprintf(stderr, "escaped: %s", line); */
678 strlcat(encoded
, line
, sizeof(encoded
));
680 len
= strlen(encoded
);
681 if (((len
% 4) == 3) &&
682 (encoded
[len
-1] == '=') &&
683 (encoded
[len
-2] == '=') &&
684 (encoded
[len
-3] == '='))
685 encoded
[len
-3] = '\0';
686 if ((r
= sshbuf_b64tod(buf
, encoded
)) != 0)
687 fatal_fr(r
, "base64 decode");
689 if ((*k
= do_convert_private_ssh2(buf
)) == NULL
)
690 fatal_f("private key conversion failed");
691 } else if ((r
= sshkey_fromb(buf
, k
)) != 0)
692 fatal_fr(r
, "parse key");
698 do_convert_from_pkcs8(struct sshkey
**k
, int *private)
703 if ((fp
= fopen(identity_file
, "r")) == NULL
)
704 fatal("%s: %s: %s", __progname
, identity_file
, strerror(errno
));
705 if ((pubkey
= PEM_read_PUBKEY(fp
, NULL
, NULL
, NULL
)) == NULL
) {
706 fatal_f("%s is not a recognised public key format",
710 switch (EVP_PKEY_base_id(pubkey
)) {
712 if ((*k
= sshkey_new(KEY_UNSPEC
)) == NULL
)
713 fatal("sshkey_new failed");
714 (*k
)->type
= KEY_RSA
;
715 (*k
)->rsa
= EVP_PKEY_get1_RSA(pubkey
);
719 if ((*k
= sshkey_new(KEY_UNSPEC
)) == NULL
)
720 fatal("sshkey_new failed");
721 (*k
)->type
= KEY_DSA
;
722 (*k
)->dsa
= EVP_PKEY_get1_DSA(pubkey
);
725 #ifdef OPENSSL_HAS_ECC
727 if ((*k
= sshkey_new(KEY_UNSPEC
)) == NULL
)
728 fatal("sshkey_new failed");
729 (*k
)->type
= KEY_ECDSA
;
730 (*k
)->ecdsa
= EVP_PKEY_get1_EC_KEY(pubkey
);
731 (*k
)->ecdsa_nid
= sshkey_ecdsa_key_to_nid((*k
)->ecdsa
);
735 fatal_f("unsupported pubkey type %d",
736 EVP_PKEY_base_id(pubkey
));
738 EVP_PKEY_free(pubkey
);
743 do_convert_from_pem(struct sshkey
**k
, int *private)
748 if ((fp
= fopen(identity_file
, "r")) == NULL
)
749 fatal("%s: %s: %s", __progname
, identity_file
, strerror(errno
));
750 if ((rsa
= PEM_read_RSAPublicKey(fp
, NULL
, NULL
, NULL
)) != NULL
) {
751 if ((*k
= sshkey_new(KEY_UNSPEC
)) == NULL
)
752 fatal("sshkey_new failed");
753 (*k
)->type
= KEY_RSA
;
758 fatal_f("unrecognised raw private key format");
762 do_convert_from(struct passwd
*pw
)
764 struct sshkey
*k
= NULL
;
765 int r
, private = 0, ok
= 0;
769 ask_filename(pw
, "Enter file in which the key is");
770 if (stat(identity_file
, &st
) == -1)
771 fatal("%s: %s: %s", __progname
, identity_file
, strerror(errno
));
773 switch (convert_format
) {
775 do_convert_from_ssh2(pw
, &k
, &private);
778 do_convert_from_pkcs8(&k
, &private);
781 do_convert_from_pem(&k
, &private);
784 fatal_f("unknown key format %d", convert_format
);
788 if ((r
= sshkey_write(k
, stdout
)) == 0)
791 fprintf(stdout
, "\n");
796 ok
= PEM_write_DSAPrivateKey(stdout
, k
->dsa
, NULL
,
797 NULL
, 0, NULL
, NULL
);
800 #ifdef OPENSSL_HAS_ECC
802 ok
= PEM_write_ECPrivateKey(stdout
, k
->ecdsa
, NULL
,
803 NULL
, 0, NULL
, NULL
);
807 ok
= PEM_write_RSAPrivateKey(stdout
, k
->rsa
, NULL
,
808 NULL
, 0, NULL
, NULL
);
811 fatal_f("unsupported key type %s", sshkey_type(k
));
816 fatal("key write failed");
823 do_print_public(struct passwd
*pw
)
828 char *comment
= NULL
;
831 ask_filename(pw
, "Enter file in which the key is");
832 if (stat(identity_file
, &st
) == -1)
833 fatal("%s: %s", identity_file
, strerror(errno
));
834 prv
= load_identity(identity_file
, &comment
);
835 if ((r
= sshkey_write(prv
, stdout
)) != 0)
836 fatal_fr(r
, "write key");
837 if (comment
!= NULL
&& *comment
!= '\0')
838 fprintf(stdout
, " %s", comment
);
839 fprintf(stdout
, "\n");
840 if (sshkey_is_sk(prv
)) {
841 debug("sk_application: \"%s\", sk_flags 0x%02x",
842 prv
->sk_application
, prv
->sk_flags
);
850 do_download(struct passwd
*pw
)
853 struct sshkey
**keys
= NULL
;
855 enum sshkey_fp_rep rep
;
857 char *fp
, *ra
, **comments
= NULL
;
859 fptype
= print_bubblebabble
? SSH_DIGEST_SHA1
: fingerprint_hash
;
860 rep
= print_bubblebabble
? SSH_FP_BUBBLEBABBLE
: SSH_FP_DEFAULT
;
863 nkeys
= pkcs11_add_provider(pkcs11provider
, NULL
, &keys
, &comments
);
865 fatal("cannot read public key from pkcs11");
866 for (i
= 0; i
< nkeys
; i
++) {
867 if (print_fingerprint
) {
868 fp
= sshkey_fingerprint(keys
[i
], fptype
, rep
);
869 ra
= sshkey_fingerprint(keys
[i
], fingerprint_hash
,
871 if (fp
== NULL
|| ra
== NULL
)
872 fatal_f("sshkey_fingerprint fail");
873 printf("%u %s %s (PKCS11 key)\n", sshkey_size(keys
[i
]),
874 fp
, sshkey_type(keys
[i
]));
875 if (log_level_get() >= SYSLOG_LEVEL_VERBOSE
)
880 (void) sshkey_write(keys
[i
], stdout
); /* XXX check */
881 fprintf(stdout
, "%s%s\n",
882 *(comments
[i
]) == '\0' ? "" : " ", comments
[i
]);
885 sshkey_free(keys
[i
]);
892 fatal("no pkcs11 support");
893 #endif /* ENABLE_PKCS11 */
896 static struct sshkey
*
897 try_read_key(char **cpp
)
902 if ((ret
= sshkey_new(KEY_UNSPEC
)) == NULL
)
903 fatal("sshkey_new failed");
904 if ((r
= sshkey_read(ret
, cpp
)) == 0)
912 fingerprint_one_key(const struct sshkey
*public, const char *comment
)
914 char *fp
= NULL
, *ra
= NULL
;
915 enum sshkey_fp_rep rep
;
918 fptype
= print_bubblebabble
? SSH_DIGEST_SHA1
: fingerprint_hash
;
919 rep
= print_bubblebabble
? SSH_FP_BUBBLEBABBLE
: SSH_FP_DEFAULT
;
920 fp
= sshkey_fingerprint(public, fptype
, rep
);
921 ra
= sshkey_fingerprint(public, fingerprint_hash
, SSH_FP_RANDOMART
);
922 if (fp
== NULL
|| ra
== NULL
)
923 fatal_f("sshkey_fingerprint failed");
924 mprintf("%u %s %s (%s)\n", sshkey_size(public), fp
,
925 comment
? comment
: "no comment", sshkey_type(public));
926 if (log_level_get() >= SYSLOG_LEVEL_VERBOSE
)
933 fingerprint_private(const char *path
)
936 char *comment
= NULL
;
937 struct sshkey
*privkey
= NULL
, *pubkey
= NULL
;
940 if (stat(identity_file
, &st
) == -1)
941 fatal("%s: %s", path
, strerror(errno
));
942 if ((r
= sshkey_load_public(path
, &pubkey
, &comment
)) != 0)
943 debug_r(r
, "load public \"%s\"", path
);
944 if (pubkey
== NULL
|| comment
== NULL
|| *comment
== '\0') {
946 if ((r
= sshkey_load_private(path
, NULL
,
947 &privkey
, &comment
)) != 0)
948 debug_r(r
, "load private \"%s\"", path
);
950 if (pubkey
== NULL
&& privkey
== NULL
)
951 fatal("%s is not a key file.", path
);
953 fingerprint_one_key(pubkey
== NULL
? privkey
: pubkey
, comment
);
955 sshkey_free(privkey
);
960 do_fingerprint(struct passwd
*pw
)
963 struct sshkey
*public = NULL
;
964 char *comment
= NULL
, *cp
, *ep
, *line
= NULL
;
971 ask_filename(pw
, "Enter file in which the key is");
972 path
= identity_file
;
974 if (strcmp(identity_file
, "-") == 0) {
977 } else if ((f
= fopen(path
, "r")) == NULL
)
978 fatal("%s: %s: %s", __progname
, path
, strerror(errno
));
980 while (getline(&line
, &linesize
, f
) != -1) {
983 cp
[strcspn(cp
, "\n")] = '\0';
984 /* Trim leading space and comments */
985 cp
= line
+ strspn(line
, " \t");
986 if (*cp
== '#' || *cp
== '\0')
990 * Input may be plain keys, private keys, authorized_keys
995 * Try private keys first. Assume a key is private if
996 * "SSH PRIVATE KEY" appears on the first line and we're
997 * not reading from stdin (XXX support private keys on stdin).
999 if (lnum
== 1 && strcmp(identity_file
, "-") != 0 &&
1000 strstr(cp
, "PRIVATE KEY") != NULL
) {
1003 fingerprint_private(path
);
1008 * If it's not a private key, then this must be prepared to
1009 * accept a public key prefixed with a hostname or options.
1010 * Try a bare key first, otherwise skip the leading stuff.
1013 if ((public = try_read_key(&cp
)) == NULL
) {
1014 i
= strtol(cp
, &ep
, 10);
1015 if (i
== 0 || ep
== NULL
||
1016 (*ep
!= ' ' && *ep
!= '\t')) {
1020 for (; *cp
&& (quoted
|| (*cp
!= ' ' &&
1021 *cp
!= '\t')); cp
++) {
1022 if (*cp
== '\\' && cp
[1] == '"')
1023 cp
++; /* Skip both */
1024 else if (*cp
== '"')
1032 /* Retry after parsing leading hostname/key options */
1033 if (public == NULL
&& (public = try_read_key(&cp
)) == NULL
) {
1034 debug("%s:%lu: not a public key", path
, lnum
);
1038 /* Find trailing comment, if any */
1039 for (; *cp
== ' ' || *cp
== '\t'; cp
++)
1041 if (*cp
!= '\0' && *cp
!= '#')
1044 fingerprint_one_key(public, comment
);
1045 sshkey_free(public);
1046 invalid
= 0; /* One good key in the file is sufficient */
1052 fatal("%s is not a public key file.", path
);
1057 do_gen_all_hostkeys(struct passwd
*pw
)
1061 char *key_type_display
;
1065 { "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE
},
1066 #ifdef OPENSSL_HAS_ECC
1067 { "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE
},
1068 #endif /* OPENSSL_HAS_ECC */
1069 #endif /* WITH_OPENSSL */
1070 { "ed25519", "ED25519",_PATH_HOST_ED25519_KEY_FILE
},
1072 { "xmss", "XMSS",_PATH_HOST_XMSS_KEY_FILE
},
1073 #endif /* WITH_XMSS */
1074 { NULL
, NULL
, NULL
}
1080 struct sshkey
*private, *public;
1081 char comment
[1024], *prv_tmp
, *pub_tmp
, *prv_file
, *pub_file
;
1084 for (i
= 0; key_types
[i
].key_type
; i
++) {
1085 public = private = NULL
;
1086 prv_tmp
= pub_tmp
= prv_file
= pub_file
= NULL
;
1088 xasprintf(&prv_file
, "%s%s",
1089 identity_file
, key_types
[i
].path
);
1091 /* Check whether private key exists and is not zero-length */
1092 if (stat(prv_file
, &st
) == 0) {
1093 if (st
.st_size
!= 0)
1095 } else if (errno
!= ENOENT
) {
1096 error("Could not stat %s: %s", key_types
[i
].path
,
1102 * Private key doesn't exist or is invalid; proceed with
1105 xasprintf(&prv_tmp
, "%s%s.XXXXXXXXXX",
1106 identity_file
, key_types
[i
].path
);
1107 xasprintf(&pub_tmp
, "%s%s.pub.XXXXXXXXXX",
1108 identity_file
, key_types
[i
].path
);
1109 xasprintf(&pub_file
, "%s%s.pub",
1110 identity_file
, key_types
[i
].path
);
1114 printf("%s: generating new host keys: ", __progname
);
1116 printf("%s ", key_types
[i
].key_type_display
);
1118 type
= sshkey_type_from_name(key_types
[i
].key_type
);
1119 if ((fd
= mkstemp(prv_tmp
)) == -1) {
1120 error("Could not save your private key in %s: %s",
1121 prv_tmp
, strerror(errno
));
1124 (void)close(fd
); /* just using mkstemp() to reserve a name */
1126 type_bits_valid(type
, NULL
, &bits
);
1127 if ((r
= sshkey_generate(type
, bits
, &private)) != 0) {
1128 error_r(r
, "sshkey_generate failed");
1131 if ((r
= sshkey_from_private(private, &public)) != 0)
1132 fatal_fr(r
, "sshkey_from_private");
1133 snprintf(comment
, sizeof comment
, "%s@%s", pw
->pw_name
,
1135 if ((r
= sshkey_save_private(private, prv_tmp
, "",
1136 comment
, private_key_format
, openssh_format_cipher
,
1138 error_r(r
, "Saving key \"%s\" failed", prv_tmp
);
1141 if ((fd
= mkstemp(pub_tmp
)) == -1) {
1142 error("Could not save your public key in %s: %s",
1143 pub_tmp
, strerror(errno
));
1146 (void)fchmod(fd
, 0644);
1148 if ((r
= sshkey_save_public(public, pub_tmp
, comment
)) != 0) {
1149 error_r(r
, "Unable to save public key to %s",
1154 /* Rename temporary files to their permanent locations. */
1155 if (rename(pub_tmp
, pub_file
) != 0) {
1156 error("Unable to move %s into position: %s",
1157 pub_file
, strerror(errno
));
1160 if (rename(prv_tmp
, prv_file
) != 0) {
1161 error("Unable to move %s into position: %s",
1162 key_types
[i
].path
, strerror(errno
));
1168 sshkey_free(private);
1169 sshkey_free(public);
1179 struct known_hosts_ctx
{
1180 const char *host
; /* Hostname searched for in find/delete case */
1181 FILE *out
; /* Output file, stdout for find_hosts case */
1182 int has_unhashed
; /* When hashing, original had unhashed hosts */
1183 int found_key
; /* For find/delete, host was found */
1184 int invalid
; /* File contained invalid items; don't delete */
1185 int hash_hosts
; /* Hash hostnames as we go */
1186 int find_host
; /* Search for specific hostname */
1187 int delete_host
; /* Delete host from known_hosts */
1191 known_hosts_hash(struct hostkey_foreach_line
*l
, void *_ctx
)
1193 struct known_hosts_ctx
*ctx
= (struct known_hosts_ctx
*)_ctx
;
1194 char *hashed
, *cp
, *hosts
, *ohosts
;
1195 int has_wild
= l
->hosts
&& strcspn(l
->hosts
, "*?!") != strlen(l
->hosts
);
1196 int was_hashed
= l
->hosts
&& l
->hosts
[0] == HASH_DELIM
;
1198 switch (l
->status
) {
1200 case HKF_STATUS_MATCHED
:
1202 * Don't hash hosts already hashed, with wildcard
1203 * characters or a CA/revocation marker.
1205 if (was_hashed
|| has_wild
|| l
->marker
!= MRK_NONE
) {
1206 fprintf(ctx
->out
, "%s\n", l
->line
);
1207 if (has_wild
&& !ctx
->find_host
) {
1208 logit("%s:%lu: ignoring host name "
1209 "with wildcard: %.64s", l
->path
,
1210 l
->linenum
, l
->hosts
);
1215 * Split any comma-separated hostnames from the host list,
1216 * hash and store separately.
1218 ohosts
= hosts
= xstrdup(l
->hosts
);
1219 while ((cp
= strsep(&hosts
, ",")) != NULL
&& *cp
!= '\0') {
1221 if ((hashed
= host_hash(cp
, NULL
, 0)) == NULL
)
1222 fatal("hash_host failed");
1223 fprintf(ctx
->out
, "%s %s\n", hashed
, l
->rawkey
);
1225 ctx
->has_unhashed
= 1;
1229 case HKF_STATUS_INVALID
:
1230 /* Retain invalid lines, but mark file as invalid. */
1232 logit("%s:%lu: invalid line", l
->path
, l
->linenum
);
1235 fprintf(ctx
->out
, "%s\n", l
->line
);
1243 known_hosts_find_delete(struct hostkey_foreach_line
*l
, void *_ctx
)
1245 struct known_hosts_ctx
*ctx
= (struct known_hosts_ctx
*)_ctx
;
1246 enum sshkey_fp_rep rep
;
1248 char *fp
= NULL
, *ra
= NULL
;
1250 fptype
= print_bubblebabble
? SSH_DIGEST_SHA1
: fingerprint_hash
;
1251 rep
= print_bubblebabble
? SSH_FP_BUBBLEBABBLE
: SSH_FP_DEFAULT
;
1253 if (l
->status
== HKF_STATUS_MATCHED
) {
1254 if (ctx
->delete_host
) {
1255 if (l
->marker
!= MRK_NONE
) {
1256 /* Don't remove CA and revocation lines */
1257 fprintf(ctx
->out
, "%s\n", l
->line
);
1260 * Hostname matches and has no CA/revoke
1261 * marker, delete it by *not* writing the
1266 printf("# Host %s found: line %lu\n",
1267 ctx
->host
, l
->linenum
);
1270 } else if (ctx
->find_host
) {
1273 printf("# Host %s found: line %lu %s\n",
1275 l
->linenum
, l
->marker
== MRK_CA
? "CA" :
1276 (l
->marker
== MRK_REVOKE
? "REVOKED" : ""));
1278 if (ctx
->hash_hosts
)
1279 known_hosts_hash(l
, ctx
);
1280 else if (print_fingerprint
) {
1281 fp
= sshkey_fingerprint(l
->key
, fptype
, rep
);
1282 ra
= sshkey_fingerprint(l
->key
,
1283 fingerprint_hash
, SSH_FP_RANDOMART
);
1284 if (fp
== NULL
|| ra
== NULL
)
1285 fatal_f("sshkey_fingerprint failed");
1286 mprintf("%s %s %s%s%s\n", ctx
->host
,
1287 sshkey_type(l
->key
), fp
,
1288 l
->comment
[0] ? " " : "",
1290 if (log_level_get() >= SYSLOG_LEVEL_VERBOSE
)
1295 fprintf(ctx
->out
, "%s\n", l
->line
);
1298 } else if (ctx
->delete_host
) {
1299 /* Retain non-matching hosts when deleting */
1300 if (l
->status
== HKF_STATUS_INVALID
) {
1302 logit("%s:%lu: invalid line", l
->path
, l
->linenum
);
1304 fprintf(ctx
->out
, "%s\n", l
->line
);
1310 do_known_hosts(struct passwd
*pw
, const char *name
, int find_host
,
1311 int delete_host
, int hash_hosts
)
1313 char *cp
, tmp
[PATH_MAX
], old
[PATH_MAX
];
1314 int r
, fd
, oerrno
, inplace
= 0;
1315 struct known_hosts_ctx ctx
;
1316 u_int foreach_options
;
1319 if (!have_identity
) {
1320 cp
= tilde_expand_filename(_PATH_SSH_USER_HOSTFILE
, pw
->pw_uid
);
1321 if (strlcpy(identity_file
, cp
, sizeof(identity_file
)) >=
1322 sizeof(identity_file
))
1323 fatal("Specified known hosts path too long");
1327 if (stat(identity_file
, &sb
) != 0)
1328 fatal("Cannot stat %s: %s", identity_file
, strerror(errno
));
1330 memset(&ctx
, 0, sizeof(ctx
));
1333 ctx
.hash_hosts
= hash_hosts
;
1334 ctx
.find_host
= find_host
;
1335 ctx
.delete_host
= delete_host
;
1338 * Find hosts goes to stdout, hash and deletions happen in-place
1339 * A corner case is ssh-keygen -HF foo, which should go to stdout
1341 if (!find_host
&& (hash_hosts
|| delete_host
)) {
1342 if (strlcpy(tmp
, identity_file
, sizeof(tmp
)) >= sizeof(tmp
) ||
1343 strlcat(tmp
, ".XXXXXXXXXX", sizeof(tmp
)) >= sizeof(tmp
) ||
1344 strlcpy(old
, identity_file
, sizeof(old
)) >= sizeof(old
) ||
1345 strlcat(old
, ".old", sizeof(old
)) >= sizeof(old
))
1346 fatal("known_hosts path too long");
1348 if ((fd
= mkstemp(tmp
)) == -1)
1349 fatal("mkstemp: %s", strerror(errno
));
1350 if ((ctx
.out
= fdopen(fd
, "w")) == NULL
) {
1353 fatal("fdopen: %s", strerror(oerrno
));
1355 (void)fchmod(fd
, sb
.st_mode
& 0644);
1358 /* XXX support identity_file == "-" for stdin */
1359 foreach_options
= find_host
? HKF_WANT_MATCH
: 0;
1360 foreach_options
|= print_fingerprint
? HKF_WANT_PARSE_KEY
: 0;
1361 if ((r
= hostkeys_foreach(identity_file
, (find_host
|| !hash_hosts
) ?
1362 known_hosts_find_delete
: known_hosts_hash
, &ctx
, name
, NULL
,
1363 foreach_options
, 0)) != 0) {
1366 fatal_fr(r
, "hostkeys_foreach");
1373 error("%s is not a valid known_hosts file.", identity_file
);
1375 error("Not replacing existing known_hosts "
1376 "file because of errors");
1380 } else if (delete_host
&& !ctx
.found_key
) {
1381 logit("Host %s not found in %s", name
, identity_file
);
1384 } else if (inplace
) {
1385 /* Backup existing file */
1386 if (unlink(old
) == -1 && errno
!= ENOENT
)
1387 fatal("unlink %.100s: %s", old
, strerror(errno
));
1388 if (link(identity_file
, old
) == -1)
1389 fatal("link %.100s to %.100s: %s", identity_file
, old
,
1391 /* Move new one into place */
1392 if (rename(tmp
, identity_file
) == -1) {
1393 error("rename\"%s\" to \"%s\": %s", tmp
, identity_file
,
1400 printf("%s updated.\n", identity_file
);
1401 printf("Original contents retained as %s\n", old
);
1402 if (ctx
.has_unhashed
) {
1403 logit("WARNING: %s contains unhashed entries", old
);
1404 logit("Delete this file to ensure privacy "
1409 exit (find_host
&& !ctx
.found_key
);
1413 * Perform changing a passphrase. The argument is the passwd structure
1414 * for the current user.
1417 do_change_passphrase(struct passwd
*pw
)
1420 char *old_passphrase
, *passphrase1
, *passphrase2
;
1422 struct sshkey
*private;
1426 ask_filename(pw
, "Enter file in which the key is");
1427 if (stat(identity_file
, &st
) == -1)
1428 fatal("%s: %s", identity_file
, strerror(errno
));
1429 /* Try to load the file with empty passphrase. */
1430 r
= sshkey_load_private(identity_file
, "", &private, &comment
);
1431 if (r
== SSH_ERR_KEY_WRONG_PASSPHRASE
) {
1432 if (identity_passphrase
)
1433 old_passphrase
= xstrdup(identity_passphrase
);
1436 read_passphrase("Enter old passphrase: ",
1438 r
= sshkey_load_private(identity_file
, old_passphrase
,
1439 &private, &comment
);
1440 freezero(old_passphrase
, strlen(old_passphrase
));
1443 } else if (r
!= 0) {
1445 fatal_r(r
, "Failed to load key %s", identity_file
);
1448 mprintf("Key has comment '%s'\n", comment
);
1450 /* Ask the new passphrase (twice). */
1451 if (identity_new_passphrase
) {
1452 passphrase1
= xstrdup(identity_new_passphrase
);
1456 read_passphrase("Enter new passphrase (empty for no "
1457 "passphrase): ", RP_ALLOW_STDIN
);
1458 passphrase2
= read_passphrase("Enter same passphrase again: ",
1461 /* Verify that they are the same. */
1462 if (strcmp(passphrase1
, passphrase2
) != 0) {
1463 explicit_bzero(passphrase1
, strlen(passphrase1
));
1464 explicit_bzero(passphrase2
, strlen(passphrase2
));
1467 printf("Pass phrases do not match. Try again.\n");
1470 /* Destroy the other copy. */
1471 freezero(passphrase2
, strlen(passphrase2
));
1474 /* Save the file using the new passphrase. */
1475 if ((r
= sshkey_save_private(private, identity_file
, passphrase1
,
1476 comment
, private_key_format
, openssh_format_cipher
, rounds
)) != 0) {
1477 error_r(r
, "Saving key \"%s\" failed", identity_file
);
1478 freezero(passphrase1
, strlen(passphrase1
));
1479 sshkey_free(private);
1483 /* Destroy the passphrase and the copy of the key in memory. */
1484 freezero(passphrase1
, strlen(passphrase1
));
1485 sshkey_free(private); /* Destroys contents */
1488 printf("Your identification has been saved with the new passphrase.\n");
1493 * Print the SSHFP RR.
1496 do_print_resource_record(struct passwd
*pw
, char *fname
, char *hname
,
1497 int print_generic
, char * const *opts
, size_t nopts
)
1499 struct sshkey
*public;
1500 char *comment
= NULL
;
1505 for (i
= 0; i
< nopts
; i
++) {
1506 if (strncasecmp(opts
[i
], "hashalg=", 8) == 0) {
1507 if ((hash
= ssh_digest_alg_by_name(opts
[i
] + 8)) == -1)
1508 fatal("Unsupported hash algorithm");
1510 error("Invalid option \"%s\"", opts
[i
]);
1511 return SSH_ERR_INVALID_ARGUMENT
;
1515 fatal_f("no filename");
1516 if (stat(fname
, &st
) == -1) {
1517 if (errno
== ENOENT
)
1519 fatal("%s: %s", fname
, strerror(errno
));
1521 if ((r
= sshkey_load_public(fname
, &public, &comment
)) != 0)
1522 fatal_r(r
, "Failed to read v2 public key from \"%s\"", fname
);
1523 export_dns_rr(hname
, public, stdout
, print_generic
, hash
);
1524 sshkey_free(public);
1530 * Change the comment of a private key file.
1533 do_change_comment(struct passwd
*pw
, const char *identity_comment
)
1535 char new_comment
[1024], *comment
, *passphrase
;
1536 struct sshkey
*private;
1537 struct sshkey
*public;
1542 ask_filename(pw
, "Enter file in which the key is");
1543 if (stat(identity_file
, &st
) == -1)
1544 fatal("%s: %s", identity_file
, strerror(errno
));
1545 if ((r
= sshkey_load_private(identity_file
, "",
1546 &private, &comment
)) == 0)
1547 passphrase
= xstrdup("");
1548 else if (r
!= SSH_ERR_KEY_WRONG_PASSPHRASE
)
1549 fatal_r(r
, "Cannot load private key \"%s\"", identity_file
);
1551 if (identity_passphrase
)
1552 passphrase
= xstrdup(identity_passphrase
);
1553 else if (identity_new_passphrase
)
1554 passphrase
= xstrdup(identity_new_passphrase
);
1556 passphrase
= read_passphrase("Enter passphrase: ",
1558 /* Try to load using the passphrase. */
1559 if ((r
= sshkey_load_private(identity_file
, passphrase
,
1560 &private, &comment
)) != 0) {
1561 freezero(passphrase
, strlen(passphrase
));
1562 fatal_r(r
, "Cannot load private key \"%s\"",
1567 if (private->type
!= KEY_ED25519
&& private->type
!= KEY_XMSS
&&
1568 private_key_format
!= SSHKEY_PRIVATE_OPENSSH
) {
1569 error("Comments are only supported for keys stored in "
1570 "the new format (-o).");
1571 explicit_bzero(passphrase
, strlen(passphrase
));
1572 sshkey_free(private);
1576 printf("Old comment: %s\n", comment
);
1578 printf("No existing comment\n");
1580 if (identity_comment
) {
1581 strlcpy(new_comment
, identity_comment
, sizeof(new_comment
));
1583 printf("New comment: ");
1585 if (!fgets(new_comment
, sizeof(new_comment
), stdin
)) {
1586 explicit_bzero(passphrase
, strlen(passphrase
));
1587 sshkey_free(private);
1590 new_comment
[strcspn(new_comment
, "\n")] = '\0';
1592 if (comment
!= NULL
&& strcmp(comment
, new_comment
) == 0) {
1593 printf("No change to comment\n");
1595 sshkey_free(private);
1600 /* Save the file using the new passphrase. */
1601 if ((r
= sshkey_save_private(private, identity_file
, passphrase
,
1602 new_comment
, private_key_format
, openssh_format_cipher
,
1604 error_r(r
, "Saving key \"%s\" failed", identity_file
);
1605 freezero(passphrase
, strlen(passphrase
));
1606 sshkey_free(private);
1610 freezero(passphrase
, strlen(passphrase
));
1611 if ((r
= sshkey_from_private(private, &public)) != 0)
1612 fatal_fr(r
, "sshkey_from_private");
1613 sshkey_free(private);
1615 strlcat(identity_file
, ".pub", sizeof(identity_file
));
1616 if ((r
= sshkey_save_public(public, identity_file
, new_comment
)) != 0)
1617 fatal_r(r
, "Unable to save public key to %s", identity_file
);
1618 sshkey_free(public);
1621 if (strlen(new_comment
) > 0)
1622 printf("Comment '%s' applied\n", new_comment
);
1624 printf("Comment removed\n");
1630 cert_ext_add(const char *key
, const char *value
, int iscrit
)
1632 cert_ext
= xreallocarray(cert_ext
, ncert_ext
+ 1, sizeof(*cert_ext
));
1633 cert_ext
[ncert_ext
].key
= xstrdup(key
);
1634 cert_ext
[ncert_ext
].val
= value
== NULL
? NULL
: xstrdup(value
);
1635 cert_ext
[ncert_ext
].crit
= iscrit
;
1639 /* qsort(3) comparison function for certificate extensions */
1641 cert_ext_cmp(const void *_a
, const void *_b
)
1643 const struct cert_ext
*a
= (const struct cert_ext
*)_a
;
1644 const struct cert_ext
*b
= (const struct cert_ext
*)_b
;
1647 if (a
->crit
!= b
->crit
)
1648 return (a
->crit
< b
->crit
) ? -1 : 1;
1649 if ((r
= strcmp(a
->key
, b
->key
)) != 0)
1651 if ((a
->val
== NULL
) != (b
->val
== NULL
))
1652 return (a
->val
== NULL
) ? -1 : 1;
1653 if (a
->val
!= NULL
&& (r
= strcmp(a
->val
, b
->val
)) != 0)
1658 #define OPTIONS_CRITICAL 1
1659 #define OPTIONS_EXTENSIONS 2
1661 prepare_options_buf(struct sshbuf
*c
, int which
)
1666 const struct cert_ext
*ext
;
1668 if ((b
= sshbuf_new()) == NULL
)
1669 fatal_f("sshbuf_new failed");
1671 for (i
= 0; i
< ncert_ext
; i
++) {
1673 if ((ext
->crit
&& (which
& OPTIONS_EXTENSIONS
)) ||
1674 (!ext
->crit
&& (which
& OPTIONS_CRITICAL
)))
1676 if (ext
->val
== NULL
) {
1678 debug3_f("%s", ext
->key
);
1679 if ((r
= sshbuf_put_cstring(c
, ext
->key
)) != 0 ||
1680 (r
= sshbuf_put_string(c
, NULL
, 0)) != 0)
1681 fatal_fr(r
, "prepare flag");
1683 /* key/value option */
1684 debug3_f("%s=%s", ext
->key
, ext
->val
);
1686 if ((r
= sshbuf_put_cstring(c
, ext
->key
)) != 0 ||
1687 (r
= sshbuf_put_cstring(b
, ext
->val
)) != 0 ||
1688 (r
= sshbuf_put_stringb(c
, b
)) != 0)
1689 fatal_fr(r
, "prepare k/v");
1696 finalise_cert_exts(void)
1698 /* critical options */
1699 if (certflags_command
!= NULL
)
1700 cert_ext_add("force-command", certflags_command
, 1);
1701 if (certflags_src_addr
!= NULL
)
1702 cert_ext_add("source-address", certflags_src_addr
, 1);
1703 if ((certflags_flags
& CERTOPT_REQUIRE_VERIFY
) != 0)
1704 cert_ext_add("verify-required", NULL
, 1);
1706 if ((certflags_flags
& CERTOPT_X_FWD
) != 0)
1707 cert_ext_add("permit-X11-forwarding", NULL
, 0);
1708 if ((certflags_flags
& CERTOPT_AGENT_FWD
) != 0)
1709 cert_ext_add("permit-agent-forwarding", NULL
, 0);
1710 if ((certflags_flags
& CERTOPT_PORT_FWD
) != 0)
1711 cert_ext_add("permit-port-forwarding", NULL
, 0);
1712 if ((certflags_flags
& CERTOPT_PTY
) != 0)
1713 cert_ext_add("permit-pty", NULL
, 0);
1714 if ((certflags_flags
& CERTOPT_USER_RC
) != 0)
1715 cert_ext_add("permit-user-rc", NULL
, 0);
1716 if ((certflags_flags
& CERTOPT_NO_REQUIRE_USER_PRESENCE
) != 0)
1717 cert_ext_add("no-touch-required", NULL
, 0);
1718 /* order lexically by key */
1720 qsort(cert_ext
, ncert_ext
, sizeof(*cert_ext
), cert_ext_cmp
);
1723 static struct sshkey
*
1724 load_pkcs11_key(char *path
)
1726 #ifdef ENABLE_PKCS11
1727 struct sshkey
**keys
= NULL
, *public, *private = NULL
;
1730 if ((r
= sshkey_load_public(path
, &public, NULL
)) != 0)
1731 fatal_r(r
, "Couldn't load CA public key \"%s\"", path
);
1733 nkeys
= pkcs11_add_provider(pkcs11provider
, identity_passphrase
,
1735 debug3_f("%d keys", nkeys
);
1737 fatal("cannot read public key from pkcs11");
1738 for (i
= 0; i
< nkeys
; i
++) {
1739 if (sshkey_equal_public(public, keys
[i
])) {
1743 sshkey_free(keys
[i
]);
1746 sshkey_free(public);
1749 fatal("no pkcs11 support");
1750 #endif /* ENABLE_PKCS11 */
1753 /* Signer for sshkey_certify_custom that uses the agent */
1755 agent_signer(struct sshkey
*key
, u_char
**sigp
, size_t *lenp
,
1756 const u_char
*data
, size_t datalen
,
1757 const char *alg
, const char *provider
, const char *pin
,
1758 u_int compat
, void *ctx
)
1760 int *agent_fdp
= (int *)ctx
;
1762 return ssh_agent_sign(*agent_fdp
, key
, sigp
, lenp
,
1763 data
, datalen
, alg
, compat
);
1767 do_ca_sign(struct passwd
*pw
, const char *ca_key_path
, int prefer_agent
,
1768 unsigned long long cert_serial
, int cert_serial_autoinc
,
1769 int argc
, char **argv
)
1771 int r
, i
, found
, agent_fd
= -1;
1773 struct sshkey
*ca
, *public;
1774 char valid
[64], *otmp
, *tmp
, *cp
, *out
, *comment
;
1775 char *ca_fp
= NULL
, **plist
= NULL
, *pin
= NULL
;
1776 struct ssh_identitylist
*agent_ids
;
1778 struct notifier_ctx
*notifier
= NULL
;
1780 #ifdef ENABLE_PKCS11
1783 tmp
= tilde_expand_filename(ca_key_path
, pw
->pw_uid
);
1784 if (pkcs11provider
!= NULL
) {
1785 /* If a PKCS#11 token was specified then try to use it */
1786 if ((ca
= load_pkcs11_key(tmp
)) == NULL
)
1787 fatal("No PKCS#11 key matching %s found", ca_key_path
);
1788 } else if (prefer_agent
) {
1790 * Agent signature requested. Try to use agent after making
1791 * sure the public key specified is actually present in the
1794 if ((r
= sshkey_load_public(tmp
, &ca
, NULL
)) != 0)
1795 fatal_r(r
, "Cannot load CA public key %s", tmp
);
1796 if ((r
= ssh_get_authentication_socket(&agent_fd
)) != 0)
1797 fatal_r(r
, "Cannot use public key for CA signature");
1798 if ((r
= ssh_fetch_identitylist(agent_fd
, &agent_ids
)) != 0)
1799 fatal_r(r
, "Retrieve agent key list");
1801 for (j
= 0; j
< agent_ids
->nkeys
; j
++) {
1802 if (sshkey_equal(ca
, agent_ids
->keys
[j
])) {
1808 fatal("CA key %s not found in agent", tmp
);
1809 ssh_free_identitylist(agent_ids
);
1810 ca
->flags
|= SSHKEY_FLAG_EXT
;
1812 /* CA key is assumed to be a private key on the filesystem */
1813 ca
= load_identity(tmp
, NULL
);
1814 if (sshkey_is_sk(ca
) &&
1815 (ca
->sk_flags
& SSH_SK_USER_VERIFICATION_REQD
)) {
1816 if ((pin
= read_passphrase("Enter PIN for CA key: ",
1817 RP_ALLOW_STDIN
)) == NULL
)
1818 fatal_f("couldn't read PIN");
1823 if (key_type_name
!= NULL
) {
1824 if (sshkey_type_from_name(key_type_name
) != ca
->type
) {
1825 fatal("CA key type %s doesn't match specified %s",
1826 sshkey_ssh_name(ca
), key_type_name
);
1828 } else if (ca
->type
== KEY_RSA
) {
1829 /* Default to a good signature algorithm */
1830 key_type_name
= "rsa-sha2-512";
1832 ca_fp
= sshkey_fingerprint(ca
, fingerprint_hash
, SSH_FP_DEFAULT
);
1834 finalise_cert_exts();
1835 for (i
= 0; i
< argc
; i
++) {
1836 /* Split list of principals */
1838 if (cert_principals
!= NULL
) {
1839 otmp
= tmp
= xstrdup(cert_principals
);
1841 for (; (cp
= strsep(&tmp
, ",")) != NULL
; n
++) {
1842 plist
= xreallocarray(plist
, n
+ 1, sizeof(*plist
));
1843 if (*(plist
[n
] = xstrdup(cp
)) == '\0')
1844 fatal("Empty principal name");
1848 if (n
> SSHKEY_CERT_MAX_PRINCIPALS
)
1849 fatal("Too many certificate principals specified");
1851 tmp
= tilde_expand_filename(argv
[i
], pw
->pw_uid
);
1852 if ((r
= sshkey_load_public(tmp
, &public, &comment
)) != 0)
1853 fatal_r(r
, "load pubkey \"%s\"", tmp
);
1854 if (sshkey_is_cert(public))
1855 fatal_f("key \"%s\" type %s cannot be certified",
1856 tmp
, sshkey_type(public));
1858 /* Prepare certificate to sign */
1859 if ((r
= sshkey_to_certified(public)) != 0)
1860 fatal_r(r
, "Could not upgrade key %s to certificate", tmp
);
1861 public->cert
->type
= cert_key_type
;
1862 public->cert
->serial
= (u_int64_t
)cert_serial
;
1863 public->cert
->key_id
= xstrdup(cert_key_id
);
1864 public->cert
->nprincipals
= n
;
1865 public->cert
->principals
= plist
;
1866 public->cert
->valid_after
= cert_valid_from
;
1867 public->cert
->valid_before
= cert_valid_to
;
1868 prepare_options_buf(public->cert
->critical
, OPTIONS_CRITICAL
);
1869 prepare_options_buf(public->cert
->extensions
,
1870 OPTIONS_EXTENSIONS
);
1871 if ((r
= sshkey_from_private(ca
,
1872 &public->cert
->signature_key
)) != 0)
1873 fatal_r(r
, "sshkey_from_private (ca key)");
1875 if (agent_fd
!= -1 && (ca
->flags
& SSHKEY_FLAG_EXT
) != 0) {
1876 if ((r
= sshkey_certify_custom(public, ca
,
1877 key_type_name
, sk_provider
, NULL
, agent_signer
,
1879 fatal_r(r
, "Couldn't certify %s via agent", tmp
);
1881 if (sshkey_is_sk(ca
) &&
1882 (ca
->sk_flags
& SSH_SK_USER_PRESENCE_REQD
)) {
1883 notifier
= notify_start(0,
1884 "Confirm user presence for key %s %s",
1885 sshkey_type(ca
), ca_fp
);
1887 r
= sshkey_certify(public, ca
, key_type_name
,
1889 notify_complete(notifier
, "User presence confirmed");
1891 fatal_r(r
, "Couldn't certify key %s", tmp
);
1894 if ((cp
= strrchr(tmp
, '.')) != NULL
&& strcmp(cp
, ".pub") == 0)
1896 xasprintf(&out
, "%s-cert.pub", tmp
);
1899 if ((r
= sshkey_save_public(public, out
, comment
)) != 0) {
1900 fatal_r(r
, "Unable to save public key to %s",
1905 sshkey_format_cert_validity(public->cert
,
1906 valid
, sizeof(valid
));
1907 logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1908 "valid %s", sshkey_cert_type(public),
1909 out
, public->cert
->key_id
,
1910 (unsigned long long)public->cert
->serial
,
1911 cert_principals
!= NULL
? " for " : "",
1912 cert_principals
!= NULL
? cert_principals
: "",
1916 sshkey_free(public);
1918 if (cert_serial_autoinc
)
1922 freezero(pin
, strlen(pin
));
1924 #ifdef ENABLE_PKCS11
1931 parse_relative_time(const char *s
, time_t now
)
1935 mul
= *s
== '-' ? -1 : 1;
1937 if ((secs
= convtime(s
+ 1)) == -1)
1938 fatal("Invalid relative certificate time %s", s
);
1939 if (mul
== -1 && secs
> now
)
1940 fatal("Certificate time %s cannot be represented", s
);
1941 return now
+ (u_int64_t
)(secs
* mul
);
1945 parse_hex_u64(const char *s
, uint64_t *up
)
1948 unsigned long long ull
;
1951 ull
= strtoull(s
, &ep
, 16);
1952 if (*s
== '\0' || *ep
!= '\0')
1953 fatal("Invalid certificate time: not a number");
1954 if (errno
== ERANGE
&& ull
== ULONG_MAX
)
1955 fatal_fr(SSH_ERR_SYSTEM_ERROR
, "Invalid certificate time");
1956 *up
= (uint64_t)ull
;
1960 parse_cert_times(char *timespec
)
1963 time_t now
= time(NULL
);
1966 /* +timespec relative to now */
1967 if (*timespec
== '+' && strchr(timespec
, ':') == NULL
) {
1968 if ((secs
= convtime(timespec
+ 1)) == -1)
1969 fatal("Invalid relative certificate life %s", timespec
);
1970 cert_valid_to
= now
+ secs
;
1972 * Backdate certificate one minute to avoid problems on hosts
1973 * with poorly-synchronised clocks.
1975 cert_valid_from
= ((now
- 59)/ 60) * 60;
1981 * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | 0x... | "always"
1982 * to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | 0x... | "forever"
1984 from
= xstrdup(timespec
);
1985 to
= strchr(from
, ':');
1986 if (to
== NULL
|| from
== to
|| *(to
+ 1) == '\0')
1987 fatal("Invalid certificate life specification %s", timespec
);
1990 if (*from
== '-' || *from
== '+')
1991 cert_valid_from
= parse_relative_time(from
, now
);
1992 else if (strcmp(from
, "always") == 0)
1993 cert_valid_from
= 0;
1994 else if (strncmp(from
, "0x", 2) == 0)
1995 parse_hex_u64(from
, &cert_valid_from
);
1996 else if (parse_absolute_time(from
, &cert_valid_from
) != 0)
1997 fatal("Invalid from time \"%s\"", from
);
1999 if (*to
== '-' || *to
== '+')
2000 cert_valid_to
= parse_relative_time(to
, now
);
2001 else if (strcmp(to
, "forever") == 0)
2002 cert_valid_to
= ~(u_int64_t
)0;
2003 else if (strncmp(to
, "0x", 2) == 0)
2004 parse_hex_u64(to
, &cert_valid_to
);
2005 else if (parse_absolute_time(to
, &cert_valid_to
) != 0)
2006 fatal("Invalid to time \"%s\"", to
);
2008 if (cert_valid_to
<= cert_valid_from
)
2009 fatal("Empty certificate validity interval");
2014 add_cert_option(char *opt
)
2019 if (strcasecmp(opt
, "clear") == 0)
2020 certflags_flags
= 0;
2021 else if (strcasecmp(opt
, "no-x11-forwarding") == 0)
2022 certflags_flags
&= ~CERTOPT_X_FWD
;
2023 else if (strcasecmp(opt
, "permit-x11-forwarding") == 0)
2024 certflags_flags
|= CERTOPT_X_FWD
;
2025 else if (strcasecmp(opt
, "no-agent-forwarding") == 0)
2026 certflags_flags
&= ~CERTOPT_AGENT_FWD
;
2027 else if (strcasecmp(opt
, "permit-agent-forwarding") == 0)
2028 certflags_flags
|= CERTOPT_AGENT_FWD
;
2029 else if (strcasecmp(opt
, "no-port-forwarding") == 0)
2030 certflags_flags
&= ~CERTOPT_PORT_FWD
;
2031 else if (strcasecmp(opt
, "permit-port-forwarding") == 0)
2032 certflags_flags
|= CERTOPT_PORT_FWD
;
2033 else if (strcasecmp(opt
, "no-pty") == 0)
2034 certflags_flags
&= ~CERTOPT_PTY
;
2035 else if (strcasecmp(opt
, "permit-pty") == 0)
2036 certflags_flags
|= CERTOPT_PTY
;
2037 else if (strcasecmp(opt
, "no-user-rc") == 0)
2038 certflags_flags
&= ~CERTOPT_USER_RC
;
2039 else if (strcasecmp(opt
, "permit-user-rc") == 0)
2040 certflags_flags
|= CERTOPT_USER_RC
;
2041 else if (strcasecmp(opt
, "touch-required") == 0)
2042 certflags_flags
&= ~CERTOPT_NO_REQUIRE_USER_PRESENCE
;
2043 else if (strcasecmp(opt
, "no-touch-required") == 0)
2044 certflags_flags
|= CERTOPT_NO_REQUIRE_USER_PRESENCE
;
2045 else if (strcasecmp(opt
, "no-verify-required") == 0)
2046 certflags_flags
&= ~CERTOPT_REQUIRE_VERIFY
;
2047 else if (strcasecmp(opt
, "verify-required") == 0)
2048 certflags_flags
|= CERTOPT_REQUIRE_VERIFY
;
2049 else if (strncasecmp(opt
, "force-command=", 14) == 0) {
2052 fatal("Empty force-command option");
2053 if (certflags_command
!= NULL
)
2054 fatal("force-command already specified");
2055 certflags_command
= xstrdup(val
);
2056 } else if (strncasecmp(opt
, "source-address=", 15) == 0) {
2059 fatal("Empty source-address option");
2060 if (certflags_src_addr
!= NULL
)
2061 fatal("source-address already specified");
2062 if (addr_match_cidr_list(NULL
, val
) != 0)
2063 fatal("Invalid source-address list");
2064 certflags_src_addr
= xstrdup(val
);
2065 } else if (strncasecmp(opt
, "extension:", 10) == 0 ||
2066 (iscrit
= (strncasecmp(opt
, "critical:", 9) == 0))) {
2067 val
= xstrdup(strchr(opt
, ':') + 1);
2068 if ((cp
= strchr(val
, '=')) != NULL
)
2070 cert_ext_add(val
, cp
, iscrit
);
2073 fatal("Unsupported certificate option \"%s\"", opt
);
2077 show_options(struct sshbuf
*optbuf
, int in_critical
)
2079 char *name
, *arg
, *hex
;
2080 struct sshbuf
*options
, *option
= NULL
;
2083 if ((options
= sshbuf_fromb(optbuf
)) == NULL
)
2084 fatal_f("sshbuf_fromb failed");
2085 while (sshbuf_len(options
) != 0) {
2086 sshbuf_free(option
);
2088 if ((r
= sshbuf_get_cstring(options
, &name
, NULL
)) != 0 ||
2089 (r
= sshbuf_froms(options
, &option
)) != 0)
2090 fatal_fr(r
, "parse option");
2091 printf(" %s", name
);
2093 (strcmp(name
, "permit-X11-forwarding") == 0 ||
2094 strcmp(name
, "permit-agent-forwarding") == 0 ||
2095 strcmp(name
, "permit-port-forwarding") == 0 ||
2096 strcmp(name
, "permit-pty") == 0 ||
2097 strcmp(name
, "permit-user-rc") == 0 ||
2098 strcmp(name
, "no-touch-required") == 0)) {
2100 } else if (in_critical
&&
2101 (strcmp(name
, "force-command") == 0 ||
2102 strcmp(name
, "source-address") == 0)) {
2103 if ((r
= sshbuf_get_cstring(option
, &arg
, NULL
)) != 0)
2104 fatal_fr(r
, "parse critical");
2105 printf(" %s\n", arg
);
2107 } else if (in_critical
&&
2108 strcmp(name
, "verify-required") == 0) {
2110 } else if (sshbuf_len(option
) > 0) {
2111 hex
= sshbuf_dtob16(option
);
2112 printf(" UNKNOWN OPTION: %s (len %zu)\n",
2113 hex
, sshbuf_len(option
));
2114 sshbuf_reset(option
);
2117 printf(" UNKNOWN FLAG OPTION\n");
2119 if (sshbuf_len(option
) != 0)
2120 fatal("Option corrupt: extra data at end");
2122 sshbuf_free(option
);
2123 sshbuf_free(options
);
2127 print_cert(struct sshkey
*key
)
2129 char valid
[64], *key_fp
, *ca_fp
;
2132 key_fp
= sshkey_fingerprint(key
, fingerprint_hash
, SSH_FP_DEFAULT
);
2133 ca_fp
= sshkey_fingerprint(key
->cert
->signature_key
,
2134 fingerprint_hash
, SSH_FP_DEFAULT
);
2135 if (key_fp
== NULL
|| ca_fp
== NULL
)
2136 fatal_f("sshkey_fingerprint fail");
2137 sshkey_format_cert_validity(key
->cert
, valid
, sizeof(valid
));
2139 printf(" Type: %s %s certificate\n", sshkey_ssh_name(key
),
2140 sshkey_cert_type(key
));
2141 printf(" Public key: %s %s\n", sshkey_type(key
), key_fp
);
2142 printf(" Signing CA: %s %s (using %s)\n",
2143 sshkey_type(key
->cert
->signature_key
), ca_fp
,
2144 key
->cert
->signature_type
);
2145 printf(" Key ID: \"%s\"\n", key
->cert
->key_id
);
2146 printf(" Serial: %llu\n", (unsigned long long)key
->cert
->serial
);
2147 printf(" Valid: %s\n", valid
);
2148 printf(" Principals: ");
2149 if (key
->cert
->nprincipals
== 0)
2152 for (i
= 0; i
< key
->cert
->nprincipals
; i
++)
2154 key
->cert
->principals
[i
]);
2157 printf(" Critical Options: ");
2158 if (sshbuf_len(key
->cert
->critical
) == 0)
2162 show_options(key
->cert
->critical
, 1);
2164 printf(" Extensions: ");
2165 if (sshbuf_len(key
->cert
->extensions
) == 0)
2169 show_options(key
->cert
->extensions
, 0);
2174 do_show_cert(struct passwd
*pw
)
2176 struct sshkey
*key
= NULL
;
2178 int r
, is_stdin
= 0, ok
= 0;
2180 char *cp
, *line
= NULL
;
2182 size_t linesize
= 0;
2186 ask_filename(pw
, "Enter file in which the key is");
2187 if (strcmp(identity_file
, "-") != 0 && stat(identity_file
, &st
) == -1)
2188 fatal("%s: %s: %s", __progname
, identity_file
, strerror(errno
));
2190 path
= identity_file
;
2191 if (strcmp(path
, "-") == 0) {
2195 } else if ((f
= fopen(identity_file
, "r")) == NULL
)
2196 fatal("fopen %s: %s", identity_file
, strerror(errno
));
2198 while (getline(&line
, &linesize
, f
) != -1) {
2202 /* Trim leading space and comments */
2203 cp
= line
+ strspn(line
, " \t");
2204 if (*cp
== '#' || *cp
== '\0')
2206 if ((key
= sshkey_new(KEY_UNSPEC
)) == NULL
)
2207 fatal("sshkey_new");
2208 if ((r
= sshkey_read(key
, &cp
)) != 0) {
2209 error_r(r
, "%s:%lu: invalid key", path
, lnum
);
2212 if (!sshkey_is_cert(key
)) {
2213 error("%s:%lu is not a certificate", path
, lnum
);
2217 if (!is_stdin
&& lnum
== 1)
2218 printf("%s:\n", path
);
2220 printf("%s:%lu:\n", path
, lnum
);
2230 load_krl(const char *path
, struct ssh_krl
**krlp
)
2232 struct sshbuf
*krlbuf
;
2235 if ((r
= sshbuf_load_file(path
, &krlbuf
)) != 0)
2236 fatal_r(r
, "Unable to load KRL %s", path
);
2237 /* XXX check sigs */
2238 if ((r
= ssh_krl_from_blob(krlbuf
, krlp
)) != 0 ||
2240 fatal_r(r
, "Invalid KRL file %s", path
);
2241 sshbuf_free(krlbuf
);
2245 hash_to_blob(const char *cp
, u_char
**blobp
, size_t *lenp
,
2246 const char *file
, u_long lnum
)
2253 if (strncmp(cp
, "SHA256:", 7) != 0)
2254 fatal("%s:%lu: unsupported hash algorithm", file
, lnum
);
2258 * OpenSSH base64 hashes omit trailing '='
2259 * characters; put them back for decode.
2261 if ((tlen
= strlen(cp
)) >= SIZE_MAX
- 5)
2262 fatal_f("hash too long: %zu bytes", tlen
);
2263 tmp
= xmalloc(tlen
+ 4 + 1);
2264 strlcpy(tmp
, cp
, tlen
+ 1);
2265 while ((tlen
% 4) != 0) {
2269 if ((b
= sshbuf_new()) == NULL
)
2270 fatal_f("sshbuf_new failed");
2271 if ((r
= sshbuf_b64tod(b
, tmp
)) != 0)
2272 fatal_r(r
, "%s:%lu: decode hash failed", file
, lnum
);
2274 *lenp
= sshbuf_len(b
);
2275 *blobp
= xmalloc(*lenp
);
2276 memcpy(*blobp
, sshbuf_ptr(b
), *lenp
);
2281 update_krl_from_file(struct passwd
*pw
, const char *file
, int wild_ca
,
2282 const struct sshkey
*ca
, struct ssh_krl
*krl
)
2284 struct sshkey
*key
= NULL
;
2286 char *path
, *cp
, *ep
, *line
= NULL
;
2287 u_char
*blob
= NULL
;
2288 size_t blen
= 0, linesize
= 0;
2289 unsigned long long serial
, serial2
;
2290 int i
, was_explicit_key
, was_sha1
, was_sha256
, was_hash
, r
;
2293 path
= tilde_expand_filename(file
, pw
->pw_uid
);
2294 if (strcmp(path
, "-") == 0) {
2297 path
= xstrdup("(standard input)");
2298 } else if ((krl_spec
= fopen(path
, "r")) == NULL
)
2299 fatal("fopen %s: %s", path
, strerror(errno
));
2302 printf("Revoking from %s\n", path
);
2303 while (getline(&line
, &linesize
, krl_spec
) != -1) {
2304 if (linesize
>= INT_MAX
) {
2305 fatal_f("%s contains unparsable line, len=%zu",
2309 was_explicit_key
= was_sha1
= was_sha256
= was_hash
= 0;
2310 cp
= line
+ strspn(line
, " \t");
2311 /* Trim trailing space, comments and strip \n */
2312 for (i
= 0, r
= -1; cp
[i
] != '\0'; i
++) {
2313 if (cp
[i
] == '#' || cp
[i
] == '\n') {
2317 if (cp
[i
] == ' ' || cp
[i
] == '\t') {
2318 /* Remember the start of a span of whitespace */
2328 if (strncasecmp(cp
, "serial:", 7) == 0) {
2329 if (ca
== NULL
&& !wild_ca
) {
2330 fatal("revoking certificates by serial number "
2331 "requires specification of a CA key");
2334 cp
= cp
+ strspn(cp
, " \t");
2336 serial
= strtoull(cp
, &ep
, 0);
2337 if (*cp
== '\0' || (*ep
!= '\0' && *ep
!= '-'))
2338 fatal("%s:%lu: invalid serial \"%s\"",
2340 if (errno
== ERANGE
&& serial
== ULLONG_MAX
)
2341 fatal("%s:%lu: serial out of range",
2347 serial2
= strtoull(cp
, &ep
, 0);
2348 if (*cp
== '\0' || *ep
!= '\0')
2349 fatal("%s:%lu: invalid serial \"%s\"",
2351 if (errno
== ERANGE
&& serial2
== ULLONG_MAX
)
2352 fatal("%s:%lu: serial out of range",
2354 if (serial2
<= serial
)
2355 fatal("%s:%lu: invalid serial range "
2356 "%llu:%llu", path
, lnum
,
2357 (unsigned long long)serial
,
2358 (unsigned long long)serial2
);
2360 if (ssh_krl_revoke_cert_by_serial_range(krl
,
2361 ca
, serial
, serial2
) != 0) {
2362 fatal_f("revoke serial failed");
2364 } else if (strncasecmp(cp
, "id:", 3) == 0) {
2365 if (ca
== NULL
&& !wild_ca
) {
2366 fatal("revoking certificates by key ID "
2367 "requires specification of a CA key");
2370 cp
= cp
+ strspn(cp
, " \t");
2371 if (ssh_krl_revoke_cert_by_key_id(krl
, ca
, cp
) != 0)
2372 fatal_f("revoke key ID failed");
2373 } else if (strncasecmp(cp
, "hash:", 5) == 0) {
2375 cp
= cp
+ strspn(cp
, " \t");
2376 hash_to_blob(cp
, &blob
, &blen
, file
, lnum
);
2377 r
= ssh_krl_revoke_key_sha256(krl
, blob
, blen
);
2379 fatal_fr(r
, "revoke key failed");
2381 if (strncasecmp(cp
, "key:", 4) == 0) {
2383 cp
= cp
+ strspn(cp
, " \t");
2384 was_explicit_key
= 1;
2385 } else if (strncasecmp(cp
, "sha1:", 5) == 0) {
2387 cp
= cp
+ strspn(cp
, " \t");
2389 } else if (strncasecmp(cp
, "sha256:", 7) == 0) {
2391 cp
= cp
+ strspn(cp
, " \t");
2394 * Just try to process the line as a key.
2395 * Parsing will fail if it isn't.
2398 if ((key
= sshkey_new(KEY_UNSPEC
)) == NULL
)
2399 fatal("sshkey_new");
2400 if ((r
= sshkey_read(key
, &cp
)) != 0)
2401 fatal_r(r
, "%s:%lu: invalid key", path
, lnum
);
2402 if (was_explicit_key
)
2403 r
= ssh_krl_revoke_key_explicit(krl
, key
);
2404 else if (was_sha1
) {
2405 if (sshkey_fingerprint_raw(key
,
2406 SSH_DIGEST_SHA1
, &blob
, &blen
) != 0) {
2407 fatal("%s:%lu: fingerprint failed",
2410 r
= ssh_krl_revoke_key_sha1(krl
, blob
, blen
);
2411 } else if (was_sha256
) {
2412 if (sshkey_fingerprint_raw(key
,
2413 SSH_DIGEST_SHA256
, &blob
, &blen
) != 0) {
2414 fatal("%s:%lu: fingerprint failed",
2417 r
= ssh_krl_revoke_key_sha256(krl
, blob
, blen
);
2419 r
= ssh_krl_revoke_key(krl
, key
);
2421 fatal_fr(r
, "revoke key failed");
2422 freezero(blob
, blen
);
2428 if (strcmp(path
, "-") != 0)
2435 do_gen_krl(struct passwd
*pw
, int updating
, const char *ca_key_path
,
2436 unsigned long long krl_version
, const char *krl_comment
,
2437 int argc
, char **argv
)
2439 struct ssh_krl
*krl
;
2441 struct sshkey
*ca
= NULL
;
2442 int i
, r
, wild_ca
= 0;
2444 struct sshbuf
*kbuf
;
2446 if (*identity_file
== '\0')
2447 fatal("KRL generation requires an output file");
2448 if (stat(identity_file
, &sb
) == -1) {
2449 if (errno
!= ENOENT
)
2450 fatal("Cannot access KRL \"%s\": %s",
2451 identity_file
, strerror(errno
));
2453 fatal("KRL \"%s\" does not exist", identity_file
);
2455 if (ca_key_path
!= NULL
) {
2456 if (strcasecmp(ca_key_path
, "none") == 0)
2459 tmp
= tilde_expand_filename(ca_key_path
, pw
->pw_uid
);
2460 if ((r
= sshkey_load_public(tmp
, &ca
, NULL
)) != 0)
2461 fatal_r(r
, "Cannot load CA public key %s", tmp
);
2467 load_krl(identity_file
, &krl
);
2468 else if ((krl
= ssh_krl_init()) == NULL
)
2469 fatal("couldn't create KRL");
2471 if (krl_version
!= 0)
2472 ssh_krl_set_version(krl
, krl_version
);
2473 if (krl_comment
!= NULL
)
2474 ssh_krl_set_comment(krl
, krl_comment
);
2476 for (i
= 0; i
< argc
; i
++)
2477 update_krl_from_file(pw
, argv
[i
], wild_ca
, ca
, krl
);
2479 if ((kbuf
= sshbuf_new()) == NULL
)
2480 fatal("sshbuf_new failed");
2481 if (ssh_krl_to_blob(krl
, kbuf
) != 0)
2482 fatal("Couldn't generate KRL");
2483 if ((r
= sshbuf_write_file(identity_file
, kbuf
)) != 0)
2484 fatal("write %s: %s", identity_file
, strerror(errno
));
2491 do_check_krl(struct passwd
*pw
, int print_krl
, int argc
, char **argv
)
2495 struct ssh_krl
*krl
;
2498 if (*identity_file
== '\0')
2499 fatal("KRL checking requires an input file");
2500 load_krl(identity_file
, &krl
);
2502 krl_dump(krl
, stdout
);
2503 for (i
= 0; i
< argc
; i
++) {
2504 if ((r
= sshkey_load_public(argv
[i
], &k
, &comment
)) != 0)
2505 fatal_r(r
, "Cannot load public key %s", argv
[i
]);
2506 r
= ssh_krl_check_key(krl
, k
);
2507 printf("%s%s%s%s: %s\n", argv
[i
],
2508 *comment
? " (" : "", comment
, *comment
? ")" : "",
2509 r
== 0 ? "ok" : "REVOKED");
2519 static struct sshkey
*
2520 load_sign_key(const char *keypath
, const struct sshkey
*pubkey
)
2522 size_t i
, slen
, plen
= strlen(keypath
);
2523 char *privpath
= xstrdup(keypath
);
2524 static const char * const suffixes
[] = { "-cert.pub", ".pub", NULL
};
2525 struct sshkey
*ret
= NULL
, *privkey
= NULL
;
2530 * If passed a public key filename, then try to locate the corresponding
2531 * private key. This lets us specify certificates on the command-line
2532 * and have ssh-keygen find the appropriate private key.
2534 for (i
= 0; suffixes
[i
]; i
++) {
2535 slen
= strlen(suffixes
[i
]);
2537 strcmp(privpath
+ plen
- slen
, suffixes
[i
]) != 0)
2539 privpath
[plen
- slen
] = '\0';
2540 debug_f("%s looks like a public key, using private key "
2541 "path %s instead", keypath
, privpath
);
2544 if (waspub
&& stat(privpath
, &st
) != 0 && errno
== ENOENT
)
2545 fatal("No private key found for public key \"%s\"", keypath
);
2546 if ((r
= sshkey_load_private(privpath
, "", &privkey
, NULL
)) != 0 &&
2547 (r
!= SSH_ERR_KEY_WRONG_PASSPHRASE
)) {
2548 debug_fr(r
, "load private key \"%s\"", privpath
);
2549 fatal("No private key found for \"%s\"", privpath
);
2550 } else if (privkey
== NULL
)
2551 privkey
= load_identity(privpath
, NULL
);
2553 if (!sshkey_equal_public(pubkey
, privkey
)) {
2554 error("Public key %s doesn't match private %s",
2558 if (sshkey_is_cert(pubkey
) && !sshkey_is_cert(privkey
)) {
2560 * Graft the certificate onto the private key to make
2561 * it capable of signing.
2563 if ((r
= sshkey_to_certified(privkey
)) != 0) {
2564 error_fr(r
, "sshkey_to_certified");
2567 if ((r
= sshkey_cert_copy(pubkey
, privkey
)) != 0) {
2568 error_fr(r
, "sshkey_cert_copy");
2576 sshkey_free(privkey
);
2582 sign_one(struct sshkey
*signkey
, const char *filename
, int fd
,
2583 const char *sig_namespace
, const char *hashalg
, sshsig_signer
*signer
,
2586 struct sshbuf
*sigbuf
= NULL
, *abuf
= NULL
;
2587 int r
= SSH_ERR_INTERNAL_ERROR
, wfd
= -1, oerrno
;
2588 char *wfile
= NULL
, *asig
= NULL
, *fp
= NULL
;
2589 char *pin
= NULL
, *prompt
= NULL
;
2592 if (fd
== STDIN_FILENO
)
2593 fprintf(stderr
, "Signing data on standard input\n");
2595 fprintf(stderr
, "Signing file %s\n", filename
);
2597 if (signer
== NULL
&& sshkey_is_sk(signkey
)) {
2598 if ((signkey
->sk_flags
& SSH_SK_USER_VERIFICATION_REQD
)) {
2599 xasprintf(&prompt
, "Enter PIN for %s key: ",
2600 sshkey_type(signkey
));
2601 if ((pin
= read_passphrase(prompt
,
2602 RP_ALLOW_STDIN
)) == NULL
)
2603 fatal_f("couldn't read PIN");
2605 if ((signkey
->sk_flags
& SSH_SK_USER_PRESENCE_REQD
)) {
2606 if ((fp
= sshkey_fingerprint(signkey
, fingerprint_hash
,
2607 SSH_FP_DEFAULT
)) == NULL
)
2608 fatal_f("fingerprint failed");
2609 fprintf(stderr
, "Confirm user presence for key %s %s\n",
2610 sshkey_type(signkey
), fp
);
2614 if ((r
= sshsig_sign_fd(signkey
, hashalg
, sk_provider
, pin
,
2615 fd
, sig_namespace
, &sigbuf
, signer
, signer_ctx
)) != 0) {
2616 error_r(r
, "Signing %s failed", filename
);
2619 if ((r
= sshsig_armor(sigbuf
, &abuf
)) != 0) {
2620 error_fr(r
, "sshsig_armor");
2623 if ((asig
= sshbuf_dup_string(abuf
)) == NULL
) {
2624 error_f("buffer error");
2625 r
= SSH_ERR_ALLOC_FAIL
;
2629 if (fd
== STDIN_FILENO
) {
2630 fputs(asig
, stdout
);
2633 xasprintf(&wfile
, "%s.sig", filename
);
2634 if (confirm_overwrite(wfile
)) {
2635 if ((wfd
= open(wfile
, O_WRONLY
|O_CREAT
|O_TRUNC
,
2638 error("Cannot open %s: %s",
2639 wfile
, strerror(errno
));
2641 r
= SSH_ERR_SYSTEM_ERROR
;
2644 if (atomicio(vwrite
, wfd
, asig
,
2645 strlen(asig
)) != strlen(asig
)) {
2647 error("Cannot write to %s: %s",
2648 wfile
, strerror(errno
));
2650 r
= SSH_ERR_SYSTEM_ERROR
;
2654 fprintf(stderr
, "Write signature to %s\n",
2666 freezero(pin
, strlen(pin
));
2668 sshbuf_free(sigbuf
);
2675 sig_process_opts(char * const *opts
, size_t nopts
, char **hashalgp
,
2676 uint64_t *verify_timep
, int *print_pubkey
)
2681 if (verify_timep
!= NULL
)
2683 if (print_pubkey
!= NULL
)
2685 if (hashalgp
!= NULL
)
2687 for (i
= 0; i
< nopts
; i
++) {
2688 if (hashalgp
!= NULL
&&
2689 strncasecmp(opts
[i
], "hashalg=", 8) == 0) {
2690 *hashalgp
= xstrdup(opts
[i
] + 8);
2691 } else if (verify_timep
&&
2692 strncasecmp(opts
[i
], "verify-time=", 12) == 0) {
2693 if (parse_absolute_time(opts
[i
] + 12,
2694 verify_timep
) != 0 || *verify_timep
== 0) {
2695 error("Invalid \"verify-time\" option");
2696 return SSH_ERR_INVALID_ARGUMENT
;
2698 } else if (print_pubkey
&&
2699 strcasecmp(opts
[i
], "print-pubkey") == 0) {
2702 error("Invalid option \"%s\"", opts
[i
]);
2703 return SSH_ERR_INVALID_ARGUMENT
;
2706 if (verify_timep
&& *verify_timep
== 0) {
2707 if ((now
= time(NULL
)) < 0) {
2708 error("Time is before epoch");
2709 return SSH_ERR_INVALID_ARGUMENT
;
2711 *verify_timep
= (uint64_t)now
;
2718 sig_sign(const char *keypath
, const char *sig_namespace
, int require_agent
,
2719 int argc
, char **argv
, char * const *opts
, size_t nopts
)
2721 int i
, fd
= -1, r
, ret
= -1;
2723 struct sshkey
*pubkey
= NULL
, *privkey
= NULL
, *signkey
= NULL
;
2724 sshsig_signer
*signer
= NULL
;
2725 char *hashalg
= NULL
;
2727 /* Check file arguments. */
2728 for (i
= 0; i
< argc
; i
++) {
2729 if (strcmp(argv
[i
], "-") != 0)
2731 if (i
> 0 || argc
> 1)
2732 fatal("Cannot sign mix of paths and standard input");
2735 if (sig_process_opts(opts
, nopts
, &hashalg
, NULL
, NULL
) != 0)
2736 goto done
; /* error already logged */
2738 if ((r
= sshkey_load_public(keypath
, &pubkey
, NULL
)) != 0) {
2739 error_r(r
, "Couldn't load public key %s", keypath
);
2743 if ((r
= ssh_get_authentication_socket(&agent_fd
)) != 0) {
2745 fatal("Couldn't get agent socket");
2746 debug_r(r
, "Couldn't get agent socket");
2748 if ((r
= ssh_agent_has_key(agent_fd
, pubkey
)) == 0)
2749 signer
= agent_signer
;
2752 fatal("Couldn't find key in agent");
2753 debug_r(r
, "Couldn't find key in agent");
2757 if (signer
== NULL
) {
2758 /* Not using agent - try to load private key */
2759 if ((privkey
= load_sign_key(keypath
, pubkey
)) == NULL
)
2763 /* Will use key in agent */
2768 if ((r
= sign_one(signkey
, "(stdin)", STDIN_FILENO
,
2769 sig_namespace
, hashalg
, signer
, &agent_fd
)) != 0)
2772 for (i
= 0; i
< argc
; i
++) {
2773 if (strcmp(argv
[i
], "-") == 0)
2775 else if ((fd
= open(argv
[i
], O_RDONLY
)) == -1) {
2776 error("Cannot open %s for signing: %s",
2777 argv
[i
], strerror(errno
));
2780 if ((r
= sign_one(signkey
, argv
[i
], fd
, sig_namespace
,
2781 hashalg
, signer
, &agent_fd
)) != 0)
2783 if (fd
!= STDIN_FILENO
)
2791 if (fd
!= -1 && fd
!= STDIN_FILENO
)
2793 sshkey_free(pubkey
);
2794 sshkey_free(privkey
);
2800 sig_verify(const char *signature
, const char *sig_namespace
,
2801 const char *principal
, const char *allowed_keys
, const char *revoked_keys
,
2802 char * const *opts
, size_t nopts
)
2805 int print_pubkey
= 0;
2806 struct sshbuf
*sigbuf
= NULL
, *abuf
= NULL
;
2807 struct sshkey
*sign_key
= NULL
;
2809 struct sshkey_sig_details
*sig_details
= NULL
;
2810 uint64_t verify_time
= 0;
2812 if (sig_process_opts(opts
, nopts
, NULL
, &verify_time
,
2813 &print_pubkey
) != 0)
2814 goto done
; /* error already logged */
2816 memset(&sig_details
, 0, sizeof(sig_details
));
2817 if ((r
= sshbuf_load_file(signature
, &abuf
)) != 0) {
2818 error_r(r
, "Couldn't read signature file");
2822 if ((r
= sshsig_dearmor(abuf
, &sigbuf
)) != 0) {
2823 error_fr(r
, "sshsig_armor");
2826 if ((r
= sshsig_verify_fd(sigbuf
, STDIN_FILENO
, sig_namespace
,
2827 &sign_key
, &sig_details
)) != 0)
2828 goto done
; /* sshsig_verify() prints error */
2830 if ((fp
= sshkey_fingerprint(sign_key
, fingerprint_hash
,
2831 SSH_FP_DEFAULT
)) == NULL
)
2832 fatal_f("sshkey_fingerprint failed");
2833 debug("Valid (unverified) signature from key %s", fp
);
2834 if (sig_details
!= NULL
) {
2835 debug2_f("signature details: counter = %u, flags = 0x%02x",
2836 sig_details
->sk_counter
, sig_details
->sk_flags
);
2841 if (revoked_keys
!= NULL
) {
2842 if ((r
= sshkey_check_revoked(sign_key
, revoked_keys
)) != 0) {
2843 debug3_fr(r
, "sshkey_check_revoked");
2848 if (allowed_keys
!= NULL
&& (r
= sshsig_check_allowed_keys(allowed_keys
,
2849 sign_key
, principal
, sig_namespace
, verify_time
)) != 0) {
2850 debug3_fr(r
, "sshsig_check_allowed_keys");
2858 if ((fp
= sshkey_fingerprint(sign_key
, fingerprint_hash
,
2859 SSH_FP_DEFAULT
)) == NULL
)
2860 fatal_f("sshkey_fingerprint failed");
2861 if (principal
== NULL
) {
2862 printf("Good \"%s\" signature with %s key %s\n",
2863 sig_namespace
, sshkey_type(sign_key
), fp
);
2866 printf("Good \"%s\" signature for %s with %s key %s\n",
2867 sig_namespace
, principal
,
2868 sshkey_type(sign_key
), fp
);
2871 printf("Could not verify signature.\n");
2874 /* Print the signature key if requested */
2875 if (ret
== 0 && print_pubkey
&& sign_key
!= NULL
) {
2876 if ((r
= sshkey_write(sign_key
, stdout
)) == 0)
2877 fputc('\n', stdout
);
2879 error_r(r
, "Could not print public key.\n");
2883 sshbuf_free(sigbuf
);
2885 sshkey_free(sign_key
);
2886 sshkey_sig_details_free(sig_details
);
2892 sig_find_principals(const char *signature
, const char *allowed_keys
,
2893 char * const *opts
, size_t nopts
)
2896 struct sshbuf
*sigbuf
= NULL
, *abuf
= NULL
;
2897 struct sshkey
*sign_key
= NULL
;
2898 char *principals
= NULL
, *cp
, *tmp
;
2899 uint64_t verify_time
= 0;
2901 if (sig_process_opts(opts
, nopts
, NULL
, &verify_time
, NULL
) != 0)
2902 goto done
; /* error already logged */
2904 if ((r
= sshbuf_load_file(signature
, &abuf
)) != 0) {
2905 error_r(r
, "Couldn't read signature file");
2908 if ((r
= sshsig_dearmor(abuf
, &sigbuf
)) != 0) {
2909 error_fr(r
, "sshsig_armor");
2912 if ((r
= sshsig_get_pubkey(sigbuf
, &sign_key
)) != 0) {
2913 error_fr(r
, "sshsig_get_pubkey");
2916 if ((r
= sshsig_find_principals(allowed_keys
, sign_key
,
2917 verify_time
, &principals
)) != 0) {
2918 if (r
!= SSH_ERR_KEY_NOT_FOUND
)
2919 error_fr(r
, "sshsig_find_principal");
2925 /* Emit matching principals one per line */
2927 while ((cp
= strsep(&tmp
, ",")) != NULL
&& *cp
!= '\0')
2930 fprintf(stderr
, "No principal matched.\n");
2932 sshbuf_free(sigbuf
);
2934 sshkey_free(sign_key
);
2940 sig_match_principals(const char *allowed_keys
, char *principal
,
2941 char * const *opts
, size_t nopts
)
2944 char **principals
= NULL
;
2945 size_t i
, nprincipals
= 0;
2947 if ((r
= sig_process_opts(opts
, nopts
, NULL
, NULL
, NULL
)) != 0)
2948 return r
; /* error already logged */
2950 if ((r
= sshsig_match_principals(allowed_keys
, principal
,
2951 &principals
, &nprincipals
)) != 0) {
2952 debug_f("match: %s", ssh_err(r
));
2953 fprintf(stderr
, "No principal matched.\n");
2956 for (i
= 0; i
< nprincipals
; i
++) {
2957 printf("%s\n", principals
[i
]);
2958 free(principals
[i
]);
2966 do_moduli_gen(const char *out_file
, char **opts
, size_t nopts
)
2969 /* Moduli generation/screening */
2970 u_int32_t memory
= 0;
2971 BIGNUM
*start
= NULL
;
2972 int moduli_bits
= 0;
2978 for (i
= 0; i
< nopts
; i
++) {
2979 if (strncmp(opts
[i
], "memory=", 7) == 0) {
2980 memory
= (u_int32_t
)strtonum(opts
[i
]+7, 1,
2983 fatal("Memory limit is %s: %s",
2986 } else if (strncmp(opts
[i
], "start=", 6) == 0) {
2987 /* XXX - also compare length against bits */
2988 if (BN_hex2bn(&start
, opts
[i
]+6) == 0)
2989 fatal("Invalid start point.");
2990 } else if (strncmp(opts
[i
], "bits=", 5) == 0) {
2991 moduli_bits
= (int)strtonum(opts
[i
]+5, 1,
2994 fatal("Invalid number: %s (%s)",
2995 opts
[i
]+12, errstr
);
2998 fatal("Option \"%s\" is unsupported for moduli "
2999 "generation", opts
[i
]);
3003 if ((out
= fopen(out_file
, "w")) == NULL
) {
3004 fatal("Couldn't open modulus candidate file \"%s\": %s",
3005 out_file
, strerror(errno
));
3007 setvbuf(out
, NULL
, _IOLBF
, 0);
3009 if (moduli_bits
== 0)
3010 moduli_bits
= DEFAULT_BITS
;
3011 if (gen_candidates(out
, memory
, moduli_bits
, start
) != 0)
3012 fatal("modulus candidate generation failed");
3013 #else /* WITH_OPENSSL */
3014 fatal("Moduli generation is not supported");
3015 #endif /* WITH_OPENSSL */
3019 do_moduli_screen(const char *out_file
, char **opts
, size_t nopts
)
3022 /* Moduli generation/screening */
3023 char *checkpoint
= NULL
;
3024 u_int32_t generator_wanted
= 0;
3025 unsigned long start_lineno
= 0, lines_to_process
= 0;
3026 int prime_tests
= 0;
3027 FILE *out
, *in
= stdin
;
3032 for (i
= 0; i
< nopts
; i
++) {
3033 if (strncmp(opts
[i
], "lines=", 6) == 0) {
3034 lines_to_process
= strtoul(opts
[i
]+6, NULL
, 10);
3035 } else if (strncmp(opts
[i
], "start-line=", 11) == 0) {
3036 start_lineno
= strtoul(opts
[i
]+11, NULL
, 10);
3037 } else if (strncmp(opts
[i
], "checkpoint=", 11) == 0) {
3039 checkpoint
= xstrdup(opts
[i
]+11);
3040 } else if (strncmp(opts
[i
], "generator=", 10) == 0) {
3041 generator_wanted
= (u_int32_t
)strtonum(
3042 opts
[i
]+10, 1, UINT_MAX
, &errstr
);
3043 if (errstr
!= NULL
) {
3044 fatal("Generator invalid: %s (%s)",
3045 opts
[i
]+10, errstr
);
3047 } else if (strncmp(opts
[i
], "prime-tests=", 12) == 0) {
3048 prime_tests
= (int)strtonum(opts
[i
]+12, 1,
3051 fatal("Invalid number: %s (%s)",
3052 opts
[i
]+12, errstr
);
3055 fatal("Option \"%s\" is unsupported for moduli "
3056 "screening", opts
[i
]);
3060 if (have_identity
&& strcmp(identity_file
, "-") != 0) {
3061 if ((in
= fopen(identity_file
, "r")) == NULL
) {
3062 fatal("Couldn't open modulus candidate "
3063 "file \"%s\": %s", identity_file
,
3068 if ((out
= fopen(out_file
, "a")) == NULL
) {
3069 fatal("Couldn't open moduli file \"%s\": %s",
3070 out_file
, strerror(errno
));
3072 setvbuf(out
, NULL
, _IOLBF
, 0);
3073 if (prime_test(in
, out
, prime_tests
== 0 ? 100 : prime_tests
,
3074 generator_wanted
, checkpoint
,
3075 start_lineno
, lines_to_process
) != 0)
3076 fatal("modulus screening failed");
3080 #else /* WITH_OPENSSL */
3081 fatal("Moduli screening is not supported");
3082 #endif /* WITH_OPENSSL */
3085 /* Read and confirm a passphrase */
3087 read_check_passphrase(const char *prompt1
, const char *prompt2
,
3088 const char *retry_prompt
)
3090 char *passphrase1
, *passphrase2
;
3093 passphrase1
= read_passphrase(prompt1
, RP_ALLOW_STDIN
);
3094 passphrase2
= read_passphrase(prompt2
, RP_ALLOW_STDIN
);
3095 if (strcmp(passphrase1
, passphrase2
) == 0) {
3096 freezero(passphrase2
, strlen(passphrase2
));
3099 /* The passphrases do not match. Clear them and retry. */
3100 freezero(passphrase1
, strlen(passphrase1
));
3101 freezero(passphrase2
, strlen(passphrase2
));
3102 fputs(retry_prompt
, stdout
);
3103 fputc('\n', stdout
);
3111 private_key_passphrase(void)
3113 if (identity_passphrase
)
3114 return xstrdup(identity_passphrase
);
3115 if (identity_new_passphrase
)
3116 return xstrdup(identity_new_passphrase
);
3118 return read_check_passphrase(
3119 "Enter passphrase (empty for no passphrase): ",
3120 "Enter same passphrase again: ",
3121 "Passphrases do not match. Try again.");
3125 sk_suffix(const char *application
, const uint8_t *user
, size_t userlen
)
3130 /* Trim off URL-like preamble */
3131 if (strncmp(application
, "ssh://", 6) == 0)
3132 ret
= xstrdup(application
+ 6);
3133 else if (strncmp(application
, "ssh:", 4) == 0)
3134 ret
= xstrdup(application
+ 4);
3136 ret
= xstrdup(application
);
3138 /* Count trailing zeros in user */
3139 for (i
= 0; i
< userlen
; i
++) {
3140 if (user
[userlen
- i
- 1] != 0)
3144 return ret
; /* user-id was default all-zeros */
3146 /* Append user-id, escaping non-UTF-8 characters */
3148 if (asmprintf(&cp
, INT_MAX
, NULL
, "%.*s", (int)slen
, user
) == -1)
3149 fatal_f("asmprintf failed");
3150 /* Don't emit a user-id that contains path or control characters */
3151 if (strchr(cp
, '/') != NULL
|| strstr(cp
, "..") != NULL
||
3152 strchr(cp
, '\\') != NULL
) {
3154 cp
= tohex(user
, slen
);
3156 xextendf(&ret
, "_", "%s", cp
);
3162 do_download_sk(const char *skprovider
, const char *device
)
3164 struct sshsk_resident_key
**srks
;
3167 char *fp
, *pin
= NULL
, *pass
= NULL
, *path
, *pubpath
;
3171 if (skprovider
== NULL
)
3172 fatal("Cannot download keys without provider");
3174 pin
= read_passphrase("Enter PIN for authenticator: ", RP_ALLOW_STDIN
);
3176 printf("You may need to touch your authenticator "
3177 "to authorize key download.\n");
3179 if ((r
= sshsk_load_resident(skprovider
, device
, pin
, 0,
3180 &srks
, &nsrks
)) != 0) {
3182 freezero(pin
, strlen(pin
));
3183 error_r(r
, "Unable to load resident keys");
3187 logit("No keys to download");
3189 freezero(pin
, strlen(pin
));
3191 for (i
= 0; i
< nsrks
; i
++) {
3193 if (key
->type
!= KEY_ECDSA_SK
&& key
->type
!= KEY_ED25519_SK
) {
3194 error("Unsupported key type %s (%d)",
3195 sshkey_type(key
), key
->type
);
3198 if ((fp
= sshkey_fingerprint(key
, fingerprint_hash
,
3199 SSH_FP_DEFAULT
)) == NULL
)
3200 fatal_f("sshkey_fingerprint failed");
3201 debug_f("key %zu: %s %s %s (flags 0x%02x)", i
,
3202 sshkey_type(key
), fp
, key
->sk_application
, key
->sk_flags
);
3203 ext
= sk_suffix(key
->sk_application
,
3204 srks
[i
]->user_id
, srks
[i
]->user_id_len
);
3205 xasprintf(&path
, "id_%s_rk%s%s",
3206 key
->type
== KEY_ECDSA_SK
? "ecdsa_sk" : "ed25519_sk",
3207 *ext
== '\0' ? "" : "_", ext
);
3209 /* If the file already exists, ask the user to confirm. */
3210 if (!confirm_overwrite(path
)) {
3215 /* Save the key with the application string as the comment */
3217 pass
= private_key_passphrase();
3218 if ((r
= sshkey_save_private(key
, path
, pass
,
3219 key
->sk_application
, private_key_format
,
3220 openssh_format_cipher
, rounds
)) != 0) {
3221 error_r(r
, "Saving key \"%s\" failed", path
);
3226 printf("Saved %s key%s%s to %s\n", sshkey_type(key
),
3227 *ext
!= '\0' ? " " : "",
3228 *ext
!= '\0' ? key
->sk_application
: "",
3232 /* Save public key too */
3233 xasprintf(&pubpath
, "%s.pub", path
);
3235 if ((r
= sshkey_save_public(key
, pubpath
,
3236 key
->sk_application
)) != 0) {
3237 error_r(r
, "Saving public key \"%s\" failed", pubpath
);
3245 ret
= 0; /* success */
3247 freezero(pass
, strlen(pass
));
3248 sshsk_free_resident_keys(srks
, nsrks
);
3253 save_attestation(struct sshbuf
*attest
, const char *path
)
3259 return; /* nothing to do */
3260 if (attest
== NULL
|| sshbuf_len(attest
) == 0)
3261 fatal("Enrollment did not return attestation data");
3263 r
= sshbuf_write_file(path
, attest
);
3266 fatal_r(r
, "Unable to write attestation data \"%s\"", path
);
3268 printf("Your FIDO attestation certificate has been saved in "
3273 confirm_sk_overwrite(const char *application
, const char *user
)
3277 printf("A resident key scoped to '%s' with user id '%s' already "
3278 "exists.\n", application
== NULL
? "ssh:" : application
,
3279 user
== NULL
? "null" : user
);
3280 printf("Overwrite key in token (y/n)? ");
3282 if (fgets(yesno
, sizeof(yesno
), stdin
) == NULL
)
3284 if (yesno
[0] != 'y' && yesno
[0] != 'Y')
3293 "usage: ssh-keygen [-q] [-a rounds] [-b bits] [-C comment] [-f output_keyfile]\n"
3294 " [-m format] [-N new_passphrase] [-O option]\n"
3295 " [-t dsa | ecdsa | ecdsa-sk | ed25519 | ed25519-sk | rsa]\n"
3296 " [-w provider] [-Z cipher]\n"
3297 " ssh-keygen -p [-a rounds] [-f keyfile] [-m format] [-N new_passphrase]\n"
3298 " [-P old_passphrase] [-Z cipher]\n"
3300 " ssh-keygen -i [-f input_keyfile] [-m key_format]\n"
3301 " ssh-keygen -e [-f input_keyfile] [-m key_format]\n"
3303 " ssh-keygen -y [-f input_keyfile]\n"
3304 " ssh-keygen -c [-a rounds] [-C comment] [-f keyfile] [-P passphrase]\n"
3305 " ssh-keygen -l [-v] [-E fingerprint_hash] [-f input_keyfile]\n"
3306 " ssh-keygen -B [-f input_keyfile]\n");
3307 #ifdef ENABLE_PKCS11
3309 " ssh-keygen -D pkcs11\n");
3312 " ssh-keygen -F hostname [-lv] [-f known_hosts_file]\n"
3313 " ssh-keygen -H [-f known_hosts_file]\n"
3314 " ssh-keygen -K [-a rounds] [-w provider]\n"
3315 " ssh-keygen -R hostname [-f known_hosts_file]\n"
3316 " ssh-keygen -r hostname [-g] [-f input_keyfile]\n"
3318 " ssh-keygen -M generate [-O option] output_file\n"
3319 " ssh-keygen -M screen [-f input_file] [-O option] output_file\n"
3321 " ssh-keygen -I certificate_identity -s ca_key [-hU] [-D pkcs11_provider]\n"
3322 " [-n principals] [-O option] [-V validity_interval]\n"
3323 " [-z serial_number] file ...\n"
3324 " ssh-keygen -L [-f input_keyfile]\n"
3325 " ssh-keygen -A [-a rounds] [-f prefix_path]\n"
3326 " ssh-keygen -k -f krl_file [-u] [-s ca_public] [-z version_number]\n"
3328 " ssh-keygen -Q [-l] -f krl_file [file ...]\n"
3329 " ssh-keygen -Y find-principals -s signature_file -f allowed_signers_file\n"
3330 " ssh-keygen -Y match-principals -I signer_identity -f allowed_signers_file\n"
3331 " ssh-keygen -Y check-novalidate -n namespace -s signature_file\n"
3332 " ssh-keygen -Y sign -f key_file -n namespace file [-O option] ...\n"
3333 " ssh-keygen -Y verify -f allowed_signers_file -I signer_identity\n"
3334 " -n namespace -s signature_file [-r krl_file] [-O option]\n");
3339 * Main program for key management.
3342 main(int argc
, char **argv
)
3344 char comment
[1024], *passphrase
= NULL
;
3345 char *rr_hostname
= NULL
, *ep
, *fp
, *ra
;
3346 struct sshkey
*private, *public;
3349 int change_passphrase
= 0, change_comment
= 0, show_cert
= 0;
3350 int find_host
= 0, delete_host
= 0, hash_hosts
= 0;
3351 int gen_all_hostkeys
= 0, gen_krl
= 0, update_krl
= 0, check_krl
= 0;
3352 int prefer_agent
= 0, convert_to
= 0, convert_from
= 0;
3353 int print_public
= 0, print_generic
= 0, cert_serial_autoinc
= 0;
3354 int do_gen_candidates
= 0, do_screen_candidates
= 0, download_sk
= 0;
3355 unsigned long long cert_serial
= 0;
3356 char *identity_comment
= NULL
, *ca_key_path
= NULL
, **opts
= NULL
;
3357 char *sk_application
= NULL
, *sk_device
= NULL
, *sk_user
= NULL
;
3358 char *sk_attestation_path
= NULL
;
3359 struct sshbuf
*challenge
= NULL
, *attest
= NULL
;
3360 size_t i
, nopts
= 0;
3362 uint8_t sk_flags
= SSH_SK_USER_PRESENCE_REQD
;
3364 int log_level
= SYSLOG_LEVEL_INFO
;
3365 char *sign_op
= NULL
;
3368 extern char *optarg
;
3370 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
3373 __progname
= ssh_get_progname(argv
[0]);
3377 log_init(argv
[0], SYSLOG_LEVEL_INFO
, SYSLOG_FACILITY_USER
, 1);
3381 /* we need this for the home * directory. */
3382 pw
= getpwuid(getuid());
3384 fatal("No user exists for uid %lu", (u_long
)getuid());
3386 if (gethostname(hostname
, sizeof(hostname
)) == -1)
3387 fatal("gethostname: %s", strerror(errno
));
3389 sk_provider
= getenv("SSH_SK_PROVIDER");
3391 /* Remaining characters: dGjJSTWx */
3392 while ((opt
= getopt(argc
, argv
, "ABHKLQUXceghiklopquvy"
3393 "C:D:E:F:I:M:N:O:P:R:V:Y:Z:"
3394 "a:b:f:g:m:n:r:s:t:w:z:")) != -1) {
3397 gen_all_hostkeys
= 1;
3400 bits
= (u_int32_t
)strtonum(optarg
, 1, UINT32_MAX
,
3403 fatal("Bits has bad value %s (%s)",
3407 fingerprint_hash
= ssh_digest_alg_by_name(optarg
);
3408 if (fingerprint_hash
== -1)
3409 fatal("Invalid hash algorithm \"%s\"", optarg
);
3413 rr_hostname
= optarg
;
3419 cert_key_id
= optarg
;
3423 rr_hostname
= optarg
;
3429 print_fingerprint
= 1;
3432 print_bubblebabble
= 1;
3435 if (strcasecmp(optarg
, "RFC4716") == 0 ||
3436 strcasecmp(optarg
, "ssh2") == 0) {
3437 convert_format
= FMT_RFC4716
;
3440 if (strcasecmp(optarg
, "PKCS8") == 0) {
3441 convert_format
= FMT_PKCS8
;
3442 private_key_format
= SSHKEY_PRIVATE_PKCS8
;
3445 if (strcasecmp(optarg
, "PEM") == 0) {
3446 convert_format
= FMT_PEM
;
3447 private_key_format
= SSHKEY_PRIVATE_PEM
;
3450 fatal("Unsupported conversion format \"%s\"", optarg
);
3452 cert_principals
= optarg
;
3455 /* no-op; new format is already the default */
3458 change_passphrase
= 1;
3464 if (strlcpy(identity_file
, optarg
,
3465 sizeof(identity_file
)) >= sizeof(identity_file
))
3466 fatal("Identity filename too long");
3476 identity_passphrase
= optarg
;
3479 identity_new_passphrase
= optarg
;
3485 opts
= xrecallocarray(opts
, nopts
, nopts
+ 1,
3487 opts
[nopts
++] = xstrdup(optarg
);
3490 openssh_format_cipher
= optarg
;
3491 if (cipher_by_name(openssh_format_cipher
) == NULL
)
3492 fatal("Invalid OpenSSH-format cipher '%s'",
3493 openssh_format_cipher
);
3496 identity_comment
= optarg
;
3506 cert_key_type
= SSH2_CERT_TYPE_HOST
;
3507 certflags_flags
= 0;
3521 ca_key_path
= optarg
;
3524 key_type_name
= optarg
;
3527 pkcs11provider
= optarg
;
3536 if (log_level
== SYSLOG_LEVEL_INFO
)
3537 log_level
= SYSLOG_LEVEL_DEBUG1
;
3539 if (log_level
>= SYSLOG_LEVEL_DEBUG1
&&
3540 log_level
< SYSLOG_LEVEL_DEBUG3
)
3545 rr_hostname
= optarg
;
3548 rounds
= (int)strtonum(optarg
, 1, INT_MAX
, &errstr
);
3550 fatal("Invalid number: %s (%s)",
3554 parse_cert_times(optarg
);
3560 sk_provider
= optarg
;
3564 if (*optarg
== '+') {
3565 cert_serial_autoinc
= 1;
3568 cert_serial
= strtoull(optarg
, &ep
, 10);
3569 if (*optarg
< '0' || *optarg
> '9' || *ep
!= '\0' ||
3570 (errno
== ERANGE
&& cert_serial
== ULLONG_MAX
))
3571 fatal("Invalid serial number \"%s\"", optarg
);
3574 if (strcmp(optarg
, "generate") == 0)
3575 do_gen_candidates
= 1;
3576 else if (strcmp(optarg
, "screen") == 0)
3577 do_screen_candidates
= 1;
3579 fatal("Unsupported moduli option %s", optarg
);
3586 #ifdef ENABLE_SK_INTERNAL
3587 if (sk_provider
== NULL
)
3588 sk_provider
= "internal";
3592 log_init(argv
[0], log_level
, SYSLOG_FACILITY_USER
, 1);
3597 if (sign_op
!= NULL
) {
3598 if (strncmp(sign_op
, "find-principals", 15) == 0) {
3599 if (ca_key_path
== NULL
) {
3600 error("Too few arguments for find-principals:"
3601 "missing signature file");
3604 if (!have_identity
) {
3605 error("Too few arguments for find-principals:"
3606 "missing allowed keys file");
3609 return sig_find_principals(ca_key_path
, identity_file
,
3611 } else if (strncmp(sign_op
, "match-principals", 16) == 0) {
3612 if (!have_identity
) {
3613 error("Too few arguments for match-principals:"
3614 "missing allowed keys file");
3617 if (cert_key_id
== NULL
) {
3618 error("Too few arguments for match-principals: "
3619 "missing principal ID");
3622 return sig_match_principals(identity_file
, cert_key_id
,
3624 } else if (strncmp(sign_op
, "sign", 4) == 0) {
3625 /* NB. cert_principals is actually namespace, via -n */
3626 if (cert_principals
== NULL
||
3627 *cert_principals
== '\0') {
3628 error("Too few arguments for sign: "
3629 "missing namespace");
3632 if (!have_identity
) {
3633 error("Too few arguments for sign: "
3637 return sig_sign(identity_file
, cert_principals
,
3638 prefer_agent
, argc
, argv
, opts
, nopts
);
3639 } else if (strncmp(sign_op
, "check-novalidate", 16) == 0) {
3640 /* NB. cert_principals is actually namespace, via -n */
3641 if (cert_principals
== NULL
||
3642 *cert_principals
== '\0') {
3643 error("Too few arguments for check-novalidate: "
3644 "missing namespace");
3647 if (ca_key_path
== NULL
) {
3648 error("Too few arguments for check-novalidate: "
3649 "missing signature file");
3652 return sig_verify(ca_key_path
, cert_principals
,
3653 NULL
, NULL
, NULL
, opts
, nopts
);
3654 } else if (strncmp(sign_op
, "verify", 6) == 0) {
3655 /* NB. cert_principals is actually namespace, via -n */
3656 if (cert_principals
== NULL
||
3657 *cert_principals
== '\0') {
3658 error("Too few arguments for verify: "
3659 "missing namespace");
3662 if (ca_key_path
== NULL
) {
3663 error("Too few arguments for verify: "
3664 "missing signature file");
3667 if (!have_identity
) {
3668 error("Too few arguments for sign: "
3669 "missing allowed keys file");
3672 if (cert_key_id
== NULL
) {
3673 error("Too few arguments for verify: "
3674 "missing principal identity");
3677 return sig_verify(ca_key_path
, cert_principals
,
3678 cert_key_id
, identity_file
, rr_hostname
,
3681 error("Unsupported operation for -Y: \"%s\"", sign_op
);
3686 if (ca_key_path
!= NULL
) {
3687 if (argc
< 1 && !gen_krl
) {
3688 error("Too few arguments.");
3691 } else if (argc
> 0 && !gen_krl
&& !check_krl
&&
3692 !do_gen_candidates
&& !do_screen_candidates
) {
3693 error("Too many arguments.");
3696 if (change_passphrase
&& change_comment
) {
3697 error("Can only have one of -p and -c.");
3700 if (print_fingerprint
&& (delete_host
|| hash_hosts
)) {
3701 error("Cannot use -l with -H or -R.");
3705 do_gen_krl(pw
, update_krl
, ca_key_path
,
3706 cert_serial
, identity_comment
, argc
, argv
);
3710 do_check_krl(pw
, print_fingerprint
, argc
, argv
);
3713 if (ca_key_path
!= NULL
) {
3714 if (cert_key_id
== NULL
)
3715 fatal("Must specify key id (-I) when certifying");
3716 for (i
= 0; i
< nopts
; i
++)
3717 add_cert_option(opts
[i
]);
3718 do_ca_sign(pw
, ca_key_path
, prefer_agent
,
3719 cert_serial
, cert_serial_autoinc
, argc
, argv
);
3723 if (delete_host
|| hash_hosts
|| find_host
) {
3724 do_known_hosts(pw
, rr_hostname
, find_host
,
3725 delete_host
, hash_hosts
);
3727 if (pkcs11provider
!= NULL
)
3730 for (i
= 0; i
< nopts
; i
++) {
3731 if (strncasecmp(opts
[i
], "device=", 7) == 0) {
3732 sk_device
= xstrdup(opts
[i
] + 7);
3734 fatal("Option \"%s\" is unsupported for "
3735 "FIDO authenticator download", opts
[i
]);
3738 return do_download_sk(sk_provider
, sk_device
);
3740 if (print_fingerprint
|| print_bubblebabble
)
3742 if (change_passphrase
)
3743 do_change_passphrase(pw
);
3745 do_change_comment(pw
, identity_comment
);
3750 do_convert_from(pw
);
3751 #else /* WITH_OPENSSL */
3752 if (convert_to
|| convert_from
)
3753 fatal("key conversion disabled at compile time");
3754 #endif /* WITH_OPENSSL */
3756 do_print_public(pw
);
3757 if (rr_hostname
!= NULL
) {
3760 if (have_identity
) {
3761 n
= do_print_resource_record(pw
, identity_file
,
3762 rr_hostname
, print_generic
, opts
, nopts
);
3764 fatal("%s: %s", identity_file
, strerror(errno
));
3768 n
+= do_print_resource_record(pw
,
3769 _PATH_HOST_RSA_KEY_FILE
, rr_hostname
,
3770 print_generic
, opts
, nopts
);
3772 n
+= do_print_resource_record(pw
,
3773 _PATH_HOST_DSA_KEY_FILE
, rr_hostname
,
3774 print_generic
, opts
, nopts
);
3776 n
+= do_print_resource_record(pw
,
3777 _PATH_HOST_ECDSA_KEY_FILE
, rr_hostname
,
3778 print_generic
, opts
, nopts
);
3779 n
+= do_print_resource_record(pw
,
3780 _PATH_HOST_ED25519_KEY_FILE
, rr_hostname
,
3781 print_generic
, opts
, nopts
);
3782 n
+= do_print_resource_record(pw
,
3783 _PATH_HOST_XMSS_KEY_FILE
, rr_hostname
,
3784 print_generic
, opts
, nopts
);
3786 fatal("no keys found.");
3791 if (do_gen_candidates
|| do_screen_candidates
) {
3793 fatal("No output file specified");
3795 fatal("Too many output files specified");
3797 if (do_gen_candidates
) {
3798 do_moduli_gen(argv
[0], opts
, nopts
);
3801 if (do_screen_candidates
) {
3802 do_moduli_screen(argv
[0], opts
, nopts
);
3806 if (gen_all_hostkeys
) {
3807 do_gen_all_hostkeys(pw
);
3811 if (key_type_name
== NULL
)
3812 key_type_name
= DEFAULT_KEY_TYPE_NAME
;
3814 type
= sshkey_type_from_name(key_type_name
);
3815 type_bits_valid(type
, key_type_name
, &bits
);
3818 printf("Generating public/private %s key pair.\n",
3822 case KEY_ED25519_SK
:
3823 for (i
= 0; i
< nopts
; i
++) {
3824 if (strcasecmp(opts
[i
], "no-touch-required") == 0) {
3825 sk_flags
&= ~SSH_SK_USER_PRESENCE_REQD
;
3826 } else if (strcasecmp(opts
[i
], "verify-required") == 0) {
3827 sk_flags
|= SSH_SK_USER_VERIFICATION_REQD
;
3828 } else if (strcasecmp(opts
[i
], "resident") == 0) {
3829 sk_flags
|= SSH_SK_RESIDENT_KEY
;
3830 } else if (strncasecmp(opts
[i
], "device=", 7) == 0) {
3831 sk_device
= xstrdup(opts
[i
] + 7);
3832 } else if (strncasecmp(opts
[i
], "user=", 5) == 0) {
3833 sk_user
= xstrdup(opts
[i
] + 5);
3834 } else if (strncasecmp(opts
[i
], "challenge=", 10) == 0) {
3835 if ((r
= sshbuf_load_file(opts
[i
] + 10,
3836 &challenge
)) != 0) {
3837 fatal_r(r
, "Unable to load FIDO "
3838 "enrollment challenge \"%s\"",
3841 } else if (strncasecmp(opts
[i
],
3842 "write-attestation=", 18) == 0) {
3843 sk_attestation_path
= opts
[i
] + 18;
3844 } else if (strncasecmp(opts
[i
],
3845 "application=", 12) == 0) {
3846 sk_application
= xstrdup(opts
[i
] + 12);
3847 if (strncmp(sk_application
, "ssh:", 4) != 0) {
3848 fatal("FIDO application string must "
3849 "begin with \"ssh:\"");
3852 fatal("Option \"%s\" is unsupported for "
3853 "FIDO authenticator enrollment", opts
[i
]);
3856 if ((attest
= sshbuf_new()) == NULL
)
3857 fatal("sshbuf_new failed");
3861 printf("You may need to touch your "
3862 "authenticator%s to authorize key "
3864 r
== 0 ? "" : " again");
3867 r
= sshsk_enroll(type
, sk_provider
, sk_device
,
3868 sk_application
== NULL
? "ssh:" : sk_application
,
3869 sk_user
, sk_flags
, passphrase
, challenge
,
3873 if (r
== SSH_ERR_KEY_BAD_PERMISSIONS
&&
3874 (sk_flags
& SSH_SK_RESIDENT_KEY
) != 0 &&
3875 (sk_flags
& SSH_SK_FORCE_OPERATION
) == 0 &&
3876 confirm_sk_overwrite(sk_application
, sk_user
)) {
3877 sk_flags
|= SSH_SK_FORCE_OPERATION
;
3880 if (r
!= SSH_ERR_KEY_WRONG_PASSPHRASE
)
3881 fatal_r(r
, "Key enrollment failed");
3882 else if (passphrase
!= NULL
) {
3883 error("PIN incorrect");
3884 freezero(passphrase
, strlen(passphrase
));
3888 fatal("Too many incorrect PINs");
3889 passphrase
= read_passphrase("Enter PIN for "
3890 "authenticator: ", RP_ALLOW_STDIN
);
3892 if (passphrase
!= NULL
) {
3893 freezero(passphrase
, strlen(passphrase
));
3898 if ((r
= sshkey_generate(type
, bits
, &private)) != 0)
3899 fatal("sshkey_generate failed");
3902 if ((r
= sshkey_from_private(private, &public)) != 0)
3903 fatal_r(r
, "sshkey_from_private");
3906 ask_filename(pw
, "Enter file in which to save the key");
3908 /* Create ~/.ssh directory if it doesn't already exist. */
3909 hostfile_create_user_ssh_dir(identity_file
, !quiet
);
3911 /* If the file already exists, ask the user to confirm. */
3912 if (!confirm_overwrite(identity_file
))
3915 /* Determine the passphrase for the private key */
3916 passphrase
= private_key_passphrase();
3917 if (identity_comment
) {
3918 strlcpy(comment
, identity_comment
, sizeof(comment
));
3920 /* Create default comment field for the passphrase. */
3921 snprintf(comment
, sizeof comment
, "%s@%s", pw
->pw_name
, hostname
);
3924 /* Save the key with the given passphrase and comment. */
3925 if ((r
= sshkey_save_private(private, identity_file
, passphrase
,
3926 comment
, private_key_format
, openssh_format_cipher
, rounds
)) != 0) {
3927 error_r(r
, "Saving key \"%s\" failed", identity_file
);
3928 freezero(passphrase
, strlen(passphrase
));
3931 freezero(passphrase
, strlen(passphrase
));
3932 sshkey_free(private);
3935 printf("Your identification has been saved in %s\n",
3939 strlcat(identity_file
, ".pub", sizeof(identity_file
));
3940 if ((r
= sshkey_save_public(public, identity_file
, comment
)) != 0)
3941 fatal_r(r
, "Unable to save public key to %s", identity_file
);
3944 fp
= sshkey_fingerprint(public, fingerprint_hash
,
3946 ra
= sshkey_fingerprint(public, fingerprint_hash
,
3948 if (fp
== NULL
|| ra
== NULL
)
3949 fatal("sshkey_fingerprint failed");
3950 printf("Your public key has been saved in %s\n",
3952 printf("The key fingerprint is:\n");
3953 printf("%s %s\n", fp
, comment
);
3954 printf("The key's randomart image is:\n");
3960 if (sk_attestation_path
!= NULL
)
3961 save_attestation(attest
, sk_attestation_path
);
3963 sshbuf_free(attest
);
3964 sshkey_free(public);