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