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