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