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