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