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