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