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