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