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