xref: /netbsd-src/crypto/external/bsd/openssh/dist/ssh-keygen.c (revision 9469f4f13c84743995b7d51c506f9c9849ba30de)
1 /*	$NetBSD: ssh-keygen.c,v 1.48 2024/09/24 21:32:19 christos Exp $	*/
2 /* $OpenBSD: ssh-keygen.c,v 1.475 2024/09/15 00:47:01 djm Exp $ */
3 
4 /*
5  * Author: Tatu Ylonen <ylo@cs.hut.fi>
6  * Copyright (c) 1994 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7  *                    All rights reserved
8  * Identity and host key generation and maintenance.
9  *
10  * As far as I am concerned, the code I have written for this software
11  * can be used freely for any purpose.  Any derived versions of this
12  * software must be clearly marked as such, and if the derived work is
13  * incompatible with the protocol description in the RFC file, it must be
14  * called by a name other than "ssh" or "Secure Shell".
15  */
16 
17 #include "includes.h"
18 __RCSID("$NetBSD: ssh-keygen.c,v 1.48 2024/09/24 21:32:19 christos Exp $");
19 #include <sys/types.h>
20 #include <sys/socket.h>
21 #include <sys/stat.h>
22 
23 #ifdef WITH_OPENSSL
24 #include <openssl/evp.h>
25 #include <openssl/pem.h>
26 #endif
27 
28 #include <stdint.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <netdb.h>
32 #include <pwd.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <limits.h>
39 #include <locale.h>
40 
41 #include "xmalloc.h"
42 #include "sshkey.h"
43 #include "authfile.h"
44 #include "sshbuf.h"
45 #include "pathnames.h"
46 #include "log.h"
47 #include "misc.h"
48 #include "match.h"
49 #include "hostfile.h"
50 #include "dns.h"
51 #include "ssh.h"
52 #include "ssh2.h"
53 #include "ssherr.h"
54 #include "atomicio.h"
55 #include "krl.h"
56 #include "digest.h"
57 #include "utf8.h"
58 #include "authfd.h"
59 #include "sshsig.h"
60 #include "ssh-sk.h"
61 #include "sk-api.h" /* XXX for SSH_SK_USER_PRESENCE_REQD; remove */
62 #include "cipher.h"
63 
64 #ifdef ENABLE_PKCS11
65 #include "ssh-pkcs11.h"
66 #endif
67 
68 #define DEFAULT_KEY_TYPE_NAME "ed25519"
69 
70 /*
71  * Default number of bits in the RSA, DSA and ECDSA keys.  These value can be
72  * overridden on the command line.
73  *
74  * These values, with the exception of DSA, provide security equivalent to at
75  * least 128 bits of security according to NIST Special Publication 800-57:
76  * Recommendation for Key Management Part 1 rev 4 section 5.6.1.
77  * For DSA it (and FIPS-186-4 section 4.2) specifies that the only size for
78  * which a 160bit hash is acceptable is 1kbit, and since ssh-dss specifies only
79  * SHA1 we limit the DSA key size 1k bits.
80  */
81 #define DEFAULT_BITS		3072
82 #define DEFAULT_BITS_DSA	1024
83 #define DEFAULT_BITS_ECDSA	256
84 
85 static int quiet = 0;
86 
87 /* Flag indicating that we just want to see the key fingerprint */
88 static int print_fingerprint = 0;
89 static int print_bubblebabble = 0;
90 
91 /* Hash algorithm to use for fingerprints. */
92 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
93 
94 /* The identity file name, given on the command line or entered by the user. */
95 static char identity_file[PATH_MAX];
96 static int have_identity = 0;
97 
98 /* This is set to the passphrase if given on the command line. */
99 static char *identity_passphrase = NULL;
100 
101 /* This is set to the new passphrase if given on the command line. */
102 static char *identity_new_passphrase = NULL;
103 
104 /* Key type when certifying */
105 static u_int cert_key_type = SSH2_CERT_TYPE_USER;
106 
107 /* "key ID" of signed key */
108 static char *cert_key_id = NULL;
109 
110 /* Comma-separated list of principal names for certifying keys */
111 static char *cert_principals = NULL;
112 
113 /* Validity period for certificates */
114 static u_int64_t cert_valid_from = 0;
115 static u_int64_t cert_valid_to = ~0ULL;
116 
117 /* Certificate options */
118 #define CERTOPT_X_FWD				(1)
119 #define CERTOPT_AGENT_FWD			(1<<1)
120 #define CERTOPT_PORT_FWD			(1<<2)
121 #define CERTOPT_PTY				(1<<3)
122 #define CERTOPT_USER_RC				(1<<4)
123 #define CERTOPT_NO_REQUIRE_USER_PRESENCE	(1<<5)
124 #define CERTOPT_REQUIRE_VERIFY			(1<<6)
125 #define CERTOPT_DEFAULT	(CERTOPT_X_FWD|CERTOPT_AGENT_FWD| \
126 			 CERTOPT_PORT_FWD|CERTOPT_PTY|CERTOPT_USER_RC)
127 static u_int32_t certflags_flags = CERTOPT_DEFAULT;
128 static char *certflags_command = NULL;
129 static char *certflags_src_addr = NULL;
130 
131 /* Arbitrary extensions specified by user */
132 struct cert_ext {
133 	char *key;
134 	char *val;
135 	int crit;
136 };
137 static struct cert_ext *cert_ext;
138 static size_t ncert_ext;
139 
140 /* Conversion to/from various formats */
141 enum {
142 	FMT_RFC4716,
143 	FMT_PKCS8,
144 	FMT_PEM
145 } convert_format = FMT_RFC4716;
146 
147 static const char *key_type_name = NULL;
148 
149 /* Load key from this PKCS#11 provider */
150 static char *pkcs11provider = NULL;
151 
152 /* FIDO/U2F provider to use */
153 static const char *sk_provider = NULL;
154 
155 /* Format for writing private keys */
156 static int private_key_format = SSHKEY_PRIVATE_OPENSSH;
157 
158 /* Cipher for new-format private keys */
159 static char *openssh_format_cipher = NULL;
160 
161 /* Number of KDF rounds to derive new format keys. */
162 static int rounds = 0;
163 
164 /* argv0 */
165 extern char *__progname;
166 
167 static char hostname[NI_MAXHOST];
168 
169 #ifdef WITH_OPENSSL
170 /* moduli.c */
171 int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
172 int prime_test(FILE *, FILE *, u_int32_t, u_int32_t, char *, unsigned long,
173     unsigned long);
174 #endif
175 
176 static void
177 type_bits_valid(int type, const char *name, u_int32_t *bitsp)
178 {
179 	if (type == KEY_UNSPEC)
180 		fatal("unknown key type %s", key_type_name);
181 	if (*bitsp == 0) {
182 #ifdef WITH_OPENSSL
183 		int nid;
184 
185 		switch(type) {
186 		case KEY_DSA:
187 			*bitsp = DEFAULT_BITS_DSA;
188 			break;
189 		case KEY_ECDSA:
190 			if (name != NULL &&
191 			    (nid = sshkey_ecdsa_nid_from_name(name)) > 0)
192 				*bitsp = sshkey_curve_nid_to_bits(nid);
193 			if (*bitsp == 0)
194 				*bitsp = DEFAULT_BITS_ECDSA;
195 			break;
196 		case KEY_RSA:
197 			*bitsp = DEFAULT_BITS;
198 			break;
199 		}
200 #endif
201 	}
202 #ifdef WITH_OPENSSL
203 	switch (type) {
204 	case KEY_DSA:
205 		if (*bitsp != 1024)
206 			fatal("Invalid DSA key length: must be 1024 bits");
207 		break;
208 	case KEY_RSA:
209 		if (*bitsp < SSH_RSA_MINIMUM_MODULUS_SIZE)
210 			fatal("Invalid RSA key length: minimum is %d bits",
211 			    SSH_RSA_MINIMUM_MODULUS_SIZE);
212 		else if (*bitsp > OPENSSL_RSA_MAX_MODULUS_BITS)
213 			fatal("Invalid RSA key length: maximum is %d bits",
214 			    OPENSSL_RSA_MAX_MODULUS_BITS);
215 		break;
216 	case KEY_ECDSA:
217 		if (sshkey_ecdsa_bits_to_nid(*bitsp) == -1)
218 			fatal("Invalid ECDSA key length: valid lengths are "
219 			    "256, 384 or 521 bits");
220 	}
221 #endif
222 }
223 
224 /*
225  * Checks whether a file exists and, if so, asks the user whether they wish
226  * to overwrite it.
227  * Returns nonzero if the file does not already exist or if the user agrees to
228  * overwrite, or zero otherwise.
229  */
230 static int
231 confirm_overwrite(const char *filename)
232 {
233 	char yesno[3];
234 	struct stat st;
235 
236 	if (stat(filename, &st) != 0)
237 		return 1;
238 	printf("%s already exists.\n", filename);
239 	printf("Overwrite (y/n)? ");
240 	fflush(stdout);
241 	if (fgets(yesno, sizeof(yesno), stdin) == NULL)
242 		return 0;
243 	if (yesno[0] != 'y' && yesno[0] != 'Y')
244 		return 0;
245 	return 1;
246 }
247 
248 static void
249 ask_filename(struct passwd *pw, const char *prompt)
250 {
251 	char buf[1024];
252 	const char *name = NULL;
253 
254 	if (key_type_name == NULL)
255 		name = _PATH_SSH_CLIENT_ID_ED25519;
256 	else {
257 		switch (sshkey_type_from_shortname(key_type_name)) {
258 #ifdef WITH_DSA
259 		case KEY_DSA_CERT:
260 		case KEY_DSA:
261 			name = _PATH_SSH_CLIENT_ID_DSA;
262 			break;
263 #endif
264 		case KEY_ECDSA_CERT:
265 		case KEY_ECDSA:
266 			name = _PATH_SSH_CLIENT_ID_ECDSA;
267 			break;
268 		case KEY_ECDSA_SK_CERT:
269 		case KEY_ECDSA_SK:
270 			name = _PATH_SSH_CLIENT_ID_ECDSA_SK;
271 			break;
272 		case KEY_RSA_CERT:
273 		case KEY_RSA:
274 			name = _PATH_SSH_CLIENT_ID_RSA;
275 			break;
276 		case KEY_ED25519:
277 		case KEY_ED25519_CERT:
278 			name = _PATH_SSH_CLIENT_ID_ED25519;
279 			break;
280 		case KEY_ED25519_SK:
281 		case KEY_ED25519_SK_CERT:
282 			name = _PATH_SSH_CLIENT_ID_ED25519_SK;
283 			break;
284 		case KEY_XMSS:
285 		case KEY_XMSS_CERT:
286 			name = _PATH_SSH_CLIENT_ID_XMSS;
287 			break;
288 		default:
289 			fatal("bad key type");
290 		}
291 	}
292 	snprintf(identity_file, sizeof(identity_file),
293 	    "%s/%s", pw->pw_dir, name);
294 	printf("%s (%s): ", prompt, identity_file);
295 	fflush(stdout);
296 	if (fgets(buf, sizeof(buf), stdin) == NULL)
297 		exit(1);
298 	buf[strcspn(buf, "\n")] = '\0';
299 	if (strcmp(buf, "") != 0)
300 		strlcpy(identity_file, buf, sizeof(identity_file));
301 	have_identity = 1;
302 }
303 
304 static struct sshkey *
305 load_identity(const char *filename, char **commentp)
306 {
307 	char *prompt, *pass;
308 	struct sshkey *prv;
309 	int r;
310 
311 	if (commentp != NULL)
312 		*commentp = NULL;
313 	if ((r = sshkey_load_private(filename, "", &prv, commentp)) == 0)
314 		return prv;
315 	if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
316 		fatal_r(r, "Load key \"%s\"", filename);
317 	if (identity_passphrase)
318 		pass = xstrdup(identity_passphrase);
319 	else {
320 		xasprintf(&prompt, "Enter passphrase for \"%s\": ", filename);
321 		pass = read_passphrase(prompt, RP_ALLOW_STDIN);
322 		free(prompt);
323 	}
324 	r = sshkey_load_private(filename, pass, &prv, commentp);
325 	freezero(pass, strlen(pass));
326 	if (r != 0)
327 		fatal_r(r, "Load key \"%s\"", filename);
328 	return prv;
329 }
330 
331 #define SSH_COM_PUBLIC_BEGIN		"---- BEGIN SSH2 PUBLIC KEY ----"
332 #define SSH_COM_PUBLIC_END		"---- END SSH2 PUBLIC KEY ----"
333 #define SSH_COM_PRIVATE_BEGIN		"---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
334 #define	SSH_COM_PRIVATE_KEY_MAGIC	0x3f6ff9eb
335 
336 #ifdef WITH_OPENSSL
337 __dead static void
338 do_convert_to_ssh2(struct passwd *pw, struct sshkey *k)
339 {
340 	struct sshbuf *b;
341 	char comment[61], *b64;
342 	int r;
343 
344 	if ((b = sshbuf_new()) == NULL)
345 		fatal_f("sshbuf_new failed");
346 	if ((r = sshkey_putb(k, b)) != 0)
347 		fatal_fr(r, "put key");
348 	if ((b64 = sshbuf_dtob64_string(b, 1)) == NULL)
349 		fatal_f("sshbuf_dtob64_string failed");
350 
351 	/* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
352 	snprintf(comment, sizeof(comment),
353 	    "%u-bit %s, converted by %s@%s from OpenSSH",
354 	    sshkey_size(k), sshkey_type(k),
355 	    pw->pw_name, hostname);
356 
357 	sshkey_free(k);
358 	sshbuf_free(b);
359 
360 	fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
361 	fprintf(stdout, "Comment: \"%s\"\n%s", comment, b64);
362 	fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
363 	free(b64);
364 	exit(0);
365 }
366 
367 __dead static void
368 do_convert_to_pkcs8(struct sshkey *k)
369 {
370 	switch (sshkey_type_plain(k->type)) {
371 	case KEY_RSA:
372 		if (!PEM_write_RSA_PUBKEY(stdout,
373 		    EVP_PKEY_get0_RSA(k->pkey)))
374 			fatal("PEM_write_RSA_PUBKEY failed");
375 		break;
376 #ifdef WITH_DSA
377 	case KEY_DSA:
378 		if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
379 			fatal("PEM_write_DSA_PUBKEY failed");
380 		break;
381 #endif
382 	case KEY_ECDSA:
383 		if (!PEM_write_EC_PUBKEY(stdout,
384 		    EVP_PKEY_get0_EC_KEY(k->pkey)))
385 			fatal("PEM_write_EC_PUBKEY failed");
386 		break;
387 	default:
388 		fatal_f("unsupported key type %s", sshkey_type(k));
389 	}
390 	exit(0);
391 }
392 
393 __dead static void
394 do_convert_to_pem(struct sshkey *k)
395 {
396 	switch (sshkey_type_plain(k->type)) {
397 	case KEY_RSA:
398 		if (!PEM_write_RSAPublicKey(stdout,
399 		    EVP_PKEY_get0_RSA(k->pkey)))
400 			fatal("PEM_write_RSAPublicKey failed");
401 		break;
402 #ifdef WITH_DSA
403 	case KEY_DSA:
404 		if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
405 			fatal("PEM_write_DSA_PUBKEY failed");
406 		break;
407 #endif
408 	case KEY_ECDSA:
409 		if (!PEM_write_EC_PUBKEY(stdout,
410 		    EVP_PKEY_get0_EC_KEY(k->pkey)))
411 			fatal("PEM_write_EC_PUBKEY failed");
412 		break;
413 	default:
414 		fatal_f("unsupported key type %s", sshkey_type(k));
415 	}
416 	exit(0);
417 }
418 
419 __dead static void
420 do_convert_to(struct passwd *pw)
421 {
422 	struct sshkey *k;
423 	struct stat st;
424 	int r;
425 
426 	if (!have_identity)
427 		ask_filename(pw, "Enter file in which the key is");
428 	if (stat(identity_file, &st) == -1)
429 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
430 	if ((r = sshkey_load_public(identity_file, &k, NULL)) != 0)
431 		k = load_identity(identity_file, NULL);
432 	switch (convert_format) {
433 	case FMT_RFC4716:
434 		do_convert_to_ssh2(pw, k);
435 		break;
436 	case FMT_PKCS8:
437 		do_convert_to_pkcs8(k);
438 		break;
439 	case FMT_PEM:
440 		do_convert_to_pem(k);
441 		break;
442 	default:
443 		fatal_f("unknown key format %d", convert_format);
444 	}
445 	exit(0);
446 }
447 
448 /*
449  * This is almost exactly the bignum1 encoding, but with 32 bit for length
450  * instead of 16.
451  */
452 static void
453 buffer_get_bignum_bits(struct sshbuf *b, BIGNUM *value)
454 {
455 	u_int bytes, bignum_bits;
456 	int r;
457 
458 	if ((r = sshbuf_get_u32(b, &bignum_bits)) != 0)
459 		fatal_fr(r, "parse");
460 	bytes = (bignum_bits + 7) / 8;
461 	if (sshbuf_len(b) < bytes)
462 		fatal_f("input buffer too small: need %d have %zu",
463 		    bytes, sshbuf_len(b));
464 	if (BN_bin2bn(sshbuf_ptr(b), bytes, value) == NULL)
465 		fatal_f("BN_bin2bn failed");
466 	if ((r = sshbuf_consume(b, bytes)) != 0)
467 		fatal_fr(r, "consume");
468 }
469 
470 static struct sshkey *
471 do_convert_private_ssh2(struct sshbuf *b)
472 {
473 	struct sshkey *key = NULL;
474 	char *type, *cipher;
475 	const char *alg = NULL;
476 	u_char e1, e2, e3, *sig = NULL, data[] = "abcde12345";
477 	int r, rlen, ktype;
478 	u_int magic, i1, i2, i3, i4;
479 	size_t slen;
480 	u_long e;
481 #ifdef WITH_DSA
482 	BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL;
483 	BIGNUM *dsa_pub_key = NULL, *dsa_priv_key = NULL;
484 #endif
485 	BIGNUM *rsa_n = NULL, *rsa_e = NULL, *rsa_d = NULL;
486 	BIGNUM *rsa_p = NULL, *rsa_q = NULL, *rsa_iqmp = NULL;
487 	BIGNUM *rsa_dmp1 = NULL, *rsa_dmq1 = NULL;
488 	RSA *rsa = NULL;
489 
490 	if ((r = sshbuf_get_u32(b, &magic)) != 0)
491 		fatal_fr(r, "parse magic");
492 
493 	if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
494 		error("bad magic 0x%x != 0x%x", magic,
495 		    SSH_COM_PRIVATE_KEY_MAGIC);
496 		return NULL;
497 	}
498 	if ((r = sshbuf_get_u32(b, &i1)) != 0 ||
499 	    (r = sshbuf_get_cstring(b, &type, NULL)) != 0 ||
500 	    (r = sshbuf_get_cstring(b, &cipher, NULL)) != 0 ||
501 	    (r = sshbuf_get_u32(b, &i2)) != 0 ||
502 	    (r = sshbuf_get_u32(b, &i3)) != 0 ||
503 	    (r = sshbuf_get_u32(b, &i4)) != 0)
504 		fatal_fr(r, "parse");
505 	debug("ignore (%d %d %d %d)", i1, i2, i3, i4);
506 	if (strcmp(cipher, "none") != 0) {
507 		error("unsupported cipher %s", cipher);
508 		free(cipher);
509 		free(type);
510 		return NULL;
511 	}
512 	free(cipher);
513 
514 	if (strstr(type, "rsa")) {
515 		ktype = KEY_RSA;
516 #ifdef WITH_DSA
517 	} else if (strstr(type, "dsa")) {
518 		ktype = KEY_DSA;
519 #endif
520 	} else {
521 		free(type);
522 		return NULL;
523 	}
524 	if ((key = sshkey_new(ktype)) == NULL)
525 		fatal("sshkey_new failed");
526 	free(type);
527 
528 	switch (key->type) {
529 #ifdef WITH_DSA
530 	case KEY_DSA:
531 		if ((dsa_p = BN_new()) == NULL ||
532 		    (dsa_q = BN_new()) == NULL ||
533 		    (dsa_g = BN_new()) == NULL ||
534 		    (dsa_pub_key = BN_new()) == NULL ||
535 		    (dsa_priv_key = BN_new()) == NULL)
536 			fatal_f("BN_new");
537 		buffer_get_bignum_bits(b, dsa_p);
538 		buffer_get_bignum_bits(b, dsa_g);
539 		buffer_get_bignum_bits(b, dsa_q);
540 		buffer_get_bignum_bits(b, dsa_pub_key);
541 		buffer_get_bignum_bits(b, dsa_priv_key);
542 		if (!DSA_set0_pqg(key->dsa, dsa_p, dsa_q, dsa_g))
543 			fatal_f("DSA_set0_pqg failed");
544 		dsa_p = dsa_q = dsa_g = NULL; /* transferred */
545 		if (!DSA_set0_key(key->dsa, dsa_pub_key, dsa_priv_key))
546 			fatal_f("DSA_set0_key failed");
547 		dsa_pub_key = dsa_priv_key = NULL; /* transferred */
548 		break;
549 #endif
550 	case KEY_RSA:
551 		if ((r = sshbuf_get_u8(b, &e1)) != 0 ||
552 		    (e1 < 30 && (r = sshbuf_get_u8(b, &e2)) != 0) ||
553 		    (e1 < 30 && (r = sshbuf_get_u8(b, &e3)) != 0))
554 			fatal_fr(r, "parse RSA");
555 		e = e1;
556 		debug("e %lx", e);
557 		if (e < 30) {
558 			e <<= 8;
559 			e += e2;
560 			debug("e %lx", e);
561 			e <<= 8;
562 			e += e3;
563 			debug("e %lx", e);
564 		}
565 		if ((rsa_e = BN_new()) == NULL)
566 			fatal_f("BN_new");
567 		if (!BN_set_word(rsa_e, e)) {
568 			BN_clear_free(rsa_e);
569 			sshkey_free(key);
570 			return NULL;
571 		}
572 		if ((rsa_n = BN_new()) == NULL ||
573 		    (rsa_d = BN_new()) == NULL ||
574 		    (rsa_p = BN_new()) == NULL ||
575 		    (rsa_q = BN_new()) == NULL ||
576 		    (rsa_iqmp = BN_new()) == NULL)
577 			fatal_f("BN_new");
578 		buffer_get_bignum_bits(b, rsa_d);
579 		buffer_get_bignum_bits(b, rsa_n);
580 		buffer_get_bignum_bits(b, rsa_iqmp);
581 		buffer_get_bignum_bits(b, rsa_q);
582 		buffer_get_bignum_bits(b, rsa_p);
583 		if ((r = ssh_rsa_complete_crt_parameters(rsa_d, rsa_p, rsa_q,
584 		    rsa_iqmp, &rsa_dmp1, &rsa_dmq1)) != 0)
585 			fatal_fr(r, "generate RSA CRT parameters");
586 		if ((key->pkey = EVP_PKEY_new()) == NULL)
587 			fatal_f("EVP_PKEY_new failed");
588 		if ((rsa = RSA_new()) == NULL)
589 			fatal_f("RSA_new failed");
590 		if (!RSA_set0_key(rsa, rsa_n, rsa_e, rsa_d))
591 			fatal_f("RSA_set0_key failed");
592 		rsa_n = rsa_e = rsa_d = NULL; /* transferred */
593 		if (!RSA_set0_factors(rsa, rsa_p, rsa_q))
594 			fatal_f("RSA_set0_factors failed");
595 		rsa_p = rsa_q = NULL; /* transferred */
596 		if (RSA_set0_crt_params(rsa, rsa_dmp1, rsa_dmq1, rsa_iqmp) != 1)
597 			fatal_f("RSA_set0_crt_params failed");
598 		rsa_dmp1 = rsa_dmq1 = rsa_iqmp = NULL;
599 		if (EVP_PKEY_set1_RSA(key->pkey, rsa) != 1)
600 			fatal_f("EVP_PKEY_set1_RSA failed");
601 		RSA_free(rsa);
602 		alg = "rsa-sha2-256";
603 		break;
604 	}
605 	rlen = sshbuf_len(b);
606 	if (rlen != 0)
607 		error_f("remaining bytes in key blob %d", rlen);
608 
609 	/* try the key */
610 	if ((r = sshkey_sign(key, &sig, &slen, data, sizeof(data),
611 	    alg, NULL, NULL, 0)) != 0)
612 		error_fr(r, "signing with converted key failed");
613 	else if ((r = sshkey_verify(key, sig, slen, data, sizeof(data),
614 	    alg, 0, NULL)) != 0)
615 		error_fr(r, "verification with converted key failed");
616 	if (r != 0) {
617 		sshkey_free(key);
618 		free(sig);
619 		return NULL;
620 	}
621 	free(sig);
622 	return key;
623 }
624 
625 static int
626 get_line(FILE *fp, char *line, size_t len)
627 {
628 	int c;
629 	size_t pos = 0;
630 
631 	line[0] = '\0';
632 	while ((c = fgetc(fp)) != EOF) {
633 		if (pos >= len - 1)
634 			fatal("input line too long.");
635 		switch (c) {
636 		case '\r':
637 			c = fgetc(fp);
638 			if (c != EOF && c != '\n' && ungetc(c, fp) == EOF)
639 				fatal("unget: %s", strerror(errno));
640 			return pos;
641 		case '\n':
642 			return pos;
643 		}
644 		line[pos++] = c;
645 		line[pos] = '\0';
646 	}
647 	/* We reached EOF */
648 	return -1;
649 }
650 
651 static void
652 do_convert_from_ssh2(struct passwd *pw, struct sshkey **k, int *private)
653 {
654 	int r, blen, escaped = 0;
655 	u_int len;
656 	char line[1024];
657 	struct sshbuf *buf;
658 	char encoded[8096];
659 	FILE *fp;
660 
661 	if ((buf = sshbuf_new()) == NULL)
662 		fatal("sshbuf_new failed");
663 	if ((fp = fopen(identity_file, "r")) == NULL)
664 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
665 	encoded[0] = '\0';
666 	while ((blen = get_line(fp, line, sizeof(line))) != -1) {
667 		if (blen > 0 && line[blen - 1] == '\\')
668 			escaped++;
669 		if (strncmp(line, "----", 4) == 0 ||
670 		    strstr(line, ": ") != NULL) {
671 			if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
672 				*private = 1;
673 			if (strstr(line, " END ") != NULL) {
674 				break;
675 			}
676 			/* fprintf(stderr, "ignore: %s", line); */
677 			continue;
678 		}
679 		if (escaped) {
680 			escaped--;
681 			/* fprintf(stderr, "escaped: %s", line); */
682 			continue;
683 		}
684 		strlcat(encoded, line, sizeof(encoded));
685 	}
686 	len = strlen(encoded);
687 	if (((len % 4) == 3) &&
688 	    (encoded[len-1] == '=') &&
689 	    (encoded[len-2] == '=') &&
690 	    (encoded[len-3] == '='))
691 		encoded[len-3] = '\0';
692 	if ((r = sshbuf_b64tod(buf, encoded)) != 0)
693 		fatal_fr(r, "base64 decode");
694 	if (*private) {
695 		if ((*k = do_convert_private_ssh2(buf)) == NULL)
696 			fatal_f("private key conversion failed");
697 	} else if ((r = sshkey_fromb(buf, k)) != 0)
698 		fatal_fr(r, "parse key");
699 	sshbuf_free(buf);
700 	fclose(fp);
701 }
702 
703 static void
704 do_convert_from_pkcs8(struct sshkey **k, int *private)
705 {
706 	EVP_PKEY *pubkey;
707 	FILE *fp;
708 
709 	if ((fp = fopen(identity_file, "r")) == NULL)
710 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
711 	if ((pubkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL)) == NULL) {
712 		fatal_f("%s is not a recognised public key format",
713 		    identity_file);
714 	}
715 	fclose(fp);
716 	switch (EVP_PKEY_base_id(pubkey)) {
717 	case EVP_PKEY_RSA:
718 		if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
719 			fatal("sshkey_new failed");
720 		(*k)->type = KEY_RSA;
721 		(*k)->pkey = pubkey;
722 		pubkey = NULL;
723 		break;
724 #ifdef WITH_DSA
725 	case EVP_PKEY_DSA:
726 		if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
727 			fatal("sshkey_new failed");
728 		(*k)->type = KEY_DSA;
729 		(*k)->dsa = EVP_PKEY_get1_DSA(pubkey);
730 		break;
731 #endif
732 	case EVP_PKEY_EC:
733 		if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
734 			fatal("sshkey_new failed");
735 		if (((*k)->ecdsa_nid = sshkey_ecdsa_fixup_group(pubkey)) == -1)
736 			fatal("sshkey_ecdsa_fixup_group failed");
737 		(*k)->type = KEY_ECDSA;
738 		(*k)->pkey = pubkey;
739 		pubkey = NULL;
740 		break;
741 	default:
742 		fatal_f("unsupported pubkey type %d",
743 		    EVP_PKEY_base_id(pubkey));
744 	}
745 	EVP_PKEY_free(pubkey);
746 	return;
747 }
748 
749 static void
750 do_convert_from_pem(struct sshkey **k, int *private)
751 {
752 	FILE *fp;
753 	RSA *rsa;
754 
755 	if ((fp = fopen(identity_file, "r")) == NULL)
756 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
757 	if ((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
758 		if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
759 			fatal("sshkey_new failed");
760 		if (((*k)->pkey = EVP_PKEY_new()) == NULL)
761 			fatal("EVP_PKEY_new failed");
762 		(*k)->type = KEY_RSA;
763 		if (EVP_PKEY_set1_RSA((*k)->pkey, rsa) != 1)
764 			fatal("EVP_PKEY_set1_RSA failed");
765 		RSA_free(rsa);
766 		fclose(fp);
767 		return;
768 	}
769 	fatal_f("unrecognised raw private key format");
770 }
771 
772 __dead static void
773 do_convert_from(struct passwd *pw)
774 {
775 	struct sshkey *k = NULL;
776 	int r, private = 0, ok = 0;
777 	struct stat st;
778 
779 	if (!have_identity)
780 		ask_filename(pw, "Enter file in which the key is");
781 	if (stat(identity_file, &st) == -1)
782 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
783 
784 	switch (convert_format) {
785 	case FMT_RFC4716:
786 		do_convert_from_ssh2(pw, &k, &private);
787 		break;
788 	case FMT_PKCS8:
789 		do_convert_from_pkcs8(&k, &private);
790 		break;
791 	case FMT_PEM:
792 		do_convert_from_pem(&k, &private);
793 		break;
794 	default:
795 		fatal_f("unknown key format %d", convert_format);
796 	}
797 
798 	if (!private) {
799 		if ((r = sshkey_write(k, stdout)) == 0)
800 			ok = 1;
801 		if (ok)
802 			fprintf(stdout, "\n");
803 	} else {
804 		switch (k->type) {
805 #ifdef WITH_DSA
806 		case KEY_DSA:
807 			ok = PEM_write_DSAPrivateKey(stdout, k->dsa, NULL,
808 			    NULL, 0, NULL, NULL);
809 			break;
810 #endif
811 		case KEY_ECDSA:
812 			ok = PEM_write_ECPrivateKey(stdout,
813 			    EVP_PKEY_get0_EC_KEY(k->pkey), NULL, NULL, 0,
814 			    NULL, NULL);
815 			break;
816 		case KEY_RSA:
817 			ok = PEM_write_RSAPrivateKey(stdout,
818 			    EVP_PKEY_get0_RSA(k->pkey), NULL, NULL, 0,
819 			    NULL, NULL);
820 			break;
821 		default:
822 			fatal_f("unsupported key type %s", sshkey_type(k));
823 		}
824 	}
825 
826 	if (!ok)
827 		fatal("key write failed");
828 	sshkey_free(k);
829 	exit(0);
830 }
831 #endif
832 
833 __dead static void
834 do_print_public(struct passwd *pw)
835 {
836 	struct sshkey *prv;
837 	struct stat st;
838 	int r;
839 	char *comment = NULL;
840 
841 	if (!have_identity)
842 		ask_filename(pw, "Enter file in which the key is");
843 	if (stat(identity_file, &st) == -1)
844 		fatal("%s: %s", identity_file, strerror(errno));
845 	prv = load_identity(identity_file, &comment);
846 	if ((r = sshkey_write(prv, stdout)) != 0)
847 		fatal_fr(r, "write key");
848 	if (comment != NULL && *comment != '\0')
849 		fprintf(stdout, " %s", comment);
850 	fprintf(stdout, "\n");
851 	if (sshkey_is_sk(prv)) {
852 		debug("sk_application: \"%s\", sk_flags 0x%02x",
853 			prv->sk_application, prv->sk_flags);
854 	}
855 	sshkey_free(prv);
856 	free(comment);
857 	exit(0);
858 }
859 
860 __dead static void
861 do_download(struct passwd *pw)
862 {
863 #ifdef ENABLE_PKCS11
864 	struct sshkey **keys = NULL;
865 	int i, nkeys;
866 	enum sshkey_fp_rep rep;
867 	int fptype;
868 	char *fp, *ra, **comments = NULL;
869 
870 	fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
871 	rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
872 
873 	pkcs11_init(1);
874 	nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys, &comments);
875 	if (nkeys <= 0)
876 		fatal("cannot read public key from pkcs11");
877 	for (i = 0; i < nkeys; i++) {
878 		if (print_fingerprint) {
879 			fp = sshkey_fingerprint(keys[i], fptype, rep);
880 			ra = sshkey_fingerprint(keys[i], fingerprint_hash,
881 			    SSH_FP_RANDOMART);
882 			if (fp == NULL || ra == NULL)
883 				fatal_f("sshkey_fingerprint fail");
884 			printf("%u %s %s (PKCS11 key)\n", sshkey_size(keys[i]),
885 			    fp, sshkey_type(keys[i]));
886 			if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
887 				printf("%s\n", ra);
888 			free(ra);
889 			free(fp);
890 		} else {
891 			(void) sshkey_write(keys[i], stdout); /* XXX check */
892 			fprintf(stdout, "%s%s\n",
893 			    *(comments[i]) == '\0' ? "" : " ", comments[i]);
894 		}
895 		free(comments[i]);
896 		sshkey_free(keys[i]);
897 	}
898 	free(comments);
899 	free(keys);
900 	pkcs11_terminate();
901 	exit(0);
902 #else
903 	fatal("no pkcs11 support");
904 #endif /* ENABLE_PKCS11 */
905 }
906 
907 static struct sshkey *
908 try_read_key(char **cpp)
909 {
910 	struct sshkey *ret;
911 	int r;
912 
913 	if ((ret = sshkey_new(KEY_UNSPEC)) == NULL)
914 		fatal("sshkey_new failed");
915 	if ((r = sshkey_read(ret, cpp)) == 0)
916 		return ret;
917 	/* Not a key */
918 	sshkey_free(ret);
919 	return NULL;
920 }
921 
922 static void
923 fingerprint_one_key(const struct sshkey *public, const char *comment)
924 {
925 	char *fp = NULL, *ra = NULL;
926 	enum sshkey_fp_rep rep;
927 	int fptype;
928 
929 	fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
930 	rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
931 	fp = sshkey_fingerprint(public, fptype, rep);
932 	ra = sshkey_fingerprint(public, fingerprint_hash, SSH_FP_RANDOMART);
933 	if (fp == NULL || ra == NULL)
934 		fatal_f("sshkey_fingerprint failed");
935 	mprintf("%u %s %s (%s)\n", sshkey_size(public), fp,
936 	    comment ? comment : "no comment", sshkey_type(public));
937 	if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
938 		printf("%s\n", ra);
939 	free(ra);
940 	free(fp);
941 }
942 
943 static void
944 fingerprint_private(const char *path)
945 {
946 	struct stat st;
947 	char *comment = NULL;
948 	struct sshkey *privkey = NULL, *pubkey = NULL;
949 	int r;
950 
951 	if (stat(identity_file, &st) == -1)
952 		fatal("%s: %s", path, strerror(errno));
953 	if ((r = sshkey_load_public(path, &pubkey, &comment)) != 0)
954 		debug_r(r, "load public \"%s\"", path);
955 	if (pubkey == NULL || comment == NULL || *comment == '\0') {
956 		free(comment);
957 		if ((r = sshkey_load_private(path, NULL,
958 		    &privkey, &comment)) != 0)
959 			debug_r(r, "load private \"%s\"", path);
960 	}
961 	if (pubkey == NULL && privkey == NULL)
962 		fatal("%s is not a key file.", path);
963 
964 	fingerprint_one_key(pubkey == NULL ? privkey : pubkey, comment);
965 	sshkey_free(pubkey);
966 	sshkey_free(privkey);
967 	free(comment);
968 }
969 
970 __dead static void
971 do_fingerprint(struct passwd *pw)
972 {
973 	FILE *f;
974 	struct sshkey *public = NULL;
975 	char *comment = NULL, *cp, *ep, *line = NULL;
976 	size_t linesize = 0;
977 	int i, invalid = 1;
978 	const char *path;
979 	u_long lnum = 0;
980 
981 	if (!have_identity)
982 		ask_filename(pw, "Enter file in which the key is");
983 	path = identity_file;
984 
985 	if (strcmp(identity_file, "-") == 0) {
986 		f = stdin;
987 		path = "(stdin)";
988 	} else if ((f = fopen(path, "r")) == NULL)
989 		fatal("%s: %s: %s", __progname, path, strerror(errno));
990 
991 	while (getline(&line, &linesize, f) != -1) {
992 		lnum++;
993 		cp = line;
994 		cp[strcspn(cp, "\n")] = '\0';
995 		/* Trim leading space and comments */
996 		cp = line + strspn(line, " \t");
997 		if (*cp == '#' || *cp == '\0')
998 			continue;
999 
1000 		/*
1001 		 * Input may be plain keys, private keys, authorized_keys
1002 		 * or known_hosts.
1003 		 */
1004 
1005 		/*
1006 		 * Try private keys first. Assume a key is private if
1007 		 * "SSH PRIVATE KEY" appears on the first line and we're
1008 		 * not reading from stdin (XXX support private keys on stdin).
1009 		 */
1010 		if (lnum == 1 && strcmp(identity_file, "-") != 0 &&
1011 		    strstr(cp, "PRIVATE KEY") != NULL) {
1012 			free(line);
1013 			fclose(f);
1014 			fingerprint_private(path);
1015 			exit(0);
1016 		}
1017 
1018 		/*
1019 		 * If it's not a private key, then this must be prepared to
1020 		 * accept a public key prefixed with a hostname or options.
1021 		 * Try a bare key first, otherwise skip the leading stuff.
1022 		 */
1023 		comment = NULL;
1024 		if ((public = try_read_key(&cp)) == NULL) {
1025 			i = strtol(cp, &ep, 10);
1026 			if (i == 0 || ep == NULL ||
1027 			    (*ep != ' ' && *ep != '\t')) {
1028 				int quoted = 0;
1029 
1030 				comment = cp;
1031 				for (; *cp && (quoted || (*cp != ' ' &&
1032 				    *cp != '\t')); cp++) {
1033 					if (*cp == '\\' && cp[1] == '"')
1034 						cp++;	/* Skip both */
1035 					else if (*cp == '"')
1036 						quoted = !quoted;
1037 				}
1038 				if (!*cp)
1039 					continue;
1040 				*cp++ = '\0';
1041 			}
1042 		}
1043 		/* Retry after parsing leading hostname/key options */
1044 		if (public == NULL && (public = try_read_key(&cp)) == NULL) {
1045 			debug("%s:%lu: not a public key", path, lnum);
1046 			continue;
1047 		}
1048 
1049 		/* Find trailing comment, if any */
1050 		for (; *cp == ' ' || *cp == '\t'; cp++)
1051 			;
1052 		if (*cp != '\0' && *cp != '#')
1053 			comment = cp;
1054 
1055 		fingerprint_one_key(public, comment);
1056 		sshkey_free(public);
1057 		invalid = 0; /* One good key in the file is sufficient */
1058 	}
1059 	fclose(f);
1060 	free(line);
1061 
1062 	if (invalid)
1063 		fatal("%s is not a public key file.", path);
1064 	exit(0);
1065 }
1066 
1067 static void
1068 do_gen_all_hostkeys(struct passwd *pw)
1069 {
1070 	struct {
1071 		const char *key_type;
1072 		const char *key_type_display;
1073 		const char *path;
1074 	} key_types[] = {
1075 #ifdef WITH_OPENSSL
1076 		{ "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE },
1077 		{ "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE },
1078 #endif /* WITH_OPENSSL */
1079 		{ "ed25519", "ED25519",_PATH_HOST_ED25519_KEY_FILE },
1080 #ifdef WITH_XMSS
1081 		{ "xmss", "XMSS",_PATH_HOST_XMSS_KEY_FILE },
1082 #endif /* WITH_XMSS */
1083 		{ NULL, NULL, NULL }
1084 	};
1085 
1086 	u_int32_t bits = 0;
1087 	int first = 0;
1088 	struct stat st;
1089 	struct sshkey *private, *public;
1090 	char comment[1024], *prv_tmp, *pub_tmp, *prv_file, *pub_file;
1091 	int i, type, fd, r;
1092 
1093 	for (i = 0; key_types[i].key_type; i++) {
1094 		public = private = NULL;
1095 		prv_tmp = pub_tmp = prv_file = pub_file = NULL;
1096 
1097 		xasprintf(&prv_file, "%s%s",
1098 		    identity_file, key_types[i].path);
1099 
1100 		/* Check whether private key exists and is not zero-length */
1101 		if (stat(prv_file, &st) == 0) {
1102 			if (st.st_size != 0)
1103 				goto next;
1104 		} else if (errno != ENOENT) {
1105 			error("Could not stat %s: %s", key_types[i].path,
1106 			    strerror(errno));
1107 			goto failnext;
1108 		}
1109 
1110 		/*
1111 		 * Private key doesn't exist or is invalid; proceed with
1112 		 * key generation.
1113 		 */
1114 		xasprintf(&prv_tmp, "%s%s.XXXXXXXXXX",
1115 		    identity_file, key_types[i].path);
1116 		xasprintf(&pub_tmp, "%s%s.pub.XXXXXXXXXX",
1117 		    identity_file, key_types[i].path);
1118 		xasprintf(&pub_file, "%s%s.pub",
1119 		    identity_file, key_types[i].path);
1120 
1121 		if (first == 0) {
1122 			first = 1;
1123 			printf("%s: generating new host keys: ", __progname);
1124 		}
1125 		printf("%s ", key_types[i].key_type_display);
1126 		fflush(stdout);
1127 		type = sshkey_type_from_shortname(key_types[i].key_type);
1128 		if ((fd = mkstemp(prv_tmp)) == -1) {
1129 			error("Could not save your private key in %s: %s",
1130 			    prv_tmp, strerror(errno));
1131 			goto failnext;
1132 		}
1133 		(void)close(fd); /* just using mkstemp() to reserve a name */
1134 		bits = 0;
1135 		type_bits_valid(type, NULL, &bits);
1136 		if ((r = sshkey_generate(type, bits, &private)) != 0) {
1137 			error_r(r, "sshkey_generate failed");
1138 			goto failnext;
1139 		}
1140 		if ((r = sshkey_from_private(private, &public)) != 0)
1141 			fatal_fr(r, "sshkey_from_private");
1142 		snprintf(comment, sizeof comment, "%s@%s", pw->pw_name,
1143 		    hostname);
1144 		if ((r = sshkey_save_private(private, prv_tmp, "",
1145 		    comment, private_key_format, openssh_format_cipher,
1146 		    rounds)) != 0) {
1147 			error_r(r, "Saving key \"%s\" failed", prv_tmp);
1148 			goto failnext;
1149 		}
1150 		if ((fd = mkstemp(pub_tmp)) == -1) {
1151 			error("Could not save your public key in %s: %s",
1152 			    pub_tmp, strerror(errno));
1153 			goto failnext;
1154 		}
1155 		(void)fchmod(fd, 0644);
1156 		(void)close(fd);
1157 		if ((r = sshkey_save_public(public, pub_tmp, comment)) != 0) {
1158 			error_r(r, "Unable to save public key to %s",
1159 			    identity_file);
1160 			goto failnext;
1161 		}
1162 
1163 		/* Rename temporary files to their permanent locations. */
1164 		if (rename(pub_tmp, pub_file) != 0) {
1165 			error("Unable to move %s into position: %s",
1166 			    pub_file, strerror(errno));
1167 			goto failnext;
1168 		}
1169 		if (rename(prv_tmp, prv_file) != 0) {
1170 			error("Unable to move %s into position: %s",
1171 			    key_types[i].path, strerror(errno));
1172  failnext:
1173 			first = 0;
1174 			goto next;
1175 		}
1176  next:
1177 		sshkey_free(private);
1178 		sshkey_free(public);
1179 		free(prv_tmp);
1180 		free(pub_tmp);
1181 		free(prv_file);
1182 		free(pub_file);
1183 	}
1184 	if (first != 0)
1185 		printf("\n");
1186 }
1187 
1188 struct known_hosts_ctx {
1189 	const char *host;	/* Hostname searched for in find/delete case */
1190 	FILE *out;		/* Output file, stdout for find_hosts case */
1191 	int has_unhashed;	/* When hashing, original had unhashed hosts */
1192 	int found_key;		/* For find/delete, host was found */
1193 	int invalid;		/* File contained invalid items; don't delete */
1194 	int hash_hosts;		/* Hash hostnames as we go */
1195 	int find_host;		/* Search for specific hostname */
1196 	int delete_host;	/* Delete host from known_hosts */
1197 };
1198 
1199 static int
1200 known_hosts_hash(struct hostkey_foreach_line *l, void *_ctx)
1201 {
1202 	struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1203 	char *hashed, *cp, *hosts, *ohosts;
1204 	int has_wild = l->hosts && strcspn(l->hosts, "*?!") != strlen(l->hosts);
1205 	int was_hashed = l->hosts && l->hosts[0] == HASH_DELIM;
1206 
1207 	switch (l->status) {
1208 	case HKF_STATUS_OK:
1209 	case HKF_STATUS_MATCHED:
1210 		/*
1211 		 * Don't hash hosts already hashed, with wildcard
1212 		 * characters or a CA/revocation marker.
1213 		 */
1214 		if (was_hashed || has_wild || l->marker != MRK_NONE) {
1215 			fprintf(ctx->out, "%s\n", l->line);
1216 			if (has_wild && !ctx->find_host) {
1217 				logit("%s:%lu: ignoring host name "
1218 				    "with wildcard: %.64s", l->path,
1219 				    l->linenum, l->hosts);
1220 			}
1221 			return 0;
1222 		}
1223 		/*
1224 		 * Split any comma-separated hostnames from the host list,
1225 		 * hash and store separately.
1226 		 */
1227 		ohosts = hosts = xstrdup(l->hosts);
1228 		while ((cp = strsep(&hosts, ",")) != NULL && *cp != '\0') {
1229 			lowercase(cp);
1230 			if ((hashed = host_hash(cp, NULL, 0)) == NULL)
1231 				fatal("hash_host failed");
1232 			fprintf(ctx->out, "%s %s\n", hashed, l->rawkey);
1233 			free(hashed);
1234 			ctx->has_unhashed = 1;
1235 		}
1236 		free(ohosts);
1237 		return 0;
1238 	case HKF_STATUS_INVALID:
1239 		/* Retain invalid lines, but mark file as invalid. */
1240 		ctx->invalid = 1;
1241 		logit("%s:%lu: invalid line", l->path, l->linenum);
1242 		/* FALLTHROUGH */
1243 	default:
1244 		fprintf(ctx->out, "%s\n", l->line);
1245 		return 0;
1246 	}
1247 	/* NOTREACHED */
1248 	return -1;
1249 }
1250 
1251 static int
1252 known_hosts_find_delete(struct hostkey_foreach_line *l, void *_ctx)
1253 {
1254 	struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1255 	enum sshkey_fp_rep rep;
1256 	int fptype;
1257 	char *fp = NULL, *ra = NULL;
1258 
1259 	fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
1260 	rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1261 
1262 	if (l->status == HKF_STATUS_MATCHED) {
1263 		if (ctx->delete_host) {
1264 			if (l->marker != MRK_NONE) {
1265 				/* Don't remove CA and revocation lines */
1266 				fprintf(ctx->out, "%s\n", l->line);
1267 			} else {
1268 				/*
1269 				 * Hostname matches and has no CA/revoke
1270 				 * marker, delete it by *not* writing the
1271 				 * line to ctx->out.
1272 				 */
1273 				ctx->found_key = 1;
1274 				if (!quiet)
1275 					printf("# Host %s found: line %lu\n",
1276 					    ctx->host, l->linenum);
1277 			}
1278 			return 0;
1279 		} else if (ctx->find_host) {
1280 			ctx->found_key = 1;
1281 			if (!quiet) {
1282 				printf("# Host %s found: line %lu %s\n",
1283 				    ctx->host,
1284 				    l->linenum, l->marker == MRK_CA ? "CA" :
1285 				    (l->marker == MRK_REVOKE ? "REVOKED" : ""));
1286 			}
1287 			if (ctx->hash_hosts)
1288 				known_hosts_hash(l, ctx);
1289 			else if (print_fingerprint) {
1290 				fp = sshkey_fingerprint(l->key, fptype, rep);
1291 				ra = sshkey_fingerprint(l->key,
1292 				    fingerprint_hash, SSH_FP_RANDOMART);
1293 				if (fp == NULL || ra == NULL)
1294 					fatal_f("sshkey_fingerprint failed");
1295 				mprintf("%s %s %s%s%s\n", ctx->host,
1296 				    sshkey_type(l->key), fp,
1297 				    l->comment[0] ? " " : "",
1298 				    l->comment);
1299 				if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
1300 					printf("%s\n", ra);
1301 				free(ra);
1302 				free(fp);
1303 			} else
1304 				fprintf(ctx->out, "%s\n", l->line);
1305 			return 0;
1306 		}
1307 	} else if (ctx->delete_host) {
1308 		/* Retain non-matching hosts when deleting */
1309 		if (l->status == HKF_STATUS_INVALID) {
1310 			ctx->invalid = 1;
1311 			logit("%s:%lu: invalid line", l->path, l->linenum);
1312 		}
1313 		fprintf(ctx->out, "%s\n", l->line);
1314 	}
1315 	return 0;
1316 }
1317 
1318 __dead static void
1319 do_known_hosts(struct passwd *pw, const char *name, int find_host,
1320     int delete_host, int hash_hosts)
1321 {
1322 	char *cp, tmp[PATH_MAX], old[PATH_MAX];
1323 	int r, fd, oerrno, inplace = 0;
1324 	struct known_hosts_ctx ctx;
1325 	u_int foreach_options;
1326 	struct stat sb;
1327 
1328 	if (!have_identity) {
1329 		cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
1330 		if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
1331 		    sizeof(identity_file))
1332 			fatal("Specified known hosts path too long");
1333 		free(cp);
1334 		have_identity = 1;
1335 	}
1336 	if (stat(identity_file, &sb) != 0)
1337 		fatal("Cannot stat %s: %s", identity_file, strerror(errno));
1338 
1339 	memset(&ctx, 0, sizeof(ctx));
1340 	ctx.out = stdout;
1341 	ctx.host = name;
1342 	ctx.hash_hosts = hash_hosts;
1343 	ctx.find_host = find_host;
1344 	ctx.delete_host = delete_host;
1345 
1346 	/*
1347 	 * Find hosts goes to stdout, hash and deletions happen in-place
1348 	 * A corner case is ssh-keygen -HF foo, which should go to stdout
1349 	 */
1350 	if (!find_host && (hash_hosts || delete_host)) {
1351 		if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
1352 		    strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
1353 		    strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
1354 		    strlcat(old, ".old", sizeof(old)) >= sizeof(old))
1355 			fatal("known_hosts path too long");
1356 		umask(077);
1357 		if ((fd = mkstemp(tmp)) == -1)
1358 			fatal("mkstemp: %s", strerror(errno));
1359 		if ((ctx.out = fdopen(fd, "w")) == NULL) {
1360 			oerrno = errno;
1361 			unlink(tmp);
1362 			fatal("fdopen: %s", strerror(oerrno));
1363 		}
1364 		(void)fchmod(fd, sb.st_mode & 0644);
1365 		inplace = 1;
1366 	}
1367 	/* XXX support identity_file == "-" for stdin */
1368 	foreach_options = find_host ? HKF_WANT_MATCH : 0;
1369 	foreach_options |= print_fingerprint ? HKF_WANT_PARSE_KEY : 0;
1370 	if ((r = hostkeys_foreach(identity_file, (find_host || !hash_hosts) ?
1371 	    known_hosts_find_delete : known_hosts_hash, &ctx, name, NULL,
1372 	    foreach_options, 0)) != 0) {
1373 		if (inplace)
1374 			unlink(tmp);
1375 		fatal_fr(r, "hostkeys_foreach");
1376 	}
1377 
1378 	if (inplace)
1379 		fclose(ctx.out);
1380 
1381 	if (ctx.invalid) {
1382 		error("%s is not a valid known_hosts file.", identity_file);
1383 		if (inplace) {
1384 			error("Not replacing existing known_hosts "
1385 			    "file because of errors");
1386 			unlink(tmp);
1387 		}
1388 		exit(1);
1389 	} else if (delete_host && !ctx.found_key) {
1390 		logit("Host %s not found in %s", name, identity_file);
1391 		if (inplace)
1392 			unlink(tmp);
1393 	} else if (inplace) {
1394 		/* Backup existing file */
1395 		if (unlink(old) == -1 && errno != ENOENT)
1396 			fatal("unlink %.100s: %s", old, strerror(errno));
1397 		if (link(identity_file, old) == -1)
1398 			fatal("link %.100s to %.100s: %s", identity_file, old,
1399 			    strerror(errno));
1400 		/* Move new one into place */
1401 		if (rename(tmp, identity_file) == -1) {
1402 			error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
1403 			    strerror(errno));
1404 			unlink(tmp);
1405 			unlink(old);
1406 			exit(1);
1407 		}
1408 
1409 		printf("%s updated.\n", identity_file);
1410 		printf("Original contents retained as %s\n", old);
1411 		if (ctx.has_unhashed) {
1412 			logit("WARNING: %s contains unhashed entries", old);
1413 			logit("Delete this file to ensure privacy "
1414 			    "of hostnames");
1415 		}
1416 	}
1417 
1418 	exit (find_host && !ctx.found_key);
1419 }
1420 
1421 /*
1422  * Perform changing a passphrase.  The argument is the passwd structure
1423  * for the current user.
1424  */
1425 __dead static void
1426 do_change_passphrase(struct passwd *pw)
1427 {
1428 	char *comment;
1429 	char *old_passphrase, *passphrase1, *passphrase2;
1430 	struct stat st;
1431 	struct sshkey *private;
1432 	int r;
1433 
1434 	if (!have_identity)
1435 		ask_filename(pw, "Enter file in which the key is");
1436 	if (stat(identity_file, &st) == -1)
1437 		fatal("%s: %s", identity_file, strerror(errno));
1438 	/* Try to load the file with empty passphrase. */
1439 	r = sshkey_load_private(identity_file, "", &private, &comment);
1440 	if (r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
1441 		if (identity_passphrase)
1442 			old_passphrase = xstrdup(identity_passphrase);
1443 		else
1444 			old_passphrase =
1445 			    read_passphrase("Enter old passphrase: ",
1446 			    RP_ALLOW_STDIN);
1447 		r = sshkey_load_private(identity_file, old_passphrase,
1448 		    &private, &comment);
1449 		freezero(old_passphrase, strlen(old_passphrase));
1450 		if (r != 0)
1451 			goto badkey;
1452 	} else if (r != 0) {
1453  badkey:
1454 		fatal_r(r, "Failed to load key %s", identity_file);
1455 	}
1456 	if (comment)
1457 		mprintf("Key has comment '%s'\n", comment);
1458 
1459 	/* Ask the new passphrase (twice). */
1460 	if (identity_new_passphrase) {
1461 		passphrase1 = xstrdup(identity_new_passphrase);
1462 		passphrase2 = NULL;
1463 	} else {
1464 		passphrase1 =
1465 			read_passphrase("Enter new passphrase (empty for no "
1466 			    "passphrase): ", RP_ALLOW_STDIN);
1467 		passphrase2 = read_passphrase("Enter same passphrase again: ",
1468 		    RP_ALLOW_STDIN);
1469 
1470 		/* Verify that they are the same. */
1471 		if (strcmp(passphrase1, passphrase2) != 0) {
1472 			explicit_bzero(passphrase1, strlen(passphrase1));
1473 			explicit_bzero(passphrase2, strlen(passphrase2));
1474 			free(passphrase1);
1475 			free(passphrase2);
1476 			printf("Pass phrases do not match.  Try again.\n");
1477 			exit(1);
1478 		}
1479 		/* Destroy the other copy. */
1480 		freezero(passphrase2, strlen(passphrase2));
1481 	}
1482 
1483 	/* Save the file using the new passphrase. */
1484 	if ((r = sshkey_save_private(private, identity_file, passphrase1,
1485 	    comment, private_key_format, openssh_format_cipher, rounds)) != 0) {
1486 		error_r(r, "Saving key \"%s\" failed", identity_file);
1487 		freezero(passphrase1, strlen(passphrase1));
1488 		sshkey_free(private);
1489 		free(comment);
1490 		exit(1);
1491 	}
1492 	/* Destroy the passphrase and the copy of the key in memory. */
1493 	freezero(passphrase1, strlen(passphrase1));
1494 	sshkey_free(private);		 /* Destroys contents */
1495 	free(comment);
1496 
1497 	printf("Your identification has been saved with the new passphrase.\n");
1498 	exit(0);
1499 }
1500 
1501 /*
1502  * Print the SSHFP RR.
1503  */
1504 static int
1505 do_print_resource_record(struct passwd *pw, const char *fname,
1506     const char *hname,
1507     int print_generic, char * const *opts, size_t nopts)
1508 {
1509 	struct sshkey *public;
1510 	char *comment = NULL;
1511 	struct stat st;
1512 	int r, hash = -1;
1513 	size_t i;
1514 
1515 	for (i = 0; i < nopts; i++) {
1516 		if (strncasecmp(opts[i], "hashalg=", 8) == 0) {
1517 			if ((hash = ssh_digest_alg_by_name(opts[i] + 8)) == -1)
1518 				fatal("Unsupported hash algorithm");
1519 		} else {
1520 			error("Invalid option \"%s\"", opts[i]);
1521 			return SSH_ERR_INVALID_ARGUMENT;
1522 		}
1523 	}
1524 	if (fname == NULL)
1525 		fatal_f("no filename");
1526 	if (stat(fname, &st) == -1) {
1527 		if (errno == ENOENT)
1528 			return 0;
1529 		fatal("%s: %s", fname, strerror(errno));
1530 	}
1531 	if ((r = sshkey_load_public(fname, &public, &comment)) != 0)
1532 		fatal_r(r, "Failed to read v2 public key from \"%s\"", fname);
1533 	export_dns_rr(hname, public, stdout, print_generic, hash);
1534 	sshkey_free(public);
1535 	free(comment);
1536 	return 1;
1537 }
1538 
1539 /*
1540  * Change the comment of a private key file.
1541  */
1542 __dead static void
1543 do_change_comment(struct passwd *pw, const char *identity_comment)
1544 {
1545 	char new_comment[1024], *comment, *passphrase;
1546 	struct sshkey *private;
1547 	struct sshkey *public;
1548 	struct stat st;
1549 	int r;
1550 
1551 	if (!have_identity)
1552 		ask_filename(pw, "Enter file in which the key is");
1553 	if (stat(identity_file, &st) == -1)
1554 		fatal("%s: %s", identity_file, strerror(errno));
1555 	if ((r = sshkey_load_private(identity_file, "",
1556 	    &private, &comment)) == 0)
1557 		passphrase = xstrdup("");
1558 	else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
1559 		fatal_r(r, "Cannot load private key \"%s\"", identity_file);
1560 	else {
1561 		if (identity_passphrase)
1562 			passphrase = xstrdup(identity_passphrase);
1563 		else if (identity_new_passphrase)
1564 			passphrase = xstrdup(identity_new_passphrase);
1565 		else
1566 			passphrase = read_passphrase("Enter passphrase: ",
1567 			    RP_ALLOW_STDIN);
1568 		/* Try to load using the passphrase. */
1569 		if ((r = sshkey_load_private(identity_file, passphrase,
1570 		    &private, &comment)) != 0) {
1571 			freezero(passphrase, strlen(passphrase));
1572 			fatal_r(r, "Cannot load private key \"%s\"",
1573 			    identity_file);
1574 		}
1575 	}
1576 
1577 	if (private->type != KEY_ED25519 && private->type != KEY_XMSS &&
1578 	    private_key_format != SSHKEY_PRIVATE_OPENSSH) {
1579 		error("Comments are only supported for keys stored in "
1580 		    "the new format (-o).");
1581 		explicit_bzero(passphrase, strlen(passphrase));
1582 		sshkey_free(private);
1583 		exit(1);
1584 	}
1585 	if (comment)
1586 		printf("Old comment: %s\n", comment);
1587 	else
1588 		printf("No existing comment\n");
1589 
1590 	if (identity_comment) {
1591 		strlcpy(new_comment, identity_comment, sizeof(new_comment));
1592 	} else {
1593 		printf("New comment: ");
1594 		fflush(stdout);
1595 		if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1596 			explicit_bzero(passphrase, strlen(passphrase));
1597 			sshkey_free(private);
1598 			exit(1);
1599 		}
1600 		new_comment[strcspn(new_comment, "\n")] = '\0';
1601 	}
1602 	if (comment != NULL && strcmp(comment, new_comment) == 0) {
1603 		printf("No change to comment\n");
1604 		free(passphrase);
1605 		sshkey_free(private);
1606 		free(comment);
1607 		exit(0);
1608 	}
1609 
1610 	/* Save the file using the new passphrase. */
1611 	if ((r = sshkey_save_private(private, identity_file, passphrase,
1612 	    new_comment, private_key_format, openssh_format_cipher,
1613 	    rounds)) != 0) {
1614 		error_r(r, "Saving key \"%s\" failed", identity_file);
1615 		freezero(passphrase, strlen(passphrase));
1616 		sshkey_free(private);
1617 		free(comment);
1618 		exit(1);
1619 	}
1620 	freezero(passphrase, strlen(passphrase));
1621 	if ((r = sshkey_from_private(private, &public)) != 0)
1622 		fatal_fr(r, "sshkey_from_private");
1623 	sshkey_free(private);
1624 
1625 	strlcat(identity_file, ".pub", sizeof(identity_file));
1626 	if ((r = sshkey_save_public(public, identity_file, new_comment)) != 0)
1627 		fatal_r(r, "Unable to save public key to %s", identity_file);
1628 	sshkey_free(public);
1629 	free(comment);
1630 
1631 	if (strlen(new_comment) > 0)
1632 		printf("Comment '%s' applied\n", new_comment);
1633 	else
1634 		printf("Comment removed\n");
1635 
1636 	exit(0);
1637 }
1638 
1639 static void
1640 cert_ext_add(const char *key, const char *value, int iscrit)
1641 {
1642 	cert_ext = xreallocarray(cert_ext, ncert_ext + 1, sizeof(*cert_ext));
1643 	cert_ext[ncert_ext].key = xstrdup(key);
1644 	cert_ext[ncert_ext].val = value == NULL ? NULL : xstrdup(value);
1645 	cert_ext[ncert_ext].crit = iscrit;
1646 	ncert_ext++;
1647 }
1648 
1649 /* qsort(3) comparison function for certificate extensions */
1650 static int
1651 cert_ext_cmp(const void *_a, const void *_b)
1652 {
1653 	const struct cert_ext *a = (const struct cert_ext *)_a;
1654 	const struct cert_ext *b = (const struct cert_ext *)_b;
1655 	int r;
1656 
1657 	if (a->crit != b->crit)
1658 		return (a->crit < b->crit) ? -1 : 1;
1659 	if ((r = strcmp(a->key, b->key)) != 0)
1660 		return r;
1661 	if ((a->val == NULL) != (b->val == NULL))
1662 		return (a->val == NULL) ? -1 : 1;
1663 	if (a->val != NULL && (r = strcmp(a->val, b->val)) != 0)
1664 		return r;
1665 	return 0;
1666 }
1667 
1668 #define OPTIONS_CRITICAL	1
1669 #define OPTIONS_EXTENSIONS	2
1670 static void
1671 prepare_options_buf(struct sshbuf *c, int which)
1672 {
1673 	struct sshbuf *b;
1674 	size_t i;
1675 	int r;
1676 	const struct cert_ext *ext;
1677 
1678 	if ((b = sshbuf_new()) == NULL)
1679 		fatal_f("sshbuf_new failed");
1680 	sshbuf_reset(c);
1681 	for (i = 0; i < ncert_ext; i++) {
1682 		ext = &cert_ext[i];
1683 		if ((ext->crit && (which & OPTIONS_EXTENSIONS)) ||
1684 		    (!ext->crit && (which & OPTIONS_CRITICAL)))
1685 			continue;
1686 		if (ext->val == NULL) {
1687 			/* flag option */
1688 			debug3_f("%s", ext->key);
1689 			if ((r = sshbuf_put_cstring(c, ext->key)) != 0 ||
1690 			    (r = sshbuf_put_string(c, NULL, 0)) != 0)
1691 				fatal_fr(r, "prepare flag");
1692 		} else {
1693 			/* key/value option */
1694 			debug3_f("%s=%s", ext->key, ext->val);
1695 			sshbuf_reset(b);
1696 			if ((r = sshbuf_put_cstring(c, ext->key)) != 0 ||
1697 			    (r = sshbuf_put_cstring(b, ext->val)) != 0 ||
1698 			    (r = sshbuf_put_stringb(c, b)) != 0)
1699 				fatal_fr(r, "prepare k/v");
1700 		}
1701 	}
1702 	sshbuf_free(b);
1703 }
1704 
1705 static void
1706 finalise_cert_exts(void)
1707 {
1708 	/* critical options */
1709 	if (certflags_command != NULL)
1710 		cert_ext_add("force-command", certflags_command, 1);
1711 	if (certflags_src_addr != NULL)
1712 		cert_ext_add("source-address", certflags_src_addr, 1);
1713 	if ((certflags_flags & CERTOPT_REQUIRE_VERIFY) != 0)
1714 		cert_ext_add("verify-required", NULL, 1);
1715 	/* extensions */
1716 	if ((certflags_flags & CERTOPT_X_FWD) != 0)
1717 		cert_ext_add("permit-X11-forwarding", NULL, 0);
1718 	if ((certflags_flags & CERTOPT_AGENT_FWD) != 0)
1719 		cert_ext_add("permit-agent-forwarding", NULL, 0);
1720 	if ((certflags_flags & CERTOPT_PORT_FWD) != 0)
1721 		cert_ext_add("permit-port-forwarding", NULL, 0);
1722 	if ((certflags_flags & CERTOPT_PTY) != 0)
1723 		cert_ext_add("permit-pty", NULL, 0);
1724 	if ((certflags_flags & CERTOPT_USER_RC) != 0)
1725 		cert_ext_add("permit-user-rc", NULL, 0);
1726 	if ((certflags_flags & CERTOPT_NO_REQUIRE_USER_PRESENCE) != 0)
1727 		cert_ext_add("no-touch-required", NULL, 0);
1728 	/* order lexically by key */
1729 	if (ncert_ext > 0)
1730 		qsort(cert_ext, ncert_ext, sizeof(*cert_ext), cert_ext_cmp);
1731 }
1732 
1733 static struct sshkey *
1734 load_pkcs11_key(char *path)
1735 {
1736 #ifdef ENABLE_PKCS11
1737 	struct sshkey **keys = NULL, *public, *private = NULL;
1738 	int r, i, nkeys;
1739 
1740 	if ((r = sshkey_load_public(path, &public, NULL)) != 0)
1741 		fatal_r(r, "Couldn't load CA public key \"%s\"", path);
1742 
1743 	nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase,
1744 	    &keys, NULL);
1745 	debug3_f("%d keys", nkeys);
1746 	if (nkeys <= 0)
1747 		fatal("cannot read public key from pkcs11");
1748 	for (i = 0; i < nkeys; i++) {
1749 		if (sshkey_equal_public(public, keys[i])) {
1750 			private = keys[i];
1751 			continue;
1752 		}
1753 		sshkey_free(keys[i]);
1754 	}
1755 	free(keys);
1756 	sshkey_free(public);
1757 	return private;
1758 #else
1759 	fatal("no pkcs11 support");
1760 #endif /* ENABLE_PKCS11 */
1761 }
1762 
1763 /* Signer for sshkey_certify_custom that uses the agent */
1764 static int
1765 agent_signer(struct sshkey *key, u_char **sigp, size_t *lenp,
1766     const u_char *data, size_t datalen,
1767     const char *alg, const char *provider, const char *pin,
1768     u_int compat, void *ctx)
1769 {
1770 	int *agent_fdp = (int *)ctx;
1771 
1772 	return ssh_agent_sign(*agent_fdp, key, sigp, lenp,
1773 	    data, datalen, alg, compat);
1774 }
1775 
1776 __dead static void
1777 do_ca_sign(struct passwd *pw, const char *ca_key_path, int prefer_agent,
1778     unsigned long long cert_serial, int cert_serial_autoinc,
1779     int argc, char **argv)
1780 {
1781 	int r, i, found, agent_fd = -1;
1782 	u_int n;
1783 	struct sshkey *ca, *public;
1784 	char valid[64], *otmp, *tmp, *cp, *out, *comment;
1785 	char *ca_fp = NULL, **plist = NULL, *pin = NULL;
1786 	struct ssh_identitylist *agent_ids;
1787 	size_t j;
1788 	struct notifier_ctx *notifier = NULL;
1789 
1790 #ifdef ENABLE_PKCS11
1791 	pkcs11_init(1);
1792 #endif
1793 	tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
1794 	if (pkcs11provider != NULL) {
1795 		/* If a PKCS#11 token was specified then try to use it */
1796 		if ((ca = load_pkcs11_key(tmp)) == NULL)
1797 			fatal("No PKCS#11 key matching %s found", ca_key_path);
1798 	} else if (prefer_agent) {
1799 		/*
1800 		 * Agent signature requested. Try to use agent after making
1801 		 * sure the public key specified is actually present in the
1802 		 * agent.
1803 		 */
1804 		if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
1805 			fatal_r(r, "Cannot load CA public key %s", tmp);
1806 		if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
1807 			fatal_r(r, "Cannot use public key for CA signature");
1808 		if ((r = ssh_fetch_identitylist(agent_fd, &agent_ids)) != 0)
1809 			fatal_r(r, "Retrieve agent key list");
1810 		found = 0;
1811 		for (j = 0; j < agent_ids->nkeys; j++) {
1812 			if (sshkey_equal(ca, agent_ids->keys[j])) {
1813 				found = 1;
1814 				break;
1815 			}
1816 		}
1817 		if (!found)
1818 			fatal("CA key %s not found in agent", tmp);
1819 		ssh_free_identitylist(agent_ids);
1820 		ca->flags |= SSHKEY_FLAG_EXT;
1821 	} else {
1822 		/* CA key is assumed to be a private key on the filesystem */
1823 		ca = load_identity(tmp, NULL);
1824 		if (sshkey_is_sk(ca) &&
1825 		    (ca->sk_flags & SSH_SK_USER_VERIFICATION_REQD)) {
1826 			if ((pin = read_passphrase("Enter PIN for CA key: ",
1827 			    RP_ALLOW_STDIN)) == NULL)
1828 				fatal_f("couldn't read PIN");
1829 		}
1830 	}
1831 	free(tmp);
1832 
1833 	if (key_type_name != NULL) {
1834 		if (sshkey_type_from_shortname(key_type_name) != ca->type) {
1835 			fatal("CA key type %s doesn't match specified %s",
1836 			    sshkey_ssh_name(ca), key_type_name);
1837 		}
1838 	} else if (ca->type == KEY_RSA) {
1839 		/* Default to a good signature algorithm */
1840 		key_type_name = "rsa-sha2-512";
1841 	}
1842 	ca_fp = sshkey_fingerprint(ca, fingerprint_hash, SSH_FP_DEFAULT);
1843 
1844 	finalise_cert_exts();
1845 	for (i = 0; i < argc; i++) {
1846 		/* Split list of principals */
1847 		n = 0;
1848 		if (cert_principals != NULL) {
1849 			otmp = tmp = xstrdup(cert_principals);
1850 			plist = NULL;
1851 			for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1852 				plist = xreallocarray(plist, n + 1, sizeof(*plist));
1853 				if (*(plist[n] = xstrdup(cp)) == '\0')
1854 					fatal("Empty principal name");
1855 			}
1856 			free(otmp);
1857 		}
1858 		if (n > SSHKEY_CERT_MAX_PRINCIPALS)
1859 			fatal("Too many certificate principals specified");
1860 
1861 		tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1862 		if ((r = sshkey_load_public(tmp, &public, &comment)) != 0)
1863 			fatal_r(r, "load pubkey \"%s\"", tmp);
1864 		if (sshkey_is_cert(public))
1865 			fatal_f("key \"%s\" type %s cannot be certified",
1866 			    tmp, sshkey_type(public));
1867 
1868 		/* Prepare certificate to sign */
1869 		if ((r = sshkey_to_certified(public)) != 0)
1870 			fatal_r(r, "Could not upgrade key %s to certificate", tmp);
1871 		public->cert->type = cert_key_type;
1872 		public->cert->serial = (u_int64_t)cert_serial;
1873 		public->cert->key_id = xstrdup(cert_key_id);
1874 		public->cert->nprincipals = n;
1875 		public->cert->principals = plist;
1876 		public->cert->valid_after = cert_valid_from;
1877 		public->cert->valid_before = cert_valid_to;
1878 		prepare_options_buf(public->cert->critical, OPTIONS_CRITICAL);
1879 		prepare_options_buf(public->cert->extensions,
1880 		    OPTIONS_EXTENSIONS);
1881 		if ((r = sshkey_from_private(ca,
1882 		    &public->cert->signature_key)) != 0)
1883 			fatal_r(r, "sshkey_from_private (ca key)");
1884 
1885 		if (agent_fd != -1 && (ca->flags & SSHKEY_FLAG_EXT) != 0) {
1886 			if ((r = sshkey_certify_custom(public, ca,
1887 			    key_type_name, sk_provider, NULL, agent_signer,
1888 			    &agent_fd)) != 0)
1889 				fatal_r(r, "Couldn't certify %s via agent", tmp);
1890 		} else {
1891 			if (sshkey_is_sk(ca) &&
1892 			    (ca->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
1893 				notifier = notify_start(0,
1894 				    "Confirm user presence for key %s %s",
1895 				    sshkey_type(ca), ca_fp);
1896 			}
1897 			r = sshkey_certify(public, ca, key_type_name,
1898 			    sk_provider, pin);
1899 			notify_complete(notifier, "User presence confirmed");
1900 			if (r != 0)
1901 				fatal_r(r, "Couldn't certify key %s", tmp);
1902 		}
1903 
1904 		if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
1905 			*cp = '\0';
1906 		xasprintf(&out, "%s-cert.pub", tmp);
1907 		free(tmp);
1908 
1909 		if ((r = sshkey_save_public(public, out, comment)) != 0) {
1910 			fatal_r(r, "Unable to save public key to %s",
1911 			    identity_file);
1912 		}
1913 
1914 		if (!quiet) {
1915 			sshkey_format_cert_validity(public->cert,
1916 			    valid, sizeof(valid));
1917 			logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1918 			    "valid %s", sshkey_cert_type(public),
1919 			    out, public->cert->key_id,
1920 			    (unsigned long long)public->cert->serial,
1921 			    cert_principals != NULL ? " for " : "",
1922 			    cert_principals != NULL ? cert_principals : "",
1923 			    valid);
1924 		}
1925 
1926 		sshkey_free(public);
1927 		free(out);
1928 		if (cert_serial_autoinc)
1929 			cert_serial++;
1930 	}
1931 	if (pin != NULL)
1932 		freezero(pin, strlen(pin));
1933 	free(ca_fp);
1934 #ifdef ENABLE_PKCS11
1935 	pkcs11_terminate();
1936 #endif
1937 	exit(0);
1938 }
1939 
1940 static u_int64_t
1941 parse_relative_time(const char *s, time_t now)
1942 {
1943 	int64_t mul, secs;
1944 
1945 	mul = *s == '-' ? -1 : 1;
1946 
1947 	if ((secs = convtime(s + 1)) == -1)
1948 		fatal("Invalid relative certificate time %s", s);
1949 	if (mul == -1 && secs > now)
1950 		fatal("Certificate time %s cannot be represented", s);
1951 	return now + (u_int64_t)(secs * mul);
1952 }
1953 
1954 static void
1955 parse_hex_u64(const char *s, uint64_t *up)
1956 {
1957 	char *ep;
1958 	unsigned long long ull;
1959 
1960 	errno = 0;
1961 	ull = strtoull(s, &ep, 16);
1962 	if (*s == '\0' || *ep != '\0')
1963 		fatal("Invalid certificate time: not a number");
1964 	if (errno == ERANGE && ull == ULONG_MAX)
1965 		fatal_fr(SSH_ERR_SYSTEM_ERROR, "Invalid certificate time");
1966 	*up = (uint64_t)ull;
1967 }
1968 
1969 static void
1970 parse_cert_times(char *timespec)
1971 {
1972 	char *from, *to;
1973 	time_t now = time(NULL);
1974 	int64_t secs;
1975 
1976 	/* +timespec relative to now */
1977 	if (*timespec == '+' && strchr(timespec, ':') == NULL) {
1978 		if ((secs = convtime(timespec + 1)) == -1)
1979 			fatal("Invalid relative certificate life %s", timespec);
1980 		cert_valid_to = now + secs;
1981 		/*
1982 		 * Backdate certificate one minute to avoid problems on hosts
1983 		 * with poorly-synchronised clocks.
1984 		 */
1985 		cert_valid_from = ((now - 59)/ 60) * 60;
1986 		return;
1987 	}
1988 
1989 	/*
1990 	 * from:to, where
1991 	 * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | 0x... | "always"
1992 	 *   to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | 0x... | "forever"
1993 	 */
1994 	from = xstrdup(timespec);
1995 	to = strchr(from, ':');
1996 	if (to == NULL || from == to || *(to + 1) == '\0')
1997 		fatal("Invalid certificate life specification %s", timespec);
1998 	*to++ = '\0';
1999 
2000 	if (*from == '-' || *from == '+')
2001 		cert_valid_from = parse_relative_time(from, now);
2002 	else if (strcmp(from, "always") == 0)
2003 		cert_valid_from = 0;
2004 	else if (strncmp(from, "0x", 2) == 0)
2005 		parse_hex_u64(from, &cert_valid_from);
2006 	else if (parse_absolute_time(from, &cert_valid_from) != 0)
2007 		fatal("Invalid from time \"%s\"", from);
2008 
2009 	if (*to == '-' || *to == '+')
2010 		cert_valid_to = parse_relative_time(to, now);
2011 	else if (strcmp(to, "forever") == 0)
2012 		cert_valid_to = ~(u_int64_t)0;
2013 	else if (strncmp(to, "0x", 2) == 0)
2014 		parse_hex_u64(to, &cert_valid_to);
2015 	else if (parse_absolute_time(to, &cert_valid_to) != 0)
2016 		fatal("Invalid to time \"%s\"", to);
2017 
2018 	if (cert_valid_to <= cert_valid_from)
2019 		fatal("Empty certificate validity interval");
2020 	free(from);
2021 }
2022 
2023 static void
2024 add_cert_option(char *opt)
2025 {
2026 	char *val, *cp;
2027 	int iscrit = 0;
2028 
2029 	if (strcasecmp(opt, "clear") == 0)
2030 		certflags_flags = 0;
2031 	else if (strcasecmp(opt, "no-x11-forwarding") == 0)
2032 		certflags_flags &= ~CERTOPT_X_FWD;
2033 	else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
2034 		certflags_flags |= CERTOPT_X_FWD;
2035 	else if (strcasecmp(opt, "no-agent-forwarding") == 0)
2036 		certflags_flags &= ~CERTOPT_AGENT_FWD;
2037 	else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
2038 		certflags_flags |= CERTOPT_AGENT_FWD;
2039 	else if (strcasecmp(opt, "no-port-forwarding") == 0)
2040 		certflags_flags &= ~CERTOPT_PORT_FWD;
2041 	else if (strcasecmp(opt, "permit-port-forwarding") == 0)
2042 		certflags_flags |= CERTOPT_PORT_FWD;
2043 	else if (strcasecmp(opt, "no-pty") == 0)
2044 		certflags_flags &= ~CERTOPT_PTY;
2045 	else if (strcasecmp(opt, "permit-pty") == 0)
2046 		certflags_flags |= CERTOPT_PTY;
2047 	else if (strcasecmp(opt, "no-user-rc") == 0)
2048 		certflags_flags &= ~CERTOPT_USER_RC;
2049 	else if (strcasecmp(opt, "permit-user-rc") == 0)
2050 		certflags_flags |= CERTOPT_USER_RC;
2051 	else if (strcasecmp(opt, "touch-required") == 0)
2052 		certflags_flags &= ~CERTOPT_NO_REQUIRE_USER_PRESENCE;
2053 	else if (strcasecmp(opt, "no-touch-required") == 0)
2054 		certflags_flags |= CERTOPT_NO_REQUIRE_USER_PRESENCE;
2055 	else if (strcasecmp(opt, "no-verify-required") == 0)
2056 		certflags_flags &= ~CERTOPT_REQUIRE_VERIFY;
2057 	else if (strcasecmp(opt, "verify-required") == 0)
2058 		certflags_flags |= CERTOPT_REQUIRE_VERIFY;
2059 	else if (strncasecmp(opt, "force-command=", 14) == 0) {
2060 		val = opt + 14;
2061 		if (*val == '\0')
2062 			fatal("Empty force-command option");
2063 		if (certflags_command != NULL)
2064 			fatal("force-command already specified");
2065 		certflags_command = xstrdup(val);
2066 	} else if (strncasecmp(opt, "source-address=", 15) == 0) {
2067 		val = opt + 15;
2068 		if (*val == '\0')
2069 			fatal("Empty source-address option");
2070 		if (certflags_src_addr != NULL)
2071 			fatal("source-address already specified");
2072 		if (addr_match_cidr_list(NULL, val) != 0)
2073 			fatal("Invalid source-address list");
2074 		certflags_src_addr = xstrdup(val);
2075 	} else if (strncasecmp(opt, "extension:", 10) == 0 ||
2076 		    (iscrit = (strncasecmp(opt, "critical:", 9) == 0))) {
2077 		val = xstrdup(strchr(opt, ':') + 1);
2078 		if ((cp = strchr(val, '=')) != NULL)
2079 			*cp++ = '\0';
2080 		cert_ext_add(val, cp, iscrit);
2081 		free(val);
2082 	} else
2083 		fatal("Unsupported certificate option \"%s\"", opt);
2084 }
2085 
2086 static void
2087 show_options(struct sshbuf *optbuf, int in_critical)
2088 {
2089 	char *name, *arg, *hex;
2090 	struct sshbuf *options, *option = NULL;
2091 	int r;
2092 
2093 	if ((options = sshbuf_fromb(optbuf)) == NULL)
2094 		fatal_f("sshbuf_fromb failed");
2095 	while (sshbuf_len(options) != 0) {
2096 		sshbuf_free(option);
2097 		option = NULL;
2098 		if ((r = sshbuf_get_cstring(options, &name, NULL)) != 0 ||
2099 		    (r = sshbuf_froms(options, &option)) != 0)
2100 			fatal_fr(r, "parse option");
2101 		printf("                %s", name);
2102 		if (!in_critical &&
2103 		    (strcmp(name, "permit-X11-forwarding") == 0 ||
2104 		    strcmp(name, "permit-agent-forwarding") == 0 ||
2105 		    strcmp(name, "permit-port-forwarding") == 0 ||
2106 		    strcmp(name, "permit-pty") == 0 ||
2107 		    strcmp(name, "permit-user-rc") == 0 ||
2108 		    strcmp(name, "no-touch-required") == 0)) {
2109 			printf("\n");
2110 		} else if (in_critical &&
2111 		    (strcmp(name, "force-command") == 0 ||
2112 		    strcmp(name, "source-address") == 0)) {
2113 			if ((r = sshbuf_get_cstring(option, &arg, NULL)) != 0)
2114 				fatal_fr(r, "parse critical");
2115 			printf(" %s\n", arg);
2116 			free(arg);
2117 		} else if (in_critical &&
2118 		    strcmp(name, "verify-required") == 0) {
2119 			printf("\n");
2120 		} else if (sshbuf_len(option) > 0) {
2121 			hex = sshbuf_dtob16(option);
2122 			printf(" UNKNOWN OPTION: %s (len %zu)\n",
2123 			    hex, sshbuf_len(option));
2124 			sshbuf_reset(option);
2125 			free(hex);
2126 		} else
2127 			printf(" UNKNOWN FLAG OPTION\n");
2128 		free(name);
2129 		if (sshbuf_len(option) != 0)
2130 			fatal("Option corrupt: extra data at end");
2131 	}
2132 	sshbuf_free(option);
2133 	sshbuf_free(options);
2134 }
2135 
2136 static void
2137 print_cert(struct sshkey *key)
2138 {
2139 	char valid[64], *key_fp, *ca_fp;
2140 	u_int i;
2141 
2142 	key_fp = sshkey_fingerprint(key, fingerprint_hash, SSH_FP_DEFAULT);
2143 	ca_fp = sshkey_fingerprint(key->cert->signature_key,
2144 	    fingerprint_hash, SSH_FP_DEFAULT);
2145 	if (key_fp == NULL || ca_fp == NULL)
2146 		fatal_f("sshkey_fingerprint fail");
2147 	sshkey_format_cert_validity(key->cert, valid, sizeof(valid));
2148 
2149 	printf("        Type: %s %s certificate\n", sshkey_ssh_name(key),
2150 	    sshkey_cert_type(key));
2151 	printf("        Public key: %s %s\n", sshkey_type(key), key_fp);
2152 	printf("        Signing CA: %s %s (using %s)\n",
2153 	    sshkey_type(key->cert->signature_key), ca_fp,
2154 	    key->cert->signature_type);
2155 	printf("        Key ID: \"%s\"\n", key->cert->key_id);
2156 	printf("        Serial: %llu\n", (unsigned long long)key->cert->serial);
2157 	printf("        Valid: %s\n", valid);
2158 	printf("        Principals: ");
2159 	if (key->cert->nprincipals == 0)
2160 		printf("(none)\n");
2161 	else {
2162 		for (i = 0; i < key->cert->nprincipals; i++)
2163 			printf("\n                %s",
2164 			    key->cert->principals[i]);
2165 		printf("\n");
2166 	}
2167 	printf("        Critical Options: ");
2168 	if (sshbuf_len(key->cert->critical) == 0)
2169 		printf("(none)\n");
2170 	else {
2171 		printf("\n");
2172 		show_options(key->cert->critical, 1);
2173 	}
2174 	printf("        Extensions: ");
2175 	if (sshbuf_len(key->cert->extensions) == 0)
2176 		printf("(none)\n");
2177 	else {
2178 		printf("\n");
2179 		show_options(key->cert->extensions, 0);
2180 	}
2181 }
2182 
2183 __dead static void
2184 do_show_cert(struct passwd *pw)
2185 {
2186 	struct sshkey *key = NULL;
2187 	struct stat st;
2188 	int r, is_stdin = 0, ok = 0;
2189 	FILE *f;
2190 	char *cp, *line = NULL;
2191 	const char *path;
2192 	size_t linesize = 0;
2193 	u_long lnum = 0;
2194 
2195 	if (!have_identity)
2196 		ask_filename(pw, "Enter file in which the key is");
2197 	if (strcmp(identity_file, "-") != 0 && stat(identity_file, &st) == -1)
2198 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
2199 
2200 	path = identity_file;
2201 	if (strcmp(path, "-") == 0) {
2202 		f = stdin;
2203 		path = "(stdin)";
2204 		is_stdin = 1;
2205 	} else if ((f = fopen(identity_file, "r")) == NULL)
2206 		fatal("fopen %s: %s", identity_file, strerror(errno));
2207 
2208 	while (getline(&line, &linesize, f) != -1) {
2209 		lnum++;
2210 		sshkey_free(key);
2211 		key = NULL;
2212 		/* Trim leading space and comments */
2213 		cp = line + strspn(line, " \t");
2214 		if (*cp == '#' || *cp == '\0')
2215 			continue;
2216 		if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2217 			fatal("sshkey_new");
2218 		if ((r = sshkey_read(key, &cp)) != 0) {
2219 			error_r(r, "%s:%lu: invalid key", path, lnum);
2220 			continue;
2221 		}
2222 		if (!sshkey_is_cert(key)) {
2223 			error("%s:%lu is not a certificate", path, lnum);
2224 			continue;
2225 		}
2226 		ok = 1;
2227 		if (!is_stdin && lnum == 1)
2228 			printf("%s:\n", path);
2229 		else
2230 			printf("%s:%lu:\n", path, lnum);
2231 		print_cert(key);
2232 	}
2233 	free(line);
2234 	sshkey_free(key);
2235 	fclose(f);
2236 	exit(ok ? 0 : 1);
2237 }
2238 
2239 static void
2240 load_krl(const char *path, struct ssh_krl **krlp)
2241 {
2242 	struct sshbuf *krlbuf;
2243 	int r;
2244 
2245 	if ((r = sshbuf_load_file(path, &krlbuf)) != 0)
2246 		fatal_r(r, "Unable to load KRL %s", path);
2247 	/* XXX check sigs */
2248 	if ((r = ssh_krl_from_blob(krlbuf, krlp)) != 0 ||
2249 	    *krlp == NULL)
2250 		fatal_r(r, "Invalid KRL file %s", path);
2251 	sshbuf_free(krlbuf);
2252 }
2253 
2254 static void
2255 hash_to_blob(const char *cp, u_char **blobp, size_t *lenp,
2256     const char *file, u_long lnum)
2257 {
2258 	char *tmp;
2259 	size_t tlen;
2260 	struct sshbuf *b;
2261 	int r;
2262 
2263 	if (strncmp(cp, "SHA256:", 7) != 0)
2264 		fatal("%s:%lu: unsupported hash algorithm", file, lnum);
2265 	cp += 7;
2266 
2267 	/*
2268 	 * OpenSSH base64 hashes omit trailing '='
2269 	 * characters; put them back for decode.
2270 	 */
2271 	if ((tlen = strlen(cp)) >= SIZE_MAX - 5)
2272 		fatal_f("hash too long: %zu bytes", tlen);
2273 	tmp = xmalloc(tlen + 4 + 1);
2274 	strlcpy(tmp, cp, tlen + 1);
2275 	while ((tlen % 4) != 0) {
2276 		tmp[tlen++] = '=';
2277 		tmp[tlen] = '\0';
2278 	}
2279 	if ((b = sshbuf_new()) == NULL)
2280 		fatal_f("sshbuf_new failed");
2281 	if ((r = sshbuf_b64tod(b, tmp)) != 0)
2282 		fatal_r(r, "%s:%lu: decode hash failed", file, lnum);
2283 	free(tmp);
2284 	*lenp = sshbuf_len(b);
2285 	*blobp = xmalloc(*lenp);
2286 	memcpy(*blobp, sshbuf_ptr(b), *lenp);
2287 	sshbuf_free(b);
2288 }
2289 
2290 static void
2291 update_krl_from_file(struct passwd *pw, const char *file, int wild_ca,
2292     const struct sshkey *ca, struct ssh_krl *krl)
2293 {
2294 	struct sshkey *key = NULL;
2295 	u_long lnum = 0;
2296 	char *path, *cp, *ep, *line = NULL;
2297 	u_char *blob = NULL;
2298 	size_t blen = 0, linesize = 0;
2299 	unsigned long long serial, serial2;
2300 	int i, was_explicit_key, was_sha1, was_sha256, was_hash, r;
2301 	FILE *krl_spec;
2302 
2303 	path = tilde_expand_filename(file, pw->pw_uid);
2304 	if (strcmp(path, "-") == 0) {
2305 		krl_spec = stdin;
2306 		free(path);
2307 		path = xstrdup("(standard input)");
2308 	} else if ((krl_spec = fopen(path, "r")) == NULL)
2309 		fatal("fopen %s: %s", path, strerror(errno));
2310 
2311 	if (!quiet)
2312 		printf("Revoking from %s\n", path);
2313 	while (getline(&line, &linesize, krl_spec) != -1) {
2314 		if (linesize >= INT_MAX) {
2315 			fatal_f("%s contains unparsable line, len=%zu",
2316 			    path, linesize);
2317 		}
2318 		lnum++;
2319 		was_explicit_key = was_sha1 = was_sha256 = was_hash = 0;
2320 		cp = line + strspn(line, " \t");
2321 		/* Trim trailing space, comments and strip \n */
2322 		for (i = 0, r = -1; cp[i] != '\0'; i++) {
2323 			if (cp[i] == '#' || cp[i] == '\n') {
2324 				cp[i] = '\0';
2325 				break;
2326 			}
2327 			if (cp[i] == ' ' || cp[i] == '\t') {
2328 				/* Remember the start of a span of whitespace */
2329 				if (r == -1)
2330 					r = i;
2331 			} else
2332 				r = -1;
2333 		}
2334 		if (r != -1)
2335 			cp[r] = '\0';
2336 		if (*cp == '\0')
2337 			continue;
2338 		if (strncasecmp(cp, "serial:", 7) == 0) {
2339 			if (ca == NULL && !wild_ca) {
2340 				fatal("revoking certificates by serial number "
2341 				    "requires specification of a CA key");
2342 			}
2343 			cp += 7;
2344 			cp = cp + strspn(cp, " \t");
2345 			errno = 0;
2346 			serial = strtoull(cp, &ep, 0);
2347 			if (*cp == '\0' || (*ep != '\0' && *ep != '-'))
2348 				fatal("%s:%lu: invalid serial \"%s\"",
2349 				    path, lnum, cp);
2350 			if (errno == ERANGE && serial == ULLONG_MAX)
2351 				fatal("%s:%lu: serial out of range",
2352 				    path, lnum);
2353 			serial2 = serial;
2354 			if (*ep == '-') {
2355 				cp = ep + 1;
2356 				errno = 0;
2357 				serial2 = strtoull(cp, &ep, 0);
2358 				if (*cp == '\0' || *ep != '\0')
2359 					fatal("%s:%lu: invalid serial \"%s\"",
2360 					    path, lnum, cp);
2361 				if (errno == ERANGE && serial2 == ULLONG_MAX)
2362 					fatal("%s:%lu: serial out of range",
2363 					    path, lnum);
2364 				if (serial2 <= serial)
2365 					fatal("%s:%lu: invalid serial range "
2366 					    "%llu:%llu", path, lnum,
2367 					    (unsigned long long)serial,
2368 					    (unsigned long long)serial2);
2369 			}
2370 			if (ssh_krl_revoke_cert_by_serial_range(krl,
2371 			    ca, serial, serial2) != 0) {
2372 				fatal_f("revoke serial failed");
2373 			}
2374 		} else if (strncasecmp(cp, "id:", 3) == 0) {
2375 			if (ca == NULL && !wild_ca) {
2376 				fatal("revoking certificates by key ID "
2377 				    "requires specification of a CA key");
2378 			}
2379 			cp += 3;
2380 			cp = cp + strspn(cp, " \t");
2381 			if (ssh_krl_revoke_cert_by_key_id(krl, ca, cp) != 0)
2382 				fatal_f("revoke key ID failed");
2383 		} else if (strncasecmp(cp, "hash:", 5) == 0) {
2384 			cp += 5;
2385 			cp = cp + strspn(cp, " \t");
2386 			hash_to_blob(cp, &blob, &blen, file, lnum);
2387 			r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2388 			if (r != 0)
2389 				fatal_fr(r, "revoke key failed");
2390 		} else {
2391 			if (strncasecmp(cp, "key:", 4) == 0) {
2392 				cp += 4;
2393 				cp = cp + strspn(cp, " \t");
2394 				was_explicit_key = 1;
2395 			} else if (strncasecmp(cp, "sha1:", 5) == 0) {
2396 				cp += 5;
2397 				cp = cp + strspn(cp, " \t");
2398 				was_sha1 = 1;
2399 			} else if (strncasecmp(cp, "sha256:", 7) == 0) {
2400 				cp += 7;
2401 				cp = cp + strspn(cp, " \t");
2402 				was_sha256 = 1;
2403 				/*
2404 				 * Just try to process the line as a key.
2405 				 * Parsing will fail if it isn't.
2406 				 */
2407 			}
2408 			if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2409 				fatal("sshkey_new");
2410 			if ((r = sshkey_read(key, &cp)) != 0)
2411 				fatal_r(r, "%s:%lu: invalid key", path, lnum);
2412 			if (was_explicit_key)
2413 				r = ssh_krl_revoke_key_explicit(krl, key);
2414 			else if (was_sha1) {
2415 				if (sshkey_fingerprint_raw(key,
2416 				    SSH_DIGEST_SHA1, &blob, &blen) != 0) {
2417 					fatal("%s:%lu: fingerprint failed",
2418 					    file, lnum);
2419 				}
2420 				r = ssh_krl_revoke_key_sha1(krl, blob, blen);
2421 			} else if (was_sha256) {
2422 				if (sshkey_fingerprint_raw(key,
2423 				    SSH_DIGEST_SHA256, &blob, &blen) != 0) {
2424 					fatal("%s:%lu: fingerprint failed",
2425 					    file, lnum);
2426 				}
2427 				r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2428 			} else
2429 				r = ssh_krl_revoke_key(krl, key);
2430 			if (r != 0)
2431 				fatal_fr(r, "revoke key failed");
2432 			freezero(blob, blen);
2433 			blob = NULL;
2434 			blen = 0;
2435 			sshkey_free(key);
2436 		}
2437 	}
2438 	if (strcmp(path, "-") != 0)
2439 		fclose(krl_spec);
2440 	free(line);
2441 	free(path);
2442 }
2443 
2444 static void
2445 do_gen_krl(struct passwd *pw, int updating, const char *ca_key_path,
2446     unsigned long long krl_version, const char *krl_comment,
2447     int argc, char **argv)
2448 {
2449 	struct ssh_krl *krl;
2450 	struct stat sb;
2451 	struct sshkey *ca = NULL;
2452 	int i, r, wild_ca = 0;
2453 	char *tmp;
2454 	struct sshbuf *kbuf;
2455 
2456 	if (*identity_file == '\0')
2457 		fatal("KRL generation requires an output file");
2458 	if (stat(identity_file, &sb) == -1) {
2459 		if (errno != ENOENT)
2460 			fatal("Cannot access KRL \"%s\": %s",
2461 			    identity_file, strerror(errno));
2462 		if (updating)
2463 			fatal("KRL \"%s\" does not exist", identity_file);
2464 	}
2465 	if (ca_key_path != NULL) {
2466 		if (strcasecmp(ca_key_path, "none") == 0)
2467 			wild_ca = 1;
2468 		else {
2469 			tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
2470 			if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
2471 				fatal_r(r, "Cannot load CA public key %s", tmp);
2472 			free(tmp);
2473 		}
2474 	}
2475 
2476 	if (updating)
2477 		load_krl(identity_file, &krl);
2478 	else if ((krl = ssh_krl_init()) == NULL)
2479 		fatal("couldn't create KRL");
2480 
2481 	if (krl_version != 0)
2482 		ssh_krl_set_version(krl, krl_version);
2483 	if (krl_comment != NULL)
2484 		ssh_krl_set_comment(krl, krl_comment);
2485 
2486 	for (i = 0; i < argc; i++)
2487 		update_krl_from_file(pw, argv[i], wild_ca, ca, krl);
2488 
2489 	if ((kbuf = sshbuf_new()) == NULL)
2490 		fatal("sshbuf_new failed");
2491 	if (ssh_krl_to_blob(krl, kbuf) != 0)
2492 		fatal("Couldn't generate KRL");
2493 	if ((r = sshbuf_write_file(identity_file, kbuf)) != 0)
2494 		fatal("write %s: %s", identity_file, strerror(errno));
2495 	sshbuf_free(kbuf);
2496 	ssh_krl_free(krl);
2497 	sshkey_free(ca);
2498 }
2499 
2500 __dead static void
2501 do_check_krl(struct passwd *pw, int print_krl, int argc, char **argv)
2502 {
2503 	int i, r, ret = 0;
2504 	char *comment;
2505 	struct ssh_krl *krl;
2506 	struct sshkey *k;
2507 
2508 	if (*identity_file == '\0')
2509 		fatal("KRL checking requires an input file");
2510 	load_krl(identity_file, &krl);
2511 	if (print_krl)
2512 		krl_dump(krl, stdout);
2513 	for (i = 0; i < argc; i++) {
2514 		if ((r = sshkey_load_public(argv[i], &k, &comment)) != 0)
2515 			fatal_r(r, "Cannot load public key %s", argv[i]);
2516 		r = ssh_krl_check_key(krl, k);
2517 		printf("%s%s%s%s: %s\n", argv[i],
2518 		    *comment ? " (" : "", comment, *comment ? ")" : "",
2519 		    r == 0 ? "ok" : "REVOKED");
2520 		if (r != 0)
2521 			ret = 1;
2522 		sshkey_free(k);
2523 		free(comment);
2524 	}
2525 	ssh_krl_free(krl);
2526 	exit(ret);
2527 }
2528 
2529 static struct sshkey *
2530 load_sign_key(const char *keypath, const struct sshkey *pubkey)
2531 {
2532 	size_t i, slen, plen = strlen(keypath);
2533 	char *privpath = xstrdup(keypath);
2534 	static const char * const suffixes[] = { "-cert.pub", ".pub", NULL };
2535 	struct sshkey *ret = NULL, *privkey = NULL;
2536 	int r, waspub = 0;
2537 	struct stat st;
2538 
2539 	/*
2540 	 * If passed a public key filename, then try to locate the corresponding
2541 	 * private key. This lets us specify certificates on the command-line
2542 	 * and have ssh-keygen find the appropriate private key.
2543 	 */
2544 	for (i = 0; suffixes[i]; i++) {
2545 		slen = strlen(suffixes[i]);
2546 		if (plen <= slen ||
2547 		    strcmp(privpath + plen - slen, suffixes[i]) != 0)
2548 			continue;
2549 		privpath[plen - slen] = '\0';
2550 		debug_f("%s looks like a public key, using private key "
2551 		    "path %s instead", keypath, privpath);
2552 		waspub = 1;
2553 	}
2554 	if (waspub && stat(privpath, &st) != 0 && errno == ENOENT)
2555 		fatal("No private key found for public key \"%s\"", keypath);
2556 	if ((r = sshkey_load_private(privpath, "", &privkey, NULL)) != 0 &&
2557 	    (r != SSH_ERR_KEY_WRONG_PASSPHRASE)) {
2558 		debug_fr(r, "load private key \"%s\"", privpath);
2559 		fatal("No private key found for \"%s\"", privpath);
2560 	} else if (privkey == NULL)
2561 		privkey = load_identity(privpath, NULL);
2562 
2563 	if (!sshkey_equal_public(pubkey, privkey)) {
2564 		error("Public key %s doesn't match private %s",
2565 		    keypath, privpath);
2566 		goto done;
2567 	}
2568 	if (sshkey_is_cert(pubkey) && !sshkey_is_cert(privkey)) {
2569 		/*
2570 		 * Graft the certificate onto the private key to make
2571 		 * it capable of signing.
2572 		 */
2573 		if ((r = sshkey_to_certified(privkey)) != 0) {
2574 			error_fr(r, "sshkey_to_certified");
2575 			goto done;
2576 		}
2577 		if ((r = sshkey_cert_copy(pubkey, privkey)) != 0) {
2578 			error_fr(r, "sshkey_cert_copy");
2579 			goto done;
2580 		}
2581 	}
2582 	/* success */
2583 	ret = privkey;
2584 	privkey = NULL;
2585  done:
2586 	sshkey_free(privkey);
2587 	free(privpath);
2588 	return ret;
2589 }
2590 
2591 static int
2592 sign_one(struct sshkey *signkey, const char *filename, int fd,
2593     const char *sig_namespace, const char *hashalg, sshsig_signer *signer,
2594     void *signer_ctx)
2595 {
2596 	struct sshbuf *sigbuf = NULL, *abuf = NULL;
2597 	int r = SSH_ERR_INTERNAL_ERROR, wfd = -1, oerrno;
2598 	char *wfile = NULL, *asig = NULL, *fp = NULL;
2599 	char *pin = NULL, *prompt = NULL;
2600 
2601 	if (!quiet) {
2602 		if (fd == STDIN_FILENO)
2603 			fprintf(stderr, "Signing data on standard input\n");
2604 		else
2605 			fprintf(stderr, "Signing file %s\n", filename);
2606 	}
2607 	if (signer == NULL && sshkey_is_sk(signkey)) {
2608 		if ((signkey->sk_flags & SSH_SK_USER_VERIFICATION_REQD)) {
2609 			xasprintf(&prompt, "Enter PIN for %s key: ",
2610 			    sshkey_type(signkey));
2611 			if ((pin = read_passphrase(prompt,
2612 			    RP_ALLOW_STDIN)) == NULL)
2613 				fatal_f("couldn't read PIN");
2614 		}
2615 		if ((signkey->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
2616 			if ((fp = sshkey_fingerprint(signkey, fingerprint_hash,
2617 			    SSH_FP_DEFAULT)) == NULL)
2618 				fatal_f("fingerprint failed");
2619 			fprintf(stderr, "Confirm user presence for key %s %s\n",
2620 			    sshkey_type(signkey), fp);
2621 			free(fp);
2622 		}
2623 	}
2624 	if ((r = sshsig_sign_fd(signkey, hashalg, sk_provider, pin,
2625 	    fd, sig_namespace, &sigbuf, signer, signer_ctx)) != 0) {
2626 		error_r(r, "Signing %s failed", filename);
2627 		goto out;
2628 	}
2629 	if ((r = sshsig_armor(sigbuf, &abuf)) != 0) {
2630 		error_fr(r, "sshsig_armor");
2631 		goto out;
2632 	}
2633 	if ((asig = sshbuf_dup_string(abuf)) == NULL) {
2634 		error_f("buffer error");
2635 		r = SSH_ERR_ALLOC_FAIL;
2636 		goto out;
2637 	}
2638 
2639 	if (fd == STDIN_FILENO) {
2640 		fputs(asig, stdout);
2641 		fflush(stdout);
2642 	} else {
2643 		xasprintf(&wfile, "%s.sig", filename);
2644 		if (confirm_overwrite(wfile)) {
2645 			if ((wfd = open(wfile, O_WRONLY|O_CREAT|O_TRUNC,
2646 			    0666)) == -1) {
2647 				oerrno = errno;
2648 				error("Cannot open %s: %s",
2649 				    wfile, strerror(errno));
2650 				errno = oerrno;
2651 				r = SSH_ERR_SYSTEM_ERROR;
2652 				goto out;
2653 			}
2654 			if (atomicio(vwrite, wfd, asig,
2655 			    strlen(asig)) != strlen(asig)) {
2656 				oerrno = errno;
2657 				error("Cannot write to %s: %s",
2658 				    wfile, strerror(errno));
2659 				errno = oerrno;
2660 				r = SSH_ERR_SYSTEM_ERROR;
2661 				goto out;
2662 			}
2663 			if (!quiet) {
2664 				fprintf(stderr, "Write signature to %s\n",
2665 				    wfile);
2666 			}
2667 		}
2668 	}
2669 	/* success */
2670 	r = 0;
2671  out:
2672 	free(wfile);
2673 	free(prompt);
2674 	free(asig);
2675 	if (pin != NULL)
2676 		freezero(pin, strlen(pin));
2677 	sshbuf_free(abuf);
2678 	sshbuf_free(sigbuf);
2679 	if (wfd != -1)
2680 		close(wfd);
2681 	return r;
2682 }
2683 
2684 static int
2685 sig_process_opts(char * const *opts, size_t nopts, char **hashalgp,
2686     uint64_t *verify_timep, int *print_pubkey)
2687 {
2688 	size_t i;
2689 	time_t now;
2690 
2691 	if (verify_timep != NULL)
2692 		*verify_timep = 0;
2693 	if (print_pubkey != NULL)
2694 		*print_pubkey = 0;
2695 	if (hashalgp != NULL)
2696 		*hashalgp = NULL;
2697 	for (i = 0; i < nopts; i++) {
2698 		if (hashalgp != NULL &&
2699 		    strncasecmp(opts[i], "hashalg=", 8) == 0) {
2700 			*hashalgp = xstrdup(opts[i] + 8);
2701 		} else if (verify_timep &&
2702 		    strncasecmp(opts[i], "verify-time=", 12) == 0) {
2703 			if (parse_absolute_time(opts[i] + 12,
2704 			    verify_timep) != 0 || *verify_timep == 0) {
2705 				error("Invalid \"verify-time\" option");
2706 				return SSH_ERR_INVALID_ARGUMENT;
2707 			}
2708 		} else if (print_pubkey &&
2709 		    strcasecmp(opts[i], "print-pubkey") == 0) {
2710 			*print_pubkey = 1;
2711 		} else {
2712 			error("Invalid option \"%s\"", opts[i]);
2713 			return SSH_ERR_INVALID_ARGUMENT;
2714 		}
2715 	}
2716 	if (verify_timep && *verify_timep == 0) {
2717 		if ((now = time(NULL)) < 0) {
2718 			error("Time is before epoch");
2719 			return SSH_ERR_INVALID_ARGUMENT;
2720 		}
2721 		*verify_timep = (uint64_t)now;
2722 	}
2723 	return 0;
2724 }
2725 
2726 
2727 static int
2728 sig_sign(const char *keypath, const char *sig_namespace, int require_agent,
2729     int argc, char **argv, char * const *opts, size_t nopts)
2730 {
2731 	int i, fd = -1, r, ret = -1;
2732 	int agent_fd = -1;
2733 	struct sshkey *pubkey = NULL, *privkey = NULL, *signkey = NULL;
2734 	sshsig_signer *signer = NULL;
2735 	char *hashalg = NULL;
2736 
2737 	/* Check file arguments. */
2738 	for (i = 0; i < argc; i++) {
2739 		if (strcmp(argv[i], "-") != 0)
2740 			continue;
2741 		if (i > 0 || argc > 1)
2742 			fatal("Cannot sign mix of paths and standard input");
2743 	}
2744 
2745 	if (sig_process_opts(opts, nopts, &hashalg, NULL, NULL) != 0)
2746 		goto done; /* error already logged */
2747 
2748 	if ((r = sshkey_load_public(keypath, &pubkey, NULL)) != 0) {
2749 		error_r(r, "Couldn't load public key %s", keypath);
2750 		goto done;
2751 	}
2752 
2753 	if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) {
2754 		if (require_agent)
2755 			fatal("Couldn't get agent socket");
2756 		debug_r(r, "Couldn't get agent socket");
2757 	} else {
2758 		if ((r = ssh_agent_has_key(agent_fd, pubkey)) == 0)
2759 			signer = agent_signer;
2760 		else {
2761 			if (require_agent)
2762 				fatal("Couldn't find key in agent");
2763 			debug_r(r, "Couldn't find key in agent");
2764 		}
2765 	}
2766 
2767 	if (signer == NULL) {
2768 		/* Not using agent - try to load private key */
2769 		if ((privkey = load_sign_key(keypath, pubkey)) == NULL)
2770 			goto done;
2771 		signkey = privkey;
2772 	} else {
2773 		/* Will use key in agent */
2774 		signkey = pubkey;
2775 	}
2776 
2777 	if (argc == 0) {
2778 		if ((r = sign_one(signkey, "(stdin)", STDIN_FILENO,
2779 		    sig_namespace, hashalg, signer, &agent_fd)) != 0)
2780 			goto done;
2781 	} else {
2782 		for (i = 0; i < argc; i++) {
2783 			if (strcmp(argv[i], "-") == 0)
2784 				fd = STDIN_FILENO;
2785 			else if ((fd = open(argv[i], O_RDONLY)) == -1) {
2786 				error("Cannot open %s for signing: %s",
2787 				    argv[i], strerror(errno));
2788 				goto done;
2789 			}
2790 			if ((r = sign_one(signkey, argv[i], fd, sig_namespace,
2791 			    hashalg, signer, &agent_fd)) != 0)
2792 				goto done;
2793 			if (fd != STDIN_FILENO)
2794 				close(fd);
2795 			fd = -1;
2796 		}
2797 	}
2798 
2799 	ret = 0;
2800 done:
2801 	if (fd != -1 && fd != STDIN_FILENO)
2802 		close(fd);
2803 	sshkey_free(pubkey);
2804 	sshkey_free(privkey);
2805 	free(hashalg);
2806 	return ret;
2807 }
2808 
2809 static int
2810 sig_verify(const char *signature, const char *sig_namespace,
2811     const char *principal, const char *allowed_keys, const char *revoked_keys,
2812     char * const *opts, size_t nopts)
2813 {
2814 	int r, ret = -1;
2815 	int print_pubkey = 0;
2816 	struct sshbuf *sigbuf = NULL, *abuf = NULL;
2817 	struct sshkey *sign_key = NULL;
2818 	char *fp = NULL;
2819 	struct sshkey_sig_details *sig_details = NULL;
2820 	uint64_t verify_time = 0;
2821 
2822 	if (sig_process_opts(opts, nopts, NULL, &verify_time,
2823 	    &print_pubkey) != 0)
2824 		goto done; /* error already logged */
2825 
2826 	memset(&sig_details, 0, sizeof(sig_details));
2827 	if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
2828 		error_r(r, "Couldn't read signature file");
2829 		goto done;
2830 	}
2831 
2832 	if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
2833 		error_fr(r, "sshsig_armor");
2834 		goto done;
2835 	}
2836 	if ((r = sshsig_verify_fd(sigbuf, STDIN_FILENO, sig_namespace,
2837 	    &sign_key, &sig_details)) != 0)
2838 		goto done; /* sshsig_verify() prints error */
2839 
2840 	if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
2841 	    SSH_FP_DEFAULT)) == NULL)
2842 		fatal_f("sshkey_fingerprint failed");
2843 	debug("Valid (unverified) signature from key %s", fp);
2844 	if (sig_details != NULL) {
2845 		debug2_f("signature details: counter = %u, flags = 0x%02x",
2846 		    sig_details->sk_counter, sig_details->sk_flags);
2847 	}
2848 	free(fp);
2849 	fp = NULL;
2850 
2851 	if (revoked_keys != NULL) {
2852 		if ((r = sshkey_check_revoked(sign_key, revoked_keys)) != 0) {
2853 			debug3_fr(r, "sshkey_check_revoked");
2854 			goto done;
2855 		}
2856 	}
2857 
2858 	if (allowed_keys != NULL && (r = sshsig_check_allowed_keys(allowed_keys,
2859 	    sign_key, principal, sig_namespace, verify_time)) != 0) {
2860 		debug3_fr(r, "sshsig_check_allowed_keys");
2861 		goto done;
2862 	}
2863 	/* success */
2864 	ret = 0;
2865 done:
2866 	if (!quiet) {
2867 		if (ret == 0) {
2868 			if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
2869 			    SSH_FP_DEFAULT)) == NULL)
2870 				fatal_f("sshkey_fingerprint failed");
2871 			if (principal == NULL) {
2872 				printf("Good \"%s\" signature with %s key %s\n",
2873 				    sig_namespace, sshkey_type(sign_key), fp);
2874 
2875 			} else {
2876 				printf("Good \"%s\" signature for %s with %s key %s\n",
2877 				    sig_namespace, principal,
2878 				    sshkey_type(sign_key), fp);
2879 			}
2880 		} else {
2881 			printf("Could not verify signature.\n");
2882 		}
2883 	}
2884 	/* Print the signature key if requested */
2885 	if (ret == 0 && print_pubkey && sign_key != NULL) {
2886 		if ((r = sshkey_write(sign_key, stdout)) == 0)
2887 			fputc('\n', stdout);
2888 		else {
2889 			error_r(r, "Could not print public key.\n");
2890 			ret = -1;
2891 		}
2892 	}
2893 	sshbuf_free(sigbuf);
2894 	sshbuf_free(abuf);
2895 	sshkey_free(sign_key);
2896 	sshkey_sig_details_free(sig_details);
2897 	free(fp);
2898 	return ret;
2899 }
2900 
2901 static int
2902 sig_find_principals(const char *signature, const char *allowed_keys,
2903     char * const *opts, size_t nopts)
2904 {
2905 	int r, ret = -1;
2906 	struct sshbuf *sigbuf = NULL, *abuf = NULL;
2907 	struct sshkey *sign_key = NULL;
2908 	char *principals = NULL, *cp, *tmp;
2909 	uint64_t verify_time = 0;
2910 
2911 	if (sig_process_opts(opts, nopts, NULL, &verify_time, NULL) != 0)
2912 		goto done; /* error already logged */
2913 
2914 	if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
2915 		error_r(r, "Couldn't read signature file");
2916 		goto done;
2917 	}
2918 	if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
2919 		error_fr(r, "sshsig_armor");
2920 		goto done;
2921 	}
2922 	if ((r = sshsig_get_pubkey(sigbuf, &sign_key)) != 0) {
2923 		error_fr(r, "sshsig_get_pubkey");
2924 		goto done;
2925 	}
2926 	if ((r = sshsig_find_principals(allowed_keys, sign_key,
2927 	    verify_time, &principals)) != 0) {
2928 		if (r != SSH_ERR_KEY_NOT_FOUND)
2929 			error_fr(r, "sshsig_find_principal");
2930 		goto done;
2931 	}
2932 	ret = 0;
2933 done:
2934 	if (ret == 0 ) {
2935 		/* Emit matching principals one per line */
2936 		tmp = principals;
2937 		while ((cp = strsep(&tmp, ",")) != NULL && *cp != '\0')
2938 			puts(cp);
2939 	} else {
2940 		fprintf(stderr, "No principal matched.\n");
2941 	}
2942 	sshbuf_free(sigbuf);
2943 	sshbuf_free(abuf);
2944 	sshkey_free(sign_key);
2945 	free(principals);
2946 	return ret;
2947 }
2948 
2949 static int
2950 sig_match_principals(const char *allowed_keys, char *principal,
2951 	char * const *opts, size_t nopts)
2952 {
2953 	int r;
2954 	char **principals = NULL;
2955 	size_t i, nprincipals = 0;
2956 
2957 	if ((r = sig_process_opts(opts, nopts, NULL, NULL, NULL)) != 0)
2958 		return r; /* error already logged */
2959 
2960 	if ((r = sshsig_match_principals(allowed_keys, principal,
2961 	    &principals, &nprincipals)) != 0) {
2962 		debug_f("match: %s", ssh_err(r));
2963 		fprintf(stderr, "No principal matched.\n");
2964 		return r;
2965 	}
2966 	for (i = 0; i < nprincipals; i++) {
2967 		printf("%s\n", principals[i]);
2968 		free(principals[i]);
2969 	}
2970 	free(principals);
2971 
2972 	return 0;
2973 }
2974 
2975 static void
2976 do_moduli_gen(const char *out_file, char **opts, size_t nopts)
2977 {
2978 #ifdef WITH_OPENSSL
2979 	/* Moduli generation/screening */
2980 	u_int32_t memory = 0;
2981 	BIGNUM *start = NULL;
2982 	int moduli_bits = 0;
2983 	FILE *out;
2984 	size_t i;
2985 	const char *errstr;
2986 
2987 	/* Parse options */
2988 	for (i = 0; i < nopts; i++) {
2989 		if (strncmp(opts[i], "memory=", 7) == 0) {
2990 			memory = (u_int32_t)strtonum(opts[i]+7, 1,
2991 			    UINT_MAX, &errstr);
2992 			if (errstr) {
2993 				fatal("Memory limit is %s: %s",
2994 				    errstr, opts[i]+7);
2995 			}
2996 		} else if (strncmp(opts[i], "start=", 6) == 0) {
2997 			/* XXX - also compare length against bits */
2998 			if (BN_hex2bn(&start, opts[i]+6) == 0)
2999 				fatal("Invalid start point.");
3000 		} else if (strncmp(opts[i], "bits=", 5) == 0) {
3001 			moduli_bits = (int)strtonum(opts[i]+5, 1,
3002 			    INT_MAX, &errstr);
3003 			if (errstr) {
3004 				fatal("Invalid number: %s (%s)",
3005 					opts[i]+12, errstr);
3006 			}
3007 		} else {
3008 			fatal("Option \"%s\" is unsupported for moduli "
3009 			    "generation", opts[i]);
3010 		}
3011 	}
3012 
3013 	if ((out = fopen(out_file, "w")) == NULL) {
3014 		fatal("Couldn't open modulus candidate file \"%s\": %s",
3015 		    out_file, strerror(errno));
3016 	}
3017 	setvbuf(out, NULL, _IOLBF, 0);
3018 
3019 	if (moduli_bits == 0)
3020 		moduli_bits = DEFAULT_BITS;
3021 	if (gen_candidates(out, memory, moduli_bits, start) != 0)
3022 		fatal("modulus candidate generation failed");
3023 #else /* WITH_OPENSSL */
3024 	fatal("Moduli generation is not supported");
3025 #endif /* WITH_OPENSSL */
3026 }
3027 
3028 static void
3029 do_moduli_screen(const char *out_file, char **opts, size_t nopts)
3030 {
3031 #ifdef WITH_OPENSSL
3032 	/* Moduli generation/screening */
3033 	char *checkpoint = NULL;
3034 	u_int32_t generator_wanted = 0;
3035 	unsigned long start_lineno = 0, lines_to_process = 0;
3036 	int prime_tests = 0;
3037 	FILE *out, *in = stdin;
3038 	size_t i;
3039 	const char *errstr;
3040 
3041 	/* Parse options */
3042 	for (i = 0; i < nopts; i++) {
3043 		if (strncmp(opts[i], "lines=", 6) == 0) {
3044 			lines_to_process = strtoul(opts[i]+6, NULL, 10);
3045 		} else if (strncmp(opts[i], "start-line=", 11) == 0) {
3046 			start_lineno = strtoul(opts[i]+11, NULL, 10);
3047 		} else if (strncmp(opts[i], "checkpoint=", 11) == 0) {
3048 			free(checkpoint);
3049 			checkpoint = xstrdup(opts[i]+11);
3050 		} else if (strncmp(opts[i], "generator=", 10) == 0) {
3051 			generator_wanted = (u_int32_t)strtonum(
3052 			    opts[i]+10, 1, UINT_MAX, &errstr);
3053 			if (errstr != NULL) {
3054 				fatal("Generator invalid: %s (%s)",
3055 				    opts[i]+10, errstr);
3056 			}
3057 		} else if (strncmp(opts[i], "prime-tests=", 12) == 0) {
3058 			prime_tests = (int)strtonum(opts[i]+12, 1,
3059 			    INT_MAX, &errstr);
3060 			if (errstr) {
3061 				fatal("Invalid number: %s (%s)",
3062 					opts[i]+12, errstr);
3063 			}
3064 		} else {
3065 			fatal("Option \"%s\" is unsupported for moduli "
3066 			    "screening", opts[i]);
3067 		}
3068 	}
3069 
3070 	if (have_identity && strcmp(identity_file, "-") != 0) {
3071 		if ((in = fopen(identity_file, "r")) == NULL) {
3072 			fatal("Couldn't open modulus candidate "
3073 			    "file \"%s\": %s", identity_file,
3074 			    strerror(errno));
3075 		}
3076 	}
3077 
3078 	if ((out = fopen(out_file, "a")) == NULL) {
3079 		fatal("Couldn't open moduli file \"%s\": %s",
3080 		    out_file, strerror(errno));
3081 	}
3082 	setvbuf(out, NULL, _IOLBF, 0);
3083 	if (prime_test(in, out, prime_tests == 0 ? 100 : prime_tests,
3084 	    generator_wanted, checkpoint,
3085 	    start_lineno, lines_to_process) != 0)
3086 		fatal("modulus screening failed");
3087 	if (in != stdin)
3088 		(void)fclose(in);
3089 	free(checkpoint);
3090 #else /* WITH_OPENSSL */
3091 	fatal("Moduli screening is not supported");
3092 #endif /* WITH_OPENSSL */
3093 }
3094 
3095 /* Read and confirm a passphrase */
3096 static char *
3097 read_check_passphrase(const char *prompt1, const char *prompt2,
3098     const char *retry_prompt)
3099 {
3100 	char *passphrase1, *passphrase2;
3101 
3102 	for (;;) {
3103 		passphrase1 = read_passphrase(prompt1, RP_ALLOW_STDIN);
3104 		passphrase2 = read_passphrase(prompt2, RP_ALLOW_STDIN);
3105 		if (strcmp(passphrase1, passphrase2) == 0) {
3106 			freezero(passphrase2, strlen(passphrase2));
3107 			return passphrase1;
3108 		}
3109 		/* The passphrases do not match. Clear them and retry. */
3110 		freezero(passphrase1, strlen(passphrase1));
3111 		freezero(passphrase2, strlen(passphrase2));
3112 		fputs(retry_prompt, stdout);
3113 		fputc('\n', stdout);
3114 		fflush(stdout);
3115 	}
3116 	/* NOTREACHED */
3117 	return NULL;
3118 }
3119 
3120 static char *
3121 private_key_passphrase(const char *path)
3122 {
3123 	char *prompt, *ret;
3124 
3125 	if (identity_passphrase)
3126 		return xstrdup(identity_passphrase);
3127 	if (identity_new_passphrase)
3128 		return xstrdup(identity_new_passphrase);
3129 
3130 	xasprintf(&prompt, "Enter passphrase for \"%s\" "
3131 	    "(empty for no passphrase): ", path);
3132 	ret = read_check_passphrase(prompt,
3133 	    "Enter same passphrase again: ",
3134 	    "Passphrases do not match.  Try again.");
3135 	free(prompt);
3136 	return ret;
3137 }
3138 
3139 static char *
3140 sk_suffix(const char *application, const uint8_t *user, size_t userlen)
3141 {
3142 	char *ret, *cp;
3143 	size_t slen, i;
3144 
3145 	/* Trim off URL-like preamble */
3146 	if (strncmp(application, "ssh://", 6) == 0)
3147 		ret =  xstrdup(application + 6);
3148 	else if (strncmp(application, "ssh:", 4) == 0)
3149 		ret =  xstrdup(application + 4);
3150 	else
3151 		ret = xstrdup(application);
3152 
3153 	/* Count trailing zeros in user */
3154 	for (i = 0; i < userlen; i++) {
3155 		if (user[userlen - i - 1] != 0)
3156 			break;
3157 	}
3158 	if (i >= userlen)
3159 		return ret; /* user-id was default all-zeros */
3160 
3161 	/* Append user-id, escaping non-UTF-8 characters */
3162 	slen = userlen - i;
3163 	if (asmprintf(&cp, INT_MAX, NULL, "%.*s", (int)slen, user) == -1)
3164 		fatal_f("asmprintf failed");
3165 	/* Don't emit a user-id that contains path or control characters */
3166 	if (strchr(cp, '/') != NULL || strstr(cp, "..") != NULL ||
3167 	    strchr(cp, '\\') != NULL) {
3168 		free(cp);
3169 		cp = tohex(user, slen);
3170 	}
3171 	xextendf(&ret, "_", "%s", cp);
3172 	free(cp);
3173 	return ret;
3174 }
3175 
3176 static int
3177 do_download_sk(const char *skprovider, const char *device)
3178 {
3179 	struct sshsk_resident_key **srks;
3180 	size_t nsrks, i;
3181 	int r, ret = -1;
3182 	char *fp, *pin = NULL, *pass = NULL, *path, *pubpath;
3183 	const char *ext;
3184 	struct sshkey *key;
3185 
3186 	if (skprovider == NULL)
3187 		fatal("Cannot download keys without provider");
3188 
3189 	pin = read_passphrase("Enter PIN for authenticator: ", RP_ALLOW_STDIN);
3190 	if (!quiet) {
3191 		printf("You may need to touch your authenticator "
3192 		    "to authorize key download.\n");
3193 	}
3194 	if ((r = sshsk_load_resident(skprovider, device, pin, 0,
3195 	    &srks, &nsrks)) != 0) {
3196 		if (pin != NULL)
3197 			freezero(pin, strlen(pin));
3198 		error_r(r, "Unable to load resident keys");
3199 		return -1;
3200 	}
3201 	if (nsrks == 0)
3202 		logit("No keys to download");
3203 	if (pin != NULL)
3204 		freezero(pin, strlen(pin));
3205 
3206 	for (i = 0; i < nsrks; i++) {
3207 		key = srks[i]->key;
3208 		if (key->type != KEY_ECDSA_SK && key->type != KEY_ED25519_SK) {
3209 			error("Unsupported key type %s (%d)",
3210 			    sshkey_type(key), key->type);
3211 			continue;
3212 		}
3213 		if ((fp = sshkey_fingerprint(key, fingerprint_hash,
3214 		    SSH_FP_DEFAULT)) == NULL)
3215 			fatal_f("sshkey_fingerprint failed");
3216 		debug_f("key %zu: %s %s %s (flags 0x%02x)", i,
3217 		    sshkey_type(key), fp, key->sk_application, key->sk_flags);
3218 		ext = sk_suffix(key->sk_application,
3219 		    srks[i]->user_id, srks[i]->user_id_len);
3220 		xasprintf(&path, "id_%s_rk%s%s",
3221 		    key->type == KEY_ECDSA_SK ? "ecdsa_sk" : "ed25519_sk",
3222 		    *ext == '\0' ? "" : "_", ext);
3223 
3224 		/* If the file already exists, ask the user to confirm. */
3225 		if (!confirm_overwrite(path)) {
3226 			free(path);
3227 			break;
3228 		}
3229 
3230 		/* Save the key with the application string as the comment */
3231 		if (pass == NULL)
3232 			pass = private_key_passphrase(path);
3233 		if ((r = sshkey_save_private(key, path, pass,
3234 		    key->sk_application, private_key_format,
3235 		    openssh_format_cipher, rounds)) != 0) {
3236 			error_r(r, "Saving key \"%s\" failed", path);
3237 			free(path);
3238 			break;
3239 		}
3240 		if (!quiet) {
3241 			printf("Saved %s key%s%s to %s\n", sshkey_type(key),
3242 			    *ext != '\0' ? " " : "",
3243 			    *ext != '\0' ? key->sk_application : "",
3244 			    path);
3245 		}
3246 
3247 		/* Save public key too */
3248 		xasprintf(&pubpath, "%s.pub", path);
3249 		free(path);
3250 		if ((r = sshkey_save_public(key, pubpath,
3251 		    key->sk_application)) != 0) {
3252 			error_r(r, "Saving public key \"%s\" failed", pubpath);
3253 			free(pubpath);
3254 			break;
3255 		}
3256 		free(pubpath);
3257 	}
3258 
3259 	if (i >= nsrks)
3260 		ret = 0; /* success */
3261 	if (pass != NULL)
3262 		freezero(pass, strlen(pass));
3263 	sshsk_free_resident_keys(srks, nsrks);
3264 	return ret;
3265 }
3266 
3267 static void
3268 save_attestation(struct sshbuf *attest, const char *path)
3269 {
3270 	mode_t omask;
3271 	int r;
3272 
3273 	if (path == NULL)
3274 		return; /* nothing to do */
3275 	if (attest == NULL || sshbuf_len(attest) == 0)
3276 		fatal("Enrollment did not return attestation data");
3277 	omask = umask(077);
3278 	r = sshbuf_write_file(path, attest);
3279 	umask(omask);
3280 	if (r != 0)
3281 		fatal_r(r, "Unable to write attestation data \"%s\"", path);
3282 	if (!quiet)
3283 		printf("Your FIDO attestation certificate has been saved in "
3284 		    "%s\n", path);
3285 }
3286 
3287 static int
3288 confirm_sk_overwrite(const char *application, const char *user)
3289 {
3290 	char yesno[3];
3291 
3292 	printf("A resident key scoped to '%s' with user id '%s' already "
3293 	    "exists.\n", application == NULL ? "ssh:" : application,
3294 	    user == NULL ? "null" : user);
3295 	printf("Overwrite key in token (y/n)? ");
3296 	fflush(stdout);
3297 	if (fgets(yesno, sizeof(yesno), stdin) == NULL)
3298 		return 0;
3299 	if (yesno[0] != 'y' && yesno[0] != 'Y')
3300 		return 0;
3301 	return 1;
3302 }
3303 
3304 __dead static void
3305 usage(void)
3306 {
3307 	fprintf(stderr,
3308 	    "usage: ssh-keygen [-q] [-a rounds] [-b bits] [-C comment] [-f output_keyfile]\n"
3309 	    "                  [-m format] [-N new_passphrase] [-O option]\n"
3310 	    "                  [-t dsa | ecdsa | ecdsa-sk | ed25519 | ed25519-sk | rsa]\n"
3311 	    "                  [-w provider] [-Z cipher]\n"
3312 	    "       ssh-keygen -p [-a rounds] [-f keyfile] [-m format] [-N new_passphrase]\n"
3313 	    "                   [-P old_passphrase] [-Z cipher]\n"
3314 #ifdef WITH_OPENSSL
3315 	    "       ssh-keygen -i [-f input_keyfile] [-m key_format]\n"
3316 	    "       ssh-keygen -e [-f input_keyfile] [-m key_format]\n"
3317 #endif
3318 	    "       ssh-keygen -y [-f input_keyfile]\n"
3319 	    "       ssh-keygen -c [-a rounds] [-C comment] [-f keyfile] [-P passphrase]\n"
3320 	    "       ssh-keygen -l [-v] [-E fingerprint_hash] [-f input_keyfile]\n"
3321 	    "       ssh-keygen -B [-f input_keyfile]\n");
3322 #ifdef ENABLE_PKCS11
3323 	fprintf(stderr,
3324 	    "       ssh-keygen -D pkcs11\n");
3325 #endif
3326 	fprintf(stderr,
3327 	    "       ssh-keygen -F hostname [-lv] [-f known_hosts_file]\n"
3328 	    "       ssh-keygen -H [-f known_hosts_file]\n"
3329 	    "       ssh-keygen -K [-a rounds] [-w provider]\n"
3330 	    "       ssh-keygen -R hostname [-f known_hosts_file]\n"
3331 	    "       ssh-keygen -r hostname [-g] [-f input_keyfile]\n"
3332 #ifdef WITH_OPENSSL
3333 	    "       ssh-keygen -M generate [-O option] output_file\n"
3334 	    "       ssh-keygen -M screen [-f input_file] [-O option] output_file\n"
3335 #endif
3336 	    "       ssh-keygen -I certificate_identity -s ca_key [-hU] [-D pkcs11_provider]\n"
3337 	    "                  [-n principals] [-O option] [-V validity_interval]\n"
3338 	    "                  [-z serial_number] file ...\n"
3339 	    "       ssh-keygen -L [-f input_keyfile]\n"
3340 	    "       ssh-keygen -A [-a rounds] [-f prefix_path]\n"
3341 	    "       ssh-keygen -k -f krl_file [-u] [-s ca_public] [-z version_number]\n"
3342 	    "                  file ...\n"
3343 	    "       ssh-keygen -Q [-l] -f krl_file [file ...]\n"
3344 	    "       ssh-keygen -Y find-principals -s signature_file -f allowed_signers_file\n"
3345 	    "       ssh-keygen -Y match-principals -I signer_identity -f allowed_signers_file\n"
3346 	    "       ssh-keygen -Y check-novalidate -n namespace -s signature_file\n"
3347 	    "       ssh-keygen -Y sign -f key_file -n namespace file [-O option] ...\n"
3348 	    "       ssh-keygen -Y verify -f allowed_signers_file -I signer_identity\n"
3349 	    "                  -n namespace -s signature_file [-r krl_file] [-O option]\n");
3350 	exit(1);
3351 }
3352 
3353 /*
3354  * Main program for key management.
3355  */
3356 int
3357 main(int argc, char **argv)
3358 {
3359 	char comment[1024], *passphrase = NULL;
3360 	char *rr_hostname = NULL, *ep, *fp, *ra;
3361 	struct sshkey *private, *public;
3362 	struct passwd *pw;
3363 	int r, opt, type;
3364 	int change_passphrase = 0, change_comment = 0, show_cert = 0;
3365 	int find_host = 0, delete_host = 0, hash_hosts = 0;
3366 	int gen_all_hostkeys = 0, gen_krl = 0, update_krl = 0, check_krl = 0;
3367 	int prefer_agent = 0, convert_to = 0, convert_from = 0;
3368 	int print_public = 0, print_generic = 0, cert_serial_autoinc = 0;
3369 	int do_gen_candidates = 0, do_screen_candidates = 0, download_sk = 0;
3370 	unsigned long long cert_serial = 0;
3371 	char *identity_comment = NULL, *ca_key_path = NULL, **opts = NULL;
3372 	char *sk_application = NULL, *sk_device = NULL, *sk_user = NULL;
3373 	char *sk_attestation_path = NULL;
3374 	struct sshbuf *challenge = NULL, *attest = NULL;
3375 	size_t i, nopts = 0;
3376 	u_int32_t bits = 0;
3377 	uint8_t sk_flags = SSH_SK_USER_PRESENCE_REQD;
3378 	const char *errstr;
3379 	int log_level = SYSLOG_LEVEL_INFO;
3380 	char *sign_op = NULL;
3381 
3382 	extern int optind;
3383 	extern char *optarg;
3384 
3385 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
3386 	sanitise_stdfd();
3387 
3388 #ifdef WITH_OPENSSL
3389 	OpenSSL_add_all_algorithms();
3390 #endif
3391 	log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
3392 
3393 	setlocale(LC_CTYPE, "");
3394 
3395 	/* we need this for the home * directory.  */
3396 	pw = getpwuid(getuid());
3397 	if (!pw)
3398 		fatal("No user exists for uid %lu", (u_long)getuid());
3399 	pw = pwcopy(pw);
3400 	if (gethostname(hostname, sizeof(hostname)) == -1)
3401 		fatal("gethostname: %s", strerror(errno));
3402 
3403 	sk_provider = getenv("SSH_SK_PROVIDER");
3404 
3405 	/* Remaining characters: dGjJSTWx */
3406 	while ((opt = getopt(argc, argv, "ABHKLQUXceghiklopquvy"
3407 	    "C:D:E:F:I:M:N:O:P:R:V:Y:Z:"
3408 	    "a:b:f:g:m:n:r:s:t:w:z:")) != -1) {
3409 		switch (opt) {
3410 		case 'A':
3411 			gen_all_hostkeys = 1;
3412 			break;
3413 		case 'b':
3414 			bits = (u_int32_t)strtonum(optarg, 1, UINT32_MAX,
3415 			    &errstr);
3416 			if (errstr)
3417 				fatal("Bits has bad value %s (%s)",
3418 					optarg, errstr);
3419 			break;
3420 		case 'E':
3421 			fingerprint_hash = ssh_digest_alg_by_name(optarg);
3422 			if (fingerprint_hash == -1)
3423 				fatal("Invalid hash algorithm \"%s\"", optarg);
3424 			break;
3425 		case 'F':
3426 			find_host = 1;
3427 			rr_hostname = optarg;
3428 			break;
3429 		case 'H':
3430 			hash_hosts = 1;
3431 			break;
3432 		case 'I':
3433 			cert_key_id = optarg;
3434 			break;
3435 		case 'R':
3436 			delete_host = 1;
3437 			rr_hostname = optarg;
3438 			break;
3439 		case 'L':
3440 			show_cert = 1;
3441 			break;
3442 		case 'l':
3443 			print_fingerprint = 1;
3444 			break;
3445 		case 'B':
3446 			print_bubblebabble = 1;
3447 			break;
3448 		case 'm':
3449 			if (strcasecmp(optarg, "RFC4716") == 0 ||
3450 			    strcasecmp(optarg, "ssh2") == 0) {
3451 				convert_format = FMT_RFC4716;
3452 				break;
3453 			}
3454 			if (strcasecmp(optarg, "PKCS8") == 0) {
3455 				convert_format = FMT_PKCS8;
3456 				private_key_format = SSHKEY_PRIVATE_PKCS8;
3457 				break;
3458 			}
3459 			if (strcasecmp(optarg, "PEM") == 0) {
3460 				convert_format = FMT_PEM;
3461 				private_key_format = SSHKEY_PRIVATE_PEM;
3462 				break;
3463 			}
3464 			fatal("Unsupported conversion format \"%s\"", optarg);
3465 		case 'n':
3466 			cert_principals = optarg;
3467 			break;
3468 		case 'o':
3469 			/* no-op; new format is already the default */
3470 			break;
3471 		case 'p':
3472 			change_passphrase = 1;
3473 			break;
3474 		case 'c':
3475 			change_comment = 1;
3476 			break;
3477 		case 'f':
3478 			if (strlcpy(identity_file, optarg,
3479 			    sizeof(identity_file)) >= sizeof(identity_file))
3480 				fatal("Identity filename too long");
3481 			have_identity = 1;
3482 			break;
3483 		case 'g':
3484 			print_generic = 1;
3485 			break;
3486 		case 'K':
3487 			download_sk = 1;
3488 			break;
3489 		case 'P':
3490 			identity_passphrase = optarg;
3491 			break;
3492 		case 'N':
3493 			identity_new_passphrase = optarg;
3494 			break;
3495 		case 'Q':
3496 			check_krl = 1;
3497 			break;
3498 		case 'O':
3499 			opts = xrecallocarray(opts, nopts, nopts + 1,
3500 			    sizeof(*opts));
3501 			opts[nopts++] = xstrdup(optarg);
3502 			break;
3503 		case 'Z':
3504 			openssh_format_cipher = optarg;
3505 			if (cipher_by_name(openssh_format_cipher) == NULL)
3506 				fatal("Invalid OpenSSH-format cipher '%s'",
3507 				    openssh_format_cipher);
3508 			break;
3509 		case 'C':
3510 			identity_comment = optarg;
3511 			break;
3512 		case 'q':
3513 			quiet = 1;
3514 			break;
3515 		case 'e':
3516 			/* export key */
3517 			convert_to = 1;
3518 			break;
3519 		case 'h':
3520 			cert_key_type = SSH2_CERT_TYPE_HOST;
3521 			certflags_flags = 0;
3522 			break;
3523 		case 'k':
3524 			gen_krl = 1;
3525 			break;
3526 		case 'i':
3527 		case 'X':
3528 			/* import key */
3529 			convert_from = 1;
3530 			break;
3531 		case 'y':
3532 			print_public = 1;
3533 			break;
3534 		case 's':
3535 			ca_key_path = optarg;
3536 			break;
3537 		case 't':
3538 			key_type_name = optarg;
3539 			break;
3540 		case 'D':
3541 			pkcs11provider = optarg;
3542 			break;
3543 		case 'U':
3544 			prefer_agent = 1;
3545 			break;
3546 		case 'u':
3547 			update_krl = 1;
3548 			break;
3549 		case 'v':
3550 			if (log_level == SYSLOG_LEVEL_INFO)
3551 				log_level = SYSLOG_LEVEL_DEBUG1;
3552 			else {
3553 				if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
3554 				    log_level < SYSLOG_LEVEL_DEBUG3)
3555 					log_level++;
3556 			}
3557 			break;
3558 		case 'r':
3559 			rr_hostname = optarg;
3560 			break;
3561 		case 'a':
3562 			rounds = (int)strtonum(optarg, 1, INT_MAX, &errstr);
3563 			if (errstr)
3564 				fatal("Invalid number: %s (%s)",
3565 					optarg, errstr);
3566 			break;
3567 		case 'V':
3568 			parse_cert_times(optarg);
3569 			break;
3570 		case 'Y':
3571 			sign_op = optarg;
3572 			break;
3573 		case 'w':
3574 			sk_provider = optarg;
3575 			break;
3576 		case 'z':
3577 			errno = 0;
3578 			if (*optarg == '+') {
3579 				cert_serial_autoinc = 1;
3580 				optarg++;
3581 			}
3582 			cert_serial = strtoull(optarg, &ep, 10);
3583 			if (*optarg < '0' || *optarg > '9' || *ep != '\0' ||
3584 			    (errno == ERANGE && cert_serial == ULLONG_MAX))
3585 				fatal("Invalid serial number \"%s\"", optarg);
3586 			break;
3587 		case 'M':
3588 			if (strcmp(optarg, "generate") == 0)
3589 				do_gen_candidates = 1;
3590 			else if (strcmp(optarg, "screen") == 0)
3591 				do_screen_candidates = 1;
3592 			else
3593 				fatal("Unsupported moduli option %s", optarg);
3594 			break;
3595 		default:
3596 			usage();
3597 		}
3598 	}
3599 
3600 	if (sk_provider == NULL)
3601 		sk_provider = "internal";
3602 
3603 	/* reinit */
3604 	log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
3605 
3606 	argv += optind;
3607 	argc -= optind;
3608 
3609 	if (sign_op != NULL) {
3610 		if (strncmp(sign_op, "find-principals", 15) == 0) {
3611 			if (ca_key_path == NULL) {
3612 				error("Too few arguments for find-principals:"
3613 				    "missing signature file");
3614 				exit(1);
3615 			}
3616 			if (!have_identity) {
3617 				error("Too few arguments for find-principals:"
3618 				    "missing allowed keys file");
3619 				exit(1);
3620 			}
3621 			return sig_find_principals(ca_key_path, identity_file,
3622 			    opts, nopts);
3623 		} else if (strncmp(sign_op, "match-principals", 16) == 0) {
3624 			if (!have_identity) {
3625 				error("Too few arguments for match-principals:"
3626 				    "missing allowed keys file");
3627 				exit(1);
3628 			}
3629 			if (cert_key_id == NULL) {
3630 				error("Too few arguments for match-principals: "
3631 				    "missing principal ID");
3632 				exit(1);
3633 			}
3634 			return sig_match_principals(identity_file, cert_key_id,
3635 			    opts, nopts);
3636 		} else if (strncmp(sign_op, "sign", 4) == 0) {
3637 			/* NB. cert_principals is actually namespace, via -n */
3638 			if (cert_principals == NULL ||
3639 			    *cert_principals == '\0') {
3640 				error("Too few arguments for sign: "
3641 				    "missing namespace");
3642 				exit(1);
3643 			}
3644 			if (!have_identity) {
3645 				error("Too few arguments for sign: "
3646 				    "missing key");
3647 				exit(1);
3648 			}
3649 			return sig_sign(identity_file, cert_principals,
3650 			    prefer_agent, argc, argv, opts, nopts);
3651 		} else if (strncmp(sign_op, "check-novalidate", 16) == 0) {
3652 			/* NB. cert_principals is actually namespace, via -n */
3653 			if (cert_principals == NULL ||
3654 			    *cert_principals == '\0') {
3655 				error("Too few arguments for check-novalidate: "
3656 				    "missing namespace");
3657 				exit(1);
3658 			}
3659 			if (ca_key_path == NULL) {
3660 				error("Too few arguments for check-novalidate: "
3661 				    "missing signature file");
3662 				exit(1);
3663 			}
3664 			return sig_verify(ca_key_path, cert_principals,
3665 			    NULL, NULL, NULL, opts, nopts);
3666 		} else if (strncmp(sign_op, "verify", 6) == 0) {
3667 			/* NB. cert_principals is actually namespace, via -n */
3668 			if (cert_principals == NULL ||
3669 			    *cert_principals == '\0') {
3670 				error("Too few arguments for verify: "
3671 				    "missing namespace");
3672 				exit(1);
3673 			}
3674 			if (ca_key_path == NULL) {
3675 				error("Too few arguments for verify: "
3676 				    "missing signature file");
3677 				exit(1);
3678 			}
3679 			if (!have_identity) {
3680 				error("Too few arguments for sign: "
3681 				    "missing allowed keys file");
3682 				exit(1);
3683 			}
3684 			if (cert_key_id == NULL) {
3685 				error("Too few arguments for verify: "
3686 				    "missing principal identity");
3687 				exit(1);
3688 			}
3689 			return sig_verify(ca_key_path, cert_principals,
3690 			    cert_key_id, identity_file, rr_hostname,
3691 			    opts, nopts);
3692 		}
3693 		error("Unsupported operation for -Y: \"%s\"", sign_op);
3694 		usage();
3695 		/* NOTREACHED */
3696 	}
3697 
3698 	if (ca_key_path != NULL) {
3699 		if (argc < 1 && !gen_krl) {
3700 			error("Too few arguments.");
3701 			usage();
3702 		}
3703 	} else if (argc > 0 && !gen_krl && !check_krl &&
3704 	    !do_gen_candidates && !do_screen_candidates) {
3705 		error("Too many arguments.");
3706 		usage();
3707 	}
3708 	if (change_passphrase && change_comment) {
3709 		error("Can only have one of -p and -c.");
3710 		usage();
3711 	}
3712 	if (print_fingerprint && (delete_host || hash_hosts)) {
3713 		error("Cannot use -l with -H or -R.");
3714 		usage();
3715 	}
3716 	if (gen_krl) {
3717 		do_gen_krl(pw, update_krl, ca_key_path,
3718 		    cert_serial, identity_comment, argc, argv);
3719 		return (0);
3720 	}
3721 	if (check_krl) {
3722 		do_check_krl(pw, print_fingerprint, argc, argv);
3723 		return (0);
3724 	}
3725 	if (ca_key_path != NULL) {
3726 		if (cert_key_id == NULL)
3727 			fatal("Must specify key id (-I) when certifying");
3728 		for (i = 0; i < nopts; i++)
3729 			add_cert_option(opts[i]);
3730 		do_ca_sign(pw, ca_key_path, prefer_agent,
3731 		    cert_serial, cert_serial_autoinc, argc, argv);
3732 	}
3733 	if (show_cert)
3734 		do_show_cert(pw);
3735 	if (delete_host || hash_hosts || find_host) {
3736 		do_known_hosts(pw, rr_hostname, find_host,
3737 		    delete_host, hash_hosts);
3738 	}
3739 	if (pkcs11provider != NULL)
3740 		do_download(pw);
3741 	if (download_sk) {
3742 		for (i = 0; i < nopts; i++) {
3743 			if (strncasecmp(opts[i], "device=", 7) == 0) {
3744 				sk_device = xstrdup(opts[i] + 7);
3745 			} else {
3746 				fatal("Option \"%s\" is unsupported for "
3747 				    "FIDO authenticator download", opts[i]);
3748 			}
3749 		}
3750 		return do_download_sk(sk_provider, sk_device);
3751 	}
3752 	if (print_fingerprint || print_bubblebabble)
3753 		do_fingerprint(pw);
3754 	if (change_passphrase)
3755 		do_change_passphrase(pw);
3756 	if (change_comment)
3757 		do_change_comment(pw, identity_comment);
3758 #ifdef WITH_OPENSSL
3759 	if (convert_to)
3760 		do_convert_to(pw);
3761 	if (convert_from)
3762 		do_convert_from(pw);
3763 #else /* WITH_OPENSSL */
3764 	if (convert_to || convert_from)
3765 		fatal("key conversion disabled at compile time");
3766 #endif /* WITH_OPENSSL */
3767 	if (print_public)
3768 		do_print_public(pw);
3769 	if (rr_hostname != NULL) {
3770 		unsigned int n = 0;
3771 
3772 		if (have_identity) {
3773 			n = do_print_resource_record(pw, identity_file,
3774 			    rr_hostname, print_generic, opts, nopts);
3775 			if (n == 0)
3776 				fatal("%s: %s", identity_file, strerror(errno));
3777 			exit(0);
3778 		} else {
3779 
3780 			n += do_print_resource_record(pw,
3781 			    _PATH_HOST_RSA_KEY_FILE, rr_hostname,
3782 			    print_generic, opts, nopts);
3783 #ifdef WITH_DSA
3784 			n += do_print_resource_record(pw,
3785 			    _PATH_HOST_DSA_KEY_FILE, rr_hostname,
3786 			    print_generic, opts, nopts);
3787 #endif
3788 			n += do_print_resource_record(pw,
3789 			    _PATH_HOST_ECDSA_KEY_FILE, rr_hostname,
3790 			    print_generic, opts, nopts);
3791 			n += do_print_resource_record(pw,
3792 			    _PATH_HOST_ED25519_KEY_FILE, rr_hostname,
3793 			    print_generic, opts, nopts);
3794 			n += do_print_resource_record(pw,
3795 			    _PATH_HOST_XMSS_KEY_FILE, rr_hostname,
3796 			    print_generic, opts, nopts);
3797 			if (n == 0)
3798 				fatal("no keys found.");
3799 			exit(0);
3800 		}
3801 	}
3802 
3803 	if (do_gen_candidates || do_screen_candidates) {
3804 		if (argc <= 0)
3805 			fatal("No output file specified");
3806 		else if (argc > 1)
3807 			fatal("Too many output files specified");
3808 	}
3809 	if (do_gen_candidates) {
3810 		do_moduli_gen(argv[0], opts, nopts);
3811 		return 0;
3812 	}
3813 	if (do_screen_candidates) {
3814 		do_moduli_screen(argv[0], opts, nopts);
3815 		return 0;
3816 	}
3817 
3818 	if (gen_all_hostkeys) {
3819 		do_gen_all_hostkeys(pw);
3820 		return (0);
3821 	}
3822 
3823 	if (key_type_name == NULL)
3824 		key_type_name = DEFAULT_KEY_TYPE_NAME;
3825 
3826 	type = sshkey_type_from_shortname(key_type_name);
3827 	type_bits_valid(type, key_type_name, &bits);
3828 
3829 	if (!quiet)
3830 		printf("Generating public/private %s key pair.\n",
3831 		    key_type_name);
3832 	switch (type) {
3833 	case KEY_ECDSA_SK:
3834 	case KEY_ED25519_SK:
3835 		for (i = 0; i < nopts; i++) {
3836 			if (strcasecmp(opts[i], "no-touch-required") == 0) {
3837 				sk_flags &= ~SSH_SK_USER_PRESENCE_REQD;
3838 			} else if (strcasecmp(opts[i], "verify-required") == 0) {
3839 				sk_flags |= SSH_SK_USER_VERIFICATION_REQD;
3840 			} else if (strcasecmp(opts[i], "resident") == 0) {
3841 				sk_flags |= SSH_SK_RESIDENT_KEY;
3842 			} else if (strncasecmp(opts[i], "device=", 7) == 0) {
3843 				sk_device = xstrdup(opts[i] + 7);
3844 			} else if (strncasecmp(opts[i], "user=", 5) == 0) {
3845 				sk_user = xstrdup(opts[i] + 5);
3846 			} else if (strncasecmp(opts[i], "challenge=", 10) == 0) {
3847 				if ((r = sshbuf_load_file(opts[i] + 10,
3848 				    &challenge)) != 0) {
3849 					fatal_r(r, "Unable to load FIDO "
3850 					    "enrollment challenge \"%s\"",
3851 					    opts[i] + 10);
3852 				}
3853 			} else if (strncasecmp(opts[i],
3854 			    "write-attestation=", 18) == 0) {
3855 				sk_attestation_path = opts[i] + 18;
3856 			} else if (strncasecmp(opts[i],
3857 			    "application=", 12) == 0) {
3858 				sk_application = xstrdup(opts[i] + 12);
3859 				if (strncmp(sk_application, "ssh:", 4) != 0) {
3860 					fatal("FIDO application string must "
3861 					    "begin with \"ssh:\"");
3862 				}
3863 			} else {
3864 				fatal("Option \"%s\" is unsupported for "
3865 				    "FIDO authenticator enrollment", opts[i]);
3866 			}
3867 		}
3868 		if ((attest = sshbuf_new()) == NULL)
3869 			fatal("sshbuf_new failed");
3870 		r = 0;
3871 		for (i = 0 ;;) {
3872 			if (!quiet) {
3873 				printf("You may need to touch your "
3874 				    "authenticator%s to authorize key "
3875 				    "generation.\n",
3876 				    r == 0 ? "" : " again");
3877 			}
3878 			fflush(stdout);
3879 			r = sshsk_enroll(type, sk_provider, sk_device,
3880 			    sk_application == NULL ? "ssh:" : sk_application,
3881 			    sk_user, sk_flags, passphrase, challenge,
3882 			    &private, attest);
3883 			if (r == 0)
3884 				break;
3885 			if (r == SSH_ERR_KEY_BAD_PERMISSIONS &&
3886 			    (sk_flags & SSH_SK_RESIDENT_KEY) != 0 &&
3887 			    (sk_flags & SSH_SK_FORCE_OPERATION) == 0 &&
3888 			    confirm_sk_overwrite(sk_application, sk_user)) {
3889 				sk_flags |= SSH_SK_FORCE_OPERATION;
3890 				continue;
3891 			}
3892 			if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
3893 				fatal_r(r, "Key enrollment failed");
3894 			else if (passphrase != NULL) {
3895 				error("PIN incorrect");
3896 				freezero(passphrase, strlen(passphrase));
3897 				passphrase = NULL;
3898 			}
3899 			if (++i >= 3)
3900 				fatal("Too many incorrect PINs");
3901 			passphrase = read_passphrase("Enter PIN for "
3902 			    "authenticator: ", RP_ALLOW_STDIN);
3903 		}
3904 		if (passphrase != NULL) {
3905 			freezero(passphrase, strlen(passphrase));
3906 			passphrase = NULL;
3907 		}
3908 		break;
3909 	default:
3910 		if ((r = sshkey_generate(type, bits, &private)) != 0)
3911 			fatal("sshkey_generate failed");
3912 		break;
3913 	}
3914 	if ((r = sshkey_from_private(private, &public)) != 0)
3915 		fatal_r(r, "sshkey_from_private");
3916 
3917 	if (!have_identity)
3918 		ask_filename(pw, "Enter file in which to save the key");
3919 
3920 	/* Create ~/.ssh directory if it doesn't already exist. */
3921 	hostfile_create_user_ssh_dir(identity_file, !quiet);
3922 
3923 	/* If the file already exists, ask the user to confirm. */
3924 	if (!confirm_overwrite(identity_file))
3925 		exit(1);
3926 
3927 	/* Determine the passphrase for the private key */
3928 	passphrase = private_key_passphrase(identity_file);
3929 	if (identity_comment) {
3930 		strlcpy(comment, identity_comment, sizeof(comment));
3931 	} else {
3932 		/* Create default comment field for the passphrase. */
3933 		snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
3934 	}
3935 
3936 	/* Save the key with the given passphrase and comment. */
3937 	if ((r = sshkey_save_private(private, identity_file, passphrase,
3938 	    comment, private_key_format, openssh_format_cipher, rounds)) != 0) {
3939 		error_r(r, "Saving key \"%s\" failed", identity_file);
3940 		freezero(passphrase, strlen(passphrase));
3941 		exit(1);
3942 	}
3943 	freezero(passphrase, strlen(passphrase));
3944 	sshkey_free(private);
3945 
3946 	if (!quiet) {
3947 		printf("Your identification has been saved in %s\n",
3948 		    identity_file);
3949 	}
3950 
3951 	strlcat(identity_file, ".pub", sizeof(identity_file));
3952 	if ((r = sshkey_save_public(public, identity_file, comment)) != 0)
3953 		fatal_r(r, "Unable to save public key to %s", identity_file);
3954 
3955 	if (!quiet) {
3956 		fp = sshkey_fingerprint(public, fingerprint_hash,
3957 		    SSH_FP_DEFAULT);
3958 		ra = sshkey_fingerprint(public, fingerprint_hash,
3959 		    SSH_FP_RANDOMART);
3960 		if (fp == NULL || ra == NULL)
3961 			fatal("sshkey_fingerprint failed");
3962 		printf("Your public key has been saved in %s\n",
3963 		    identity_file);
3964 		printf("The key fingerprint is:\n");
3965 		printf("%s %s\n", fp, comment);
3966 		printf("The key's randomart image is:\n");
3967 		printf("%s\n", ra);
3968 		free(ra);
3969 		free(fp);
3970 	}
3971 
3972 	if (sk_attestation_path != NULL)
3973 		save_attestation(attest, sk_attestation_path);
3974 
3975 	sshbuf_free(attest);
3976 	sshkey_free(public);
3977 
3978 	exit(0);
3979 }
3980