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