xref: /openbsd-src/usr.bin/ssh/ssh-keygen.c (revision aa1fa3d4849d8c6172fb7a884e8fa612b2ab7385)
1 /* $OpenBSD: ssh-keygen.c,v 1.415 2020/08/03 02:53:51 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, 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 	sshkey_free(prv);
799 	if (comment != NULL && *comment != '\0')
800 		fprintf(stdout, " %s", comment);
801 	fprintf(stdout, "\n");
802 	free(comment);
803 	exit(0);
804 }
805 
806 static void
807 do_download(struct passwd *pw)
808 {
809 #ifdef ENABLE_PKCS11
810 	struct sshkey **keys = NULL;
811 	int i, nkeys;
812 	enum sshkey_fp_rep rep;
813 	int fptype;
814 	char *fp, *ra, **comments = NULL;
815 
816 	fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
817 	rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
818 
819 	pkcs11_init(1);
820 	nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys, &comments);
821 	if (nkeys <= 0)
822 		fatal("cannot read public key from pkcs11");
823 	for (i = 0; i < nkeys; i++) {
824 		if (print_fingerprint) {
825 			fp = sshkey_fingerprint(keys[i], fptype, rep);
826 			ra = sshkey_fingerprint(keys[i], fingerprint_hash,
827 			    SSH_FP_RANDOMART);
828 			if (fp == NULL || ra == NULL)
829 				fatal("%s: sshkey_fingerprint fail", __func__);
830 			printf("%u %s %s (PKCS11 key)\n", sshkey_size(keys[i]),
831 			    fp, sshkey_type(keys[i]));
832 			if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
833 				printf("%s\n", ra);
834 			free(ra);
835 			free(fp);
836 		} else {
837 			(void) sshkey_write(keys[i], stdout); /* XXX check */
838 			fprintf(stdout, "%s%s\n",
839 			    *(comments[i]) == '\0' ? "" : " ", comments[i]);
840 		}
841 		free(comments[i]);
842 		sshkey_free(keys[i]);
843 	}
844 	free(comments);
845 	free(keys);
846 	pkcs11_terminate();
847 	exit(0);
848 #else
849 	fatal("no pkcs11 support");
850 #endif /* ENABLE_PKCS11 */
851 }
852 
853 static struct sshkey *
854 try_read_key(char **cpp)
855 {
856 	struct sshkey *ret;
857 	int r;
858 
859 	if ((ret = sshkey_new(KEY_UNSPEC)) == NULL)
860 		fatal("sshkey_new failed");
861 	if ((r = sshkey_read(ret, cpp)) == 0)
862 		return ret;
863 	/* Not a key */
864 	sshkey_free(ret);
865 	return NULL;
866 }
867 
868 static void
869 fingerprint_one_key(const struct sshkey *public, const char *comment)
870 {
871 	char *fp = NULL, *ra = NULL;
872 	enum sshkey_fp_rep rep;
873 	int fptype;
874 
875 	fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
876 	rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
877 	fp = sshkey_fingerprint(public, fptype, rep);
878 	ra = sshkey_fingerprint(public, fingerprint_hash, SSH_FP_RANDOMART);
879 	if (fp == NULL || ra == NULL)
880 		fatal("%s: sshkey_fingerprint failed", __func__);
881 	mprintf("%u %s %s (%s)\n", sshkey_size(public), fp,
882 	    comment ? comment : "no comment", sshkey_type(public));
883 	if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
884 		printf("%s\n", ra);
885 	free(ra);
886 	free(fp);
887 }
888 
889 static void
890 fingerprint_private(const char *path)
891 {
892 	struct stat st;
893 	char *comment = NULL;
894 	struct sshkey *privkey = NULL, *pubkey = NULL;
895 	int r;
896 
897 	if (stat(identity_file, &st) == -1)
898 		fatal("%s: %s", path, strerror(errno));
899 	if ((r = sshkey_load_public(path, &pubkey, &comment)) != 0)
900 		debug("load public \"%s\": %s", path, ssh_err(r));
901 	if (pubkey == NULL || comment == NULL || *comment == '\0') {
902 		free(comment);
903 		if ((r = sshkey_load_private(path, NULL,
904 		    &privkey, &comment)) != 0)
905 			debug("load private \"%s\": %s", path, ssh_err(r));
906 	}
907 	if (pubkey == NULL && privkey == NULL)
908 		fatal("%s is not a key file.", path);
909 
910 	fingerprint_one_key(pubkey == NULL ? privkey : pubkey, comment);
911 	sshkey_free(pubkey);
912 	sshkey_free(privkey);
913 	free(comment);
914 }
915 
916 static void
917 do_fingerprint(struct passwd *pw)
918 {
919 	FILE *f;
920 	struct sshkey *public = NULL;
921 	char *comment = NULL, *cp, *ep, *line = NULL;
922 	size_t linesize = 0;
923 	int i, invalid = 1;
924 	const char *path;
925 	u_long lnum = 0;
926 
927 	if (!have_identity)
928 		ask_filename(pw, "Enter file in which the key is");
929 	path = identity_file;
930 
931 	if (strcmp(identity_file, "-") == 0) {
932 		f = stdin;
933 		path = "(stdin)";
934 	} else if ((f = fopen(path, "r")) == NULL)
935 		fatal("%s: %s: %s", __progname, path, strerror(errno));
936 
937 	while (getline(&line, &linesize, f) != -1) {
938 		lnum++;
939 		cp = line;
940 		cp[strcspn(cp, "\n")] = '\0';
941 		/* Trim leading space and comments */
942 		cp = line + strspn(line, " \t");
943 		if (*cp == '#' || *cp == '\0')
944 			continue;
945 
946 		/*
947 		 * Input may be plain keys, private keys, authorized_keys
948 		 * or known_hosts.
949 		 */
950 
951 		/*
952 		 * Try private keys first. Assume a key is private if
953 		 * "SSH PRIVATE KEY" appears on the first line and we're
954 		 * not reading from stdin (XXX support private keys on stdin).
955 		 */
956 		if (lnum == 1 && strcmp(identity_file, "-") != 0 &&
957 		    strstr(cp, "PRIVATE KEY") != NULL) {
958 			free(line);
959 			fclose(f);
960 			fingerprint_private(path);
961 			exit(0);
962 		}
963 
964 		/*
965 		 * If it's not a private key, then this must be prepared to
966 		 * accept a public key prefixed with a hostname or options.
967 		 * Try a bare key first, otherwise skip the leading stuff.
968 		 */
969 		if ((public = try_read_key(&cp)) == NULL) {
970 			i = strtol(cp, &ep, 10);
971 			if (i == 0 || ep == NULL ||
972 			    (*ep != ' ' && *ep != '\t')) {
973 				int quoted = 0;
974 
975 				comment = cp;
976 				for (; *cp && (quoted || (*cp != ' ' &&
977 				    *cp != '\t')); cp++) {
978 					if (*cp == '\\' && cp[1] == '"')
979 						cp++;	/* Skip both */
980 					else if (*cp == '"')
981 						quoted = !quoted;
982 				}
983 				if (!*cp)
984 					continue;
985 				*cp++ = '\0';
986 			}
987 		}
988 		/* Retry after parsing leading hostname/key options */
989 		if (public == NULL && (public = try_read_key(&cp)) == NULL) {
990 			debug("%s:%lu: not a public key", path, lnum);
991 			continue;
992 		}
993 
994 		/* Find trailing comment, if any */
995 		for (; *cp == ' ' || *cp == '\t'; cp++)
996 			;
997 		if (*cp != '\0' && *cp != '#')
998 			comment = cp;
999 
1000 		fingerprint_one_key(public, comment);
1001 		sshkey_free(public);
1002 		invalid = 0; /* One good key in the file is sufficient */
1003 	}
1004 	fclose(f);
1005 	free(line);
1006 
1007 	if (invalid)
1008 		fatal("%s is not a public key file.", path);
1009 	exit(0);
1010 }
1011 
1012 static void
1013 do_gen_all_hostkeys(struct passwd *pw)
1014 {
1015 	struct {
1016 		char *key_type;
1017 		char *key_type_display;
1018 		char *path;
1019 	} key_types[] = {
1020 #ifdef WITH_OPENSSL
1021 		{ "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE },
1022 		{ "dsa", "DSA", _PATH_HOST_DSA_KEY_FILE },
1023 		{ "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE },
1024 #endif /* WITH_OPENSSL */
1025 		{ "ed25519", "ED25519",_PATH_HOST_ED25519_KEY_FILE },
1026 #ifdef WITH_XMSS
1027 		{ "xmss", "XMSS",_PATH_HOST_XMSS_KEY_FILE },
1028 #endif /* WITH_XMSS */
1029 		{ NULL, NULL, NULL }
1030 	};
1031 
1032 	u_int32_t bits = 0;
1033 	int first = 0;
1034 	struct stat st;
1035 	struct sshkey *private, *public;
1036 	char comment[1024], *prv_tmp, *pub_tmp, *prv_file, *pub_file;
1037 	int i, type, fd, r;
1038 
1039 	for (i = 0; key_types[i].key_type; i++) {
1040 		public = private = NULL;
1041 		prv_tmp = pub_tmp = prv_file = pub_file = NULL;
1042 
1043 		xasprintf(&prv_file, "%s%s",
1044 		    identity_file, key_types[i].path);
1045 
1046 		/* Check whether private key exists and is not zero-length */
1047 		if (stat(prv_file, &st) == 0) {
1048 			if (st.st_size != 0)
1049 				goto next;
1050 		} else if (errno != ENOENT) {
1051 			error("Could not stat %s: %s", key_types[i].path,
1052 			    strerror(errno));
1053 			goto failnext;
1054 		}
1055 
1056 		/*
1057 		 * Private key doesn't exist or is invalid; proceed with
1058 		 * key generation.
1059 		 */
1060 		xasprintf(&prv_tmp, "%s%s.XXXXXXXXXX",
1061 		    identity_file, key_types[i].path);
1062 		xasprintf(&pub_tmp, "%s%s.pub.XXXXXXXXXX",
1063 		    identity_file, key_types[i].path);
1064 		xasprintf(&pub_file, "%s%s.pub",
1065 		    identity_file, key_types[i].path);
1066 
1067 		if (first == 0) {
1068 			first = 1;
1069 			printf("%s: generating new host keys: ", __progname);
1070 		}
1071 		printf("%s ", key_types[i].key_type_display);
1072 		fflush(stdout);
1073 		type = sshkey_type_from_name(key_types[i].key_type);
1074 		if ((fd = mkstemp(prv_tmp)) == -1) {
1075 			error("Could not save your private key in %s: %s",
1076 			    prv_tmp, strerror(errno));
1077 			goto failnext;
1078 		}
1079 		(void)close(fd); /* just using mkstemp() to reserve a name */
1080 		bits = 0;
1081 		type_bits_valid(type, NULL, &bits);
1082 		if ((r = sshkey_generate(type, bits, &private)) != 0) {
1083 			error("sshkey_generate failed: %s", ssh_err(r));
1084 			goto failnext;
1085 		}
1086 		if ((r = sshkey_from_private(private, &public)) != 0)
1087 			fatal("sshkey_from_private failed: %s", ssh_err(r));
1088 		snprintf(comment, sizeof comment, "%s@%s", pw->pw_name,
1089 		    hostname);
1090 		if ((r = sshkey_save_private(private, prv_tmp, "",
1091 		    comment, private_key_format, openssh_format_cipher,
1092 		    rounds)) != 0) {
1093 			error("Saving key \"%s\" failed: %s",
1094 			    prv_tmp, ssh_err(r));
1095 			goto failnext;
1096 		}
1097 		if ((fd = mkstemp(pub_tmp)) == -1) {
1098 			error("Could not save your public key in %s: %s",
1099 			    pub_tmp, strerror(errno));
1100 			goto failnext;
1101 		}
1102 		(void)fchmod(fd, 0644);
1103 		(void)close(fd);
1104 		if ((r = sshkey_save_public(public, pub_tmp, comment)) != 0) {
1105 			fatal("Unable to save public key to %s: %s",
1106 			    identity_file, ssh_err(r));
1107 			goto failnext;
1108 		}
1109 
1110 		/* Rename temporary files to their permanent locations. */
1111 		if (rename(pub_tmp, pub_file) != 0) {
1112 			error("Unable to move %s into position: %s",
1113 			    pub_file, strerror(errno));
1114 			goto failnext;
1115 		}
1116 		if (rename(prv_tmp, prv_file) != 0) {
1117 			error("Unable to move %s into position: %s",
1118 			    key_types[i].path, strerror(errno));
1119  failnext:
1120 			first = 0;
1121 			goto next;
1122 		}
1123  next:
1124 		sshkey_free(private);
1125 		sshkey_free(public);
1126 		free(prv_tmp);
1127 		free(pub_tmp);
1128 		free(prv_file);
1129 		free(pub_file);
1130 	}
1131 	if (first != 0)
1132 		printf("\n");
1133 }
1134 
1135 struct known_hosts_ctx {
1136 	const char *host;	/* Hostname searched for in find/delete case */
1137 	FILE *out;		/* Output file, stdout for find_hosts case */
1138 	int has_unhashed;	/* When hashing, original had unhashed hosts */
1139 	int found_key;		/* For find/delete, host was found */
1140 	int invalid;		/* File contained invalid items; don't delete */
1141 	int hash_hosts;		/* Hash hostnames as we go */
1142 	int find_host;		/* Search for specific hostname */
1143 	int delete_host;	/* Delete host from known_hosts */
1144 };
1145 
1146 static int
1147 known_hosts_hash(struct hostkey_foreach_line *l, void *_ctx)
1148 {
1149 	struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1150 	char *hashed, *cp, *hosts, *ohosts;
1151 	int has_wild = l->hosts && strcspn(l->hosts, "*?!") != strlen(l->hosts);
1152 	int was_hashed = l->hosts && l->hosts[0] == HASH_DELIM;
1153 
1154 	switch (l->status) {
1155 	case HKF_STATUS_OK:
1156 	case HKF_STATUS_MATCHED:
1157 		/*
1158 		 * Don't hash hosts already already hashed, with wildcard
1159 		 * characters or a CA/revocation marker.
1160 		 */
1161 		if (was_hashed || has_wild || l->marker != MRK_NONE) {
1162 			fprintf(ctx->out, "%s\n", l->line);
1163 			if (has_wild && !ctx->find_host) {
1164 				logit("%s:%lu: ignoring host name "
1165 				    "with wildcard: %.64s", l->path,
1166 				    l->linenum, l->hosts);
1167 			}
1168 			return 0;
1169 		}
1170 		/*
1171 		 * Split any comma-separated hostnames from the host list,
1172 		 * hash and store separately.
1173 		 */
1174 		ohosts = hosts = xstrdup(l->hosts);
1175 		while ((cp = strsep(&hosts, ",")) != NULL && *cp != '\0') {
1176 			lowercase(cp);
1177 			if ((hashed = host_hash(cp, NULL, 0)) == NULL)
1178 				fatal("hash_host failed");
1179 			fprintf(ctx->out, "%s %s\n", hashed, l->rawkey);
1180 			ctx->has_unhashed = 1;
1181 		}
1182 		free(ohosts);
1183 		return 0;
1184 	case HKF_STATUS_INVALID:
1185 		/* Retain invalid lines, but mark file as invalid. */
1186 		ctx->invalid = 1;
1187 		logit("%s:%lu: invalid line", l->path, l->linenum);
1188 		/* FALLTHROUGH */
1189 	default:
1190 		fprintf(ctx->out, "%s\n", l->line);
1191 		return 0;
1192 	}
1193 	/* NOTREACHED */
1194 	return -1;
1195 }
1196 
1197 static int
1198 known_hosts_find_delete(struct hostkey_foreach_line *l, void *_ctx)
1199 {
1200 	struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1201 	enum sshkey_fp_rep rep;
1202 	int fptype;
1203 	char *fp = NULL, *ra = NULL;
1204 
1205 	fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
1206 	rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1207 
1208 	if (l->status == HKF_STATUS_MATCHED) {
1209 		if (ctx->delete_host) {
1210 			if (l->marker != MRK_NONE) {
1211 				/* Don't remove CA and revocation lines */
1212 				fprintf(ctx->out, "%s\n", l->line);
1213 			} else {
1214 				/*
1215 				 * Hostname matches and has no CA/revoke
1216 				 * marker, delete it by *not* writing the
1217 				 * line to ctx->out.
1218 				 */
1219 				ctx->found_key = 1;
1220 				if (!quiet)
1221 					printf("# Host %s found: line %lu\n",
1222 					    ctx->host, l->linenum);
1223 			}
1224 			return 0;
1225 		} else if (ctx->find_host) {
1226 			ctx->found_key = 1;
1227 			if (!quiet) {
1228 				printf("# Host %s found: line %lu %s\n",
1229 				    ctx->host,
1230 				    l->linenum, l->marker == MRK_CA ? "CA" :
1231 				    (l->marker == MRK_REVOKE ? "REVOKED" : ""));
1232 			}
1233 			if (ctx->hash_hosts)
1234 				known_hosts_hash(l, ctx);
1235 			else if (print_fingerprint) {
1236 				fp = sshkey_fingerprint(l->key, fptype, rep);
1237 				ra = sshkey_fingerprint(l->key,
1238 				    fingerprint_hash, SSH_FP_RANDOMART);
1239 				if (fp == NULL || ra == NULL)
1240 					fatal("%s: sshkey_fingerprint failed",
1241 					    __func__);
1242 				mprintf("%s %s %s%s%s\n", ctx->host,
1243 				    sshkey_type(l->key), fp,
1244 				    l->comment[0] ? " " : "",
1245 				    l->comment);
1246 				if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
1247 					printf("%s\n", ra);
1248 				free(ra);
1249 				free(fp);
1250 			} else
1251 				fprintf(ctx->out, "%s\n", l->line);
1252 			return 0;
1253 		}
1254 	} else if (ctx->delete_host) {
1255 		/* Retain non-matching hosts when deleting */
1256 		if (l->status == HKF_STATUS_INVALID) {
1257 			ctx->invalid = 1;
1258 			logit("%s:%lu: invalid line", l->path, l->linenum);
1259 		}
1260 		fprintf(ctx->out, "%s\n", l->line);
1261 	}
1262 	return 0;
1263 }
1264 
1265 static void
1266 do_known_hosts(struct passwd *pw, const char *name, int find_host,
1267     int delete_host, int hash_hosts)
1268 {
1269 	char *cp, tmp[PATH_MAX], old[PATH_MAX];
1270 	int r, fd, oerrno, inplace = 0;
1271 	struct known_hosts_ctx ctx;
1272 	u_int foreach_options;
1273 	struct stat sb;
1274 
1275 	if (!have_identity) {
1276 		cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
1277 		if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
1278 		    sizeof(identity_file))
1279 			fatal("Specified known hosts path too long");
1280 		free(cp);
1281 		have_identity = 1;
1282 	}
1283 	if (stat(identity_file, &sb) != 0)
1284 		fatal("Cannot stat %s: %s", identity_file, strerror(errno));
1285 
1286 	memset(&ctx, 0, sizeof(ctx));
1287 	ctx.out = stdout;
1288 	ctx.host = name;
1289 	ctx.hash_hosts = hash_hosts;
1290 	ctx.find_host = find_host;
1291 	ctx.delete_host = delete_host;
1292 
1293 	/*
1294 	 * Find hosts goes to stdout, hash and deletions happen in-place
1295 	 * A corner case is ssh-keygen -HF foo, which should go to stdout
1296 	 */
1297 	if (!find_host && (hash_hosts || delete_host)) {
1298 		if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
1299 		    strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
1300 		    strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
1301 		    strlcat(old, ".old", sizeof(old)) >= sizeof(old))
1302 			fatal("known_hosts path too long");
1303 		umask(077);
1304 		if ((fd = mkstemp(tmp)) == -1)
1305 			fatal("mkstemp: %s", strerror(errno));
1306 		if ((ctx.out = fdopen(fd, "w")) == NULL) {
1307 			oerrno = errno;
1308 			unlink(tmp);
1309 			fatal("fdopen: %s", strerror(oerrno));
1310 		}
1311 		fchmod(fd, sb.st_mode & 0644);
1312 		inplace = 1;
1313 	}
1314 	/* XXX support identity_file == "-" for stdin */
1315 	foreach_options = find_host ? HKF_WANT_MATCH : 0;
1316 	foreach_options |= print_fingerprint ? HKF_WANT_PARSE_KEY : 0;
1317 	if ((r = hostkeys_foreach(identity_file, (find_host || !hash_hosts) ?
1318 	    known_hosts_find_delete : known_hosts_hash, &ctx, name, NULL,
1319 	    foreach_options)) != 0) {
1320 		if (inplace)
1321 			unlink(tmp);
1322 		fatal("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
1323 	}
1324 
1325 	if (inplace)
1326 		fclose(ctx.out);
1327 
1328 	if (ctx.invalid) {
1329 		error("%s is not a valid known_hosts file.", identity_file);
1330 		if (inplace) {
1331 			error("Not replacing existing known_hosts "
1332 			    "file because of errors");
1333 			unlink(tmp);
1334 		}
1335 		exit(1);
1336 	} else if (delete_host && !ctx.found_key) {
1337 		logit("Host %s not found in %s", name, identity_file);
1338 		if (inplace)
1339 			unlink(tmp);
1340 	} else if (inplace) {
1341 		/* Backup existing file */
1342 		if (unlink(old) == -1 && errno != ENOENT)
1343 			fatal("unlink %.100s: %s", old, strerror(errno));
1344 		if (link(identity_file, old) == -1)
1345 			fatal("link %.100s to %.100s: %s", identity_file, old,
1346 			    strerror(errno));
1347 		/* Move new one into place */
1348 		if (rename(tmp, identity_file) == -1) {
1349 			error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
1350 			    strerror(errno));
1351 			unlink(tmp);
1352 			unlink(old);
1353 			exit(1);
1354 		}
1355 
1356 		printf("%s updated.\n", identity_file);
1357 		printf("Original contents retained as %s\n", old);
1358 		if (ctx.has_unhashed) {
1359 			logit("WARNING: %s contains unhashed entries", old);
1360 			logit("Delete this file to ensure privacy "
1361 			    "of hostnames");
1362 		}
1363 	}
1364 
1365 	exit (find_host && !ctx.found_key);
1366 }
1367 
1368 /*
1369  * Perform changing a passphrase.  The argument is the passwd structure
1370  * for the current user.
1371  */
1372 static void
1373 do_change_passphrase(struct passwd *pw)
1374 {
1375 	char *comment;
1376 	char *old_passphrase, *passphrase1, *passphrase2;
1377 	struct stat st;
1378 	struct sshkey *private;
1379 	int r;
1380 
1381 	if (!have_identity)
1382 		ask_filename(pw, "Enter file in which the key is");
1383 	if (stat(identity_file, &st) == -1)
1384 		fatal("%s: %s", identity_file, strerror(errno));
1385 	/* Try to load the file with empty passphrase. */
1386 	r = sshkey_load_private(identity_file, "", &private, &comment);
1387 	if (r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
1388 		if (identity_passphrase)
1389 			old_passphrase = xstrdup(identity_passphrase);
1390 		else
1391 			old_passphrase =
1392 			    read_passphrase("Enter old passphrase: ",
1393 			    RP_ALLOW_STDIN);
1394 		r = sshkey_load_private(identity_file, old_passphrase,
1395 		    &private, &comment);
1396 		freezero(old_passphrase, strlen(old_passphrase));
1397 		if (r != 0)
1398 			goto badkey;
1399 	} else if (r != 0) {
1400  badkey:
1401 		fatal("Failed to load key %s: %s", identity_file, ssh_err(r));
1402 	}
1403 	if (comment)
1404 		mprintf("Key has comment '%s'\n", comment);
1405 
1406 	/* Ask the new passphrase (twice). */
1407 	if (identity_new_passphrase) {
1408 		passphrase1 = xstrdup(identity_new_passphrase);
1409 		passphrase2 = NULL;
1410 	} else {
1411 		passphrase1 =
1412 			read_passphrase("Enter new passphrase (empty for no "
1413 			    "passphrase): ", RP_ALLOW_STDIN);
1414 		passphrase2 = read_passphrase("Enter same passphrase again: ",
1415 		    RP_ALLOW_STDIN);
1416 
1417 		/* Verify that they are the same. */
1418 		if (strcmp(passphrase1, passphrase2) != 0) {
1419 			explicit_bzero(passphrase1, strlen(passphrase1));
1420 			explicit_bzero(passphrase2, strlen(passphrase2));
1421 			free(passphrase1);
1422 			free(passphrase2);
1423 			printf("Pass phrases do not match.  Try again.\n");
1424 			exit(1);
1425 		}
1426 		/* Destroy the other copy. */
1427 		freezero(passphrase2, strlen(passphrase2));
1428 	}
1429 
1430 	/* Save the file using the new passphrase. */
1431 	if ((r = sshkey_save_private(private, identity_file, passphrase1,
1432 	    comment, private_key_format, openssh_format_cipher, rounds)) != 0) {
1433 		error("Saving key \"%s\" failed: %s.",
1434 		    identity_file, ssh_err(r));
1435 		freezero(passphrase1, strlen(passphrase1));
1436 		sshkey_free(private);
1437 		free(comment);
1438 		exit(1);
1439 	}
1440 	/* Destroy the passphrase and the copy of the key in memory. */
1441 	freezero(passphrase1, strlen(passphrase1));
1442 	sshkey_free(private);		 /* Destroys contents */
1443 	free(comment);
1444 
1445 	printf("Your identification has been saved with the new passphrase.\n");
1446 	exit(0);
1447 }
1448 
1449 /*
1450  * Print the SSHFP RR.
1451  */
1452 static int
1453 do_print_resource_record(struct passwd *pw, char *fname, char *hname,
1454     int print_generic)
1455 {
1456 	struct sshkey *public;
1457 	char *comment = NULL;
1458 	struct stat st;
1459 	int r;
1460 
1461 	if (fname == NULL)
1462 		fatal("%s: no filename", __func__);
1463 	if (stat(fname, &st) == -1) {
1464 		if (errno == ENOENT)
1465 			return 0;
1466 		fatal("%s: %s", fname, strerror(errno));
1467 	}
1468 	if ((r = sshkey_load_public(fname, &public, &comment)) != 0)
1469 		fatal("Failed to read v2 public key from \"%s\": %s.",
1470 		    fname, ssh_err(r));
1471 	export_dns_rr(hname, public, stdout, print_generic);
1472 	sshkey_free(public);
1473 	free(comment);
1474 	return 1;
1475 }
1476 
1477 /*
1478  * Change the comment of a private key file.
1479  */
1480 static void
1481 do_change_comment(struct passwd *pw, const char *identity_comment)
1482 {
1483 	char new_comment[1024], *comment, *passphrase;
1484 	struct sshkey *private;
1485 	struct sshkey *public;
1486 	struct stat st;
1487 	int r;
1488 
1489 	if (!have_identity)
1490 		ask_filename(pw, "Enter file in which the key is");
1491 	if (stat(identity_file, &st) == -1)
1492 		fatal("%s: %s", identity_file, strerror(errno));
1493 	if ((r = sshkey_load_private(identity_file, "",
1494 	    &private, &comment)) == 0)
1495 		passphrase = xstrdup("");
1496 	else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
1497 		fatal("Cannot load private key \"%s\": %s.",
1498 		    identity_file, ssh_err(r));
1499 	else {
1500 		if (identity_passphrase)
1501 			passphrase = xstrdup(identity_passphrase);
1502 		else if (identity_new_passphrase)
1503 			passphrase = xstrdup(identity_new_passphrase);
1504 		else
1505 			passphrase = read_passphrase("Enter passphrase: ",
1506 			    RP_ALLOW_STDIN);
1507 		/* Try to load using the passphrase. */
1508 		if ((r = sshkey_load_private(identity_file, passphrase,
1509 		    &private, &comment)) != 0) {
1510 			freezero(passphrase, strlen(passphrase));
1511 			fatal("Cannot load private key \"%s\": %s.",
1512 			    identity_file, ssh_err(r));
1513 		}
1514 	}
1515 
1516 	if (private->type != KEY_ED25519 && private->type != KEY_XMSS &&
1517 	    private_key_format != SSHKEY_PRIVATE_OPENSSH) {
1518 		error("Comments are only supported for keys stored in "
1519 		    "the new format (-o).");
1520 		explicit_bzero(passphrase, strlen(passphrase));
1521 		sshkey_free(private);
1522 		exit(1);
1523 	}
1524 	if (comment)
1525 		printf("Old comment: %s\n", comment);
1526 	else
1527 		printf("No existing comment\n");
1528 
1529 	if (identity_comment) {
1530 		strlcpy(new_comment, identity_comment, sizeof(new_comment));
1531 	} else {
1532 		printf("New comment: ");
1533 		fflush(stdout);
1534 		if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1535 			explicit_bzero(passphrase, strlen(passphrase));
1536 			sshkey_free(private);
1537 			exit(1);
1538 		}
1539 		new_comment[strcspn(new_comment, "\n")] = '\0';
1540 	}
1541 	if (comment != NULL && strcmp(comment, new_comment) == 0) {
1542 		printf("No change to comment\n");
1543 		free(passphrase);
1544 		sshkey_free(private);
1545 		free(comment);
1546 		exit(0);
1547 	}
1548 
1549 	/* Save the file using the new passphrase. */
1550 	if ((r = sshkey_save_private(private, identity_file, passphrase,
1551 	    new_comment, private_key_format, openssh_format_cipher,
1552 	    rounds)) != 0) {
1553 		error("Saving key \"%s\" failed: %s",
1554 		    identity_file, ssh_err(r));
1555 		freezero(passphrase, strlen(passphrase));
1556 		sshkey_free(private);
1557 		free(comment);
1558 		exit(1);
1559 	}
1560 	freezero(passphrase, strlen(passphrase));
1561 	if ((r = sshkey_from_private(private, &public)) != 0)
1562 		fatal("sshkey_from_private failed: %s", ssh_err(r));
1563 	sshkey_free(private);
1564 
1565 	strlcat(identity_file, ".pub", sizeof(identity_file));
1566 	if ((r = sshkey_save_public(public, identity_file, new_comment)) != 0) {
1567 		fatal("Unable to save public key to %s: %s",
1568 		    identity_file, ssh_err(r));
1569 	}
1570 	sshkey_free(public);
1571 	free(comment);
1572 
1573 	if (strlen(new_comment) > 0)
1574 		printf("Comment '%s' applied\n", new_comment);
1575 	else
1576 		printf("Comment removed\n");
1577 
1578 	exit(0);
1579 }
1580 
1581 static void
1582 cert_ext_add(const char *key, const char *value, int iscrit)
1583 {
1584 	cert_ext = xreallocarray(cert_ext, ncert_ext + 1, sizeof(*cert_ext));
1585 	cert_ext[ncert_ext].key = xstrdup(key);
1586 	cert_ext[ncert_ext].val = value == NULL ? NULL : xstrdup(value);
1587 	cert_ext[ncert_ext].crit = iscrit;
1588 	ncert_ext++;
1589 }
1590 
1591 /* qsort(3) comparison function for certificate extensions */
1592 static int
1593 cert_ext_cmp(const void *_a, const void *_b)
1594 {
1595 	const struct cert_ext *a = (const struct cert_ext *)_a;
1596 	const struct cert_ext *b = (const struct cert_ext *)_b;
1597 	int r;
1598 
1599 	if (a->crit != b->crit)
1600 		return (a->crit < b->crit) ? -1 : 1;
1601 	if ((r = strcmp(a->key, b->key)) != 0)
1602 		return r;
1603 	if ((a->val == NULL) != (b->val == NULL))
1604 		return (a->val == NULL) ? -1 : 1;
1605 	if (a->val != NULL && (r = strcmp(a->val, b->val)) != 0)
1606 		return r;
1607 	return 0;
1608 }
1609 
1610 #define OPTIONS_CRITICAL	1
1611 #define OPTIONS_EXTENSIONS	2
1612 static void
1613 prepare_options_buf(struct sshbuf *c, int which)
1614 {
1615 	struct sshbuf *b;
1616 	size_t i;
1617 	int r;
1618 	const struct cert_ext *ext;
1619 
1620 	if ((b = sshbuf_new()) == NULL)
1621 		fatal("%s: sshbuf_new failed", __func__);
1622 	sshbuf_reset(c);
1623 	for (i = 0; i < ncert_ext; i++) {
1624 		ext = &cert_ext[i];
1625 		if ((ext->crit && (which & OPTIONS_EXTENSIONS)) ||
1626 		    (!ext->crit && (which & OPTIONS_CRITICAL)))
1627 			continue;
1628 		if (ext->val == NULL) {
1629 			/* flag option */
1630 			debug3("%s: %s", __func__, ext->key);
1631 			if ((r = sshbuf_put_cstring(c, ext->key)) != 0 ||
1632 			    (r = sshbuf_put_string(c, NULL, 0)) != 0)
1633 				fatal("%s: buffer: %s", __func__, ssh_err(r));
1634 		} else {
1635 			/* key/value option */
1636 			debug3("%s: %s=%s", __func__, ext->key, ext->val);
1637 			sshbuf_reset(b);
1638 			if ((r = sshbuf_put_cstring(c, ext->key)) != 0 ||
1639 			    (r = sshbuf_put_cstring(b, ext->val)) != 0 ||
1640 			    (r = sshbuf_put_stringb(c, b)) != 0)
1641 				fatal("%s: buffer: %s", __func__, ssh_err(r));
1642 		}
1643 	}
1644 	sshbuf_free(b);
1645 }
1646 
1647 static void
1648 finalise_cert_exts(void)
1649 {
1650 	/* critical options */
1651 	if (certflags_command != NULL)
1652 		cert_ext_add("force-command", certflags_command, 1);
1653 	if (certflags_src_addr != NULL)
1654 		cert_ext_add("source-address", certflags_src_addr, 1);
1655 	/* extensions */
1656 	if ((certflags_flags & CERTOPT_X_FWD) != 0)
1657 		cert_ext_add("permit-X11-forwarding", NULL, 0);
1658 	if ((certflags_flags & CERTOPT_AGENT_FWD) != 0)
1659 		cert_ext_add("permit-agent-forwarding", NULL, 0);
1660 	if ((certflags_flags & CERTOPT_PORT_FWD) != 0)
1661 		cert_ext_add("permit-port-forwarding", NULL, 0);
1662 	if ((certflags_flags & CERTOPT_PTY) != 0)
1663 		cert_ext_add("permit-pty", NULL, 0);
1664 	if ((certflags_flags & CERTOPT_USER_RC) != 0)
1665 		cert_ext_add("permit-user-rc", NULL, 0);
1666 	if ((certflags_flags & CERTOPT_NO_REQUIRE_USER_PRESENCE) != 0)
1667 		cert_ext_add("no-touch-required", NULL, 0);
1668 	/* order lexically by key */
1669 	if (ncert_ext > 0)
1670 		qsort(cert_ext, ncert_ext, sizeof(*cert_ext), cert_ext_cmp);
1671 }
1672 
1673 static struct sshkey *
1674 load_pkcs11_key(char *path)
1675 {
1676 #ifdef ENABLE_PKCS11
1677 	struct sshkey **keys = NULL, *public, *private = NULL;
1678 	int r, i, nkeys;
1679 
1680 	if ((r = sshkey_load_public(path, &public, NULL)) != 0)
1681 		fatal("Couldn't load CA public key \"%s\": %s",
1682 		    path, ssh_err(r));
1683 
1684 	nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase,
1685 	    &keys, NULL);
1686 	debug3("%s: %d keys", __func__, nkeys);
1687 	if (nkeys <= 0)
1688 		fatal("cannot read public key from pkcs11");
1689 	for (i = 0; i < nkeys; i++) {
1690 		if (sshkey_equal_public(public, keys[i])) {
1691 			private = keys[i];
1692 			continue;
1693 		}
1694 		sshkey_free(keys[i]);
1695 	}
1696 	free(keys);
1697 	sshkey_free(public);
1698 	return private;
1699 #else
1700 	fatal("no pkcs11 support");
1701 #endif /* ENABLE_PKCS11 */
1702 }
1703 
1704 /* Signer for sshkey_certify_custom that uses the agent */
1705 static int
1706 agent_signer(struct sshkey *key, u_char **sigp, size_t *lenp,
1707     const u_char *data, size_t datalen,
1708     const char *alg, const char *provider, u_int compat, void *ctx)
1709 {
1710 	int *agent_fdp = (int *)ctx;
1711 
1712 	return ssh_agent_sign(*agent_fdp, key, sigp, lenp,
1713 	    data, datalen, alg, compat);
1714 }
1715 
1716 static void
1717 do_ca_sign(struct passwd *pw, const char *ca_key_path, int prefer_agent,
1718     unsigned long long cert_serial, int cert_serial_autoinc,
1719     int argc, char **argv)
1720 {
1721 	int r, i, found, agent_fd = -1;
1722 	u_int n;
1723 	struct sshkey *ca, *public;
1724 	char valid[64], *otmp, *tmp, *cp, *out, *comment;
1725 	char *ca_fp = NULL, **plist = NULL;
1726 	struct ssh_identitylist *agent_ids;
1727 	size_t j;
1728 	struct notifier_ctx *notifier = NULL;
1729 
1730 #ifdef ENABLE_PKCS11
1731 	pkcs11_init(1);
1732 #endif
1733 	tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
1734 	if (pkcs11provider != NULL) {
1735 		/* If a PKCS#11 token was specified then try to use it */
1736 		if ((ca = load_pkcs11_key(tmp)) == NULL)
1737 			fatal("No PKCS#11 key matching %s found", ca_key_path);
1738 	} else if (prefer_agent) {
1739 		/*
1740 		 * Agent signature requested. Try to use agent after making
1741 		 * sure the public key specified is actually present in the
1742 		 * agent.
1743 		 */
1744 		if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
1745 			fatal("Cannot load CA public key %s: %s",
1746 			    tmp, ssh_err(r));
1747 		if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
1748 			fatal("Cannot use public key for CA signature: %s",
1749 			    ssh_err(r));
1750 		if ((r = ssh_fetch_identitylist(agent_fd, &agent_ids)) != 0)
1751 			fatal("Retrieve agent key list: %s", ssh_err(r));
1752 		found = 0;
1753 		for (j = 0; j < agent_ids->nkeys; j++) {
1754 			if (sshkey_equal(ca, agent_ids->keys[j])) {
1755 				found = 1;
1756 				break;
1757 			}
1758 		}
1759 		if (!found)
1760 			fatal("CA key %s not found in agent", tmp);
1761 		ssh_free_identitylist(agent_ids);
1762 		ca->flags |= SSHKEY_FLAG_EXT;
1763 	} else {
1764 		/* CA key is assumed to be a private key on the filesystem */
1765 		ca = load_identity(tmp, NULL);
1766 	}
1767 	free(tmp);
1768 
1769 	if (key_type_name != NULL) {
1770 		if (sshkey_type_from_name(key_type_name) != ca->type) {
1771 			fatal("CA key type %s doesn't match specified %s",
1772 			    sshkey_ssh_name(ca), key_type_name);
1773 		}
1774 	} else if (ca->type == KEY_RSA) {
1775 		/* Default to a good signature algorithm */
1776 		key_type_name = "rsa-sha2-512";
1777 	}
1778 	ca_fp = sshkey_fingerprint(ca, fingerprint_hash, SSH_FP_DEFAULT);
1779 
1780 	finalise_cert_exts();
1781 	for (i = 0; i < argc; i++) {
1782 		/* Split list of principals */
1783 		n = 0;
1784 		if (cert_principals != NULL) {
1785 			otmp = tmp = xstrdup(cert_principals);
1786 			plist = NULL;
1787 			for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1788 				plist = xreallocarray(plist, n + 1, sizeof(*plist));
1789 				if (*(plist[n] = xstrdup(cp)) == '\0')
1790 					fatal("Empty principal name");
1791 			}
1792 			free(otmp);
1793 		}
1794 		if (n > SSHKEY_CERT_MAX_PRINCIPALS)
1795 			fatal("Too many certificate principals specified");
1796 
1797 		tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1798 		if ((r = sshkey_load_public(tmp, &public, &comment)) != 0)
1799 			fatal("%s: unable to open \"%s\": %s",
1800 			    __func__, tmp, ssh_err(r));
1801 		if (sshkey_is_cert(public))
1802 			fatal("%s: key \"%s\" type %s cannot be certified",
1803 			    __func__, tmp, sshkey_type(public));
1804 
1805 		/* Prepare certificate to sign */
1806 		if ((r = sshkey_to_certified(public)) != 0)
1807 			fatal("Could not upgrade key %s to certificate: %s",
1808 			    tmp, ssh_err(r));
1809 		public->cert->type = cert_key_type;
1810 		public->cert->serial = (u_int64_t)cert_serial;
1811 		public->cert->key_id = xstrdup(cert_key_id);
1812 		public->cert->nprincipals = n;
1813 		public->cert->principals = plist;
1814 		public->cert->valid_after = cert_valid_from;
1815 		public->cert->valid_before = cert_valid_to;
1816 		prepare_options_buf(public->cert->critical, OPTIONS_CRITICAL);
1817 		prepare_options_buf(public->cert->extensions,
1818 		    OPTIONS_EXTENSIONS);
1819 		if ((r = sshkey_from_private(ca,
1820 		    &public->cert->signature_key)) != 0)
1821 			fatal("sshkey_from_private (ca key): %s", ssh_err(r));
1822 
1823 		if (agent_fd != -1 && (ca->flags & SSHKEY_FLAG_EXT) != 0) {
1824 			if ((r = sshkey_certify_custom(public, ca,
1825 			    key_type_name, sk_provider, agent_signer,
1826 			    &agent_fd)) != 0)
1827 				fatal("Couldn't certify key %s via agent: %s",
1828 				    tmp, ssh_err(r));
1829 		} else {
1830 			if (sshkey_is_sk(ca) &&
1831 			    (ca->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
1832 				notifier = notify_start(0,
1833 				    "Confirm user presence for key %s %s",
1834 				    sshkey_type(ca), ca_fp);
1835 			}
1836 			r = sshkey_certify(public, ca, key_type_name,
1837 			    sk_provider);
1838 			notify_complete(notifier);
1839 			if (r != 0)
1840 				fatal("Couldn't certify key %s: %s",
1841 				    tmp, ssh_err(r));
1842 		}
1843 
1844 		if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
1845 			*cp = '\0';
1846 		xasprintf(&out, "%s-cert.pub", tmp);
1847 		free(tmp);
1848 
1849 		if ((r = sshkey_save_public(public, out, comment)) != 0) {
1850 			fatal("Unable to save public key to %s: %s",
1851 			    identity_file, ssh_err(r));
1852 		}
1853 
1854 		if (!quiet) {
1855 			sshkey_format_cert_validity(public->cert,
1856 			    valid, sizeof(valid));
1857 			logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1858 			    "valid %s", sshkey_cert_type(public),
1859 			    out, public->cert->key_id,
1860 			    (unsigned long long)public->cert->serial,
1861 			    cert_principals != NULL ? " for " : "",
1862 			    cert_principals != NULL ? cert_principals : "",
1863 			    valid);
1864 		}
1865 
1866 		sshkey_free(public);
1867 		free(out);
1868 		if (cert_serial_autoinc)
1869 			cert_serial++;
1870 	}
1871 	free(ca_fp);
1872 #ifdef ENABLE_PKCS11
1873 	pkcs11_terminate();
1874 #endif
1875 	exit(0);
1876 }
1877 
1878 static u_int64_t
1879 parse_relative_time(const char *s, time_t now)
1880 {
1881 	int64_t mul, secs;
1882 
1883 	mul = *s == '-' ? -1 : 1;
1884 
1885 	if ((secs = convtime(s + 1)) == -1)
1886 		fatal("Invalid relative certificate time %s", s);
1887 	if (mul == -1 && secs > now)
1888 		fatal("Certificate time %s cannot be represented", s);
1889 	return now + (u_int64_t)(secs * mul);
1890 }
1891 
1892 static void
1893 parse_cert_times(char *timespec)
1894 {
1895 	char *from, *to;
1896 	time_t now = time(NULL);
1897 	int64_t secs;
1898 
1899 	/* +timespec relative to now */
1900 	if (*timespec == '+' && strchr(timespec, ':') == NULL) {
1901 		if ((secs = convtime(timespec + 1)) == -1)
1902 			fatal("Invalid relative certificate life %s", timespec);
1903 		cert_valid_to = now + secs;
1904 		/*
1905 		 * Backdate certificate one minute to avoid problems on hosts
1906 		 * with poorly-synchronised clocks.
1907 		 */
1908 		cert_valid_from = ((now - 59)/ 60) * 60;
1909 		return;
1910 	}
1911 
1912 	/*
1913 	 * from:to, where
1914 	 * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "always"
1915 	 *   to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "forever"
1916 	 */
1917 	from = xstrdup(timespec);
1918 	to = strchr(from, ':');
1919 	if (to == NULL || from == to || *(to + 1) == '\0')
1920 		fatal("Invalid certificate life specification %s", timespec);
1921 	*to++ = '\0';
1922 
1923 	if (*from == '-' || *from == '+')
1924 		cert_valid_from = parse_relative_time(from, now);
1925 	else if (strcmp(from, "always") == 0)
1926 		cert_valid_from = 0;
1927 	else if (parse_absolute_time(from, &cert_valid_from) != 0)
1928 		fatal("Invalid from time \"%s\"", from);
1929 
1930 	if (*to == '-' || *to == '+')
1931 		cert_valid_to = parse_relative_time(to, now);
1932 	else if (strcmp(to, "forever") == 0)
1933 		cert_valid_to = ~(u_int64_t)0;
1934 	else if (parse_absolute_time(to, &cert_valid_to) != 0)
1935 		fatal("Invalid to time \"%s\"", to);
1936 
1937 	if (cert_valid_to <= cert_valid_from)
1938 		fatal("Empty certificate validity interval");
1939 	free(from);
1940 }
1941 
1942 static void
1943 add_cert_option(char *opt)
1944 {
1945 	char *val, *cp;
1946 	int iscrit = 0;
1947 
1948 	if (strcasecmp(opt, "clear") == 0)
1949 		certflags_flags = 0;
1950 	else if (strcasecmp(opt, "no-x11-forwarding") == 0)
1951 		certflags_flags &= ~CERTOPT_X_FWD;
1952 	else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
1953 		certflags_flags |= CERTOPT_X_FWD;
1954 	else if (strcasecmp(opt, "no-agent-forwarding") == 0)
1955 		certflags_flags &= ~CERTOPT_AGENT_FWD;
1956 	else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
1957 		certflags_flags |= CERTOPT_AGENT_FWD;
1958 	else if (strcasecmp(opt, "no-port-forwarding") == 0)
1959 		certflags_flags &= ~CERTOPT_PORT_FWD;
1960 	else if (strcasecmp(opt, "permit-port-forwarding") == 0)
1961 		certflags_flags |= CERTOPT_PORT_FWD;
1962 	else if (strcasecmp(opt, "no-pty") == 0)
1963 		certflags_flags &= ~CERTOPT_PTY;
1964 	else if (strcasecmp(opt, "permit-pty") == 0)
1965 		certflags_flags |= CERTOPT_PTY;
1966 	else if (strcasecmp(opt, "no-user-rc") == 0)
1967 		certflags_flags &= ~CERTOPT_USER_RC;
1968 	else if (strcasecmp(opt, "permit-user-rc") == 0)
1969 		certflags_flags |= CERTOPT_USER_RC;
1970 	else if (strcasecmp(opt, "touch-required") == 0)
1971 		certflags_flags &= ~CERTOPT_NO_REQUIRE_USER_PRESENCE;
1972 	else if (strcasecmp(opt, "no-touch-required") == 0)
1973 		certflags_flags |= CERTOPT_NO_REQUIRE_USER_PRESENCE;
1974 	else if (strncasecmp(opt, "force-command=", 14) == 0) {
1975 		val = opt + 14;
1976 		if (*val == '\0')
1977 			fatal("Empty force-command option");
1978 		if (certflags_command != NULL)
1979 			fatal("force-command already specified");
1980 		certflags_command = xstrdup(val);
1981 	} else if (strncasecmp(opt, "source-address=", 15) == 0) {
1982 		val = opt + 15;
1983 		if (*val == '\0')
1984 			fatal("Empty source-address option");
1985 		if (certflags_src_addr != NULL)
1986 			fatal("source-address already specified");
1987 		if (addr_match_cidr_list(NULL, val) != 0)
1988 			fatal("Invalid source-address list");
1989 		certflags_src_addr = xstrdup(val);
1990 	} else if (strncasecmp(opt, "extension:", 10) == 0 ||
1991 		   (iscrit = (strncasecmp(opt, "critical:", 9) == 0))) {
1992 		val = xstrdup(strchr(opt, ':') + 1);
1993 		if ((cp = strchr(val, '=')) != NULL)
1994 			*cp++ = '\0';
1995 		cert_ext_add(val, cp, iscrit);
1996 		free(val);
1997 	} else
1998 		fatal("Unsupported certificate option \"%s\"", opt);
1999 }
2000 
2001 static void
2002 show_options(struct sshbuf *optbuf, int in_critical)
2003 {
2004 	char *name, *arg, *hex;
2005 	struct sshbuf *options, *option = NULL;
2006 	int r;
2007 
2008 	if ((options = sshbuf_fromb(optbuf)) == NULL)
2009 		fatal("%s: sshbuf_fromb failed", __func__);
2010 	while (sshbuf_len(options) != 0) {
2011 		sshbuf_free(option);
2012 		option = NULL;
2013 		if ((r = sshbuf_get_cstring(options, &name, NULL)) != 0 ||
2014 		    (r = sshbuf_froms(options, &option)) != 0)
2015 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
2016 		printf("                %s", name);
2017 		if (!in_critical &&
2018 		    (strcmp(name, "permit-X11-forwarding") == 0 ||
2019 		    strcmp(name, "permit-agent-forwarding") == 0 ||
2020 		    strcmp(name, "permit-port-forwarding") == 0 ||
2021 		    strcmp(name, "permit-pty") == 0 ||
2022 		    strcmp(name, "permit-user-rc") == 0 ||
2023 		    strcmp(name, "no-touch-required") == 0)) {
2024 			printf("\n");
2025 		} else if (in_critical &&
2026 		    (strcmp(name, "force-command") == 0 ||
2027 		    strcmp(name, "source-address") == 0)) {
2028 			if ((r = sshbuf_get_cstring(option, &arg, NULL)) != 0)
2029 				fatal("%s: buffer error: %s",
2030 				    __func__, ssh_err(r));
2031 			printf(" %s\n", arg);
2032 			free(arg);
2033 		} else if (sshbuf_len(option) > 0) {
2034 			hex = sshbuf_dtob16(option);
2035 			printf(" UNKNOWN OPTION: %s (len %zu)\n",
2036 			    hex, sshbuf_len(option));
2037 			sshbuf_reset(option);
2038 			free(hex);
2039 		} else
2040 			printf(" UNKNOWN FLAG OPTION\n");
2041 		free(name);
2042 		if (sshbuf_len(option) != 0)
2043 			fatal("Option corrupt: extra data at end");
2044 	}
2045 	sshbuf_free(option);
2046 	sshbuf_free(options);
2047 }
2048 
2049 static void
2050 print_cert(struct sshkey *key)
2051 {
2052 	char valid[64], *key_fp, *ca_fp;
2053 	u_int i;
2054 
2055 	key_fp = sshkey_fingerprint(key, fingerprint_hash, SSH_FP_DEFAULT);
2056 	ca_fp = sshkey_fingerprint(key->cert->signature_key,
2057 	    fingerprint_hash, SSH_FP_DEFAULT);
2058 	if (key_fp == NULL || ca_fp == NULL)
2059 		fatal("%s: sshkey_fingerprint fail", __func__);
2060 	sshkey_format_cert_validity(key->cert, valid, sizeof(valid));
2061 
2062 	printf("        Type: %s %s certificate\n", sshkey_ssh_name(key),
2063 	    sshkey_cert_type(key));
2064 	printf("        Public key: %s %s\n", sshkey_type(key), key_fp);
2065 	printf("        Signing CA: %s %s (using %s)\n",
2066 	    sshkey_type(key->cert->signature_key), ca_fp,
2067 	    key->cert->signature_type);
2068 	printf("        Key ID: \"%s\"\n", key->cert->key_id);
2069 	printf("        Serial: %llu\n", (unsigned long long)key->cert->serial);
2070 	printf("        Valid: %s\n", valid);
2071 	printf("        Principals: ");
2072 	if (key->cert->nprincipals == 0)
2073 		printf("(none)\n");
2074 	else {
2075 		for (i = 0; i < key->cert->nprincipals; i++)
2076 			printf("\n                %s",
2077 			    key->cert->principals[i]);
2078 		printf("\n");
2079 	}
2080 	printf("        Critical Options: ");
2081 	if (sshbuf_len(key->cert->critical) == 0)
2082 		printf("(none)\n");
2083 	else {
2084 		printf("\n");
2085 		show_options(key->cert->critical, 1);
2086 	}
2087 	printf("        Extensions: ");
2088 	if (sshbuf_len(key->cert->extensions) == 0)
2089 		printf("(none)\n");
2090 	else {
2091 		printf("\n");
2092 		show_options(key->cert->extensions, 0);
2093 	}
2094 }
2095 
2096 static void
2097 do_show_cert(struct passwd *pw)
2098 {
2099 	struct sshkey *key = NULL;
2100 	struct stat st;
2101 	int r, is_stdin = 0, ok = 0;
2102 	FILE *f;
2103 	char *cp, *line = NULL;
2104 	const char *path;
2105 	size_t linesize = 0;
2106 	u_long lnum = 0;
2107 
2108 	if (!have_identity)
2109 		ask_filename(pw, "Enter file in which the key is");
2110 	if (strcmp(identity_file, "-") != 0 && stat(identity_file, &st) == -1)
2111 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
2112 
2113 	path = identity_file;
2114 	if (strcmp(path, "-") == 0) {
2115 		f = stdin;
2116 		path = "(stdin)";
2117 		is_stdin = 1;
2118 	} else if ((f = fopen(identity_file, "r")) == NULL)
2119 		fatal("fopen %s: %s", identity_file, strerror(errno));
2120 
2121 	while (getline(&line, &linesize, f) != -1) {
2122 		lnum++;
2123 		sshkey_free(key);
2124 		key = NULL;
2125 		/* Trim leading space and comments */
2126 		cp = line + strspn(line, " \t");
2127 		if (*cp == '#' || *cp == '\0')
2128 			continue;
2129 		if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2130 			fatal("sshkey_new");
2131 		if ((r = sshkey_read(key, &cp)) != 0) {
2132 			error("%s:%lu: invalid key: %s", path,
2133 			    lnum, ssh_err(r));
2134 			continue;
2135 		}
2136 		if (!sshkey_is_cert(key)) {
2137 			error("%s:%lu is not a certificate", path, lnum);
2138 			continue;
2139 		}
2140 		ok = 1;
2141 		if (!is_stdin && lnum == 1)
2142 			printf("%s:\n", path);
2143 		else
2144 			printf("%s:%lu:\n", path, lnum);
2145 		print_cert(key);
2146 	}
2147 	free(line);
2148 	sshkey_free(key);
2149 	fclose(f);
2150 	exit(ok ? 0 : 1);
2151 }
2152 
2153 static void
2154 load_krl(const char *path, struct ssh_krl **krlp)
2155 {
2156 	struct sshbuf *krlbuf;
2157 	int r;
2158 
2159 	if ((r = sshbuf_load_file(path, &krlbuf)) != 0)
2160 		fatal("Unable to load KRL: %s", ssh_err(r));
2161 	/* XXX check sigs */
2162 	if ((r = ssh_krl_from_blob(krlbuf, krlp, NULL, 0)) != 0 ||
2163 	    *krlp == NULL)
2164 		fatal("Invalid KRL file: %s", ssh_err(r));
2165 	sshbuf_free(krlbuf);
2166 }
2167 
2168 static void
2169 hash_to_blob(const char *cp, u_char **blobp, size_t *lenp,
2170     const char *file, u_long lnum)
2171 {
2172 	char *tmp;
2173 	size_t tlen;
2174 	struct sshbuf *b;
2175 	int r;
2176 
2177 	if (strncmp(cp, "SHA256:", 7) != 0)
2178 		fatal("%s:%lu: unsupported hash algorithm", file, lnum);
2179 	cp += 7;
2180 
2181 	/*
2182 	 * OpenSSH base64 hashes omit trailing '='
2183 	 * characters; put them back for decode.
2184 	 */
2185 	tlen = strlen(cp);
2186 	tmp = xmalloc(tlen + 4 + 1);
2187 	strlcpy(tmp, cp, tlen + 1);
2188 	while ((tlen % 4) != 0) {
2189 		tmp[tlen++] = '=';
2190 		tmp[tlen] = '\0';
2191 	}
2192 	if ((b = sshbuf_new()) == NULL)
2193 		fatal("%s: sshbuf_new failed", __func__);
2194 	if ((r = sshbuf_b64tod(b, tmp)) != 0)
2195 		fatal("%s:%lu: decode hash failed: %s", file, lnum, ssh_err(r));
2196 	free(tmp);
2197 	*lenp = sshbuf_len(b);
2198 	*blobp = xmalloc(*lenp);
2199 	memcpy(*blobp, sshbuf_ptr(b), *lenp);
2200 	sshbuf_free(b);
2201 }
2202 
2203 static void
2204 update_krl_from_file(struct passwd *pw, const char *file, int wild_ca,
2205     const struct sshkey *ca, struct ssh_krl *krl)
2206 {
2207 	struct sshkey *key = NULL;
2208 	u_long lnum = 0;
2209 	char *path, *cp, *ep, *line = NULL;
2210 	u_char *blob = NULL;
2211 	size_t blen = 0, linesize = 0;
2212 	unsigned long long serial, serial2;
2213 	int i, was_explicit_key, was_sha1, was_sha256, was_hash, r;
2214 	FILE *krl_spec;
2215 
2216 	path = tilde_expand_filename(file, pw->pw_uid);
2217 	if (strcmp(path, "-") == 0) {
2218 		krl_spec = stdin;
2219 		free(path);
2220 		path = xstrdup("(standard input)");
2221 	} else if ((krl_spec = fopen(path, "r")) == NULL)
2222 		fatal("fopen %s: %s", path, strerror(errno));
2223 
2224 	if (!quiet)
2225 		printf("Revoking from %s\n", path);
2226 	while (getline(&line, &linesize, krl_spec) != -1) {
2227 		lnum++;
2228 		was_explicit_key = was_sha1 = was_sha256 = was_hash = 0;
2229 		cp = line + strspn(line, " \t");
2230 		/* Trim trailing space, comments and strip \n */
2231 		for (i = 0, r = -1; cp[i] != '\0'; i++) {
2232 			if (cp[i] == '#' || cp[i] == '\n') {
2233 				cp[i] = '\0';
2234 				break;
2235 			}
2236 			if (cp[i] == ' ' || cp[i] == '\t') {
2237 				/* Remember the start of a span of whitespace */
2238 				if (r == -1)
2239 					r = i;
2240 			} else
2241 				r = -1;
2242 		}
2243 		if (r != -1)
2244 			cp[r] = '\0';
2245 		if (*cp == '\0')
2246 			continue;
2247 		if (strncasecmp(cp, "serial:", 7) == 0) {
2248 			if (ca == NULL && !wild_ca) {
2249 				fatal("revoking certificates by serial number "
2250 				    "requires specification of a CA key");
2251 			}
2252 			cp += 7;
2253 			cp = cp + strspn(cp, " \t");
2254 			errno = 0;
2255 			serial = strtoull(cp, &ep, 0);
2256 			if (*cp == '\0' || (*ep != '\0' && *ep != '-'))
2257 				fatal("%s:%lu: invalid serial \"%s\"",
2258 				    path, lnum, cp);
2259 			if (errno == ERANGE && serial == ULLONG_MAX)
2260 				fatal("%s:%lu: serial out of range",
2261 				    path, lnum);
2262 			serial2 = serial;
2263 			if (*ep == '-') {
2264 				cp = ep + 1;
2265 				errno = 0;
2266 				serial2 = strtoull(cp, &ep, 0);
2267 				if (*cp == '\0' || *ep != '\0')
2268 					fatal("%s:%lu: invalid serial \"%s\"",
2269 					    path, lnum, cp);
2270 				if (errno == ERANGE && serial2 == ULLONG_MAX)
2271 					fatal("%s:%lu: serial out of range",
2272 					    path, lnum);
2273 				if (serial2 <= serial)
2274 					fatal("%s:%lu: invalid serial range "
2275 					    "%llu:%llu", path, lnum,
2276 					    (unsigned long long)serial,
2277 					    (unsigned long long)serial2);
2278 			}
2279 			if (ssh_krl_revoke_cert_by_serial_range(krl,
2280 			    ca, serial, serial2) != 0) {
2281 				fatal("%s: revoke serial failed",
2282 				    __func__);
2283 			}
2284 		} else if (strncasecmp(cp, "id:", 3) == 0) {
2285 			if (ca == NULL && !wild_ca) {
2286 				fatal("revoking certificates by key ID "
2287 				    "requires specification of a CA key");
2288 			}
2289 			cp += 3;
2290 			cp = cp + strspn(cp, " \t");
2291 			if (ssh_krl_revoke_cert_by_key_id(krl, ca, cp) != 0)
2292 				fatal("%s: revoke key ID failed", __func__);
2293 		} else if (strncasecmp(cp, "hash:", 5) == 0) {
2294 			cp += 5;
2295 			cp = cp + strspn(cp, " \t");
2296 			hash_to_blob(cp, &blob, &blen, file, lnum);
2297 			r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2298 			if (r != 0)
2299 				fatal("%s: revoke key failed: %s",
2300 				    __func__, ssh_err(r));
2301 		} else {
2302 			if (strncasecmp(cp, "key:", 4) == 0) {
2303 				cp += 4;
2304 				cp = cp + strspn(cp, " \t");
2305 				was_explicit_key = 1;
2306 			} else if (strncasecmp(cp, "sha1:", 5) == 0) {
2307 				cp += 5;
2308 				cp = cp + strspn(cp, " \t");
2309 				was_sha1 = 1;
2310 			} else if (strncasecmp(cp, "sha256:", 7) == 0) {
2311 				cp += 7;
2312 				cp = cp + strspn(cp, " \t");
2313 				was_sha256 = 1;
2314 				/*
2315 				 * Just try to process the line as a key.
2316 				 * Parsing will fail if it isn't.
2317 				 */
2318 			}
2319 			if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2320 				fatal("sshkey_new");
2321 			if ((r = sshkey_read(key, &cp)) != 0)
2322 				fatal("%s:%lu: invalid key: %s",
2323 				    path, lnum, ssh_err(r));
2324 			if (was_explicit_key)
2325 				r = ssh_krl_revoke_key_explicit(krl, key);
2326 			else if (was_sha1) {
2327 				if (sshkey_fingerprint_raw(key,
2328 				    SSH_DIGEST_SHA1, &blob, &blen) != 0) {
2329 					fatal("%s:%lu: fingerprint failed",
2330 					    file, lnum);
2331 				}
2332 				r = ssh_krl_revoke_key_sha1(krl, blob, blen);
2333 			} else if (was_sha256) {
2334 				if (sshkey_fingerprint_raw(key,
2335 				    SSH_DIGEST_SHA256, &blob, &blen) != 0) {
2336 					fatal("%s:%lu: fingerprint failed",
2337 					    file, lnum);
2338 				}
2339 				r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2340 			} else
2341 				r = ssh_krl_revoke_key(krl, key);
2342 			if (r != 0)
2343 				fatal("%s: revoke key failed: %s",
2344 				    __func__, ssh_err(r));
2345 			freezero(blob, blen);
2346 			blob = NULL;
2347 			blen = 0;
2348 			sshkey_free(key);
2349 		}
2350 	}
2351 	if (strcmp(path, "-") != 0)
2352 		fclose(krl_spec);
2353 	free(line);
2354 	free(path);
2355 }
2356 
2357 static void
2358 do_gen_krl(struct passwd *pw, int updating, const char *ca_key_path,
2359     unsigned long long krl_version, const char *krl_comment,
2360     int argc, char **argv)
2361 {
2362 	struct ssh_krl *krl;
2363 	struct stat sb;
2364 	struct sshkey *ca = NULL;
2365 	int i, r, wild_ca = 0;
2366 	char *tmp;
2367 	struct sshbuf *kbuf;
2368 
2369 	if (*identity_file == '\0')
2370 		fatal("KRL generation requires an output file");
2371 	if (stat(identity_file, &sb) == -1) {
2372 		if (errno != ENOENT)
2373 			fatal("Cannot access KRL \"%s\": %s",
2374 			    identity_file, strerror(errno));
2375 		if (updating)
2376 			fatal("KRL \"%s\" does not exist", identity_file);
2377 	}
2378 	if (ca_key_path != NULL) {
2379 		if (strcasecmp(ca_key_path, "none") == 0)
2380 			wild_ca = 1;
2381 		else {
2382 			tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
2383 			if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
2384 				fatal("Cannot load CA public key %s: %s",
2385 				    tmp, ssh_err(r));
2386 			free(tmp);
2387 		}
2388 	}
2389 
2390 	if (updating)
2391 		load_krl(identity_file, &krl);
2392 	else if ((krl = ssh_krl_init()) == NULL)
2393 		fatal("couldn't create KRL");
2394 
2395 	if (krl_version != 0)
2396 		ssh_krl_set_version(krl, krl_version);
2397 	if (krl_comment != NULL)
2398 		ssh_krl_set_comment(krl, krl_comment);
2399 
2400 	for (i = 0; i < argc; i++)
2401 		update_krl_from_file(pw, argv[i], wild_ca, ca, krl);
2402 
2403 	if ((kbuf = sshbuf_new()) == NULL)
2404 		fatal("sshbuf_new failed");
2405 	if (ssh_krl_to_blob(krl, kbuf, NULL, 0) != 0)
2406 		fatal("Couldn't generate KRL");
2407 	if ((r = sshbuf_write_file(identity_file, kbuf)) != 0)
2408 		fatal("write %s: %s", identity_file, strerror(errno));
2409 	sshbuf_free(kbuf);
2410 	ssh_krl_free(krl);
2411 	sshkey_free(ca);
2412 }
2413 
2414 static void
2415 do_check_krl(struct passwd *pw, int print_krl, int argc, char **argv)
2416 {
2417 	int i, r, ret = 0;
2418 	char *comment;
2419 	struct ssh_krl *krl;
2420 	struct sshkey *k;
2421 
2422 	if (*identity_file == '\0')
2423 		fatal("KRL checking requires an input file");
2424 	load_krl(identity_file, &krl);
2425 	if (print_krl)
2426 		krl_dump(krl, stdout);
2427 	for (i = 0; i < argc; i++) {
2428 		if ((r = sshkey_load_public(argv[i], &k, &comment)) != 0)
2429 			fatal("Cannot load public key %s: %s",
2430 			    argv[i], ssh_err(r));
2431 		r = ssh_krl_check_key(krl, k);
2432 		printf("%s%s%s%s: %s\n", argv[i],
2433 		    *comment ? " (" : "", comment, *comment ? ")" : "",
2434 		    r == 0 ? "ok" : "REVOKED");
2435 		if (r != 0)
2436 			ret = 1;
2437 		sshkey_free(k);
2438 		free(comment);
2439 	}
2440 	ssh_krl_free(krl);
2441 	exit(ret);
2442 }
2443 
2444 static struct sshkey *
2445 load_sign_key(const char *keypath, const struct sshkey *pubkey)
2446 {
2447 	size_t i, slen, plen = strlen(keypath);
2448 	char *privpath = xstrdup(keypath);
2449 	const char *suffixes[] = { "-cert.pub", ".pub", NULL };
2450 	struct sshkey *ret = NULL, *privkey = NULL;
2451 	int r;
2452 
2453 	/*
2454 	 * If passed a public key filename, then try to locate the corresponding
2455 	 * private key. This lets us specify certificates on the command-line
2456 	 * and have ssh-keygen find the appropriate private key.
2457 	 */
2458 	for (i = 0; suffixes[i]; i++) {
2459 		slen = strlen(suffixes[i]);
2460 		if (plen <= slen ||
2461 		    strcmp(privpath + plen - slen, suffixes[i]) != 0)
2462 			continue;
2463 		privpath[plen - slen] = '\0';
2464 		debug("%s: %s looks like a public key, using private key "
2465 		    "path %s instead", __func__, keypath, privpath);
2466 	}
2467 	if ((privkey = load_identity(privpath, NULL)) == NULL) {
2468 		error("Couldn't load identity %s", keypath);
2469 		goto done;
2470 	}
2471 	if (!sshkey_equal_public(pubkey, privkey)) {
2472 		error("Public key %s doesn't match private %s",
2473 		    keypath, privpath);
2474 		goto done;
2475 	}
2476 	if (sshkey_is_cert(pubkey) && !sshkey_is_cert(privkey)) {
2477 		/*
2478 		 * Graft the certificate onto the private key to make
2479 		 * it capable of signing.
2480 		 */
2481 		if ((r = sshkey_to_certified(privkey)) != 0) {
2482 			error("%s: sshkey_to_certified: %s", __func__,
2483 			    ssh_err(r));
2484 			goto done;
2485 		}
2486 		if ((r = sshkey_cert_copy(pubkey, privkey)) != 0) {
2487 			error("%s: sshkey_cert_copy: %s", __func__, ssh_err(r));
2488 			goto done;
2489 		}
2490 	}
2491 	/* success */
2492 	ret = privkey;
2493 	privkey = NULL;
2494  done:
2495 	sshkey_free(privkey);
2496 	free(privpath);
2497 	return ret;
2498 }
2499 
2500 static int
2501 sign_one(struct sshkey *signkey, const char *filename, int fd,
2502     const char *sig_namespace, sshsig_signer *signer, void *signer_ctx)
2503 {
2504 	struct sshbuf *sigbuf = NULL, *abuf = NULL;
2505 	int r = SSH_ERR_INTERNAL_ERROR, wfd = -1, oerrno;
2506 	char *wfile = NULL, *asig = NULL, *fp = NULL;
2507 
2508 	if (!quiet) {
2509 		if (fd == STDIN_FILENO)
2510 			fprintf(stderr, "Signing data on standard input\n");
2511 		else
2512 			fprintf(stderr, "Signing file %s\n", filename);
2513 	}
2514 	if (signer == NULL && sshkey_is_sk(signkey) &&
2515 	    (signkey->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
2516 		if ((fp = sshkey_fingerprint(signkey, fingerprint_hash,
2517 		    SSH_FP_DEFAULT)) == NULL)
2518 			fatal("%s: sshkey_fingerprint failed", __func__);
2519 		fprintf(stderr, "Confirm user presence for key %s %s\n",
2520 		    sshkey_type(signkey), fp);
2521 		free(fp);
2522 	}
2523 	if ((r = sshsig_sign_fd(signkey, NULL, sk_provider, fd, sig_namespace,
2524 	    &sigbuf, signer, signer_ctx)) != 0) {
2525 		error("Signing %s failed: %s", filename, ssh_err(r));
2526 		goto out;
2527 	}
2528 	if ((r = sshsig_armor(sigbuf, &abuf)) != 0) {
2529 		error("%s: sshsig_armor: %s", __func__, ssh_err(r));
2530 		goto out;
2531 	}
2532 	if ((asig = sshbuf_dup_string(abuf)) == NULL) {
2533 		error("%s: buffer error", __func__);
2534 		r = SSH_ERR_ALLOC_FAIL;
2535 		goto out;
2536 	}
2537 
2538 	if (fd == STDIN_FILENO) {
2539 		fputs(asig, stdout);
2540 		fflush(stdout);
2541 	} else {
2542 		xasprintf(&wfile, "%s.sig", filename);
2543 		if (confirm_overwrite(wfile)) {
2544 			if ((wfd = open(wfile, O_WRONLY|O_CREAT|O_TRUNC,
2545 			    0666)) == -1) {
2546 				oerrno = errno;
2547 				error("Cannot open %s: %s",
2548 				    wfile, strerror(errno));
2549 				errno = oerrno;
2550 				r = SSH_ERR_SYSTEM_ERROR;
2551 				goto out;
2552 			}
2553 			if (atomicio(vwrite, wfd, asig,
2554 			    strlen(asig)) != strlen(asig)) {
2555 				oerrno = errno;
2556 				error("Cannot write to %s: %s",
2557 				    wfile, strerror(errno));
2558 				errno = oerrno;
2559 				r = SSH_ERR_SYSTEM_ERROR;
2560 				goto out;
2561 			}
2562 			if (!quiet) {
2563 				fprintf(stderr, "Write signature to %s\n",
2564 				    wfile);
2565 			}
2566 		}
2567 	}
2568 	/* success */
2569 	r = 0;
2570  out:
2571 	free(wfile);
2572 	free(asig);
2573 	sshbuf_free(abuf);
2574 	sshbuf_free(sigbuf);
2575 	if (wfd != -1)
2576 		close(wfd);
2577 	return r;
2578 }
2579 
2580 static int
2581 sig_sign(const char *keypath, const char *sig_namespace, int argc, char **argv)
2582 {
2583 	int i, fd = -1, r, ret = -1;
2584 	int agent_fd = -1;
2585 	struct sshkey *pubkey = NULL, *privkey = NULL, *signkey = NULL;
2586 	sshsig_signer *signer = NULL;
2587 
2588 	/* Check file arguments. */
2589 	for (i = 0; i < argc; i++) {
2590 		if (strcmp(argv[i], "-") != 0)
2591 			continue;
2592 		if (i > 0 || argc > 1)
2593 			fatal("Cannot sign mix of paths and standard input");
2594 	}
2595 
2596 	if ((r = sshkey_load_public(keypath, &pubkey, NULL)) != 0) {
2597 		error("Couldn't load public key %s: %s", keypath, ssh_err(r));
2598 		goto done;
2599 	}
2600 
2601 	if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
2602 		debug("Couldn't get agent socket: %s", ssh_err(r));
2603 	else {
2604 		if ((r = ssh_agent_has_key(agent_fd, pubkey)) == 0)
2605 			signer = agent_signer;
2606 		else
2607 			debug("Couldn't find key in agent: %s", ssh_err(r));
2608 	}
2609 
2610 	if (signer == NULL) {
2611 		/* Not using agent - try to load private key */
2612 		if ((privkey = load_sign_key(keypath, pubkey)) == NULL)
2613 			goto done;
2614 		signkey = privkey;
2615 	} else {
2616 		/* Will use key in agent */
2617 		signkey = pubkey;
2618 	}
2619 
2620 	if (argc == 0) {
2621 		if ((r = sign_one(signkey, "(stdin)", STDIN_FILENO,
2622 		    sig_namespace, signer, &agent_fd)) != 0)
2623 			goto done;
2624 	} else {
2625 		for (i = 0; i < argc; i++) {
2626 			if (strcmp(argv[i], "-") == 0)
2627 				fd = STDIN_FILENO;
2628 			else if ((fd = open(argv[i], O_RDONLY)) == -1) {
2629 				error("Cannot open %s for signing: %s",
2630 				    argv[i], strerror(errno));
2631 				goto done;
2632 			}
2633 			if ((r = sign_one(signkey, argv[i], fd, sig_namespace,
2634 			    signer, &agent_fd)) != 0)
2635 				goto done;
2636 			if (fd != STDIN_FILENO)
2637 				close(fd);
2638 			fd = -1;
2639 		}
2640 	}
2641 
2642 	ret = 0;
2643 done:
2644 	if (fd != -1 && fd != STDIN_FILENO)
2645 		close(fd);
2646 	sshkey_free(pubkey);
2647 	sshkey_free(privkey);
2648 	return ret;
2649 }
2650 
2651 static int
2652 sig_verify(const char *signature, const char *sig_namespace,
2653     const char *principal, const char *allowed_keys, const char *revoked_keys)
2654 {
2655 	int r, ret = -1;
2656 	struct sshbuf *sigbuf = NULL, *abuf = NULL;
2657 	struct sshkey *sign_key = NULL;
2658 	char *fp = NULL;
2659 	struct sshkey_sig_details *sig_details = NULL;
2660 
2661 	memset(&sig_details, 0, sizeof(sig_details));
2662 	if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
2663 		error("Couldn't read signature file: %s", ssh_err(r));
2664 		goto done;
2665 	}
2666 
2667 	if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
2668 		error("%s: sshsig_armor: %s", __func__, ssh_err(r));
2669 		goto done;
2670 	}
2671 	if ((r = sshsig_verify_fd(sigbuf, STDIN_FILENO, sig_namespace,
2672 	    &sign_key, &sig_details)) != 0)
2673 		goto done; /* sshsig_verify() prints error */
2674 
2675 	if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
2676 	    SSH_FP_DEFAULT)) == NULL)
2677 		fatal("%s: sshkey_fingerprint failed", __func__);
2678 	debug("Valid (unverified) signature from key %s", fp);
2679 	if (sig_details != NULL) {
2680 		debug2("%s: signature details: counter = %u, flags = 0x%02x",
2681 		    __func__, sig_details->sk_counter, sig_details->sk_flags);
2682 	}
2683 	free(fp);
2684 	fp = NULL;
2685 
2686 	if (revoked_keys != NULL) {
2687 		if ((r = sshkey_check_revoked(sign_key, revoked_keys)) != 0) {
2688 			debug3("sshkey_check_revoked failed: %s", ssh_err(r));
2689 			goto done;
2690 		}
2691 	}
2692 
2693 	if (allowed_keys != NULL &&
2694 	    (r = sshsig_check_allowed_keys(allowed_keys, sign_key,
2695 					   principal, sig_namespace)) != 0) {
2696 		debug3("sshsig_check_allowed_keys failed: %s", ssh_err(r));
2697 		goto done;
2698 	}
2699 	/* success */
2700 	ret = 0;
2701 done:
2702 	if (!quiet) {
2703 		if (ret == 0) {
2704 			if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
2705 			    SSH_FP_DEFAULT)) == NULL) {
2706 				fatal("%s: sshkey_fingerprint failed",
2707 				    __func__);
2708 			}
2709 			if (principal == NULL) {
2710 				printf("Good \"%s\" signature with %s key %s\n",
2711 				       sig_namespace, sshkey_type(sign_key), fp);
2712 
2713 			} else {
2714 				printf("Good \"%s\" signature for %s with %s key %s\n",
2715 				       sig_namespace, principal,
2716 				       sshkey_type(sign_key), fp);
2717 			}
2718 		} else {
2719 			printf("Could not verify signature.\n");
2720 		}
2721 	}
2722 	sshbuf_free(sigbuf);
2723 	sshbuf_free(abuf);
2724 	sshkey_free(sign_key);
2725 	sshkey_sig_details_free(sig_details);
2726 	free(fp);
2727 	return ret;
2728 }
2729 
2730 static int
2731 sig_find_principals(const char *signature, const char *allowed_keys) {
2732 	int r, ret = -1;
2733 	struct sshbuf *sigbuf = NULL, *abuf = NULL;
2734 	struct sshkey *sign_key = NULL;
2735 	char *principals = NULL, *cp, *tmp;
2736 
2737 	if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
2738 		error("Couldn't read signature file: %s", ssh_err(r));
2739 		goto done;
2740 	}
2741 	if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
2742 		error("%s: sshsig_armor: %s", __func__, ssh_err(r));
2743 		goto done;
2744 	}
2745 	if ((r = sshsig_get_pubkey(sigbuf, &sign_key)) != 0) {
2746 		error("%s: sshsig_get_pubkey: %s",
2747 		    __func__, ssh_err(r));
2748 		goto done;
2749 	}
2750 	if ((r = sshsig_find_principals(allowed_keys, sign_key,
2751 	    &principals)) != 0) {
2752 		error("%s: sshsig_get_principal: %s",
2753 		      __func__, ssh_err(r));
2754 		goto done;
2755 	}
2756 	ret = 0;
2757 done:
2758 	if (ret == 0 ) {
2759 		/* Emit matching principals one per line */
2760 		tmp = principals;
2761 		while ((cp = strsep(&tmp, ",")) != NULL && *cp != '\0')
2762 			puts(cp);
2763 	} else {
2764 		fprintf(stderr, "No principal matched.\n");
2765 	}
2766 	sshbuf_free(sigbuf);
2767 	sshbuf_free(abuf);
2768 	sshkey_free(sign_key);
2769 	free(principals);
2770 	return ret;
2771 }
2772 
2773 static void
2774 do_moduli_gen(const char *out_file, char **opts, size_t nopts)
2775 {
2776 #ifdef WITH_OPENSSL
2777 	/* Moduli generation/screening */
2778 	u_int32_t memory = 0;
2779 	BIGNUM *start = NULL;
2780 	int moduli_bits = 0;
2781 	FILE *out;
2782 	size_t i;
2783 	const char *errstr;
2784 
2785 	/* Parse options */
2786 	for (i = 0; i < nopts; i++) {
2787 		if (strncmp(opts[i], "memory=", 7) == 0) {
2788 			memory = (u_int32_t)strtonum(opts[i]+7, 1,
2789 			    UINT_MAX, &errstr);
2790 			if (errstr) {
2791 				fatal("Memory limit is %s: %s",
2792 				    errstr, opts[i]+7);
2793 			}
2794 		} else if (strncmp(opts[i], "start=", 6) == 0) {
2795 			/* XXX - also compare length against bits */
2796 			if (BN_hex2bn(&start, opts[i]+6) == 0)
2797 				fatal("Invalid start point.");
2798 		} else if (strncmp(opts[i], "bits=", 5) == 0) {
2799 			moduli_bits = (int)strtonum(opts[i]+5, 1,
2800 			    INT_MAX, &errstr);
2801 			if (errstr) {
2802 				fatal("Invalid number: %s (%s)",
2803 					opts[i]+12, errstr);
2804 			}
2805 		} else {
2806 			fatal("Option \"%s\" is unsupported for moduli "
2807 			    "generation", opts[i]);
2808 		}
2809 	}
2810 
2811 	if ((out = fopen(out_file, "w")) == NULL) {
2812 		fatal("Couldn't open modulus candidate file \"%s\": %s",
2813 		    out_file, strerror(errno));
2814 	}
2815 	setvbuf(out, NULL, _IOLBF, 0);
2816 
2817 	if (moduli_bits == 0)
2818 		moduli_bits = DEFAULT_BITS;
2819 	if (gen_candidates(out, memory, moduli_bits, start) != 0)
2820 		fatal("modulus candidate generation failed");
2821 #else /* WITH_OPENSSL */
2822 	fatal("Moduli generation is not supported");
2823 #endif /* WITH_OPENSSL */
2824 }
2825 
2826 static void
2827 do_moduli_screen(const char *out_file, char **opts, size_t nopts)
2828 {
2829 #ifdef WITH_OPENSSL
2830 	/* Moduli generation/screening */
2831 	char *checkpoint = NULL;
2832 	u_int32_t generator_wanted = 0;
2833 	unsigned long start_lineno = 0, lines_to_process = 0;
2834 	int prime_tests = 0;
2835 	FILE *out, *in = stdin;
2836 	size_t i;
2837 	const char *errstr;
2838 
2839 	/* Parse options */
2840 	for (i = 0; i < nopts; i++) {
2841 		if (strncmp(opts[i], "lines=", 6) == 0) {
2842 			lines_to_process = strtoul(opts[i]+6, NULL, 10);
2843 		} else if (strncmp(opts[i], "start-line=", 11) == 0) {
2844 			start_lineno = strtoul(opts[i]+11, NULL, 10);
2845 		} else if (strncmp(opts[i], "checkpoint=", 11) == 0) {
2846 			checkpoint = xstrdup(opts[i]+11);
2847 		} else if (strncmp(opts[i], "generator=", 10) == 0) {
2848 			generator_wanted = (u_int32_t)strtonum(
2849 			    opts[i]+10, 1, UINT_MAX, &errstr);
2850 			if (errstr != NULL) {
2851 				fatal("Generator invalid: %s (%s)",
2852 				    opts[i]+10, errstr);
2853 			}
2854 		} else if (strncmp(opts[i], "prime-tests=", 12) == 0) {
2855 			prime_tests = (int)strtonum(opts[i]+12, 1,
2856 			    INT_MAX, &errstr);
2857 			if (errstr) {
2858 				fatal("Invalid number: %s (%s)",
2859 					opts[i]+12, errstr);
2860 			}
2861 		} else {
2862 			fatal("Option \"%s\" is unsupported for moduli "
2863 			    "screening", opts[i]);
2864 		}
2865 	}
2866 
2867 	if (have_identity && strcmp(identity_file, "-") != 0) {
2868 		if ((in = fopen(identity_file, "r")) == NULL) {
2869 			fatal("Couldn't open modulus candidate "
2870 			    "file \"%s\": %s", identity_file,
2871 			    strerror(errno));
2872 		}
2873 	}
2874 
2875 	if ((out = fopen(out_file, "a")) == NULL) {
2876 		fatal("Couldn't open moduli file \"%s\": %s",
2877 		    out_file, strerror(errno));
2878 	}
2879 	setvbuf(out, NULL, _IOLBF, 0);
2880 	if (prime_test(in, out, prime_tests == 0 ? 100 : prime_tests,
2881 	    generator_wanted, checkpoint,
2882 	    start_lineno, lines_to_process) != 0)
2883 		fatal("modulus screening failed");
2884 #else /* WITH_OPENSSL */
2885 	fatal("Moduli screening is not supported");
2886 #endif /* WITH_OPENSSL */
2887 }
2888 
2889 static char *
2890 private_key_passphrase(void)
2891 {
2892 	char *passphrase1, *passphrase2;
2893 
2894 	/* Ask for a passphrase (twice). */
2895 	if (identity_passphrase)
2896 		passphrase1 = xstrdup(identity_passphrase);
2897 	else if (identity_new_passphrase)
2898 		passphrase1 = xstrdup(identity_new_passphrase);
2899 	else {
2900 passphrase_again:
2901 		passphrase1 =
2902 			read_passphrase("Enter passphrase (empty for no "
2903 			    "passphrase): ", RP_ALLOW_STDIN);
2904 		passphrase2 = read_passphrase("Enter same passphrase again: ",
2905 		    RP_ALLOW_STDIN);
2906 		if (strcmp(passphrase1, passphrase2) != 0) {
2907 			/*
2908 			 * The passphrases do not match.  Clear them and
2909 			 * retry.
2910 			 */
2911 			freezero(passphrase1, strlen(passphrase1));
2912 			freezero(passphrase2, strlen(passphrase2));
2913 			printf("Passphrases do not match.  Try again.\n");
2914 			goto passphrase_again;
2915 		}
2916 		/* Clear the other copy of the passphrase. */
2917 		freezero(passphrase2, strlen(passphrase2));
2918 	}
2919 	return passphrase1;
2920 }
2921 
2922 static const char *
2923 skip_ssh_url_preamble(const char *s)
2924 {
2925 	if (strncmp(s, "ssh://", 6) == 0)
2926 		return s + 6;
2927 	else if (strncmp(s, "ssh:", 4) == 0)
2928 		return s + 4;
2929 	return s;
2930 }
2931 
2932 static int
2933 do_download_sk(const char *skprovider, const char *device)
2934 {
2935 	struct sshkey **keys;
2936 	size_t nkeys, i;
2937 	int r, ret = -1;
2938 	char *fp, *pin = NULL, *pass = NULL, *path, *pubpath;
2939 	const char *ext;
2940 
2941 	if (skprovider == NULL)
2942 		fatal("Cannot download keys without provider");
2943 
2944 	for (i = 0; i < 2; i++) {
2945 		if (i == 1) {
2946 			pin = read_passphrase("Enter PIN for authenticator: ",
2947 			    RP_ALLOW_STDIN);
2948 		}
2949 		if ((r = sshsk_load_resident(skprovider, device, pin,
2950 		    &keys, &nkeys)) != 0) {
2951 			if (i == 0 && r == SSH_ERR_KEY_WRONG_PASSPHRASE)
2952 				continue;
2953 			if (pin != NULL)
2954 				freezero(pin, strlen(pin));
2955 			error("Unable to load resident keys: %s", ssh_err(r));
2956 			return -1;
2957 		}
2958 	}
2959 	if (nkeys == 0)
2960 		logit("No keys to download");
2961 	if (pin != NULL)
2962 		freezero(pin, strlen(pin));
2963 
2964 	for (i = 0; i < nkeys; i++) {
2965 		if (keys[i]->type != KEY_ECDSA_SK &&
2966 		    keys[i]->type != KEY_ED25519_SK) {
2967 			error("Unsupported key type %s (%d)",
2968 			    sshkey_type(keys[i]), keys[i]->type);
2969 			continue;
2970 		}
2971 		if ((fp = sshkey_fingerprint(keys[i],
2972 		    fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
2973 			fatal("%s: sshkey_fingerprint failed", __func__);
2974 		debug("%s: key %zu: %s %s %s (flags 0x%02x)", __func__, i,
2975 		    sshkey_type(keys[i]), fp, keys[i]->sk_application,
2976 		    keys[i]->sk_flags);
2977 		ext = skip_ssh_url_preamble(keys[i]->sk_application);
2978 		xasprintf(&path, "id_%s_rk%s%s",
2979 		    keys[i]->type == KEY_ECDSA_SK ? "ecdsa_sk" : "ed25519_sk",
2980 		    *ext == '\0' ? "" : "_", ext);
2981 
2982 		/* If the file already exists, ask the user to confirm. */
2983 		if (!confirm_overwrite(path)) {
2984 			free(path);
2985 			break;
2986 		}
2987 
2988 		/* Save the key with the application string as the comment */
2989 		if (pass == NULL)
2990 			pass = private_key_passphrase();
2991 		if ((r = sshkey_save_private(keys[i], path, pass,
2992 		    keys[i]->sk_application, private_key_format,
2993 		    openssh_format_cipher, rounds)) != 0) {
2994 			error("Saving key \"%s\" failed: %s",
2995 			    path, ssh_err(r));
2996 			free(path);
2997 			break;
2998 		}
2999 		if (!quiet) {
3000 			printf("Saved %s key%s%s to %s\n",
3001 			    sshkey_type(keys[i]),
3002 			    *ext != '\0' ? " " : "",
3003 			    *ext != '\0' ? keys[i]->sk_application : "",
3004 			    path);
3005 		}
3006 
3007 		/* Save public key too */
3008 		xasprintf(&pubpath, "%s.pub", path);
3009 		free(path);
3010 		if ((r = sshkey_save_public(keys[i], pubpath,
3011 		    keys[i]->sk_application)) != 0) {
3012 			error("Saving public key \"%s\" failed: %s",
3013 			    pubpath, ssh_err(r));
3014 			free(pubpath);
3015 			break;
3016 		}
3017 		free(pubpath);
3018 	}
3019 
3020 	if (i >= nkeys)
3021 		ret = 0; /* success */
3022 	if (pass != NULL)
3023 		freezero(pass, strlen(pass));
3024 	for (i = 0; i < nkeys; i++)
3025 		sshkey_free(keys[i]);
3026 	free(keys);
3027 	return ret;
3028 }
3029 
3030 static void
3031 usage(void)
3032 {
3033 	fprintf(stderr,
3034 	    "usage: ssh-keygen [-q] [-a rounds] [-b bits] [-C comment] [-f output_keyfile]\n"
3035 	    "                  [-m format] [-N new_passphrase] [-O option]\n"
3036 	    "                  [-t dsa | ecdsa | ecdsa-sk | ed25519 | ed25519-sk | rsa]\n"
3037 	    "                  [-w provider]\n"
3038 	    "       ssh-keygen -p [-a rounds] [-f keyfile] [-m format] [-N new_passphrase]\n"
3039 	    "                   [-P old_passphrase]\n"
3040 	    "       ssh-keygen -i [-f input_keyfile] [-m key_format]\n"
3041 	    "       ssh-keygen -e [-f input_keyfile] [-m key_format]\n"
3042 	    "       ssh-keygen -y [-f input_keyfile]\n"
3043 	    "       ssh-keygen -c [-a rounds] [-C comment] [-f keyfile] [-P passphrase]\n"
3044 	    "       ssh-keygen -l [-v] [-E fingerprint_hash] [-f input_keyfile]\n"
3045 	    "       ssh-keygen -B [-f input_keyfile]\n");
3046 #ifdef ENABLE_PKCS11
3047 	fprintf(stderr,
3048 	    "       ssh-keygen -D pkcs11\n");
3049 #endif
3050 	fprintf(stderr,
3051 	    "       ssh-keygen -F hostname [-lv] [-f known_hosts_file]\n"
3052 	    "       ssh-keygen -H [-f known_hosts_file]\n"
3053 	    "       ssh-keygen -K [-a rounds] [-w provider]\n"
3054 	    "       ssh-keygen -R hostname [-f known_hosts_file]\n"
3055 	    "       ssh-keygen -r hostname [-g] [-f input_keyfile]\n"
3056 #ifdef WITH_OPENSSL
3057 	    "       ssh-keygen -M generate [-O option] output_file\n"
3058 	    "       ssh-keygen -M screen [-f input_file] [-O option] output_file\n"
3059 #endif
3060 	    "       ssh-keygen -I certificate_identity -s ca_key [-hU] [-D pkcs11_provider]\n"
3061 	    "                  [-n principals] [-O option] [-V validity_interval]\n"
3062 	    "                  [-z serial_number] file ...\n"
3063 	    "       ssh-keygen -L [-f input_keyfile]\n"
3064 	    "       ssh-keygen -A [-a rounds] [-f prefix_path]\n"
3065 	    "       ssh-keygen -k -f krl_file [-u] [-s ca_public] [-z version_number]\n"
3066 	    "                  file ...\n"
3067 	    "       ssh-keygen -Q [-l] -f krl_file [file ...]\n"
3068 	    "       ssh-keygen -Y find-principals -s signature_file -f allowed_signers_file\n"
3069 	    "       ssh-keygen -Y check-novalidate -n namespace -s signature_file\n"
3070 	    "       ssh-keygen -Y sign -f key_file -n namespace file ...\n"
3071 	    "       ssh-keygen -Y verify -f allowed_signers_file -I signer_identity\n"
3072 	    "       		-n namespace -s signature_file [-r revocation_file]\n");
3073 	exit(1);
3074 }
3075 
3076 /*
3077  * Main program for key management.
3078  */
3079 int
3080 main(int argc, char **argv)
3081 {
3082 	char comment[1024], *passphrase;
3083 	char *rr_hostname = NULL, *ep, *fp, *ra;
3084 	struct sshkey *private, *public;
3085 	struct passwd *pw;
3086 	int r, opt, type;
3087 	int change_passphrase = 0, change_comment = 0, show_cert = 0;
3088 	int find_host = 0, delete_host = 0, hash_hosts = 0;
3089 	int gen_all_hostkeys = 0, gen_krl = 0, update_krl = 0, check_krl = 0;
3090 	int prefer_agent = 0, convert_to = 0, convert_from = 0;
3091 	int print_public = 0, print_generic = 0, cert_serial_autoinc = 0;
3092 	int do_gen_candidates = 0, do_screen_candidates = 0, download_sk = 0;
3093 	unsigned long long cert_serial = 0;
3094 	char *identity_comment = NULL, *ca_key_path = NULL, **opts = NULL;
3095 	char *sk_application = NULL, *sk_device = NULL, *sk_user = NULL;
3096 	char *sk_attestaion_path = NULL;
3097 	struct sshbuf *challenge = NULL, *attest = NULL;
3098 	size_t i, nopts = 0;
3099 	u_int32_t bits = 0;
3100 	uint8_t sk_flags = SSH_SK_USER_PRESENCE_REQD;
3101 	const char *errstr;
3102 	int log_level = SYSLOG_LEVEL_INFO;
3103 	char *sign_op = NULL;
3104 
3105 	extern int optind;
3106 	extern char *optarg;
3107 
3108 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
3109 	sanitise_stdfd();
3110 
3111 #ifdef WITH_OPENSSL
3112 	OpenSSL_add_all_algorithms();
3113 #endif
3114 	log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
3115 
3116 	setlocale(LC_CTYPE, "");
3117 
3118 	/* we need this for the home * directory.  */
3119 	pw = getpwuid(getuid());
3120 	if (!pw)
3121 		fatal("No user exists for uid %lu", (u_long)getuid());
3122 	if (gethostname(hostname, sizeof(hostname)) == -1)
3123 		fatal("gethostname: %s", strerror(errno));
3124 
3125 	sk_provider = getenv("SSH_SK_PROVIDER");
3126 
3127 	/* Remaining characters: dGjJSTWx */
3128 	while ((opt = getopt(argc, argv, "ABHKLQUXceghiklopquvy"
3129 	    "C:D:E:F:I:M:N:O:P:R:V:Y:Z:"
3130 	    "a:b:f:g:m:n:r:s:t:w:z:")) != -1) {
3131 		switch (opt) {
3132 		case 'A':
3133 			gen_all_hostkeys = 1;
3134 			break;
3135 		case 'b':
3136 			bits = (u_int32_t)strtonum(optarg, 1, UINT32_MAX,
3137 			    &errstr);
3138 			if (errstr)
3139 				fatal("Bits has bad value %s (%s)",
3140 					optarg, errstr);
3141 			break;
3142 		case 'E':
3143 			fingerprint_hash = ssh_digest_alg_by_name(optarg);
3144 			if (fingerprint_hash == -1)
3145 				fatal("Invalid hash algorithm \"%s\"", optarg);
3146 			break;
3147 		case 'F':
3148 			find_host = 1;
3149 			rr_hostname = optarg;
3150 			break;
3151 		case 'H':
3152 			hash_hosts = 1;
3153 			break;
3154 		case 'I':
3155 			cert_key_id = optarg;
3156 			break;
3157 		case 'R':
3158 			delete_host = 1;
3159 			rr_hostname = optarg;
3160 			break;
3161 		case 'L':
3162 			show_cert = 1;
3163 			break;
3164 		case 'l':
3165 			print_fingerprint = 1;
3166 			break;
3167 		case 'B':
3168 			print_bubblebabble = 1;
3169 			break;
3170 		case 'm':
3171 			if (strcasecmp(optarg, "RFC4716") == 0 ||
3172 			    strcasecmp(optarg, "ssh2") == 0) {
3173 				convert_format = FMT_RFC4716;
3174 				break;
3175 			}
3176 			if (strcasecmp(optarg, "PKCS8") == 0) {
3177 				convert_format = FMT_PKCS8;
3178 				private_key_format = SSHKEY_PRIVATE_PKCS8;
3179 				break;
3180 			}
3181 			if (strcasecmp(optarg, "PEM") == 0) {
3182 				convert_format = FMT_PEM;
3183 				private_key_format = SSHKEY_PRIVATE_PEM;
3184 				break;
3185 			}
3186 			fatal("Unsupported conversion format \"%s\"", optarg);
3187 		case 'n':
3188 			cert_principals = optarg;
3189 			break;
3190 		case 'o':
3191 			/* no-op; new format is already the default */
3192 			break;
3193 		case 'p':
3194 			change_passphrase = 1;
3195 			break;
3196 		case 'c':
3197 			change_comment = 1;
3198 			break;
3199 		case 'f':
3200 			if (strlcpy(identity_file, optarg,
3201 			    sizeof(identity_file)) >= sizeof(identity_file))
3202 				fatal("Identity filename too long");
3203 			have_identity = 1;
3204 			break;
3205 		case 'g':
3206 			print_generic = 1;
3207 			break;
3208 		case 'K':
3209 			download_sk = 1;
3210 			break;
3211 		case 'P':
3212 			identity_passphrase = optarg;
3213 			break;
3214 		case 'N':
3215 			identity_new_passphrase = optarg;
3216 			break;
3217 		case 'Q':
3218 			check_krl = 1;
3219 			break;
3220 		case 'O':
3221 			opts = xrecallocarray(opts, nopts, nopts + 1,
3222 			    sizeof(*opts));
3223 			opts[nopts++] = xstrdup(optarg);
3224 			break;
3225 		case 'Z':
3226 			openssh_format_cipher = optarg;
3227 			break;
3228 		case 'C':
3229 			identity_comment = optarg;
3230 			break;
3231 		case 'q':
3232 			quiet = 1;
3233 			break;
3234 		case 'e':
3235 			/* export key */
3236 			convert_to = 1;
3237 			break;
3238 		case 'h':
3239 			cert_key_type = SSH2_CERT_TYPE_HOST;
3240 			certflags_flags = 0;
3241 			break;
3242 		case 'k':
3243 			gen_krl = 1;
3244 			break;
3245 		case 'i':
3246 		case 'X':
3247 			/* import key */
3248 			convert_from = 1;
3249 			break;
3250 		case 'y':
3251 			print_public = 1;
3252 			break;
3253 		case 's':
3254 			ca_key_path = optarg;
3255 			break;
3256 		case 't':
3257 			key_type_name = optarg;
3258 			break;
3259 		case 'D':
3260 			pkcs11provider = optarg;
3261 			break;
3262 		case 'U':
3263 			prefer_agent = 1;
3264 			break;
3265 		case 'u':
3266 			update_krl = 1;
3267 			break;
3268 		case 'v':
3269 			if (log_level == SYSLOG_LEVEL_INFO)
3270 				log_level = SYSLOG_LEVEL_DEBUG1;
3271 			else {
3272 				if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
3273 				    log_level < SYSLOG_LEVEL_DEBUG3)
3274 					log_level++;
3275 			}
3276 			break;
3277 		case 'r':
3278 			rr_hostname = optarg;
3279 			break;
3280 		case 'a':
3281 			rounds = (int)strtonum(optarg, 1, INT_MAX, &errstr);
3282 			if (errstr)
3283 				fatal("Invalid number: %s (%s)",
3284 					optarg, errstr);
3285 			break;
3286 		case 'V':
3287 			parse_cert_times(optarg);
3288 			break;
3289 		case 'Y':
3290 			sign_op = optarg;
3291 			break;
3292 		case 'w':
3293 			sk_provider = optarg;
3294 			break;
3295 		case 'z':
3296 			errno = 0;
3297 			if (*optarg == '+') {
3298 				cert_serial_autoinc = 1;
3299 				optarg++;
3300 			}
3301 			cert_serial = strtoull(optarg, &ep, 10);
3302 			if (*optarg < '0' || *optarg > '9' || *ep != '\0' ||
3303 			    (errno == ERANGE && cert_serial == ULLONG_MAX))
3304 				fatal("Invalid serial number \"%s\"", optarg);
3305 			break;
3306 		case 'M':
3307 			if (strcmp(optarg, "generate") == 0)
3308 				do_gen_candidates = 1;
3309 			else if (strcmp(optarg, "screen") == 0)
3310 				do_screen_candidates = 1;
3311 			else
3312 				fatal("Unsupported moduli option %s", optarg);
3313 			break;
3314 		case '?':
3315 		default:
3316 			usage();
3317 		}
3318 	}
3319 
3320 	if (sk_provider == NULL)
3321 		sk_provider = "internal";
3322 
3323 	/* reinit */
3324 	log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
3325 
3326 	argv += optind;
3327 	argc -= optind;
3328 
3329 	if (sign_op != NULL) {
3330 		if (strncmp(sign_op, "find-principals", 15) == 0) {
3331 			if (ca_key_path == NULL) {
3332 				error("Too few arguments for find-principals:"
3333 				      "missing signature file");
3334 				exit(1);
3335 			}
3336 			if (!have_identity) {
3337 				error("Too few arguments for find-principals:"
3338 				      "missing allowed keys file");
3339 				exit(1);
3340 			}
3341 			return sig_find_principals(ca_key_path, identity_file);
3342 		} else if (strncmp(sign_op, "sign", 4) == 0) {
3343 			if (cert_principals == NULL ||
3344 			    *cert_principals == '\0') {
3345 				error("Too few arguments for sign: "
3346 				    "missing namespace");
3347 				exit(1);
3348 			}
3349 			if (!have_identity) {
3350 				error("Too few arguments for sign: "
3351 				    "missing key");
3352 				exit(1);
3353 			}
3354 			return sig_sign(identity_file, cert_principals,
3355 			    argc, argv);
3356 		} else if (strncmp(sign_op, "check-novalidate", 16) == 0) {
3357 			if (ca_key_path == NULL) {
3358 				error("Too few arguments for check-novalidate: "
3359 				      "missing signature file");
3360 				exit(1);
3361 			}
3362 			return sig_verify(ca_key_path, cert_principals,
3363 			    NULL, NULL, NULL);
3364 		} else if (strncmp(sign_op, "verify", 6) == 0) {
3365 			if (cert_principals == NULL ||
3366 			    *cert_principals == '\0') {
3367 				error("Too few arguments for verify: "
3368 				    "missing namespace");
3369 				exit(1);
3370 			}
3371 			if (ca_key_path == NULL) {
3372 				error("Too few arguments for verify: "
3373 				    "missing signature file");
3374 				exit(1);
3375 			}
3376 			if (!have_identity) {
3377 				error("Too few arguments for sign: "
3378 				    "missing allowed keys file");
3379 				exit(1);
3380 			}
3381 			if (cert_key_id == NULL) {
3382 				error("Too few arguments for verify: "
3383 				    "missing principal ID");
3384 				exit(1);
3385 			}
3386 			return sig_verify(ca_key_path, cert_principals,
3387 			    cert_key_id, identity_file, rr_hostname);
3388 		}
3389 		error("Unsupported operation for -Y: \"%s\"", sign_op);
3390 		usage();
3391 		/* NOTREACHED */
3392 	}
3393 
3394 	if (ca_key_path != NULL) {
3395 		if (argc < 1 && !gen_krl) {
3396 			error("Too few arguments.");
3397 			usage();
3398 		}
3399 	} else if (argc > 0 && !gen_krl && !check_krl &&
3400 	    !do_gen_candidates && !do_screen_candidates) {
3401 		error("Too many arguments.");
3402 		usage();
3403 	}
3404 	if (change_passphrase && change_comment) {
3405 		error("Can only have one of -p and -c.");
3406 		usage();
3407 	}
3408 	if (print_fingerprint && (delete_host || hash_hosts)) {
3409 		error("Cannot use -l with -H or -R.");
3410 		usage();
3411 	}
3412 	if (gen_krl) {
3413 		do_gen_krl(pw, update_krl, ca_key_path,
3414 		    cert_serial, identity_comment, argc, argv);
3415 		return (0);
3416 	}
3417 	if (check_krl) {
3418 		do_check_krl(pw, print_fingerprint, argc, argv);
3419 		return (0);
3420 	}
3421 	if (ca_key_path != NULL) {
3422 		if (cert_key_id == NULL)
3423 			fatal("Must specify key id (-I) when certifying");
3424 		for (i = 0; i < nopts; i++)
3425 			add_cert_option(opts[i]);
3426 		do_ca_sign(pw, ca_key_path, prefer_agent,
3427 		    cert_serial, cert_serial_autoinc, argc, argv);
3428 	}
3429 	if (show_cert)
3430 		do_show_cert(pw);
3431 	if (delete_host || hash_hosts || find_host) {
3432 		do_known_hosts(pw, rr_hostname, find_host,
3433 		    delete_host, hash_hosts);
3434 	}
3435 	if (pkcs11provider != NULL)
3436 		do_download(pw);
3437 	if (download_sk) {
3438 		for (i = 0; i < nopts; i++) {
3439 			if (strncasecmp(opts[i], "device=", 7) == 0) {
3440 				sk_device = xstrdup(opts[i] + 7);
3441 			} else {
3442 				fatal("Option \"%s\" is unsupported for "
3443 				    "FIDO authenticator download", opts[i]);
3444 			}
3445 		}
3446 		return do_download_sk(sk_provider, sk_device);
3447 	}
3448 	if (print_fingerprint || print_bubblebabble)
3449 		do_fingerprint(pw);
3450 	if (change_passphrase)
3451 		do_change_passphrase(pw);
3452 	if (change_comment)
3453 		do_change_comment(pw, identity_comment);
3454 #ifdef WITH_OPENSSL
3455 	if (convert_to)
3456 		do_convert_to(pw);
3457 	if (convert_from)
3458 		do_convert_from(pw);
3459 #else /* WITH_OPENSSL */
3460 	if (convert_to || convert_from)
3461 		fatal("key conversion disabled at compile time");
3462 #endif /* WITH_OPENSSL */
3463 	if (print_public)
3464 		do_print_public(pw);
3465 	if (rr_hostname != NULL) {
3466 		unsigned int n = 0;
3467 
3468 		if (have_identity) {
3469 			n = do_print_resource_record(pw, identity_file,
3470 			    rr_hostname, print_generic);
3471 			if (n == 0)
3472 				fatal("%s: %s", identity_file, strerror(errno));
3473 			exit(0);
3474 		} else {
3475 
3476 			n += do_print_resource_record(pw,
3477 			    _PATH_HOST_RSA_KEY_FILE, rr_hostname,
3478 			    print_generic);
3479 			n += do_print_resource_record(pw,
3480 			    _PATH_HOST_DSA_KEY_FILE, rr_hostname,
3481 			    print_generic);
3482 			n += do_print_resource_record(pw,
3483 			    _PATH_HOST_ECDSA_KEY_FILE, rr_hostname,
3484 			    print_generic);
3485 			n += do_print_resource_record(pw,
3486 			    _PATH_HOST_ED25519_KEY_FILE, rr_hostname,
3487 			    print_generic);
3488 			n += do_print_resource_record(pw,
3489 			    _PATH_HOST_XMSS_KEY_FILE, rr_hostname,
3490 			    print_generic);
3491 			if (n == 0)
3492 				fatal("no keys found.");
3493 			exit(0);
3494 		}
3495 	}
3496 
3497 	if (do_gen_candidates || do_screen_candidates) {
3498 		if (argc <= 0)
3499 			fatal("No output file specified");
3500 		else if (argc > 1)
3501 			fatal("Too many output files specified");
3502 	}
3503 	if (do_gen_candidates) {
3504 		do_moduli_gen(argv[0], opts, nopts);
3505 		return 0;
3506 	}
3507 	if (do_screen_candidates) {
3508 		do_moduli_screen(argv[0], opts, nopts);
3509 		return 0;
3510 	}
3511 
3512 	if (gen_all_hostkeys) {
3513 		do_gen_all_hostkeys(pw);
3514 		return (0);
3515 	}
3516 
3517 	if (key_type_name == NULL)
3518 		key_type_name = DEFAULT_KEY_TYPE_NAME;
3519 
3520 	type = sshkey_type_from_name(key_type_name);
3521 	type_bits_valid(type, key_type_name, &bits);
3522 
3523 	if (!quiet)
3524 		printf("Generating public/private %s key pair.\n",
3525 		    key_type_name);
3526 	switch (type) {
3527 	case KEY_ECDSA_SK:
3528 	case KEY_ED25519_SK:
3529 		for (i = 0; i < nopts; i++) {
3530 			if (strcasecmp(opts[i], "no-touch-required") == 0) {
3531 				sk_flags &= ~SSH_SK_USER_PRESENCE_REQD;
3532 			} else if (strcasecmp(opts[i], "resident") == 0) {
3533 				sk_flags |= SSH_SK_RESIDENT_KEY;
3534 			} else if (strncasecmp(opts[i], "device=", 7) == 0) {
3535 				sk_device = xstrdup(opts[i] + 7);
3536 			} else if (strncasecmp(opts[i], "user=", 5) == 0) {
3537 				sk_user = xstrdup(opts[i] + 5);
3538 			} else if (strncasecmp(opts[i], "challenge=", 10) == 0) {
3539 				if ((r = sshbuf_load_file(opts[i] + 10,
3540 				    &challenge)) != 0) {
3541 					fatal("Unable to load FIDO enrollment "
3542 					    "challenge \"%s\": %s",
3543 					    opts[i] + 10, ssh_err(r));
3544 				}
3545 			} else if (strncasecmp(opts[i],
3546 			    "write-attestation=", 18) == 0) {
3547 				sk_attestaion_path = opts[i] + 18;
3548 			} else if (strncasecmp(opts[i],
3549 			    "application=", 12) == 0) {
3550 				sk_application = xstrdup(opts[i] + 12);
3551 				if (strncmp(sk_application, "ssh:", 4) != 0) {
3552 					fatal("FIDO application string must "
3553 					    "begin with \"ssh:\"");
3554 				}
3555 			} else {
3556 				fatal("Option \"%s\" is unsupported for "
3557 				    "FIDO authenticator enrollment", opts[i]);
3558 			}
3559 		}
3560 		if (!quiet) {
3561 			printf("You may need to touch your authenticator "
3562 			    "to authorize key generation.\n");
3563 		}
3564 		passphrase = NULL;
3565 		if ((attest = sshbuf_new()) == NULL)
3566 			fatal("sshbuf_new failed");
3567 		for (i = 0 ; ; i++) {
3568 			fflush(stdout);
3569 			r = sshsk_enroll(type, sk_provider, sk_device,
3570 			    sk_application == NULL ? "ssh:" : sk_application,
3571 			    sk_user, sk_flags, passphrase, challenge,
3572 			    &private, attest);
3573 			if (r == 0)
3574 				break;
3575 			if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
3576 				fatal("Key enrollment failed: %s", ssh_err(r));
3577 			else if (i > 0)
3578 				error("PIN incorrect");
3579 			if (passphrase != NULL) {
3580 				freezero(passphrase, strlen(passphrase));
3581 				passphrase = NULL;
3582 			}
3583 			if (i >= 3)
3584 				fatal("Too many incorrect PINs");
3585 			passphrase = read_passphrase("Enter PIN for "
3586 			    "authenticator: ", RP_ALLOW_STDIN);
3587 		}
3588 		if (passphrase != NULL) {
3589 			freezero(passphrase, strlen(passphrase));
3590 			passphrase = NULL;
3591 		}
3592 		break;
3593 	default:
3594 		if ((r = sshkey_generate(type, bits, &private)) != 0)
3595 			fatal("sshkey_generate failed");
3596 		break;
3597 	}
3598 	if ((r = sshkey_from_private(private, &public)) != 0)
3599 		fatal("sshkey_from_private failed: %s\n", ssh_err(r));
3600 
3601 	if (!have_identity)
3602 		ask_filename(pw, "Enter file in which to save the key");
3603 
3604 	/* Create ~/.ssh directory if it doesn't already exist. */
3605 	hostfile_create_user_ssh_dir(identity_file, !quiet);
3606 
3607 	/* If the file already exists, ask the user to confirm. */
3608 	if (!confirm_overwrite(identity_file))
3609 		exit(1);
3610 
3611 	/* Determine the passphrase for the private key */
3612 	passphrase = private_key_passphrase();
3613 	if (identity_comment) {
3614 		strlcpy(comment, identity_comment, sizeof(comment));
3615 	} else {
3616 		/* Create default comment field for the passphrase. */
3617 		snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
3618 	}
3619 
3620 	/* Save the key with the given passphrase and comment. */
3621 	if ((r = sshkey_save_private(private, identity_file, passphrase,
3622 	    comment, private_key_format, openssh_format_cipher, rounds)) != 0) {
3623 		error("Saving key \"%s\" failed: %s",
3624 		    identity_file, ssh_err(r));
3625 		freezero(passphrase, strlen(passphrase));
3626 		exit(1);
3627 	}
3628 	freezero(passphrase, strlen(passphrase));
3629 	sshkey_free(private);
3630 
3631 	if (!quiet) {
3632 		printf("Your identification has been saved in %s\n",
3633 		    identity_file);
3634 	}
3635 
3636 	strlcat(identity_file, ".pub", sizeof(identity_file));
3637 	if ((r = sshkey_save_public(public, identity_file, comment)) != 0) {
3638 		fatal("Unable to save public key to %s: %s",
3639 		    identity_file, ssh_err(r));
3640 	}
3641 
3642 	if (!quiet) {
3643 		fp = sshkey_fingerprint(public, fingerprint_hash,
3644 		    SSH_FP_DEFAULT);
3645 		ra = sshkey_fingerprint(public, fingerprint_hash,
3646 		    SSH_FP_RANDOMART);
3647 		if (fp == NULL || ra == NULL)
3648 			fatal("sshkey_fingerprint failed");
3649 		printf("Your public key has been saved in %s\n",
3650 		    identity_file);
3651 		printf("The key fingerprint is:\n");
3652 		printf("%s %s\n", fp, comment);
3653 		printf("The key's randomart image is:\n");
3654 		printf("%s\n", ra);
3655 		free(ra);
3656 		free(fp);
3657 	}
3658 
3659 	if (sk_attestaion_path != NULL) {
3660 		if (attest == NULL || sshbuf_len(attest) == 0) {
3661 			fatal("Enrollment did not return attestation "
3662 			    "certificate");
3663 		}
3664 		if ((r = sshbuf_write_file(sk_attestaion_path, attest)) != 0) {
3665 			fatal("Unable to write attestation certificate "
3666 			    "\"%s\": %s", sk_attestaion_path, ssh_err(r));
3667 		}
3668 		if (!quiet) {
3669 			printf("Your FIDO attestation certificate has been "
3670 			    "saved in %s\n", sk_attestaion_path);
3671 		}
3672 	}
3673 	sshbuf_free(attest);
3674 	sshkey_free(public);
3675 
3676 	exit(0);
3677 }
3678