xref: /openssh-portable/ssh-keygen.c (revision f07519a2)
1 /* $OpenBSD: ssh-keygen.c,v 1.428 2021/03/12 03:43:40 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 "includes.h"
16 
17 #include <sys/types.h>
18 #include <sys/socket.h>
19 #include <sys/stat.h>
20 
21 #ifdef WITH_OPENSSL
22 #include <openssl/evp.h>
23 #include <openssl/pem.h>
24 #include "openbsd-compat/openssl-compat.h"
25 #endif
26 
27 #ifdef HAVE_STDINT_H
28 # include <stdint.h>
29 #endif
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <netdb.h>
33 #ifdef HAVE_PATHS_H
34 # include <paths.h>
35 #endif
36 #include <pwd.h>
37 #include <stdarg.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h>
42 #include <limits.h>
43 #include <locale.h>
44 #include <time.h>
45 
46 #include "xmalloc.h"
47 #include "sshkey.h"
48 #include "authfile.h"
49 #include "sshbuf.h"
50 #include "pathnames.h"
51 #include "log.h"
52 #include "misc.h"
53 #include "match.h"
54 #include "hostfile.h"
55 #include "dns.h"
56 #include "ssh.h"
57 #include "ssh2.h"
58 #include "ssherr.h"
59 #include "ssh-pkcs11.h"
60 #include "atomicio.h"
61 #include "krl.h"
62 #include "digest.h"
63 #include "utf8.h"
64 #include "authfd.h"
65 #include "sshsig.h"
66 #include "ssh-sk.h"
67 #include "sk-api.h" /* XXX for SSH_SK_USER_PRESENCE_REQD; remove */
68 #include "cipher.h"
69 
70 #ifdef WITH_OPENSSL
71 # define DEFAULT_KEY_TYPE_NAME "rsa"
72 #else
73 # define DEFAULT_KEY_TYPE_NAME "ed25519"
74 #endif
75 
76 /*
77  * Default number of bits in the RSA, DSA and ECDSA keys.  These value can be
78  * overridden on the command line.
79  *
80  * These values, with the exception of DSA, provide security equivalent to at
81  * least 128 bits of security according to NIST Special Publication 800-57:
82  * Recommendation for Key Management Part 1 rev 4 section 5.6.1.
83  * For DSA it (and FIPS-186-4 section 4.2) specifies that the only size for
84  * which a 160bit hash is acceptable is 1kbit, and since ssh-dss specifies only
85  * SHA1 we limit the DSA key size 1k bits.
86  */
87 #define DEFAULT_BITS		3072
88 #define DEFAULT_BITS_DSA	1024
89 #define DEFAULT_BITS_ECDSA	256
90 
91 static int quiet = 0;
92 
93 /* Flag indicating that we just want to see the key fingerprint */
94 static int print_fingerprint = 0;
95 static int print_bubblebabble = 0;
96 
97 /* Hash algorithm to use for fingerprints. */
98 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
99 
100 /* The identity file name, given on the command line or entered by the user. */
101 static char identity_file[PATH_MAX];
102 static int have_identity = 0;
103 
104 /* This is set to the passphrase if given on the command line. */
105 static char *identity_passphrase = NULL;
106 
107 /* This is set to the new passphrase if given on the command line. */
108 static char *identity_new_passphrase = NULL;
109 
110 /* Key type when certifying */
111 static u_int cert_key_type = SSH2_CERT_TYPE_USER;
112 
113 /* "key ID" of signed key */
114 static char *cert_key_id = NULL;
115 
116 /* Comma-separated list of principal names for certifying keys */
117 static char *cert_principals = NULL;
118 
119 /* Validity period for certificates */
120 static u_int64_t cert_valid_from = 0;
121 static u_int64_t cert_valid_to = ~0ULL;
122 
123 /* Certificate options */
124 #define CERTOPT_X_FWD				(1)
125 #define CERTOPT_AGENT_FWD			(1<<1)
126 #define CERTOPT_PORT_FWD			(1<<2)
127 #define CERTOPT_PTY				(1<<3)
128 #define CERTOPT_USER_RC				(1<<4)
129 #define CERTOPT_NO_REQUIRE_USER_PRESENCE	(1<<5)
130 #define CERTOPT_DEFAULT	(CERTOPT_X_FWD|CERTOPT_AGENT_FWD| \
131 			 CERTOPT_PORT_FWD|CERTOPT_PTY|CERTOPT_USER_RC)
132 static u_int32_t certflags_flags = CERTOPT_DEFAULT;
133 static char *certflags_command = NULL;
134 static char *certflags_src_addr = NULL;
135 
136 /* Arbitrary extensions specified by user */
137 struct cert_ext {
138 	char *key;
139 	char *val;
140 	int crit;
141 };
142 static struct cert_ext *cert_ext;
143 static size_t ncert_ext;
144 
145 /* Conversion to/from various formats */
146 enum {
147 	FMT_RFC4716,
148 	FMT_PKCS8,
149 	FMT_PEM
150 } convert_format = FMT_RFC4716;
151 
152 static char *key_type_name = NULL;
153 
154 /* Load key from this PKCS#11 provider */
155 static char *pkcs11provider = NULL;
156 
157 /* FIDO/U2F provider to use */
158 static char *sk_provider = NULL;
159 
160 /* Format for writing private keys */
161 static int private_key_format = SSHKEY_PRIVATE_OPENSSH;
162 
163 /* Cipher for new-format private keys */
164 static char *openssh_format_cipher = NULL;
165 
166 /* Number of KDF rounds to derive new format keys. */
167 static int rounds = 0;
168 
169 /* argv0 */
170 extern char *__progname;
171 
172 static char hostname[NI_MAXHOST];
173 
174 #ifdef WITH_OPENSSL
175 /* moduli.c */
176 int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
177 int prime_test(FILE *, FILE *, u_int32_t, u_int32_t, char *, unsigned long,
178     unsigned long);
179 #endif
180 
181 static void
182 type_bits_valid(int type, const char *name, u_int32_t *bitsp)
183 {
184 	if (type == KEY_UNSPEC)
185 		fatal("unknown key type %s", key_type_name);
186 	if (*bitsp == 0) {
187 #ifdef WITH_OPENSSL
188 		int nid;
189 
190 		switch(type) {
191 		case KEY_DSA:
192 			*bitsp = DEFAULT_BITS_DSA;
193 			break;
194 		case KEY_ECDSA:
195 			if (name != NULL &&
196 			    (nid = sshkey_ecdsa_nid_from_name(name)) > 0)
197 				*bitsp = sshkey_curve_nid_to_bits(nid);
198 			if (*bitsp == 0)
199 				*bitsp = DEFAULT_BITS_ECDSA;
200 			break;
201 		case KEY_RSA:
202 			*bitsp = DEFAULT_BITS;
203 			break;
204 		}
205 #endif
206 	}
207 #ifdef WITH_OPENSSL
208 	switch (type) {
209 	case KEY_DSA:
210 		if (*bitsp != 1024)
211 			fatal("Invalid DSA key length: must be 1024 bits");
212 		break;
213 	case KEY_RSA:
214 		if (*bitsp < SSH_RSA_MINIMUM_MODULUS_SIZE)
215 			fatal("Invalid RSA key length: minimum is %d bits",
216 			    SSH_RSA_MINIMUM_MODULUS_SIZE);
217 		else if (*bitsp > OPENSSL_RSA_MAX_MODULUS_BITS)
218 			fatal("Invalid RSA key length: maximum is %d bits",
219 			    OPENSSL_RSA_MAX_MODULUS_BITS);
220 		break;
221 	case KEY_ECDSA:
222 		if (sshkey_ecdsa_bits_to_nid(*bitsp) == -1)
223 #ifdef OPENSSL_HAS_NISTP521
224 			fatal("Invalid ECDSA key length: valid lengths are "
225 			    "256, 384 or 521 bits");
226 #else
227 			fatal("Invalid ECDSA key length: valid lengths are "
228 			    "256 or 384 bits");
229 #endif
230 	}
231 #endif
232 }
233 
234 /*
235  * Checks whether a file exists and, if so, asks the user whether they wish
236  * to overwrite it.
237  * Returns nonzero if the file does not already exist or if the user agrees to
238  * overwrite, or zero otherwise.
239  */
240 static int
241 confirm_overwrite(const char *filename)
242 {
243 	char yesno[3];
244 	struct stat st;
245 
246 	if (stat(filename, &st) != 0)
247 		return 1;
248 	printf("%s already exists.\n", filename);
249 	printf("Overwrite (y/n)? ");
250 	fflush(stdout);
251 	if (fgets(yesno, sizeof(yesno), stdin) == NULL)
252 		return 0;
253 	if (yesno[0] != 'y' && yesno[0] != 'Y')
254 		return 0;
255 	return 1;
256 }
257 
258 static void
259 ask_filename(struct passwd *pw, const char *prompt)
260 {
261 	char buf[1024];
262 	char *name = NULL;
263 
264 	if (key_type_name == NULL)
265 		name = _PATH_SSH_CLIENT_ID_RSA;
266 	else {
267 		switch (sshkey_type_from_name(key_type_name)) {
268 		case KEY_DSA_CERT:
269 		case KEY_DSA:
270 			name = _PATH_SSH_CLIENT_ID_DSA;
271 			break;
272 #ifdef OPENSSL_HAS_ECC
273 		case KEY_ECDSA_CERT:
274 		case KEY_ECDSA:
275 			name = _PATH_SSH_CLIENT_ID_ECDSA;
276 			break;
277 		case KEY_ECDSA_SK_CERT:
278 		case KEY_ECDSA_SK:
279 			name = _PATH_SSH_CLIENT_ID_ECDSA_SK;
280 			break;
281 #endif
282 		case KEY_RSA_CERT:
283 		case KEY_RSA:
284 			name = _PATH_SSH_CLIENT_ID_RSA;
285 			break;
286 		case KEY_ED25519:
287 		case KEY_ED25519_CERT:
288 			name = _PATH_SSH_CLIENT_ID_ED25519;
289 			break;
290 		case KEY_ED25519_SK:
291 		case KEY_ED25519_SK_CERT:
292 			name = _PATH_SSH_CLIENT_ID_ED25519_SK;
293 			break;
294 		case KEY_XMSS:
295 		case KEY_XMSS_CERT:
296 			name = _PATH_SSH_CLIENT_ID_XMSS;
297 			break;
298 		default:
299 			fatal("bad key type");
300 		}
301 	}
302 	snprintf(identity_file, sizeof(identity_file),
303 	    "%s/%s", pw->pw_dir, name);
304 	printf("%s (%s): ", prompt, identity_file);
305 	fflush(stdout);
306 	if (fgets(buf, sizeof(buf), stdin) == NULL)
307 		exit(1);
308 	buf[strcspn(buf, "\n")] = '\0';
309 	if (strcmp(buf, "") != 0)
310 		strlcpy(identity_file, buf, sizeof(identity_file));
311 	have_identity = 1;
312 }
313 
314 static struct sshkey *
315 load_identity(const char *filename, char **commentp)
316 {
317 	char *pass;
318 	struct sshkey *prv;
319 	int r;
320 
321 	if (commentp != NULL)
322 		*commentp = NULL;
323 	if ((r = sshkey_load_private(filename, "", &prv, commentp)) == 0)
324 		return prv;
325 	if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
326 		fatal_r(r, "Load key \"%s\"", filename);
327 	if (identity_passphrase)
328 		pass = xstrdup(identity_passphrase);
329 	else
330 		pass = read_passphrase("Enter passphrase: ", RP_ALLOW_STDIN);
331 	r = sshkey_load_private(filename, pass, &prv, commentp);
332 	freezero(pass, strlen(pass));
333 	if (r != 0)
334 		fatal_r(r, "Load key \"%s\"", filename);
335 	return prv;
336 }
337 
338 #define SSH_COM_PUBLIC_BEGIN		"---- BEGIN SSH2 PUBLIC KEY ----"
339 #define SSH_COM_PUBLIC_END		"---- END SSH2 PUBLIC KEY ----"
340 #define SSH_COM_PRIVATE_BEGIN		"---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
341 #define	SSH_COM_PRIVATE_KEY_MAGIC	0x3f6ff9eb
342 
343 #ifdef WITH_OPENSSL
344 static void
345 do_convert_to_ssh2(struct passwd *pw, struct sshkey *k)
346 {
347 	struct sshbuf *b;
348 	char comment[61], *b64;
349 	int r;
350 
351 	if ((b = sshbuf_new()) == NULL)
352 		fatal_f("sshbuf_new failed");
353 	if ((r = sshkey_putb(k, b)) != 0)
354 		fatal_fr(r, "put key");
355 	if ((b64 = sshbuf_dtob64_string(b, 1)) == NULL)
356 		fatal_f("sshbuf_dtob64_string failed");
357 
358 	/* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
359 	snprintf(comment, sizeof(comment),
360 	    "%u-bit %s, converted by %s@%s from OpenSSH",
361 	    sshkey_size(k), sshkey_type(k),
362 	    pw->pw_name, hostname);
363 
364 	sshkey_free(k);
365 	sshbuf_free(b);
366 
367 	fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
368 	fprintf(stdout, "Comment: \"%s\"\n%s", comment, b64);
369 	fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
370 	free(b64);
371 	exit(0);
372 }
373 
374 static void
375 do_convert_to_pkcs8(struct sshkey *k)
376 {
377 	switch (sshkey_type_plain(k->type)) {
378 	case KEY_RSA:
379 		if (!PEM_write_RSA_PUBKEY(stdout, k->rsa))
380 			fatal("PEM_write_RSA_PUBKEY failed");
381 		break;
382 	case KEY_DSA:
383 		if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
384 			fatal("PEM_write_DSA_PUBKEY failed");
385 		break;
386 #ifdef OPENSSL_HAS_ECC
387 	case KEY_ECDSA:
388 		if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
389 			fatal("PEM_write_EC_PUBKEY failed");
390 		break;
391 #endif
392 	default:
393 		fatal_f("unsupported key type %s", sshkey_type(k));
394 	}
395 	exit(0);
396 }
397 
398 static void
399 do_convert_to_pem(struct sshkey *k)
400 {
401 	switch (sshkey_type_plain(k->type)) {
402 	case KEY_RSA:
403 		if (!PEM_write_RSAPublicKey(stdout, k->rsa))
404 			fatal("PEM_write_RSAPublicKey failed");
405 		break;
406 	case KEY_DSA:
407 		if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
408 			fatal("PEM_write_DSA_PUBKEY failed");
409 		break;
410 #ifdef OPENSSL_HAS_ECC
411 	case KEY_ECDSA:
412 		if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
413 			fatal("PEM_write_EC_PUBKEY failed");
414 		break;
415 #endif
416 	default:
417 		fatal_f("unsupported key type %s", sshkey_type(k));
418 	}
419 	exit(0);
420 }
421 
422 static void
423 do_convert_to(struct passwd *pw)
424 {
425 	struct sshkey *k;
426 	struct stat st;
427 	int r;
428 
429 	if (!have_identity)
430 		ask_filename(pw, "Enter file in which the key is");
431 	if (stat(identity_file, &st) == -1)
432 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
433 	if ((r = sshkey_load_public(identity_file, &k, NULL)) != 0)
434 		k = load_identity(identity_file, NULL);
435 	switch (convert_format) {
436 	case FMT_RFC4716:
437 		do_convert_to_ssh2(pw, k);
438 		break;
439 	case FMT_PKCS8:
440 		do_convert_to_pkcs8(k);
441 		break;
442 	case FMT_PEM:
443 		do_convert_to_pem(k);
444 		break;
445 	default:
446 		fatal_f("unknown key format %d", convert_format);
447 	}
448 	exit(0);
449 }
450 
451 /*
452  * This is almost exactly the bignum1 encoding, but with 32 bit for length
453  * instead of 16.
454  */
455 static void
456 buffer_get_bignum_bits(struct sshbuf *b, BIGNUM *value)
457 {
458 	u_int bytes, bignum_bits;
459 	int r;
460 
461 	if ((r = sshbuf_get_u32(b, &bignum_bits)) != 0)
462 		fatal_fr(r, "parse");
463 	bytes = (bignum_bits + 7) / 8;
464 	if (sshbuf_len(b) < bytes)
465 		fatal_f("input buffer too small: need %d have %zu",
466 		    bytes, sshbuf_len(b));
467 	if (BN_bin2bn(sshbuf_ptr(b), bytes, value) == NULL)
468 		fatal_f("BN_bin2bn failed");
469 	if ((r = sshbuf_consume(b, bytes)) != 0)
470 		fatal_fr(r, "consume");
471 }
472 
473 static struct sshkey *
474 do_convert_private_ssh2(struct sshbuf *b)
475 {
476 	struct sshkey *key = NULL;
477 	char *type, *cipher;
478 	u_char e1, e2, e3, *sig = NULL, data[] = "abcde12345";
479 	int r, rlen, ktype;
480 	u_int magic, i1, i2, i3, i4;
481 	size_t slen;
482 	u_long e;
483 	BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL;
484 	BIGNUM *dsa_pub_key = NULL, *dsa_priv_key = NULL;
485 	BIGNUM *rsa_n = NULL, *rsa_e = NULL, *rsa_d = NULL;
486 	BIGNUM *rsa_p = NULL, *rsa_q = NULL, *rsa_iqmp = NULL;
487 
488 	if ((r = sshbuf_get_u32(b, &magic)) != 0)
489 		fatal_fr(r, "parse magic");
490 
491 	if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
492 		error("bad magic 0x%x != 0x%x", magic,
493 		    SSH_COM_PRIVATE_KEY_MAGIC);
494 		return NULL;
495 	}
496 	if ((r = sshbuf_get_u32(b, &i1)) != 0 ||
497 	    (r = sshbuf_get_cstring(b, &type, NULL)) != 0 ||
498 	    (r = sshbuf_get_cstring(b, &cipher, NULL)) != 0 ||
499 	    (r = sshbuf_get_u32(b, &i2)) != 0 ||
500 	    (r = sshbuf_get_u32(b, &i3)) != 0 ||
501 	    (r = sshbuf_get_u32(b, &i4)) != 0)
502 		fatal_fr(r, "parse");
503 	debug("ignore (%d %d %d %d)", i1, i2, i3, i4);
504 	if (strcmp(cipher, "none") != 0) {
505 		error("unsupported cipher %s", cipher);
506 		free(cipher);
507 		free(type);
508 		return NULL;
509 	}
510 	free(cipher);
511 
512 	if (strstr(type, "dsa")) {
513 		ktype = KEY_DSA;
514 	} else if (strstr(type, "rsa")) {
515 		ktype = KEY_RSA;
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 	case KEY_DSA:
526 		if ((dsa_p = BN_new()) == NULL ||
527 		    (dsa_q = BN_new()) == NULL ||
528 		    (dsa_g = BN_new()) == NULL ||
529 		    (dsa_pub_key = BN_new()) == NULL ||
530 		    (dsa_priv_key = BN_new()) == NULL)
531 			fatal_f("BN_new");
532 		buffer_get_bignum_bits(b, dsa_p);
533 		buffer_get_bignum_bits(b, dsa_g);
534 		buffer_get_bignum_bits(b, dsa_q);
535 		buffer_get_bignum_bits(b, dsa_pub_key);
536 		buffer_get_bignum_bits(b, dsa_priv_key);
537 		if (!DSA_set0_pqg(key->dsa, dsa_p, dsa_q, dsa_g))
538 			fatal_f("DSA_set0_pqg failed");
539 		dsa_p = dsa_q = dsa_g = NULL; /* transferred */
540 		if (!DSA_set0_key(key->dsa, dsa_pub_key, dsa_priv_key))
541 			fatal_f("DSA_set0_key failed");
542 		dsa_pub_key = dsa_priv_key = NULL; /* transferred */
543 		break;
544 	case KEY_RSA:
545 		if ((r = sshbuf_get_u8(b, &e1)) != 0 ||
546 		    (e1 < 30 && (r = sshbuf_get_u8(b, &e2)) != 0) ||
547 		    (e1 < 30 && (r = sshbuf_get_u8(b, &e3)) != 0))
548 			fatal_fr(r, "parse RSA");
549 		e = e1;
550 		debug("e %lx", e);
551 		if (e < 30) {
552 			e <<= 8;
553 			e += e2;
554 			debug("e %lx", e);
555 			e <<= 8;
556 			e += e3;
557 			debug("e %lx", e);
558 		}
559 		if ((rsa_e = BN_new()) == NULL)
560 			fatal_f("BN_new");
561 		if (!BN_set_word(rsa_e, e)) {
562 			BN_clear_free(rsa_e);
563 			sshkey_free(key);
564 			return NULL;
565 		}
566 		if ((rsa_n = BN_new()) == NULL ||
567 		    (rsa_d = BN_new()) == NULL ||
568 		    (rsa_p = BN_new()) == NULL ||
569 		    (rsa_q = BN_new()) == NULL ||
570 		    (rsa_iqmp = BN_new()) == NULL)
571 			fatal_f("BN_new");
572 		buffer_get_bignum_bits(b, rsa_d);
573 		buffer_get_bignum_bits(b, rsa_n);
574 		buffer_get_bignum_bits(b, rsa_iqmp);
575 		buffer_get_bignum_bits(b, rsa_q);
576 		buffer_get_bignum_bits(b, rsa_p);
577 		if (!RSA_set0_key(key->rsa, rsa_n, rsa_e, rsa_d))
578 			fatal_f("RSA_set0_key failed");
579 		rsa_n = rsa_e = rsa_d = NULL; /* transferred */
580 		if (!RSA_set0_factors(key->rsa, rsa_p, rsa_q))
581 			fatal_f("RSA_set0_factors failed");
582 		rsa_p = rsa_q = NULL; /* transferred */
583 		if ((r = ssh_rsa_complete_crt_parameters(key, rsa_iqmp)) != 0)
584 			fatal_fr(r, "generate RSA parameters");
585 		BN_clear_free(rsa_iqmp);
586 		break;
587 	}
588 	rlen = sshbuf_len(b);
589 	if (rlen != 0)
590 		error_f("remaining bytes in key blob %d", rlen);
591 
592 	/* try the key */
593 	if (sshkey_sign(key, &sig, &slen, data, sizeof(data),
594 	    NULL, NULL, NULL, 0) != 0 ||
595 	    sshkey_verify(key, sig, slen, data, sizeof(data),
596 	    NULL, 0, NULL) != 0) {
597 		sshkey_free(key);
598 		free(sig);
599 		return NULL;
600 	}
601 	free(sig);
602 	return key;
603 }
604 
605 static int
606 get_line(FILE *fp, char *line, size_t len)
607 {
608 	int c;
609 	size_t pos = 0;
610 
611 	line[0] = '\0';
612 	while ((c = fgetc(fp)) != EOF) {
613 		if (pos >= len - 1)
614 			fatal("input line too long.");
615 		switch (c) {
616 		case '\r':
617 			c = fgetc(fp);
618 			if (c != EOF && c != '\n' && ungetc(c, fp) == EOF)
619 				fatal("unget: %s", strerror(errno));
620 			return pos;
621 		case '\n':
622 			return pos;
623 		}
624 		line[pos++] = c;
625 		line[pos] = '\0';
626 	}
627 	/* We reached EOF */
628 	return -1;
629 }
630 
631 static void
632 do_convert_from_ssh2(struct passwd *pw, struct sshkey **k, int *private)
633 {
634 	int r, blen, escaped = 0;
635 	u_int len;
636 	char line[1024];
637 	struct sshbuf *buf;
638 	char encoded[8096];
639 	FILE *fp;
640 
641 	if ((buf = sshbuf_new()) == NULL)
642 		fatal("sshbuf_new failed");
643 	if ((fp = fopen(identity_file, "r")) == NULL)
644 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
645 	encoded[0] = '\0';
646 	while ((blen = get_line(fp, line, sizeof(line))) != -1) {
647 		if (blen > 0 && line[blen - 1] == '\\')
648 			escaped++;
649 		if (strncmp(line, "----", 4) == 0 ||
650 		    strstr(line, ": ") != NULL) {
651 			if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
652 				*private = 1;
653 			if (strstr(line, " END ") != NULL) {
654 				break;
655 			}
656 			/* fprintf(stderr, "ignore: %s", line); */
657 			continue;
658 		}
659 		if (escaped) {
660 			escaped--;
661 			/* fprintf(stderr, "escaped: %s", line); */
662 			continue;
663 		}
664 		strlcat(encoded, line, sizeof(encoded));
665 	}
666 	len = strlen(encoded);
667 	if (((len % 4) == 3) &&
668 	    (encoded[len-1] == '=') &&
669 	    (encoded[len-2] == '=') &&
670 	    (encoded[len-3] == '='))
671 		encoded[len-3] = '\0';
672 	if ((r = sshbuf_b64tod(buf, encoded)) != 0)
673 		fatal_fr(r, "base64 decode");
674 	if (*private) {
675 		if ((*k = do_convert_private_ssh2(buf)) == NULL)
676 			fatal_f("private key conversion failed");
677 	} else if ((r = sshkey_fromb(buf, k)) != 0)
678 		fatal_fr(r, "parse key");
679 	sshbuf_free(buf);
680 	fclose(fp);
681 }
682 
683 static void
684 do_convert_from_pkcs8(struct sshkey **k, int *private)
685 {
686 	EVP_PKEY *pubkey;
687 	FILE *fp;
688 
689 	if ((fp = fopen(identity_file, "r")) == NULL)
690 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
691 	if ((pubkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL)) == NULL) {
692 		fatal_f("%s is not a recognised public key format",
693 		    identity_file);
694 	}
695 	fclose(fp);
696 	switch (EVP_PKEY_base_id(pubkey)) {
697 	case EVP_PKEY_RSA:
698 		if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
699 			fatal("sshkey_new failed");
700 		(*k)->type = KEY_RSA;
701 		(*k)->rsa = EVP_PKEY_get1_RSA(pubkey);
702 		break;
703 	case EVP_PKEY_DSA:
704 		if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
705 			fatal("sshkey_new failed");
706 		(*k)->type = KEY_DSA;
707 		(*k)->dsa = EVP_PKEY_get1_DSA(pubkey);
708 		break;
709 #ifdef OPENSSL_HAS_ECC
710 	case EVP_PKEY_EC:
711 		if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
712 			fatal("sshkey_new failed");
713 		(*k)->type = KEY_ECDSA;
714 		(*k)->ecdsa = EVP_PKEY_get1_EC_KEY(pubkey);
715 		(*k)->ecdsa_nid = sshkey_ecdsa_key_to_nid((*k)->ecdsa);
716 		break;
717 #endif
718 	default:
719 		fatal_f("unsupported pubkey type %d",
720 		    EVP_PKEY_base_id(pubkey));
721 	}
722 	EVP_PKEY_free(pubkey);
723 	return;
724 }
725 
726 static void
727 do_convert_from_pem(struct sshkey **k, int *private)
728 {
729 	FILE *fp;
730 	RSA *rsa;
731 
732 	if ((fp = fopen(identity_file, "r")) == NULL)
733 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
734 	if ((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
735 		if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
736 			fatal("sshkey_new failed");
737 		(*k)->type = KEY_RSA;
738 		(*k)->rsa = rsa;
739 		fclose(fp);
740 		return;
741 	}
742 	fatal_f("unrecognised raw private key format");
743 }
744 
745 static void
746 do_convert_from(struct passwd *pw)
747 {
748 	struct sshkey *k = NULL;
749 	int r, private = 0, ok = 0;
750 	struct stat st;
751 
752 	if (!have_identity)
753 		ask_filename(pw, "Enter file in which the key is");
754 	if (stat(identity_file, &st) == -1)
755 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
756 
757 	switch (convert_format) {
758 	case FMT_RFC4716:
759 		do_convert_from_ssh2(pw, &k, &private);
760 		break;
761 	case FMT_PKCS8:
762 		do_convert_from_pkcs8(&k, &private);
763 		break;
764 	case FMT_PEM:
765 		do_convert_from_pem(&k, &private);
766 		break;
767 	default:
768 		fatal_f("unknown key format %d", convert_format);
769 	}
770 
771 	if (!private) {
772 		if ((r = sshkey_write(k, stdout)) == 0)
773 			ok = 1;
774 		if (ok)
775 			fprintf(stdout, "\n");
776 	} else {
777 		switch (k->type) {
778 		case KEY_DSA:
779 			ok = PEM_write_DSAPrivateKey(stdout, k->dsa, NULL,
780 			    NULL, 0, NULL, NULL);
781 			break;
782 #ifdef OPENSSL_HAS_ECC
783 		case KEY_ECDSA:
784 			ok = PEM_write_ECPrivateKey(stdout, k->ecdsa, NULL,
785 			    NULL, 0, NULL, NULL);
786 			break;
787 #endif
788 		case KEY_RSA:
789 			ok = PEM_write_RSAPrivateKey(stdout, k->rsa, NULL,
790 			    NULL, 0, NULL, NULL);
791 			break;
792 		default:
793 			fatal_f("unsupported key type %s", sshkey_type(k));
794 		}
795 	}
796 
797 	if (!ok)
798 		fatal("key write failed");
799 	sshkey_free(k);
800 	exit(0);
801 }
802 #endif
803 
804 static void
805 do_print_public(struct passwd *pw)
806 {
807 	struct sshkey *prv;
808 	struct stat st;
809 	int r;
810 	char *comment = NULL;
811 
812 	if (!have_identity)
813 		ask_filename(pw, "Enter file in which the key is");
814 	if (stat(identity_file, &st) == -1)
815 		fatal("%s: %s", identity_file, strerror(errno));
816 	prv = load_identity(identity_file, &comment);
817 	if ((r = sshkey_write(prv, stdout)) != 0)
818 		fatal_fr(r, "write key");
819 	if (comment != NULL && *comment != '\0')
820 		fprintf(stdout, " %s", comment);
821 	fprintf(stdout, "\n");
822 	if (sshkey_is_sk(prv)) {
823 		debug("sk_application: \"%s\", sk_flags 0x%02x",
824 			prv->sk_application, prv->sk_flags);
825 	}
826 	sshkey_free(prv);
827 	free(comment);
828 	exit(0);
829 }
830 
831 static void
832 do_download(struct passwd *pw)
833 {
834 #ifdef ENABLE_PKCS11
835 	struct sshkey **keys = NULL;
836 	int i, nkeys;
837 	enum sshkey_fp_rep rep;
838 	int fptype;
839 	char *fp, *ra, **comments = NULL;
840 
841 	fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
842 	rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
843 
844 	pkcs11_init(1);
845 	nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys, &comments);
846 	if (nkeys <= 0)
847 		fatal("cannot read public key from pkcs11");
848 	for (i = 0; i < nkeys; i++) {
849 		if (print_fingerprint) {
850 			fp = sshkey_fingerprint(keys[i], fptype, rep);
851 			ra = sshkey_fingerprint(keys[i], fingerprint_hash,
852 			    SSH_FP_RANDOMART);
853 			if (fp == NULL || ra == NULL)
854 				fatal_f("sshkey_fingerprint fail");
855 			printf("%u %s %s (PKCS11 key)\n", sshkey_size(keys[i]),
856 			    fp, sshkey_type(keys[i]));
857 			if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
858 				printf("%s\n", ra);
859 			free(ra);
860 			free(fp);
861 		} else {
862 			(void) sshkey_write(keys[i], stdout); /* XXX check */
863 			fprintf(stdout, "%s%s\n",
864 			    *(comments[i]) == '\0' ? "" : " ", comments[i]);
865 		}
866 		free(comments[i]);
867 		sshkey_free(keys[i]);
868 	}
869 	free(comments);
870 	free(keys);
871 	pkcs11_terminate();
872 	exit(0);
873 #else
874 	fatal("no pkcs11 support");
875 #endif /* ENABLE_PKCS11 */
876 }
877 
878 static struct sshkey *
879 try_read_key(char **cpp)
880 {
881 	struct sshkey *ret;
882 	int r;
883 
884 	if ((ret = sshkey_new(KEY_UNSPEC)) == NULL)
885 		fatal("sshkey_new failed");
886 	if ((r = sshkey_read(ret, cpp)) == 0)
887 		return ret;
888 	/* Not a key */
889 	sshkey_free(ret);
890 	return NULL;
891 }
892 
893 static void
894 fingerprint_one_key(const struct sshkey *public, const char *comment)
895 {
896 	char *fp = NULL, *ra = NULL;
897 	enum sshkey_fp_rep rep;
898 	int fptype;
899 
900 	fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
901 	rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
902 	fp = sshkey_fingerprint(public, fptype, rep);
903 	ra = sshkey_fingerprint(public, fingerprint_hash, SSH_FP_RANDOMART);
904 	if (fp == NULL || ra == NULL)
905 		fatal_f("sshkey_fingerprint failed");
906 	mprintf("%u %s %s (%s)\n", sshkey_size(public), fp,
907 	    comment ? comment : "no comment", sshkey_type(public));
908 	if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
909 		printf("%s\n", ra);
910 	free(ra);
911 	free(fp);
912 }
913 
914 static void
915 fingerprint_private(const char *path)
916 {
917 	struct stat st;
918 	char *comment = NULL;
919 	struct sshkey *privkey = NULL, *pubkey = NULL;
920 	int r;
921 
922 	if (stat(identity_file, &st) == -1)
923 		fatal("%s: %s", path, strerror(errno));
924 	if ((r = sshkey_load_public(path, &pubkey, &comment)) != 0)
925 		debug_r(r, "load public \"%s\"", path);
926 	if (pubkey == NULL || comment == NULL || *comment == '\0') {
927 		free(comment);
928 		if ((r = sshkey_load_private(path, NULL,
929 		    &privkey, &comment)) != 0)
930 			debug_r(r, "load private \"%s\"", path);
931 	}
932 	if (pubkey == NULL && privkey == NULL)
933 		fatal("%s is not a key file.", path);
934 
935 	fingerprint_one_key(pubkey == NULL ? privkey : pubkey, comment);
936 	sshkey_free(pubkey);
937 	sshkey_free(privkey);
938 	free(comment);
939 }
940 
941 static void
942 do_fingerprint(struct passwd *pw)
943 {
944 	FILE *f;
945 	struct sshkey *public = NULL;
946 	char *comment = NULL, *cp, *ep, *line = NULL;
947 	size_t linesize = 0;
948 	int i, invalid = 1;
949 	const char *path;
950 	u_long lnum = 0;
951 
952 	if (!have_identity)
953 		ask_filename(pw, "Enter file in which the key is");
954 	path = identity_file;
955 
956 	if (strcmp(identity_file, "-") == 0) {
957 		f = stdin;
958 		path = "(stdin)";
959 	} else if ((f = fopen(path, "r")) == NULL)
960 		fatal("%s: %s: %s", __progname, path, strerror(errno));
961 
962 	while (getline(&line, &linesize, f) != -1) {
963 		lnum++;
964 		cp = line;
965 		cp[strcspn(cp, "\n")] = '\0';
966 		/* Trim leading space and comments */
967 		cp = line + strspn(line, " \t");
968 		if (*cp == '#' || *cp == '\0')
969 			continue;
970 
971 		/*
972 		 * Input may be plain keys, private keys, authorized_keys
973 		 * or known_hosts.
974 		 */
975 
976 		/*
977 		 * Try private keys first. Assume a key is private if
978 		 * "SSH PRIVATE KEY" appears on the first line and we're
979 		 * not reading from stdin (XXX support private keys on stdin).
980 		 */
981 		if (lnum == 1 && strcmp(identity_file, "-") != 0 &&
982 		    strstr(cp, "PRIVATE KEY") != NULL) {
983 			free(line);
984 			fclose(f);
985 			fingerprint_private(path);
986 			exit(0);
987 		}
988 
989 		/*
990 		 * If it's not a private key, then this must be prepared to
991 		 * accept a public key prefixed with a hostname or options.
992 		 * Try a bare key first, otherwise skip the leading stuff.
993 		 */
994 		if ((public = try_read_key(&cp)) == NULL) {
995 			i = strtol(cp, &ep, 10);
996 			if (i == 0 || ep == NULL ||
997 			    (*ep != ' ' && *ep != '\t')) {
998 				int quoted = 0;
999 
1000 				comment = cp;
1001 				for (; *cp && (quoted || (*cp != ' ' &&
1002 				    *cp != '\t')); cp++) {
1003 					if (*cp == '\\' && cp[1] == '"')
1004 						cp++;	/* Skip both */
1005 					else if (*cp == '"')
1006 						quoted = !quoted;
1007 				}
1008 				if (!*cp)
1009 					continue;
1010 				*cp++ = '\0';
1011 			}
1012 		}
1013 		/* Retry after parsing leading hostname/key options */
1014 		if (public == NULL && (public = try_read_key(&cp)) == NULL) {
1015 			debug("%s:%lu: not a public key", path, lnum);
1016 			continue;
1017 		}
1018 
1019 		/* Find trailing comment, if any */
1020 		for (; *cp == ' ' || *cp == '\t'; cp++)
1021 			;
1022 		if (*cp != '\0' && *cp != '#')
1023 			comment = cp;
1024 
1025 		fingerprint_one_key(public, comment);
1026 		sshkey_free(public);
1027 		invalid = 0; /* One good key in the file is sufficient */
1028 	}
1029 	fclose(f);
1030 	free(line);
1031 
1032 	if (invalid)
1033 		fatal("%s is not a public key file.", path);
1034 	exit(0);
1035 }
1036 
1037 static void
1038 do_gen_all_hostkeys(struct passwd *pw)
1039 {
1040 	struct {
1041 		char *key_type;
1042 		char *key_type_display;
1043 		char *path;
1044 	} key_types[] = {
1045 #ifdef WITH_OPENSSL
1046 		{ "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE },
1047 		{ "dsa", "DSA", _PATH_HOST_DSA_KEY_FILE },
1048 #ifdef OPENSSL_HAS_ECC
1049 		{ "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE },
1050 #endif /* OPENSSL_HAS_ECC */
1051 #endif /* WITH_OPENSSL */
1052 		{ "ed25519", "ED25519",_PATH_HOST_ED25519_KEY_FILE },
1053 #ifdef WITH_XMSS
1054 		{ "xmss", "XMSS",_PATH_HOST_XMSS_KEY_FILE },
1055 #endif /* WITH_XMSS */
1056 		{ NULL, NULL, NULL }
1057 	};
1058 
1059 	u_int32_t bits = 0;
1060 	int first = 0;
1061 	struct stat st;
1062 	struct sshkey *private, *public;
1063 	char comment[1024], *prv_tmp, *pub_tmp, *prv_file, *pub_file;
1064 	int i, type, fd, r;
1065 
1066 	for (i = 0; key_types[i].key_type; i++) {
1067 		public = private = NULL;
1068 		prv_tmp = pub_tmp = prv_file = pub_file = NULL;
1069 
1070 		xasprintf(&prv_file, "%s%s",
1071 		    identity_file, key_types[i].path);
1072 
1073 		/* Check whether private key exists and is not zero-length */
1074 		if (stat(prv_file, &st) == 0) {
1075 			if (st.st_size != 0)
1076 				goto next;
1077 		} else if (errno != ENOENT) {
1078 			error("Could not stat %s: %s", key_types[i].path,
1079 			    strerror(errno));
1080 			goto failnext;
1081 		}
1082 
1083 		/*
1084 		 * Private key doesn't exist or is invalid; proceed with
1085 		 * key generation.
1086 		 */
1087 		xasprintf(&prv_tmp, "%s%s.XXXXXXXXXX",
1088 		    identity_file, key_types[i].path);
1089 		xasprintf(&pub_tmp, "%s%s.pub.XXXXXXXXXX",
1090 		    identity_file, key_types[i].path);
1091 		xasprintf(&pub_file, "%s%s.pub",
1092 		    identity_file, key_types[i].path);
1093 
1094 		if (first == 0) {
1095 			first = 1;
1096 			printf("%s: generating new host keys: ", __progname);
1097 		}
1098 		printf("%s ", key_types[i].key_type_display);
1099 		fflush(stdout);
1100 		type = sshkey_type_from_name(key_types[i].key_type);
1101 		if ((fd = mkstemp(prv_tmp)) == -1) {
1102 			error("Could not save your private key in %s: %s",
1103 			    prv_tmp, strerror(errno));
1104 			goto failnext;
1105 		}
1106 		(void)close(fd); /* just using mkstemp() to reserve a name */
1107 		bits = 0;
1108 		type_bits_valid(type, NULL, &bits);
1109 		if ((r = sshkey_generate(type, bits, &private)) != 0) {
1110 			error_r(r, "sshkey_generate failed");
1111 			goto failnext;
1112 		}
1113 		if ((r = sshkey_from_private(private, &public)) != 0)
1114 			fatal_fr(r, "sshkey_from_private");
1115 		snprintf(comment, sizeof comment, "%s@%s", pw->pw_name,
1116 		    hostname);
1117 		if ((r = sshkey_save_private(private, prv_tmp, "",
1118 		    comment, private_key_format, openssh_format_cipher,
1119 		    rounds)) != 0) {
1120 			error_r(r, "Saving key \"%s\" failed", prv_tmp);
1121 			goto failnext;
1122 		}
1123 		if ((fd = mkstemp(pub_tmp)) == -1) {
1124 			error("Could not save your public key in %s: %s",
1125 			    pub_tmp, strerror(errno));
1126 			goto failnext;
1127 		}
1128 		(void)fchmod(fd, 0644);
1129 		(void)close(fd);
1130 		if ((r = sshkey_save_public(public, pub_tmp, comment)) != 0) {
1131 			error_r(r, "Unable to save public key to %s",
1132 			    identity_file);
1133 			goto failnext;
1134 		}
1135 
1136 		/* Rename temporary files to their permanent locations. */
1137 		if (rename(pub_tmp, pub_file) != 0) {
1138 			error("Unable to move %s into position: %s",
1139 			    pub_file, strerror(errno));
1140 			goto failnext;
1141 		}
1142 		if (rename(prv_tmp, prv_file) != 0) {
1143 			error("Unable to move %s into position: %s",
1144 			    key_types[i].path, strerror(errno));
1145  failnext:
1146 			first = 0;
1147 			goto next;
1148 		}
1149  next:
1150 		sshkey_free(private);
1151 		sshkey_free(public);
1152 		free(prv_tmp);
1153 		free(pub_tmp);
1154 		free(prv_file);
1155 		free(pub_file);
1156 	}
1157 	if (first != 0)
1158 		printf("\n");
1159 }
1160 
1161 struct known_hosts_ctx {
1162 	const char *host;	/* Hostname searched for in find/delete case */
1163 	FILE *out;		/* Output file, stdout for find_hosts case */
1164 	int has_unhashed;	/* When hashing, original had unhashed hosts */
1165 	int found_key;		/* For find/delete, host was found */
1166 	int invalid;		/* File contained invalid items; don't delete */
1167 	int hash_hosts;		/* Hash hostnames as we go */
1168 	int find_host;		/* Search for specific hostname */
1169 	int delete_host;	/* Delete host from known_hosts */
1170 };
1171 
1172 static int
1173 known_hosts_hash(struct hostkey_foreach_line *l, void *_ctx)
1174 {
1175 	struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1176 	char *hashed, *cp, *hosts, *ohosts;
1177 	int has_wild = l->hosts && strcspn(l->hosts, "*?!") != strlen(l->hosts);
1178 	int was_hashed = l->hosts && l->hosts[0] == HASH_DELIM;
1179 
1180 	switch (l->status) {
1181 	case HKF_STATUS_OK:
1182 	case HKF_STATUS_MATCHED:
1183 		/*
1184 		 * Don't hash hosts already already hashed, with wildcard
1185 		 * characters or a CA/revocation marker.
1186 		 */
1187 		if (was_hashed || has_wild || l->marker != MRK_NONE) {
1188 			fprintf(ctx->out, "%s\n", l->line);
1189 			if (has_wild && !ctx->find_host) {
1190 				logit("%s:%lu: ignoring host name "
1191 				    "with wildcard: %.64s", l->path,
1192 				    l->linenum, l->hosts);
1193 			}
1194 			return 0;
1195 		}
1196 		/*
1197 		 * Split any comma-separated hostnames from the host list,
1198 		 * hash and store separately.
1199 		 */
1200 		ohosts = hosts = xstrdup(l->hosts);
1201 		while ((cp = strsep(&hosts, ",")) != NULL && *cp != '\0') {
1202 			lowercase(cp);
1203 			if ((hashed = host_hash(cp, NULL, 0)) == NULL)
1204 				fatal("hash_host failed");
1205 			fprintf(ctx->out, "%s %s\n", hashed, l->rawkey);
1206 			ctx->has_unhashed = 1;
1207 		}
1208 		free(ohosts);
1209 		return 0;
1210 	case HKF_STATUS_INVALID:
1211 		/* Retain invalid lines, but mark file as invalid. */
1212 		ctx->invalid = 1;
1213 		logit("%s:%lu: invalid line", l->path, l->linenum);
1214 		/* FALLTHROUGH */
1215 	default:
1216 		fprintf(ctx->out, "%s\n", l->line);
1217 		return 0;
1218 	}
1219 	/* NOTREACHED */
1220 	return -1;
1221 }
1222 
1223 static int
1224 known_hosts_find_delete(struct hostkey_foreach_line *l, void *_ctx)
1225 {
1226 	struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1227 	enum sshkey_fp_rep rep;
1228 	int fptype;
1229 	char *fp = NULL, *ra = NULL;
1230 
1231 	fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
1232 	rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1233 
1234 	if (l->status == HKF_STATUS_MATCHED) {
1235 		if (ctx->delete_host) {
1236 			if (l->marker != MRK_NONE) {
1237 				/* Don't remove CA and revocation lines */
1238 				fprintf(ctx->out, "%s\n", l->line);
1239 			} else {
1240 				/*
1241 				 * Hostname matches and has no CA/revoke
1242 				 * marker, delete it by *not* writing the
1243 				 * line to ctx->out.
1244 				 */
1245 				ctx->found_key = 1;
1246 				if (!quiet)
1247 					printf("# Host %s found: line %lu\n",
1248 					    ctx->host, l->linenum);
1249 			}
1250 			return 0;
1251 		} else if (ctx->find_host) {
1252 			ctx->found_key = 1;
1253 			if (!quiet) {
1254 				printf("# Host %s found: line %lu %s\n",
1255 				    ctx->host,
1256 				    l->linenum, l->marker == MRK_CA ? "CA" :
1257 				    (l->marker == MRK_REVOKE ? "REVOKED" : ""));
1258 			}
1259 			if (ctx->hash_hosts)
1260 				known_hosts_hash(l, ctx);
1261 			else if (print_fingerprint) {
1262 				fp = sshkey_fingerprint(l->key, fptype, rep);
1263 				ra = sshkey_fingerprint(l->key,
1264 				    fingerprint_hash, SSH_FP_RANDOMART);
1265 				if (fp == NULL || ra == NULL)
1266 					fatal_f("sshkey_fingerprint failed");
1267 				mprintf("%s %s %s%s%s\n", ctx->host,
1268 				    sshkey_type(l->key), fp,
1269 				    l->comment[0] ? " " : "",
1270 				    l->comment);
1271 				if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
1272 					printf("%s\n", ra);
1273 				free(ra);
1274 				free(fp);
1275 			} else
1276 				fprintf(ctx->out, "%s\n", l->line);
1277 			return 0;
1278 		}
1279 	} else if (ctx->delete_host) {
1280 		/* Retain non-matching hosts when deleting */
1281 		if (l->status == HKF_STATUS_INVALID) {
1282 			ctx->invalid = 1;
1283 			logit("%s:%lu: invalid line", l->path, l->linenum);
1284 		}
1285 		fprintf(ctx->out, "%s\n", l->line);
1286 	}
1287 	return 0;
1288 }
1289 
1290 static void
1291 do_known_hosts(struct passwd *pw, const char *name, int find_host,
1292     int delete_host, int hash_hosts)
1293 {
1294 	char *cp, tmp[PATH_MAX], old[PATH_MAX];
1295 	int r, fd, oerrno, inplace = 0;
1296 	struct known_hosts_ctx ctx;
1297 	u_int foreach_options;
1298 	struct stat sb;
1299 
1300 	if (!have_identity) {
1301 		cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
1302 		if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
1303 		    sizeof(identity_file))
1304 			fatal("Specified known hosts path too long");
1305 		free(cp);
1306 		have_identity = 1;
1307 	}
1308 	if (stat(identity_file, &sb) != 0)
1309 		fatal("Cannot stat %s: %s", identity_file, strerror(errno));
1310 
1311 	memset(&ctx, 0, sizeof(ctx));
1312 	ctx.out = stdout;
1313 	ctx.host = name;
1314 	ctx.hash_hosts = hash_hosts;
1315 	ctx.find_host = find_host;
1316 	ctx.delete_host = delete_host;
1317 
1318 	/*
1319 	 * Find hosts goes to stdout, hash and deletions happen in-place
1320 	 * A corner case is ssh-keygen -HF foo, which should go to stdout
1321 	 */
1322 	if (!find_host && (hash_hosts || delete_host)) {
1323 		if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
1324 		    strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
1325 		    strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
1326 		    strlcat(old, ".old", sizeof(old)) >= sizeof(old))
1327 			fatal("known_hosts path too long");
1328 		umask(077);
1329 		if ((fd = mkstemp(tmp)) == -1)
1330 			fatal("mkstemp: %s", strerror(errno));
1331 		if ((ctx.out = fdopen(fd, "w")) == NULL) {
1332 			oerrno = errno;
1333 			unlink(tmp);
1334 			fatal("fdopen: %s", strerror(oerrno));
1335 		}
1336 		fchmod(fd, sb.st_mode & 0644);
1337 		inplace = 1;
1338 	}
1339 	/* XXX support identity_file == "-" for stdin */
1340 	foreach_options = find_host ? HKF_WANT_MATCH : 0;
1341 	foreach_options |= print_fingerprint ? HKF_WANT_PARSE_KEY : 0;
1342 	if ((r = hostkeys_foreach(identity_file, (find_host || !hash_hosts) ?
1343 	    known_hosts_find_delete : known_hosts_hash, &ctx, name, NULL,
1344 	    foreach_options, 0)) != 0) {
1345 		if (inplace)
1346 			unlink(tmp);
1347 		fatal_fr(r, "hostkeys_foreach");
1348 	}
1349 
1350 	if (inplace)
1351 		fclose(ctx.out);
1352 
1353 	if (ctx.invalid) {
1354 		error("%s is not a valid known_hosts file.", identity_file);
1355 		if (inplace) {
1356 			error("Not replacing existing known_hosts "
1357 			    "file because of errors");
1358 			unlink(tmp);
1359 		}
1360 		exit(1);
1361 	} else if (delete_host && !ctx.found_key) {
1362 		logit("Host %s not found in %s", name, identity_file);
1363 		if (inplace)
1364 			unlink(tmp);
1365 	} else if (inplace) {
1366 		/* Backup existing file */
1367 		if (unlink(old) == -1 && errno != ENOENT)
1368 			fatal("unlink %.100s: %s", old, strerror(errno));
1369 		if (link(identity_file, old) == -1)
1370 			fatal("link %.100s to %.100s: %s", identity_file, old,
1371 			    strerror(errno));
1372 		/* Move new one into place */
1373 		if (rename(tmp, identity_file) == -1) {
1374 			error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
1375 			    strerror(errno));
1376 			unlink(tmp);
1377 			unlink(old);
1378 			exit(1);
1379 		}
1380 
1381 		printf("%s updated.\n", identity_file);
1382 		printf("Original contents retained as %s\n", old);
1383 		if (ctx.has_unhashed) {
1384 			logit("WARNING: %s contains unhashed entries", old);
1385 			logit("Delete this file to ensure privacy "
1386 			    "of hostnames");
1387 		}
1388 	}
1389 
1390 	exit (find_host && !ctx.found_key);
1391 }
1392 
1393 /*
1394  * Perform changing a passphrase.  The argument is the passwd structure
1395  * for the current user.
1396  */
1397 static void
1398 do_change_passphrase(struct passwd *pw)
1399 {
1400 	char *comment;
1401 	char *old_passphrase, *passphrase1, *passphrase2;
1402 	struct stat st;
1403 	struct sshkey *private;
1404 	int r;
1405 
1406 	if (!have_identity)
1407 		ask_filename(pw, "Enter file in which the key is");
1408 	if (stat(identity_file, &st) == -1)
1409 		fatal("%s: %s", identity_file, strerror(errno));
1410 	/* Try to load the file with empty passphrase. */
1411 	r = sshkey_load_private(identity_file, "", &private, &comment);
1412 	if (r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
1413 		if (identity_passphrase)
1414 			old_passphrase = xstrdup(identity_passphrase);
1415 		else
1416 			old_passphrase =
1417 			    read_passphrase("Enter old passphrase: ",
1418 			    RP_ALLOW_STDIN);
1419 		r = sshkey_load_private(identity_file, old_passphrase,
1420 		    &private, &comment);
1421 		freezero(old_passphrase, strlen(old_passphrase));
1422 		if (r != 0)
1423 			goto badkey;
1424 	} else if (r != 0) {
1425  badkey:
1426 		fatal_r(r, "Failed to load key %s", identity_file);
1427 	}
1428 	if (comment)
1429 		mprintf("Key has comment '%s'\n", comment);
1430 
1431 	/* Ask the new passphrase (twice). */
1432 	if (identity_new_passphrase) {
1433 		passphrase1 = xstrdup(identity_new_passphrase);
1434 		passphrase2 = NULL;
1435 	} else {
1436 		passphrase1 =
1437 			read_passphrase("Enter new passphrase (empty for no "
1438 			    "passphrase): ", RP_ALLOW_STDIN);
1439 		passphrase2 = read_passphrase("Enter same passphrase again: ",
1440 		    RP_ALLOW_STDIN);
1441 
1442 		/* Verify that they are the same. */
1443 		if (strcmp(passphrase1, passphrase2) != 0) {
1444 			explicit_bzero(passphrase1, strlen(passphrase1));
1445 			explicit_bzero(passphrase2, strlen(passphrase2));
1446 			free(passphrase1);
1447 			free(passphrase2);
1448 			printf("Pass phrases do not match.  Try again.\n");
1449 			exit(1);
1450 		}
1451 		/* Destroy the other copy. */
1452 		freezero(passphrase2, strlen(passphrase2));
1453 	}
1454 
1455 	/* Save the file using the new passphrase. */
1456 	if ((r = sshkey_save_private(private, identity_file, passphrase1,
1457 	    comment, private_key_format, openssh_format_cipher, rounds)) != 0) {
1458 		error_r(r, "Saving key \"%s\" failed", identity_file);
1459 		freezero(passphrase1, strlen(passphrase1));
1460 		sshkey_free(private);
1461 		free(comment);
1462 		exit(1);
1463 	}
1464 	/* Destroy the passphrase and the copy of the key in memory. */
1465 	freezero(passphrase1, strlen(passphrase1));
1466 	sshkey_free(private);		 /* Destroys contents */
1467 	free(comment);
1468 
1469 	printf("Your identification has been saved with the new passphrase.\n");
1470 	exit(0);
1471 }
1472 
1473 /*
1474  * Print the SSHFP RR.
1475  */
1476 static int
1477 do_print_resource_record(struct passwd *pw, char *fname, char *hname,
1478     int print_generic)
1479 {
1480 	struct sshkey *public;
1481 	char *comment = NULL;
1482 	struct stat st;
1483 	int r;
1484 
1485 	if (fname == NULL)
1486 		fatal_f("no filename");
1487 	if (stat(fname, &st) == -1) {
1488 		if (errno == ENOENT)
1489 			return 0;
1490 		fatal("%s: %s", fname, strerror(errno));
1491 	}
1492 	if ((r = sshkey_load_public(fname, &public, &comment)) != 0)
1493 		fatal_r(r, "Failed to read v2 public key from \"%s\"", fname);
1494 	export_dns_rr(hname, public, stdout, print_generic);
1495 	sshkey_free(public);
1496 	free(comment);
1497 	return 1;
1498 }
1499 
1500 /*
1501  * Change the comment of a private key file.
1502  */
1503 static void
1504 do_change_comment(struct passwd *pw, const char *identity_comment)
1505 {
1506 	char new_comment[1024], *comment, *passphrase;
1507 	struct sshkey *private;
1508 	struct sshkey *public;
1509 	struct stat st;
1510 	int r;
1511 
1512 	if (!have_identity)
1513 		ask_filename(pw, "Enter file in which the key is");
1514 	if (stat(identity_file, &st) == -1)
1515 		fatal("%s: %s", identity_file, strerror(errno));
1516 	if ((r = sshkey_load_private(identity_file, "",
1517 	    &private, &comment)) == 0)
1518 		passphrase = xstrdup("");
1519 	else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
1520 		fatal_r(r, "Cannot load private key \"%s\"", identity_file);
1521 	else {
1522 		if (identity_passphrase)
1523 			passphrase = xstrdup(identity_passphrase);
1524 		else if (identity_new_passphrase)
1525 			passphrase = xstrdup(identity_new_passphrase);
1526 		else
1527 			passphrase = read_passphrase("Enter passphrase: ",
1528 			    RP_ALLOW_STDIN);
1529 		/* Try to load using the passphrase. */
1530 		if ((r = sshkey_load_private(identity_file, passphrase,
1531 		    &private, &comment)) != 0) {
1532 			freezero(passphrase, strlen(passphrase));
1533 			fatal_r(r, "Cannot load private key \"%s\"",
1534 			    identity_file);
1535 		}
1536 	}
1537 
1538 	if (private->type != KEY_ED25519 && private->type != KEY_XMSS &&
1539 	    private_key_format != SSHKEY_PRIVATE_OPENSSH) {
1540 		error("Comments are only supported for keys stored in "
1541 		    "the new format (-o).");
1542 		explicit_bzero(passphrase, strlen(passphrase));
1543 		sshkey_free(private);
1544 		exit(1);
1545 	}
1546 	if (comment)
1547 		printf("Old comment: %s\n", comment);
1548 	else
1549 		printf("No existing comment\n");
1550 
1551 	if (identity_comment) {
1552 		strlcpy(new_comment, identity_comment, sizeof(new_comment));
1553 	} else {
1554 		printf("New comment: ");
1555 		fflush(stdout);
1556 		if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1557 			explicit_bzero(passphrase, strlen(passphrase));
1558 			sshkey_free(private);
1559 			exit(1);
1560 		}
1561 		new_comment[strcspn(new_comment, "\n")] = '\0';
1562 	}
1563 	if (comment != NULL && strcmp(comment, new_comment) == 0) {
1564 		printf("No change to comment\n");
1565 		free(passphrase);
1566 		sshkey_free(private);
1567 		free(comment);
1568 		exit(0);
1569 	}
1570 
1571 	/* Save the file using the new passphrase. */
1572 	if ((r = sshkey_save_private(private, identity_file, passphrase,
1573 	    new_comment, private_key_format, openssh_format_cipher,
1574 	    rounds)) != 0) {
1575 		error_r(r, "Saving key \"%s\" failed", identity_file);
1576 		freezero(passphrase, strlen(passphrase));
1577 		sshkey_free(private);
1578 		free(comment);
1579 		exit(1);
1580 	}
1581 	freezero(passphrase, strlen(passphrase));
1582 	if ((r = sshkey_from_private(private, &public)) != 0)
1583 		fatal_fr(r, "sshkey_from_private");
1584 	sshkey_free(private);
1585 
1586 	strlcat(identity_file, ".pub", sizeof(identity_file));
1587 	if ((r = sshkey_save_public(public, identity_file, new_comment)) != 0)
1588 		fatal_r(r, "Unable to save public key to %s", identity_file);
1589 	sshkey_free(public);
1590 	free(comment);
1591 
1592 	if (strlen(new_comment) > 0)
1593 		printf("Comment '%s' applied\n", new_comment);
1594 	else
1595 		printf("Comment removed\n");
1596 
1597 	exit(0);
1598 }
1599 
1600 static void
1601 cert_ext_add(const char *key, const char *value, int iscrit)
1602 {
1603 	cert_ext = xreallocarray(cert_ext, ncert_ext + 1, sizeof(*cert_ext));
1604 	cert_ext[ncert_ext].key = xstrdup(key);
1605 	cert_ext[ncert_ext].val = value == NULL ? NULL : xstrdup(value);
1606 	cert_ext[ncert_ext].crit = iscrit;
1607 	ncert_ext++;
1608 }
1609 
1610 /* qsort(3) comparison function for certificate extensions */
1611 static int
1612 cert_ext_cmp(const void *_a, const void *_b)
1613 {
1614 	const struct cert_ext *a = (const struct cert_ext *)_a;
1615 	const struct cert_ext *b = (const struct cert_ext *)_b;
1616 	int r;
1617 
1618 	if (a->crit != b->crit)
1619 		return (a->crit < b->crit) ? -1 : 1;
1620 	if ((r = strcmp(a->key, b->key)) != 0)
1621 		return r;
1622 	if ((a->val == NULL) != (b->val == NULL))
1623 		return (a->val == NULL) ? -1 : 1;
1624 	if (a->val != NULL && (r = strcmp(a->val, b->val)) != 0)
1625 		return r;
1626 	return 0;
1627 }
1628 
1629 #define OPTIONS_CRITICAL	1
1630 #define OPTIONS_EXTENSIONS	2
1631 static void
1632 prepare_options_buf(struct sshbuf *c, int which)
1633 {
1634 	struct sshbuf *b;
1635 	size_t i;
1636 	int r;
1637 	const struct cert_ext *ext;
1638 
1639 	if ((b = sshbuf_new()) == NULL)
1640 		fatal_f("sshbuf_new failed");
1641 	sshbuf_reset(c);
1642 	for (i = 0; i < ncert_ext; i++) {
1643 		ext = &cert_ext[i];
1644 		if ((ext->crit && (which & OPTIONS_EXTENSIONS)) ||
1645 		    (!ext->crit && (which & OPTIONS_CRITICAL)))
1646 			continue;
1647 		if (ext->val == NULL) {
1648 			/* flag option */
1649 			debug3_f("%s", ext->key);
1650 			if ((r = sshbuf_put_cstring(c, ext->key)) != 0 ||
1651 			    (r = sshbuf_put_string(c, NULL, 0)) != 0)
1652 				fatal_fr(r, "prepare flag");
1653 		} else {
1654 			/* key/value option */
1655 			debug3_f("%s=%s", ext->key, ext->val);
1656 			sshbuf_reset(b);
1657 			if ((r = sshbuf_put_cstring(c, ext->key)) != 0 ||
1658 			    (r = sshbuf_put_cstring(b, ext->val)) != 0 ||
1659 			    (r = sshbuf_put_stringb(c, b)) != 0)
1660 				fatal_fr(r, "prepare k/v");
1661 		}
1662 	}
1663 	sshbuf_free(b);
1664 }
1665 
1666 static void
1667 finalise_cert_exts(void)
1668 {
1669 	/* critical options */
1670 	if (certflags_command != NULL)
1671 		cert_ext_add("force-command", certflags_command, 1);
1672 	if (certflags_src_addr != NULL)
1673 		cert_ext_add("source-address", certflags_src_addr, 1);
1674 	/* extensions */
1675 	if ((certflags_flags & CERTOPT_X_FWD) != 0)
1676 		cert_ext_add("permit-X11-forwarding", NULL, 0);
1677 	if ((certflags_flags & CERTOPT_AGENT_FWD) != 0)
1678 		cert_ext_add("permit-agent-forwarding", NULL, 0);
1679 	if ((certflags_flags & CERTOPT_PORT_FWD) != 0)
1680 		cert_ext_add("permit-port-forwarding", NULL, 0);
1681 	if ((certflags_flags & CERTOPT_PTY) != 0)
1682 		cert_ext_add("permit-pty", NULL, 0);
1683 	if ((certflags_flags & CERTOPT_USER_RC) != 0)
1684 		cert_ext_add("permit-user-rc", NULL, 0);
1685 	if ((certflags_flags & CERTOPT_NO_REQUIRE_USER_PRESENCE) != 0)
1686 		cert_ext_add("no-touch-required", NULL, 0);
1687 	/* order lexically by key */
1688 	if (ncert_ext > 0)
1689 		qsort(cert_ext, ncert_ext, sizeof(*cert_ext), cert_ext_cmp);
1690 }
1691 
1692 static struct sshkey *
1693 load_pkcs11_key(char *path)
1694 {
1695 #ifdef ENABLE_PKCS11
1696 	struct sshkey **keys = NULL, *public, *private = NULL;
1697 	int r, i, nkeys;
1698 
1699 	if ((r = sshkey_load_public(path, &public, NULL)) != 0)
1700 		fatal_r(r, "Couldn't load CA public key \"%s\"", path);
1701 
1702 	nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase,
1703 	    &keys, NULL);
1704 	debug3_f("%d keys", nkeys);
1705 	if (nkeys <= 0)
1706 		fatal("cannot read public key from pkcs11");
1707 	for (i = 0; i < nkeys; i++) {
1708 		if (sshkey_equal_public(public, keys[i])) {
1709 			private = keys[i];
1710 			continue;
1711 		}
1712 		sshkey_free(keys[i]);
1713 	}
1714 	free(keys);
1715 	sshkey_free(public);
1716 	return private;
1717 #else
1718 	fatal("no pkcs11 support");
1719 #endif /* ENABLE_PKCS11 */
1720 }
1721 
1722 /* Signer for sshkey_certify_custom that uses the agent */
1723 static int
1724 agent_signer(struct sshkey *key, u_char **sigp, size_t *lenp,
1725     const u_char *data, size_t datalen,
1726     const char *alg, const char *provider, const char *pin,
1727     u_int compat, void *ctx)
1728 {
1729 	int *agent_fdp = (int *)ctx;
1730 
1731 	return ssh_agent_sign(*agent_fdp, key, sigp, lenp,
1732 	    data, datalen, alg, compat);
1733 }
1734 
1735 static void
1736 do_ca_sign(struct passwd *pw, const char *ca_key_path, int prefer_agent,
1737     unsigned long long cert_serial, int cert_serial_autoinc,
1738     int argc, char **argv)
1739 {
1740 	int r, i, found, agent_fd = -1;
1741 	u_int n;
1742 	struct sshkey *ca, *public;
1743 	char valid[64], *otmp, *tmp, *cp, *out, *comment;
1744 	char *ca_fp = NULL, **plist = NULL, *pin = NULL;
1745 	struct ssh_identitylist *agent_ids;
1746 	size_t j;
1747 	struct notifier_ctx *notifier = NULL;
1748 
1749 #ifdef ENABLE_PKCS11
1750 	pkcs11_init(1);
1751 #endif
1752 	tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
1753 	if (pkcs11provider != NULL) {
1754 		/* If a PKCS#11 token was specified then try to use it */
1755 		if ((ca = load_pkcs11_key(tmp)) == NULL)
1756 			fatal("No PKCS#11 key matching %s found", ca_key_path);
1757 	} else if (prefer_agent) {
1758 		/*
1759 		 * Agent signature requested. Try to use agent after making
1760 		 * sure the public key specified is actually present in the
1761 		 * agent.
1762 		 */
1763 		if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
1764 			fatal_r(r, "Cannot load CA public key %s", tmp);
1765 		if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
1766 			fatal_r(r, "Cannot use public key for CA signature");
1767 		if ((r = ssh_fetch_identitylist(agent_fd, &agent_ids)) != 0)
1768 			fatal_r(r, "Retrieve agent key list");
1769 		found = 0;
1770 		for (j = 0; j < agent_ids->nkeys; j++) {
1771 			if (sshkey_equal(ca, agent_ids->keys[j])) {
1772 				found = 1;
1773 				break;
1774 			}
1775 		}
1776 		if (!found)
1777 			fatal("CA key %s not found in agent", tmp);
1778 		ssh_free_identitylist(agent_ids);
1779 		ca->flags |= SSHKEY_FLAG_EXT;
1780 	} else {
1781 		/* CA key is assumed to be a private key on the filesystem */
1782 		ca = load_identity(tmp, NULL);
1783 		if (sshkey_is_sk(ca) &&
1784 		    (ca->sk_flags & SSH_SK_USER_VERIFICATION_REQD)) {
1785 			if ((pin = read_passphrase("Enter PIN for CA key: ",
1786 			    RP_ALLOW_STDIN)) == NULL)
1787 				fatal_f("couldn't read PIN");
1788 		}
1789 	}
1790 	free(tmp);
1791 
1792 	if (key_type_name != NULL) {
1793 		if (sshkey_type_from_name(key_type_name) != ca->type) {
1794 			fatal("CA key type %s doesn't match specified %s",
1795 			    sshkey_ssh_name(ca), key_type_name);
1796 		}
1797 	} else if (ca->type == KEY_RSA) {
1798 		/* Default to a good signature algorithm */
1799 		key_type_name = "rsa-sha2-512";
1800 	}
1801 	ca_fp = sshkey_fingerprint(ca, fingerprint_hash, SSH_FP_DEFAULT);
1802 
1803 	finalise_cert_exts();
1804 	for (i = 0; i < argc; i++) {
1805 		/* Split list of principals */
1806 		n = 0;
1807 		if (cert_principals != NULL) {
1808 			otmp = tmp = xstrdup(cert_principals);
1809 			plist = NULL;
1810 			for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1811 				plist = xreallocarray(plist, n + 1, sizeof(*plist));
1812 				if (*(plist[n] = xstrdup(cp)) == '\0')
1813 					fatal("Empty principal name");
1814 			}
1815 			free(otmp);
1816 		}
1817 		if (n > SSHKEY_CERT_MAX_PRINCIPALS)
1818 			fatal("Too many certificate principals specified");
1819 
1820 		tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1821 		if ((r = sshkey_load_public(tmp, &public, &comment)) != 0)
1822 			fatal_r(r, "load pubkey \"%s\"", tmp);
1823 		if (sshkey_is_cert(public))
1824 			fatal_f("key \"%s\" type %s cannot be certified",
1825 			    tmp, sshkey_type(public));
1826 
1827 		/* Prepare certificate to sign */
1828 		if ((r = sshkey_to_certified(public)) != 0)
1829 			fatal_r(r, "Could not upgrade key %s to certificate", tmp);
1830 		public->cert->type = cert_key_type;
1831 		public->cert->serial = (u_int64_t)cert_serial;
1832 		public->cert->key_id = xstrdup(cert_key_id);
1833 		public->cert->nprincipals = n;
1834 		public->cert->principals = plist;
1835 		public->cert->valid_after = cert_valid_from;
1836 		public->cert->valid_before = cert_valid_to;
1837 		prepare_options_buf(public->cert->critical, OPTIONS_CRITICAL);
1838 		prepare_options_buf(public->cert->extensions,
1839 		    OPTIONS_EXTENSIONS);
1840 		if ((r = sshkey_from_private(ca,
1841 		    &public->cert->signature_key)) != 0)
1842 			fatal_r(r, "sshkey_from_private (ca key)");
1843 
1844 		if (agent_fd != -1 && (ca->flags & SSHKEY_FLAG_EXT) != 0) {
1845 			if ((r = sshkey_certify_custom(public, ca,
1846 			    key_type_name, sk_provider, NULL, agent_signer,
1847 			    &agent_fd)) != 0)
1848 				fatal_r(r, "Couldn't certify %s via agent", tmp);
1849 		} else {
1850 			if (sshkey_is_sk(ca) &&
1851 			    (ca->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
1852 				notifier = notify_start(0,
1853 				    "Confirm user presence for key %s %s",
1854 				    sshkey_type(ca), ca_fp);
1855 			}
1856 			r = sshkey_certify(public, ca, key_type_name,
1857 			    sk_provider, pin);
1858 			notify_complete(notifier, "User presence confirmed");
1859 			if (r != 0)
1860 				fatal_r(r, "Couldn't certify key %s", tmp);
1861 		}
1862 
1863 		if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
1864 			*cp = '\0';
1865 		xasprintf(&out, "%s-cert.pub", tmp);
1866 		free(tmp);
1867 
1868 		if ((r = sshkey_save_public(public, out, comment)) != 0) {
1869 			fatal_r(r, "Unable to save public key to %s",
1870 			    identity_file);
1871 		}
1872 
1873 		if (!quiet) {
1874 			sshkey_format_cert_validity(public->cert,
1875 			    valid, sizeof(valid));
1876 			logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1877 			    "valid %s", sshkey_cert_type(public),
1878 			    out, public->cert->key_id,
1879 			    (unsigned long long)public->cert->serial,
1880 			    cert_principals != NULL ? " for " : "",
1881 			    cert_principals != NULL ? cert_principals : "",
1882 			    valid);
1883 		}
1884 
1885 		sshkey_free(public);
1886 		free(out);
1887 		if (cert_serial_autoinc)
1888 			cert_serial++;
1889 	}
1890 	if (pin != NULL)
1891 		freezero(pin, strlen(pin));
1892 	free(ca_fp);
1893 #ifdef ENABLE_PKCS11
1894 	pkcs11_terminate();
1895 #endif
1896 	exit(0);
1897 }
1898 
1899 static u_int64_t
1900 parse_relative_time(const char *s, time_t now)
1901 {
1902 	int64_t mul, secs;
1903 
1904 	mul = *s == '-' ? -1 : 1;
1905 
1906 	if ((secs = convtime(s + 1)) == -1)
1907 		fatal("Invalid relative certificate time %s", s);
1908 	if (mul == -1 && secs > now)
1909 		fatal("Certificate time %s cannot be represented", s);
1910 	return now + (u_int64_t)(secs * mul);
1911 }
1912 
1913 static void
1914 parse_cert_times(char *timespec)
1915 {
1916 	char *from, *to;
1917 	time_t now = time(NULL);
1918 	int64_t secs;
1919 
1920 	/* +timespec relative to now */
1921 	if (*timespec == '+' && strchr(timespec, ':') == NULL) {
1922 		if ((secs = convtime(timespec + 1)) == -1)
1923 			fatal("Invalid relative certificate life %s", timespec);
1924 		cert_valid_to = now + secs;
1925 		/*
1926 		 * Backdate certificate one minute to avoid problems on hosts
1927 		 * with poorly-synchronised clocks.
1928 		 */
1929 		cert_valid_from = ((now - 59)/ 60) * 60;
1930 		return;
1931 	}
1932 
1933 	/*
1934 	 * from:to, where
1935 	 * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "always"
1936 	 *   to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "forever"
1937 	 */
1938 	from = xstrdup(timespec);
1939 	to = strchr(from, ':');
1940 	if (to == NULL || from == to || *(to + 1) == '\0')
1941 		fatal("Invalid certificate life specification %s", timespec);
1942 	*to++ = '\0';
1943 
1944 	if (*from == '-' || *from == '+')
1945 		cert_valid_from = parse_relative_time(from, now);
1946 	else if (strcmp(from, "always") == 0)
1947 		cert_valid_from = 0;
1948 	else if (parse_absolute_time(from, &cert_valid_from) != 0)
1949 		fatal("Invalid from time \"%s\"", from);
1950 
1951 	if (*to == '-' || *to == '+')
1952 		cert_valid_to = parse_relative_time(to, now);
1953 	else if (strcmp(to, "forever") == 0)
1954 		cert_valid_to = ~(u_int64_t)0;
1955 	else if (parse_absolute_time(to, &cert_valid_to) != 0)
1956 		fatal("Invalid to time \"%s\"", to);
1957 
1958 	if (cert_valid_to <= cert_valid_from)
1959 		fatal("Empty certificate validity interval");
1960 	free(from);
1961 }
1962 
1963 static void
1964 add_cert_option(char *opt)
1965 {
1966 	char *val, *cp;
1967 	int iscrit = 0;
1968 
1969 	if (strcasecmp(opt, "clear") == 0)
1970 		certflags_flags = 0;
1971 	else if (strcasecmp(opt, "no-x11-forwarding") == 0)
1972 		certflags_flags &= ~CERTOPT_X_FWD;
1973 	else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
1974 		certflags_flags |= CERTOPT_X_FWD;
1975 	else if (strcasecmp(opt, "no-agent-forwarding") == 0)
1976 		certflags_flags &= ~CERTOPT_AGENT_FWD;
1977 	else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
1978 		certflags_flags |= CERTOPT_AGENT_FWD;
1979 	else if (strcasecmp(opt, "no-port-forwarding") == 0)
1980 		certflags_flags &= ~CERTOPT_PORT_FWD;
1981 	else if (strcasecmp(opt, "permit-port-forwarding") == 0)
1982 		certflags_flags |= CERTOPT_PORT_FWD;
1983 	else if (strcasecmp(opt, "no-pty") == 0)
1984 		certflags_flags &= ~CERTOPT_PTY;
1985 	else if (strcasecmp(opt, "permit-pty") == 0)
1986 		certflags_flags |= CERTOPT_PTY;
1987 	else if (strcasecmp(opt, "no-user-rc") == 0)
1988 		certflags_flags &= ~CERTOPT_USER_RC;
1989 	else if (strcasecmp(opt, "permit-user-rc") == 0)
1990 		certflags_flags |= CERTOPT_USER_RC;
1991 	else if (strcasecmp(opt, "touch-required") == 0)
1992 		certflags_flags &= ~CERTOPT_NO_REQUIRE_USER_PRESENCE;
1993 	else if (strcasecmp(opt, "no-touch-required") == 0)
1994 		certflags_flags |= CERTOPT_NO_REQUIRE_USER_PRESENCE;
1995 	else if (strncasecmp(opt, "force-command=", 14) == 0) {
1996 		val = opt + 14;
1997 		if (*val == '\0')
1998 			fatal("Empty force-command option");
1999 		if (certflags_command != NULL)
2000 			fatal("force-command already specified");
2001 		certflags_command = xstrdup(val);
2002 	} else if (strncasecmp(opt, "source-address=", 15) == 0) {
2003 		val = opt + 15;
2004 		if (*val == '\0')
2005 			fatal("Empty source-address option");
2006 		if (certflags_src_addr != NULL)
2007 			fatal("source-address already specified");
2008 		if (addr_match_cidr_list(NULL, val) != 0)
2009 			fatal("Invalid source-address list");
2010 		certflags_src_addr = xstrdup(val);
2011 	} else if (strncasecmp(opt, "extension:", 10) == 0 ||
2012 		   (iscrit = (strncasecmp(opt, "critical:", 9) == 0))) {
2013 		val = xstrdup(strchr(opt, ':') + 1);
2014 		if ((cp = strchr(val, '=')) != NULL)
2015 			*cp++ = '\0';
2016 		cert_ext_add(val, cp, iscrit);
2017 		free(val);
2018 	} else
2019 		fatal("Unsupported certificate option \"%s\"", opt);
2020 }
2021 
2022 static void
2023 show_options(struct sshbuf *optbuf, int in_critical)
2024 {
2025 	char *name, *arg, *hex;
2026 	struct sshbuf *options, *option = NULL;
2027 	int r;
2028 
2029 	if ((options = sshbuf_fromb(optbuf)) == NULL)
2030 		fatal_f("sshbuf_fromb failed");
2031 	while (sshbuf_len(options) != 0) {
2032 		sshbuf_free(option);
2033 		option = NULL;
2034 		if ((r = sshbuf_get_cstring(options, &name, NULL)) != 0 ||
2035 		    (r = sshbuf_froms(options, &option)) != 0)
2036 			fatal_fr(r, "parse option");
2037 		printf("                %s", name);
2038 		if (!in_critical &&
2039 		    (strcmp(name, "permit-X11-forwarding") == 0 ||
2040 		    strcmp(name, "permit-agent-forwarding") == 0 ||
2041 		    strcmp(name, "permit-port-forwarding") == 0 ||
2042 		    strcmp(name, "permit-pty") == 0 ||
2043 		    strcmp(name, "permit-user-rc") == 0 ||
2044 		    strcmp(name, "no-touch-required") == 0)) {
2045 			printf("\n");
2046 		} else if (in_critical &&
2047 		    (strcmp(name, "force-command") == 0 ||
2048 		    strcmp(name, "source-address") == 0)) {
2049 			if ((r = sshbuf_get_cstring(option, &arg, NULL)) != 0)
2050 				fatal_fr(r, "parse critical");
2051 			printf(" %s\n", arg);
2052 			free(arg);
2053 		} else if (sshbuf_len(option) > 0) {
2054 			hex = sshbuf_dtob16(option);
2055 			printf(" UNKNOWN OPTION: %s (len %zu)\n",
2056 			    hex, sshbuf_len(option));
2057 			sshbuf_reset(option);
2058 			free(hex);
2059 		} else
2060 			printf(" UNKNOWN FLAG OPTION\n");
2061 		free(name);
2062 		if (sshbuf_len(option) != 0)
2063 			fatal("Option corrupt: extra data at end");
2064 	}
2065 	sshbuf_free(option);
2066 	sshbuf_free(options);
2067 }
2068 
2069 static void
2070 print_cert(struct sshkey *key)
2071 {
2072 	char valid[64], *key_fp, *ca_fp;
2073 	u_int i;
2074 
2075 	key_fp = sshkey_fingerprint(key, fingerprint_hash, SSH_FP_DEFAULT);
2076 	ca_fp = sshkey_fingerprint(key->cert->signature_key,
2077 	    fingerprint_hash, SSH_FP_DEFAULT);
2078 	if (key_fp == NULL || ca_fp == NULL)
2079 		fatal_f("sshkey_fingerprint fail");
2080 	sshkey_format_cert_validity(key->cert, valid, sizeof(valid));
2081 
2082 	printf("        Type: %s %s certificate\n", sshkey_ssh_name(key),
2083 	    sshkey_cert_type(key));
2084 	printf("        Public key: %s %s\n", sshkey_type(key), key_fp);
2085 	printf("        Signing CA: %s %s (using %s)\n",
2086 	    sshkey_type(key->cert->signature_key), ca_fp,
2087 	    key->cert->signature_type);
2088 	printf("        Key ID: \"%s\"\n", key->cert->key_id);
2089 	printf("        Serial: %llu\n", (unsigned long long)key->cert->serial);
2090 	printf("        Valid: %s\n", valid);
2091 	printf("        Principals: ");
2092 	if (key->cert->nprincipals == 0)
2093 		printf("(none)\n");
2094 	else {
2095 		for (i = 0; i < key->cert->nprincipals; i++)
2096 			printf("\n                %s",
2097 			    key->cert->principals[i]);
2098 		printf("\n");
2099 	}
2100 	printf("        Critical Options: ");
2101 	if (sshbuf_len(key->cert->critical) == 0)
2102 		printf("(none)\n");
2103 	else {
2104 		printf("\n");
2105 		show_options(key->cert->critical, 1);
2106 	}
2107 	printf("        Extensions: ");
2108 	if (sshbuf_len(key->cert->extensions) == 0)
2109 		printf("(none)\n");
2110 	else {
2111 		printf("\n");
2112 		show_options(key->cert->extensions, 0);
2113 	}
2114 }
2115 
2116 static void
2117 do_show_cert(struct passwd *pw)
2118 {
2119 	struct sshkey *key = NULL;
2120 	struct stat st;
2121 	int r, is_stdin = 0, ok = 0;
2122 	FILE *f;
2123 	char *cp, *line = NULL;
2124 	const char *path;
2125 	size_t linesize = 0;
2126 	u_long lnum = 0;
2127 
2128 	if (!have_identity)
2129 		ask_filename(pw, "Enter file in which the key is");
2130 	if (strcmp(identity_file, "-") != 0 && stat(identity_file, &st) == -1)
2131 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
2132 
2133 	path = identity_file;
2134 	if (strcmp(path, "-") == 0) {
2135 		f = stdin;
2136 		path = "(stdin)";
2137 		is_stdin = 1;
2138 	} else if ((f = fopen(identity_file, "r")) == NULL)
2139 		fatal("fopen %s: %s", identity_file, strerror(errno));
2140 
2141 	while (getline(&line, &linesize, f) != -1) {
2142 		lnum++;
2143 		sshkey_free(key);
2144 		key = NULL;
2145 		/* Trim leading space and comments */
2146 		cp = line + strspn(line, " \t");
2147 		if (*cp == '#' || *cp == '\0')
2148 			continue;
2149 		if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2150 			fatal("sshkey_new");
2151 		if ((r = sshkey_read(key, &cp)) != 0) {
2152 			error_r(r, "%s:%lu: invalid key", path, lnum);
2153 			continue;
2154 		}
2155 		if (!sshkey_is_cert(key)) {
2156 			error("%s:%lu is not a certificate", path, lnum);
2157 			continue;
2158 		}
2159 		ok = 1;
2160 		if (!is_stdin && lnum == 1)
2161 			printf("%s:\n", path);
2162 		else
2163 			printf("%s:%lu:\n", path, lnum);
2164 		print_cert(key);
2165 	}
2166 	free(line);
2167 	sshkey_free(key);
2168 	fclose(f);
2169 	exit(ok ? 0 : 1);
2170 }
2171 
2172 static void
2173 load_krl(const char *path, struct ssh_krl **krlp)
2174 {
2175 	struct sshbuf *krlbuf;
2176 	int r;
2177 
2178 	if ((r = sshbuf_load_file(path, &krlbuf)) != 0)
2179 		fatal_r(r, "Unable to load KRL %s", path);
2180 	/* XXX check sigs */
2181 	if ((r = ssh_krl_from_blob(krlbuf, krlp, NULL, 0)) != 0 ||
2182 	    *krlp == NULL)
2183 		fatal_r(r, "Invalid KRL file %s", path);
2184 	sshbuf_free(krlbuf);
2185 }
2186 
2187 static void
2188 hash_to_blob(const char *cp, u_char **blobp, size_t *lenp,
2189     const char *file, u_long lnum)
2190 {
2191 	char *tmp;
2192 	size_t tlen;
2193 	struct sshbuf *b;
2194 	int r;
2195 
2196 	if (strncmp(cp, "SHA256:", 7) != 0)
2197 		fatal("%s:%lu: unsupported hash algorithm", file, lnum);
2198 	cp += 7;
2199 
2200 	/*
2201 	 * OpenSSH base64 hashes omit trailing '='
2202 	 * characters; put them back for decode.
2203 	 */
2204 	tlen = strlen(cp);
2205 	tmp = xmalloc(tlen + 4 + 1);
2206 	strlcpy(tmp, cp, tlen + 1);
2207 	while ((tlen % 4) != 0) {
2208 		tmp[tlen++] = '=';
2209 		tmp[tlen] = '\0';
2210 	}
2211 	if ((b = sshbuf_new()) == NULL)
2212 		fatal_f("sshbuf_new failed");
2213 	if ((r = sshbuf_b64tod(b, tmp)) != 0)
2214 		fatal_r(r, "%s:%lu: decode hash failed", file, lnum);
2215 	free(tmp);
2216 	*lenp = sshbuf_len(b);
2217 	*blobp = xmalloc(*lenp);
2218 	memcpy(*blobp, sshbuf_ptr(b), *lenp);
2219 	sshbuf_free(b);
2220 }
2221 
2222 static void
2223 update_krl_from_file(struct passwd *pw, const char *file, int wild_ca,
2224     const struct sshkey *ca, struct ssh_krl *krl)
2225 {
2226 	struct sshkey *key = NULL;
2227 	u_long lnum = 0;
2228 	char *path, *cp, *ep, *line = NULL;
2229 	u_char *blob = NULL;
2230 	size_t blen = 0, linesize = 0;
2231 	unsigned long long serial, serial2;
2232 	int i, was_explicit_key, was_sha1, was_sha256, was_hash, r;
2233 	FILE *krl_spec;
2234 
2235 	path = tilde_expand_filename(file, pw->pw_uid);
2236 	if (strcmp(path, "-") == 0) {
2237 		krl_spec = stdin;
2238 		free(path);
2239 		path = xstrdup("(standard input)");
2240 	} else if ((krl_spec = fopen(path, "r")) == NULL)
2241 		fatal("fopen %s: %s", path, strerror(errno));
2242 
2243 	if (!quiet)
2244 		printf("Revoking from %s\n", path);
2245 	while (getline(&line, &linesize, krl_spec) != -1) {
2246 		lnum++;
2247 		was_explicit_key = was_sha1 = was_sha256 = was_hash = 0;
2248 		cp = line + strspn(line, " \t");
2249 		/* Trim trailing space, comments and strip \n */
2250 		for (i = 0, r = -1; cp[i] != '\0'; i++) {
2251 			if (cp[i] == '#' || cp[i] == '\n') {
2252 				cp[i] = '\0';
2253 				break;
2254 			}
2255 			if (cp[i] == ' ' || cp[i] == '\t') {
2256 				/* Remember the start of a span of whitespace */
2257 				if (r == -1)
2258 					r = i;
2259 			} else
2260 				r = -1;
2261 		}
2262 		if (r != -1)
2263 			cp[r] = '\0';
2264 		if (*cp == '\0')
2265 			continue;
2266 		if (strncasecmp(cp, "serial:", 7) == 0) {
2267 			if (ca == NULL && !wild_ca) {
2268 				fatal("revoking certificates by serial number "
2269 				    "requires specification of a CA key");
2270 			}
2271 			cp += 7;
2272 			cp = cp + strspn(cp, " \t");
2273 			errno = 0;
2274 			serial = strtoull(cp, &ep, 0);
2275 			if (*cp == '\0' || (*ep != '\0' && *ep != '-'))
2276 				fatal("%s:%lu: invalid serial \"%s\"",
2277 				    path, lnum, cp);
2278 			if (errno == ERANGE && serial == ULLONG_MAX)
2279 				fatal("%s:%lu: serial out of range",
2280 				    path, lnum);
2281 			serial2 = serial;
2282 			if (*ep == '-') {
2283 				cp = ep + 1;
2284 				errno = 0;
2285 				serial2 = strtoull(cp, &ep, 0);
2286 				if (*cp == '\0' || *ep != '\0')
2287 					fatal("%s:%lu: invalid serial \"%s\"",
2288 					    path, lnum, cp);
2289 				if (errno == ERANGE && serial2 == ULLONG_MAX)
2290 					fatal("%s:%lu: serial out of range",
2291 					    path, lnum);
2292 				if (serial2 <= serial)
2293 					fatal("%s:%lu: invalid serial range "
2294 					    "%llu:%llu", path, lnum,
2295 					    (unsigned long long)serial,
2296 					    (unsigned long long)serial2);
2297 			}
2298 			if (ssh_krl_revoke_cert_by_serial_range(krl,
2299 			    ca, serial, serial2) != 0) {
2300 				fatal_f("revoke serial failed");
2301 			}
2302 		} else if (strncasecmp(cp, "id:", 3) == 0) {
2303 			if (ca == NULL && !wild_ca) {
2304 				fatal("revoking certificates by key ID "
2305 				    "requires specification of a CA key");
2306 			}
2307 			cp += 3;
2308 			cp = cp + strspn(cp, " \t");
2309 			if (ssh_krl_revoke_cert_by_key_id(krl, ca, cp) != 0)
2310 				fatal_f("revoke key ID failed");
2311 		} else if (strncasecmp(cp, "hash:", 5) == 0) {
2312 			cp += 5;
2313 			cp = cp + strspn(cp, " \t");
2314 			hash_to_blob(cp, &blob, &blen, file, lnum);
2315 			r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2316 			if (r != 0)
2317 				fatal_fr(r, "revoke key failed");
2318 		} else {
2319 			if (strncasecmp(cp, "key:", 4) == 0) {
2320 				cp += 4;
2321 				cp = cp + strspn(cp, " \t");
2322 				was_explicit_key = 1;
2323 			} else if (strncasecmp(cp, "sha1:", 5) == 0) {
2324 				cp += 5;
2325 				cp = cp + strspn(cp, " \t");
2326 				was_sha1 = 1;
2327 			} else if (strncasecmp(cp, "sha256:", 7) == 0) {
2328 				cp += 7;
2329 				cp = cp + strspn(cp, " \t");
2330 				was_sha256 = 1;
2331 				/*
2332 				 * Just try to process the line as a key.
2333 				 * Parsing will fail if it isn't.
2334 				 */
2335 			}
2336 			if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2337 				fatal("sshkey_new");
2338 			if ((r = sshkey_read(key, &cp)) != 0)
2339 				fatal_r(r, "%s:%lu: invalid key", path, lnum);
2340 			if (was_explicit_key)
2341 				r = ssh_krl_revoke_key_explicit(krl, key);
2342 			else if (was_sha1) {
2343 				if (sshkey_fingerprint_raw(key,
2344 				    SSH_DIGEST_SHA1, &blob, &blen) != 0) {
2345 					fatal("%s:%lu: fingerprint failed",
2346 					    file, lnum);
2347 				}
2348 				r = ssh_krl_revoke_key_sha1(krl, blob, blen);
2349 			} else if (was_sha256) {
2350 				if (sshkey_fingerprint_raw(key,
2351 				    SSH_DIGEST_SHA256, &blob, &blen) != 0) {
2352 					fatal("%s:%lu: fingerprint failed",
2353 					    file, lnum);
2354 				}
2355 				r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2356 			} else
2357 				r = ssh_krl_revoke_key(krl, key);
2358 			if (r != 0)
2359 				fatal_fr(r, "revoke key failed");
2360 			freezero(blob, blen);
2361 			blob = NULL;
2362 			blen = 0;
2363 			sshkey_free(key);
2364 		}
2365 	}
2366 	if (strcmp(path, "-") != 0)
2367 		fclose(krl_spec);
2368 	free(line);
2369 	free(path);
2370 }
2371 
2372 static void
2373 do_gen_krl(struct passwd *pw, int updating, const char *ca_key_path,
2374     unsigned long long krl_version, const char *krl_comment,
2375     int argc, char **argv)
2376 {
2377 	struct ssh_krl *krl;
2378 	struct stat sb;
2379 	struct sshkey *ca = NULL;
2380 	int i, r, wild_ca = 0;
2381 	char *tmp;
2382 	struct sshbuf *kbuf;
2383 
2384 	if (*identity_file == '\0')
2385 		fatal("KRL generation requires an output file");
2386 	if (stat(identity_file, &sb) == -1) {
2387 		if (errno != ENOENT)
2388 			fatal("Cannot access KRL \"%s\": %s",
2389 			    identity_file, strerror(errno));
2390 		if (updating)
2391 			fatal("KRL \"%s\" does not exist", identity_file);
2392 	}
2393 	if (ca_key_path != NULL) {
2394 		if (strcasecmp(ca_key_path, "none") == 0)
2395 			wild_ca = 1;
2396 		else {
2397 			tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
2398 			if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
2399 				fatal_r(r, "Cannot load CA public key %s", tmp);
2400 			free(tmp);
2401 		}
2402 	}
2403 
2404 	if (updating)
2405 		load_krl(identity_file, &krl);
2406 	else if ((krl = ssh_krl_init()) == NULL)
2407 		fatal("couldn't create KRL");
2408 
2409 	if (krl_version != 0)
2410 		ssh_krl_set_version(krl, krl_version);
2411 	if (krl_comment != NULL)
2412 		ssh_krl_set_comment(krl, krl_comment);
2413 
2414 	for (i = 0; i < argc; i++)
2415 		update_krl_from_file(pw, argv[i], wild_ca, ca, krl);
2416 
2417 	if ((kbuf = sshbuf_new()) == NULL)
2418 		fatal("sshbuf_new failed");
2419 	if (ssh_krl_to_blob(krl, kbuf, NULL, 0) != 0)
2420 		fatal("Couldn't generate KRL");
2421 	if ((r = sshbuf_write_file(identity_file, kbuf)) != 0)
2422 		fatal("write %s: %s", identity_file, strerror(errno));
2423 	sshbuf_free(kbuf);
2424 	ssh_krl_free(krl);
2425 	sshkey_free(ca);
2426 }
2427 
2428 static void
2429 do_check_krl(struct passwd *pw, int print_krl, int argc, char **argv)
2430 {
2431 	int i, r, ret = 0;
2432 	char *comment;
2433 	struct ssh_krl *krl;
2434 	struct sshkey *k;
2435 
2436 	if (*identity_file == '\0')
2437 		fatal("KRL checking requires an input file");
2438 	load_krl(identity_file, &krl);
2439 	if (print_krl)
2440 		krl_dump(krl, stdout);
2441 	for (i = 0; i < argc; i++) {
2442 		if ((r = sshkey_load_public(argv[i], &k, &comment)) != 0)
2443 			fatal_r(r, "Cannot load public key %s", argv[i]);
2444 		r = ssh_krl_check_key(krl, k);
2445 		printf("%s%s%s%s: %s\n", argv[i],
2446 		    *comment ? " (" : "", comment, *comment ? ")" : "",
2447 		    r == 0 ? "ok" : "REVOKED");
2448 		if (r != 0)
2449 			ret = 1;
2450 		sshkey_free(k);
2451 		free(comment);
2452 	}
2453 	ssh_krl_free(krl);
2454 	exit(ret);
2455 }
2456 
2457 static struct sshkey *
2458 load_sign_key(const char *keypath, const struct sshkey *pubkey)
2459 {
2460 	size_t i, slen, plen = strlen(keypath);
2461 	char *privpath = xstrdup(keypath);
2462 	const char *suffixes[] = { "-cert.pub", ".pub", NULL };
2463 	struct sshkey *ret = NULL, *privkey = NULL;
2464 	int r;
2465 
2466 	/*
2467 	 * If passed a public key filename, then try to locate the corresponding
2468 	 * private key. This lets us specify certificates on the command-line
2469 	 * and have ssh-keygen find the appropriate private key.
2470 	 */
2471 	for (i = 0; suffixes[i]; i++) {
2472 		slen = strlen(suffixes[i]);
2473 		if (plen <= slen ||
2474 		    strcmp(privpath + plen - slen, suffixes[i]) != 0)
2475 			continue;
2476 		privpath[plen - slen] = '\0';
2477 		debug_f("%s looks like a public key, using private key "
2478 		    "path %s instead", keypath, privpath);
2479 	}
2480 	if ((privkey = load_identity(privpath, NULL)) == NULL) {
2481 		error("Couldn't load identity %s", keypath);
2482 		goto done;
2483 	}
2484 	if (!sshkey_equal_public(pubkey, privkey)) {
2485 		error("Public key %s doesn't match private %s",
2486 		    keypath, privpath);
2487 		goto done;
2488 	}
2489 	if (sshkey_is_cert(pubkey) && !sshkey_is_cert(privkey)) {
2490 		/*
2491 		 * Graft the certificate onto the private key to make
2492 		 * it capable of signing.
2493 		 */
2494 		if ((r = sshkey_to_certified(privkey)) != 0) {
2495 			error_fr(r, "sshkey_to_certified");
2496 			goto done;
2497 		}
2498 		if ((r = sshkey_cert_copy(pubkey, privkey)) != 0) {
2499 			error_fr(r, "sshkey_cert_copy");
2500 			goto done;
2501 		}
2502 	}
2503 	/* success */
2504 	ret = privkey;
2505 	privkey = NULL;
2506  done:
2507 	sshkey_free(privkey);
2508 	free(privpath);
2509 	return ret;
2510 }
2511 
2512 static int
2513 sign_one(struct sshkey *signkey, const char *filename, int fd,
2514     const char *sig_namespace, sshsig_signer *signer, void *signer_ctx)
2515 {
2516 	struct sshbuf *sigbuf = NULL, *abuf = NULL;
2517 	int r = SSH_ERR_INTERNAL_ERROR, wfd = -1, oerrno;
2518 	char *wfile = NULL, *asig = NULL, *fp = NULL;
2519 	char *pin = NULL, *prompt = NULL;
2520 
2521 	if (!quiet) {
2522 		if (fd == STDIN_FILENO)
2523 			fprintf(stderr, "Signing data on standard input\n");
2524 		else
2525 			fprintf(stderr, "Signing file %s\n", filename);
2526 	}
2527 	if (signer == NULL && sshkey_is_sk(signkey)) {
2528 		if ((signkey->sk_flags & SSH_SK_USER_VERIFICATION_REQD)) {
2529 			xasprintf(&prompt, "Enter PIN for %s key: ",
2530 			    sshkey_type(signkey));
2531 			if ((pin = read_passphrase(prompt,
2532 			    RP_ALLOW_STDIN)) == NULL)
2533 				fatal_f("couldn't read PIN");
2534 		}
2535 		if ((signkey->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
2536 			if ((fp = sshkey_fingerprint(signkey, fingerprint_hash,
2537 			    SSH_FP_DEFAULT)) == NULL)
2538 				fatal_f("fingerprint failed");
2539 			fprintf(stderr, "Confirm user presence for key %s %s\n",
2540 			    sshkey_type(signkey), fp);
2541 			free(fp);
2542 		}
2543 	}
2544 	if ((r = sshsig_sign_fd(signkey, NULL, sk_provider, pin,
2545 	    fd, sig_namespace, &sigbuf, signer, signer_ctx)) != 0) {
2546 		error_r(r, "Signing %s failed", filename);
2547 		goto out;
2548 	}
2549 	if ((r = sshsig_armor(sigbuf, &abuf)) != 0) {
2550 		error_fr(r, "sshsig_armor");
2551 		goto out;
2552 	}
2553 	if ((asig = sshbuf_dup_string(abuf)) == NULL) {
2554 		error_f("buffer error");
2555 		r = SSH_ERR_ALLOC_FAIL;
2556 		goto out;
2557 	}
2558 
2559 	if (fd == STDIN_FILENO) {
2560 		fputs(asig, stdout);
2561 		fflush(stdout);
2562 	} else {
2563 		xasprintf(&wfile, "%s.sig", filename);
2564 		if (confirm_overwrite(wfile)) {
2565 			if ((wfd = open(wfile, O_WRONLY|O_CREAT|O_TRUNC,
2566 			    0666)) == -1) {
2567 				oerrno = errno;
2568 				error("Cannot open %s: %s",
2569 				    wfile, strerror(errno));
2570 				errno = oerrno;
2571 				r = SSH_ERR_SYSTEM_ERROR;
2572 				goto out;
2573 			}
2574 			if (atomicio(vwrite, wfd, asig,
2575 			    strlen(asig)) != strlen(asig)) {
2576 				oerrno = errno;
2577 				error("Cannot write to %s: %s",
2578 				    wfile, strerror(errno));
2579 				errno = oerrno;
2580 				r = SSH_ERR_SYSTEM_ERROR;
2581 				goto out;
2582 			}
2583 			if (!quiet) {
2584 				fprintf(stderr, "Write signature to %s\n",
2585 				    wfile);
2586 			}
2587 		}
2588 	}
2589 	/* success */
2590 	r = 0;
2591  out:
2592 	free(wfile);
2593 	free(prompt);
2594 	free(asig);
2595 	if (pin != NULL)
2596 		freezero(pin, strlen(pin));
2597 	sshbuf_free(abuf);
2598 	sshbuf_free(sigbuf);
2599 	if (wfd != -1)
2600 		close(wfd);
2601 	return r;
2602 }
2603 
2604 static int
2605 sig_sign(const char *keypath, const char *sig_namespace, int argc, char **argv)
2606 {
2607 	int i, fd = -1, r, ret = -1;
2608 	int agent_fd = -1;
2609 	struct sshkey *pubkey = NULL, *privkey = NULL, *signkey = NULL;
2610 	sshsig_signer *signer = NULL;
2611 
2612 	/* Check file arguments. */
2613 	for (i = 0; i < argc; i++) {
2614 		if (strcmp(argv[i], "-") != 0)
2615 			continue;
2616 		if (i > 0 || argc > 1)
2617 			fatal("Cannot sign mix of paths and standard input");
2618 	}
2619 
2620 	if ((r = sshkey_load_public(keypath, &pubkey, NULL)) != 0) {
2621 		error_r(r, "Couldn't load public key %s", keypath);
2622 		goto done;
2623 	}
2624 
2625 	if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
2626 		debug_r(r, "Couldn't get agent socket");
2627 	else {
2628 		if ((r = ssh_agent_has_key(agent_fd, pubkey)) == 0)
2629 			signer = agent_signer;
2630 		else
2631 			debug_r(r, "Couldn't find key in agent");
2632 	}
2633 
2634 	if (signer == NULL) {
2635 		/* Not using agent - try to load private key */
2636 		if ((privkey = load_sign_key(keypath, pubkey)) == NULL)
2637 			goto done;
2638 		signkey = privkey;
2639 	} else {
2640 		/* Will use key in agent */
2641 		signkey = pubkey;
2642 	}
2643 
2644 	if (argc == 0) {
2645 		if ((r = sign_one(signkey, "(stdin)", STDIN_FILENO,
2646 		    sig_namespace, signer, &agent_fd)) != 0)
2647 			goto done;
2648 	} else {
2649 		for (i = 0; i < argc; i++) {
2650 			if (strcmp(argv[i], "-") == 0)
2651 				fd = STDIN_FILENO;
2652 			else if ((fd = open(argv[i], O_RDONLY)) == -1) {
2653 				error("Cannot open %s for signing: %s",
2654 				    argv[i], strerror(errno));
2655 				goto done;
2656 			}
2657 			if ((r = sign_one(signkey, argv[i], fd, sig_namespace,
2658 			    signer, &agent_fd)) != 0)
2659 				goto done;
2660 			if (fd != STDIN_FILENO)
2661 				close(fd);
2662 			fd = -1;
2663 		}
2664 	}
2665 
2666 	ret = 0;
2667 done:
2668 	if (fd != -1 && fd != STDIN_FILENO)
2669 		close(fd);
2670 	sshkey_free(pubkey);
2671 	sshkey_free(privkey);
2672 	return ret;
2673 }
2674 
2675 static int
2676 sig_verify(const char *signature, const char *sig_namespace,
2677     const char *principal, const char *allowed_keys, const char *revoked_keys)
2678 {
2679 	int r, ret = -1;
2680 	struct sshbuf *sigbuf = NULL, *abuf = NULL;
2681 	struct sshkey *sign_key = NULL;
2682 	char *fp = NULL;
2683 	struct sshkey_sig_details *sig_details = NULL;
2684 
2685 	memset(&sig_details, 0, sizeof(sig_details));
2686 	if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
2687 		error_r(r, "Couldn't read signature file");
2688 		goto done;
2689 	}
2690 
2691 	if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
2692 		error_fr(r, "sshsig_armor");
2693 		goto done;
2694 	}
2695 	if ((r = sshsig_verify_fd(sigbuf, STDIN_FILENO, sig_namespace,
2696 	    &sign_key, &sig_details)) != 0)
2697 		goto done; /* sshsig_verify() prints error */
2698 
2699 	if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
2700 	    SSH_FP_DEFAULT)) == NULL)
2701 		fatal_f("sshkey_fingerprint failed");
2702 	debug("Valid (unverified) signature from key %s", fp);
2703 	if (sig_details != NULL) {
2704 		debug2_f("signature details: counter = %u, flags = 0x%02x",
2705 		    sig_details->sk_counter, sig_details->sk_flags);
2706 	}
2707 	free(fp);
2708 	fp = NULL;
2709 
2710 	if (revoked_keys != NULL) {
2711 		if ((r = sshkey_check_revoked(sign_key, revoked_keys)) != 0) {
2712 			debug3_fr(r, "sshkey_check_revoked");
2713 			goto done;
2714 		}
2715 	}
2716 
2717 	if (allowed_keys != NULL && (r = sshsig_check_allowed_keys(allowed_keys,
2718 	    sign_key, principal, sig_namespace)) != 0) {
2719 		debug3_fr(r, "sshsig_check_allowed_keys");
2720 		goto done;
2721 	}
2722 	/* success */
2723 	ret = 0;
2724 done:
2725 	if (!quiet) {
2726 		if (ret == 0) {
2727 			if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
2728 			    SSH_FP_DEFAULT)) == NULL)
2729 				fatal_f("sshkey_fingerprint failed");
2730 			if (principal == NULL) {
2731 				printf("Good \"%s\" signature with %s key %s\n",
2732 				       sig_namespace, sshkey_type(sign_key), fp);
2733 
2734 			} else {
2735 				printf("Good \"%s\" signature for %s with %s key %s\n",
2736 				       sig_namespace, principal,
2737 				       sshkey_type(sign_key), fp);
2738 			}
2739 		} else {
2740 			printf("Could not verify signature.\n");
2741 		}
2742 	}
2743 	sshbuf_free(sigbuf);
2744 	sshbuf_free(abuf);
2745 	sshkey_free(sign_key);
2746 	sshkey_sig_details_free(sig_details);
2747 	free(fp);
2748 	return ret;
2749 }
2750 
2751 static int
2752 sig_find_principals(const char *signature, const char *allowed_keys) {
2753 	int r, ret = -1;
2754 	struct sshbuf *sigbuf = NULL, *abuf = NULL;
2755 	struct sshkey *sign_key = NULL;
2756 	char *principals = NULL, *cp, *tmp;
2757 
2758 	if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
2759 		error_r(r, "Couldn't read signature file");
2760 		goto done;
2761 	}
2762 	if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
2763 		error_fr(r, "sshsig_armor");
2764 		goto done;
2765 	}
2766 	if ((r = sshsig_get_pubkey(sigbuf, &sign_key)) != 0) {
2767 		error_fr(r, "sshsig_get_pubkey");
2768 		goto done;
2769 	}
2770 	if ((r = sshsig_find_principals(allowed_keys, sign_key,
2771 	    &principals)) != 0) {
2772 		error_fr(r, "sshsig_get_principal");
2773 		goto done;
2774 	}
2775 	ret = 0;
2776 done:
2777 	if (ret == 0 ) {
2778 		/* Emit matching principals one per line */
2779 		tmp = principals;
2780 		while ((cp = strsep(&tmp, ",")) != NULL && *cp != '\0')
2781 			puts(cp);
2782 	} else {
2783 		fprintf(stderr, "No principal matched.\n");
2784 	}
2785 	sshbuf_free(sigbuf);
2786 	sshbuf_free(abuf);
2787 	sshkey_free(sign_key);
2788 	free(principals);
2789 	return ret;
2790 }
2791 
2792 static void
2793 do_moduli_gen(const char *out_file, char **opts, size_t nopts)
2794 {
2795 #ifdef WITH_OPENSSL
2796 	/* Moduli generation/screening */
2797 	u_int32_t memory = 0;
2798 	BIGNUM *start = NULL;
2799 	int moduli_bits = 0;
2800 	FILE *out;
2801 	size_t i;
2802 	const char *errstr;
2803 
2804 	/* Parse options */
2805 	for (i = 0; i < nopts; i++) {
2806 		if (strncmp(opts[i], "memory=", 7) == 0) {
2807 			memory = (u_int32_t)strtonum(opts[i]+7, 1,
2808 			    UINT_MAX, &errstr);
2809 			if (errstr) {
2810 				fatal("Memory limit is %s: %s",
2811 				    errstr, opts[i]+7);
2812 			}
2813 		} else if (strncmp(opts[i], "start=", 6) == 0) {
2814 			/* XXX - also compare length against bits */
2815 			if (BN_hex2bn(&start, opts[i]+6) == 0)
2816 				fatal("Invalid start point.");
2817 		} else if (strncmp(opts[i], "bits=", 5) == 0) {
2818 			moduli_bits = (int)strtonum(opts[i]+5, 1,
2819 			    INT_MAX, &errstr);
2820 			if (errstr) {
2821 				fatal("Invalid number: %s (%s)",
2822 					opts[i]+12, errstr);
2823 			}
2824 		} else {
2825 			fatal("Option \"%s\" is unsupported for moduli "
2826 			    "generation", opts[i]);
2827 		}
2828 	}
2829 
2830 	if ((out = fopen(out_file, "w")) == NULL) {
2831 		fatal("Couldn't open modulus candidate file \"%s\": %s",
2832 		    out_file, strerror(errno));
2833 	}
2834 	setvbuf(out, NULL, _IOLBF, 0);
2835 
2836 	if (moduli_bits == 0)
2837 		moduli_bits = DEFAULT_BITS;
2838 	if (gen_candidates(out, memory, moduli_bits, start) != 0)
2839 		fatal("modulus candidate generation failed");
2840 #else /* WITH_OPENSSL */
2841 	fatal("Moduli generation is not supported");
2842 #endif /* WITH_OPENSSL */
2843 }
2844 
2845 static void
2846 do_moduli_screen(const char *out_file, char **opts, size_t nopts)
2847 {
2848 #ifdef WITH_OPENSSL
2849 	/* Moduli generation/screening */
2850 	char *checkpoint = NULL;
2851 	u_int32_t generator_wanted = 0;
2852 	unsigned long start_lineno = 0, lines_to_process = 0;
2853 	int prime_tests = 0;
2854 	FILE *out, *in = stdin;
2855 	size_t i;
2856 	const char *errstr;
2857 
2858 	/* Parse options */
2859 	for (i = 0; i < nopts; i++) {
2860 		if (strncmp(opts[i], "lines=", 6) == 0) {
2861 			lines_to_process = strtoul(opts[i]+6, NULL, 10);
2862 		} else if (strncmp(opts[i], "start-line=", 11) == 0) {
2863 			start_lineno = strtoul(opts[i]+11, NULL, 10);
2864 		} else if (strncmp(opts[i], "checkpoint=", 11) == 0) {
2865 			checkpoint = xstrdup(opts[i]+11);
2866 		} else if (strncmp(opts[i], "generator=", 10) == 0) {
2867 			generator_wanted = (u_int32_t)strtonum(
2868 			    opts[i]+10, 1, UINT_MAX, &errstr);
2869 			if (errstr != NULL) {
2870 				fatal("Generator invalid: %s (%s)",
2871 				    opts[i]+10, errstr);
2872 			}
2873 		} else if (strncmp(opts[i], "prime-tests=", 12) == 0) {
2874 			prime_tests = (int)strtonum(opts[i]+12, 1,
2875 			    INT_MAX, &errstr);
2876 			if (errstr) {
2877 				fatal("Invalid number: %s (%s)",
2878 					opts[i]+12, errstr);
2879 			}
2880 		} else {
2881 			fatal("Option \"%s\" is unsupported for moduli "
2882 			    "screening", opts[i]);
2883 		}
2884 	}
2885 
2886 	if (have_identity && strcmp(identity_file, "-") != 0) {
2887 		if ((in = fopen(identity_file, "r")) == NULL) {
2888 			fatal("Couldn't open modulus candidate "
2889 			    "file \"%s\": %s", identity_file,
2890 			    strerror(errno));
2891 		}
2892 	}
2893 
2894 	if ((out = fopen(out_file, "a")) == NULL) {
2895 		fatal("Couldn't open moduli file \"%s\": %s",
2896 		    out_file, strerror(errno));
2897 	}
2898 	setvbuf(out, NULL, _IOLBF, 0);
2899 	if (prime_test(in, out, prime_tests == 0 ? 100 : prime_tests,
2900 	    generator_wanted, checkpoint,
2901 	    start_lineno, lines_to_process) != 0)
2902 		fatal("modulus screening failed");
2903 #else /* WITH_OPENSSL */
2904 	fatal("Moduli screening is not supported");
2905 #endif /* WITH_OPENSSL */
2906 }
2907 
2908 static char *
2909 private_key_passphrase(void)
2910 {
2911 	char *passphrase1, *passphrase2;
2912 
2913 	/* Ask for a passphrase (twice). */
2914 	if (identity_passphrase)
2915 		passphrase1 = xstrdup(identity_passphrase);
2916 	else if (identity_new_passphrase)
2917 		passphrase1 = xstrdup(identity_new_passphrase);
2918 	else {
2919 passphrase_again:
2920 		passphrase1 =
2921 			read_passphrase("Enter passphrase (empty for no "
2922 			    "passphrase): ", RP_ALLOW_STDIN);