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