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