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