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