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