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