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