xref: /openbsd-src/usr.bin/ssh/ssh-keygen.c (revision 897fc685943471cf985a0fe38ba076ea6fe74fa5)
1 /* $OpenBSD: ssh-keygen.c,v 1.314 2018/03/12 00:52:01 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 		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 void
1786 parse_cert_times(char *timespec)
1787 {
1788 	char *from, *to;
1789 	time_t now = time(NULL);
1790 	int64_t secs;
1791 
1792 	/* +timespec relative to now */
1793 	if (*timespec == '+' && strchr(timespec, ':') == NULL) {
1794 		if ((secs = convtime(timespec + 1)) == -1)
1795 			fatal("Invalid relative certificate life %s", timespec);
1796 		cert_valid_to = now + secs;
1797 		/*
1798 		 * Backdate certificate one minute to avoid problems on hosts
1799 		 * with poorly-synchronised clocks.
1800 		 */
1801 		cert_valid_from = ((now - 59)/ 60) * 60;
1802 		return;
1803 	}
1804 
1805 	/*
1806 	 * from:to, where
1807 	 * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "always"
1808 	 *   to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "forever"
1809 	 */
1810 	from = xstrdup(timespec);
1811 	to = strchr(from, ':');
1812 	if (to == NULL || from == to || *(to + 1) == '\0')
1813 		fatal("Invalid certificate life specification %s", timespec);
1814 	*to++ = '\0';
1815 
1816 	if (*from == '-' || *from == '+')
1817 		cert_valid_from = parse_relative_time(from, now);
1818 	else if (strcmp(from, "always") == 0)
1819 		cert_valid_from = 0;
1820 	else if (parse_absolute_time(from, &cert_valid_from) != 0)
1821 		fatal("Invalid from time \"%s\"", from);
1822 
1823 	if (*to == '-' || *to == '+')
1824 		cert_valid_to = parse_relative_time(to, now);
1825 	else if (strcmp(to, "forever") == 0)
1826 		cert_valid_to = ~(u_int64_t)0;
1827 	else if (parse_absolute_time(to, &cert_valid_to) != 0)
1828 		fatal("Invalid to time \"%s\"", to);
1829 
1830 	if (cert_valid_to <= cert_valid_from)
1831 		fatal("Empty certificate validity interval");
1832 	free(from);
1833 }
1834 
1835 static void
1836 add_cert_option(char *opt)
1837 {
1838 	char *val, *cp;
1839 	int iscrit = 0;
1840 
1841 	if (strcasecmp(opt, "clear") == 0)
1842 		certflags_flags = 0;
1843 	else if (strcasecmp(opt, "no-x11-forwarding") == 0)
1844 		certflags_flags &= ~CERTOPT_X_FWD;
1845 	else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
1846 		certflags_flags |= CERTOPT_X_FWD;
1847 	else if (strcasecmp(opt, "no-agent-forwarding") == 0)
1848 		certflags_flags &= ~CERTOPT_AGENT_FWD;
1849 	else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
1850 		certflags_flags |= CERTOPT_AGENT_FWD;
1851 	else if (strcasecmp(opt, "no-port-forwarding") == 0)
1852 		certflags_flags &= ~CERTOPT_PORT_FWD;
1853 	else if (strcasecmp(opt, "permit-port-forwarding") == 0)
1854 		certflags_flags |= CERTOPT_PORT_FWD;
1855 	else if (strcasecmp(opt, "no-pty") == 0)
1856 		certflags_flags &= ~CERTOPT_PTY;
1857 	else if (strcasecmp(opt, "permit-pty") == 0)
1858 		certflags_flags |= CERTOPT_PTY;
1859 	else if (strcasecmp(opt, "no-user-rc") == 0)
1860 		certflags_flags &= ~CERTOPT_USER_RC;
1861 	else if (strcasecmp(opt, "permit-user-rc") == 0)
1862 		certflags_flags |= CERTOPT_USER_RC;
1863 	else if (strncasecmp(opt, "force-command=", 14) == 0) {
1864 		val = opt + 14;
1865 		if (*val == '\0')
1866 			fatal("Empty force-command option");
1867 		if (certflags_command != NULL)
1868 			fatal("force-command already specified");
1869 		certflags_command = xstrdup(val);
1870 	} else if (strncasecmp(opt, "source-address=", 15) == 0) {
1871 		val = opt + 15;
1872 		if (*val == '\0')
1873 			fatal("Empty source-address option");
1874 		if (certflags_src_addr != NULL)
1875 			fatal("source-address already specified");
1876 		if (addr_match_cidr_list(NULL, val) != 0)
1877 			fatal("Invalid source-address list");
1878 		certflags_src_addr = xstrdup(val);
1879 	} else if (strncasecmp(opt, "extension:", 10) == 0 ||
1880 		   (iscrit = (strncasecmp(opt, "critical:", 9) == 0))) {
1881 		val = xstrdup(strchr(opt, ':') + 1);
1882 		if ((cp = strchr(val, '=')) != NULL)
1883 			*cp++ = '\0';
1884 		cert_userext = xreallocarray(cert_userext, ncert_userext + 1,
1885 		    sizeof(*cert_userext));
1886 		cert_userext[ncert_userext].key = val;
1887 		cert_userext[ncert_userext].val = cp == NULL ?
1888 		    NULL : xstrdup(cp);
1889 		cert_userext[ncert_userext].crit = iscrit;
1890 		ncert_userext++;
1891 	} else
1892 		fatal("Unsupported certificate option \"%s\"", opt);
1893 }
1894 
1895 static void
1896 show_options(struct sshbuf *optbuf, int in_critical)
1897 {
1898 	char *name, *arg;
1899 	struct sshbuf *options, *option = NULL;
1900 	int r;
1901 
1902 	if ((options = sshbuf_fromb(optbuf)) == NULL)
1903 		fatal("%s: sshbuf_fromb failed", __func__);
1904 	while (sshbuf_len(options) != 0) {
1905 		sshbuf_free(option);
1906 		option = NULL;
1907 		if ((r = sshbuf_get_cstring(options, &name, NULL)) != 0 ||
1908 		    (r = sshbuf_froms(options, &option)) != 0)
1909 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
1910 		printf("                %s", name);
1911 		if (!in_critical &&
1912 		    (strcmp(name, "permit-X11-forwarding") == 0 ||
1913 		    strcmp(name, "permit-agent-forwarding") == 0 ||
1914 		    strcmp(name, "permit-port-forwarding") == 0 ||
1915 		    strcmp(name, "permit-pty") == 0 ||
1916 		    strcmp(name, "permit-user-rc") == 0))
1917 			printf("\n");
1918 		else if (in_critical &&
1919 		    (strcmp(name, "force-command") == 0 ||
1920 		    strcmp(name, "source-address") == 0)) {
1921 			if ((r = sshbuf_get_cstring(option, &arg, NULL)) != 0)
1922 				fatal("%s: buffer error: %s",
1923 				    __func__, ssh_err(r));
1924 			printf(" %s\n", arg);
1925 			free(arg);
1926 		} else {
1927 			printf(" UNKNOWN OPTION (len %zu)\n",
1928 			    sshbuf_len(option));
1929 			sshbuf_reset(option);
1930 		}
1931 		free(name);
1932 		if (sshbuf_len(option) != 0)
1933 			fatal("Option corrupt: extra data at end");
1934 	}
1935 	sshbuf_free(option);
1936 	sshbuf_free(options);
1937 }
1938 
1939 static void
1940 print_cert(struct sshkey *key)
1941 {
1942 	char valid[64], *key_fp, *ca_fp;
1943 	u_int i;
1944 
1945 	key_fp = sshkey_fingerprint(key, fingerprint_hash, SSH_FP_DEFAULT);
1946 	ca_fp = sshkey_fingerprint(key->cert->signature_key,
1947 	    fingerprint_hash, SSH_FP_DEFAULT);
1948 	if (key_fp == NULL || ca_fp == NULL)
1949 		fatal("%s: sshkey_fingerprint fail", __func__);
1950 	sshkey_format_cert_validity(key->cert, valid, sizeof(valid));
1951 
1952 	printf("        Type: %s %s certificate\n", sshkey_ssh_name(key),
1953 	    sshkey_cert_type(key));
1954 	printf("        Public key: %s %s\n", sshkey_type(key), key_fp);
1955 	printf("        Signing CA: %s %s\n",
1956 	    sshkey_type(key->cert->signature_key), ca_fp);
1957 	printf("        Key ID: \"%s\"\n", key->cert->key_id);
1958 	printf("        Serial: %llu\n", (unsigned long long)key->cert->serial);
1959 	printf("        Valid: %s\n", valid);
1960 	printf("        Principals: ");
1961 	if (key->cert->nprincipals == 0)
1962 		printf("(none)\n");
1963 	else {
1964 		for (i = 0; i < key->cert->nprincipals; i++)
1965 			printf("\n                %s",
1966 			    key->cert->principals[i]);
1967 		printf("\n");
1968 	}
1969 	printf("        Critical Options: ");
1970 	if (sshbuf_len(key->cert->critical) == 0)
1971 		printf("(none)\n");
1972 	else {
1973 		printf("\n");
1974 		show_options(key->cert->critical, 1);
1975 	}
1976 	printf("        Extensions: ");
1977 	if (sshbuf_len(key->cert->extensions) == 0)
1978 		printf("(none)\n");
1979 	else {
1980 		printf("\n");
1981 		show_options(key->cert->extensions, 0);
1982 	}
1983 }
1984 
1985 static void
1986 do_show_cert(struct passwd *pw)
1987 {
1988 	struct sshkey *key = NULL;
1989 	struct stat st;
1990 	int r, is_stdin = 0, ok = 0;
1991 	FILE *f;
1992 	char *cp, line[SSH_MAX_PUBKEY_BYTES];
1993 	const char *path;
1994 	u_long lnum = 0;
1995 
1996 	if (!have_identity)
1997 		ask_filename(pw, "Enter file in which the key is");
1998 	if (strcmp(identity_file, "-") != 0 && stat(identity_file, &st) < 0)
1999 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
2000 
2001 	path = identity_file;
2002 	if (strcmp(path, "-") == 0) {
2003 		f = stdin;
2004 		path = "(stdin)";
2005 		is_stdin = 1;
2006 	} else if ((f = fopen(identity_file, "r")) == NULL)
2007 		fatal("fopen %s: %s", identity_file, strerror(errno));
2008 
2009 	while (read_keyfile_line(f, path, line, sizeof(line), &lnum) == 0) {
2010 		sshkey_free(key);
2011 		key = NULL;
2012 		/* Trim leading space and comments */
2013 		cp = line + strspn(line, " \t");
2014 		if (*cp == '#' || *cp == '\0')
2015 			continue;
2016 		if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2017 			fatal("sshkey_new");
2018 		if ((r = sshkey_read(key, &cp)) != 0) {
2019 			error("%s:%lu: invalid key: %s", path,
2020 			    lnum, ssh_err(r));
2021 			continue;
2022 		}
2023 		if (!sshkey_is_cert(key)) {
2024 			error("%s:%lu is not a certificate", path, lnum);
2025 			continue;
2026 		}
2027 		ok = 1;
2028 		if (!is_stdin && lnum == 1)
2029 			printf("%s:\n", path);
2030 		else
2031 			printf("%s:%lu:\n", path, lnum);
2032 		print_cert(key);
2033 	}
2034 	sshkey_free(key);
2035 	fclose(f);
2036 	exit(ok ? 0 : 1);
2037 }
2038 
2039 #ifdef WITH_OPENSSL
2040 static void
2041 load_krl(const char *path, struct ssh_krl **krlp)
2042 {
2043 	struct sshbuf *krlbuf;
2044 	int r, fd;
2045 
2046 	if ((krlbuf = sshbuf_new()) == NULL)
2047 		fatal("sshbuf_new failed");
2048 	if ((fd = open(path, O_RDONLY)) == -1)
2049 		fatal("open %s: %s", path, strerror(errno));
2050 	if ((r = sshkey_load_file(fd, krlbuf)) != 0)
2051 		fatal("Unable to load KRL: %s", ssh_err(r));
2052 	close(fd);
2053 	/* XXX check sigs */
2054 	if ((r = ssh_krl_from_blob(krlbuf, krlp, NULL, 0)) != 0 ||
2055 	    *krlp == NULL)
2056 		fatal("Invalid KRL file: %s", ssh_err(r));
2057 	sshbuf_free(krlbuf);
2058 }
2059 
2060 static void
2061 update_krl_from_file(struct passwd *pw, const char *file, int wild_ca,
2062     const struct sshkey *ca, struct ssh_krl *krl)
2063 {
2064 	struct sshkey *key = NULL;
2065 	u_long lnum = 0;
2066 	char *path, *cp, *ep, line[SSH_MAX_PUBKEY_BYTES];
2067 	unsigned long long serial, serial2;
2068 	int i, was_explicit_key, was_sha1, r;
2069 	FILE *krl_spec;
2070 
2071 	path = tilde_expand_filename(file, pw->pw_uid);
2072 	if (strcmp(path, "-") == 0) {
2073 		krl_spec = stdin;
2074 		free(path);
2075 		path = xstrdup("(standard input)");
2076 	} else if ((krl_spec = fopen(path, "r")) == NULL)
2077 		fatal("fopen %s: %s", path, strerror(errno));
2078 
2079 	if (!quiet)
2080 		printf("Revoking from %s\n", path);
2081 	while (read_keyfile_line(krl_spec, path, line, sizeof(line),
2082 	    &lnum) == 0) {
2083 		was_explicit_key = was_sha1 = 0;
2084 		cp = line + strspn(line, " \t");
2085 		/* Trim trailing space, comments and strip \n */
2086 		for (i = 0, r = -1; cp[i] != '\0'; i++) {
2087 			if (cp[i] == '#' || cp[i] == '\n') {
2088 				cp[i] = '\0';
2089 				break;
2090 			}
2091 			if (cp[i] == ' ' || cp[i] == '\t') {
2092 				/* Remember the start of a span of whitespace */
2093 				if (r == -1)
2094 					r = i;
2095 			} else
2096 				r = -1;
2097 		}
2098 		if (r != -1)
2099 			cp[r] = '\0';
2100 		if (*cp == '\0')
2101 			continue;
2102 		if (strncasecmp(cp, "serial:", 7) == 0) {
2103 			if (ca == NULL && !wild_ca) {
2104 				fatal("revoking certificates by serial number "
2105 				    "requires specification of a CA key");
2106 			}
2107 			cp += 7;
2108 			cp = cp + strspn(cp, " \t");
2109 			errno = 0;
2110 			serial = strtoull(cp, &ep, 0);
2111 			if (*cp == '\0' || (*ep != '\0' && *ep != '-'))
2112 				fatal("%s:%lu: invalid serial \"%s\"",
2113 				    path, lnum, cp);
2114 			if (errno == ERANGE && serial == ULLONG_MAX)
2115 				fatal("%s:%lu: serial out of range",
2116 				    path, lnum);
2117 			serial2 = serial;
2118 			if (*ep == '-') {
2119 				cp = ep + 1;
2120 				errno = 0;
2121 				serial2 = strtoull(cp, &ep, 0);
2122 				if (*cp == '\0' || *ep != '\0')
2123 					fatal("%s:%lu: invalid serial \"%s\"",
2124 					    path, lnum, cp);
2125 				if (errno == ERANGE && serial2 == ULLONG_MAX)
2126 					fatal("%s:%lu: serial out of range",
2127 					    path, lnum);
2128 				if (serial2 <= serial)
2129 					fatal("%s:%lu: invalid serial range "
2130 					    "%llu:%llu", path, lnum,
2131 					    (unsigned long long)serial,
2132 					    (unsigned long long)serial2);
2133 			}
2134 			if (ssh_krl_revoke_cert_by_serial_range(krl,
2135 			    ca, serial, serial2) != 0) {
2136 				fatal("%s: revoke serial failed",
2137 				    __func__);
2138 			}
2139 		} else if (strncasecmp(cp, "id:", 3) == 0) {
2140 			if (ca == NULL && !wild_ca) {
2141 				fatal("revoking certificates by key ID "
2142 				    "requires specification of a CA key");
2143 			}
2144 			cp += 3;
2145 			cp = cp + strspn(cp, " \t");
2146 			if (ssh_krl_revoke_cert_by_key_id(krl, ca, cp) != 0)
2147 				fatal("%s: revoke key ID failed", __func__);
2148 		} else {
2149 			if (strncasecmp(cp, "key:", 4) == 0) {
2150 				cp += 4;
2151 				cp = cp + strspn(cp, " \t");
2152 				was_explicit_key = 1;
2153 			} else if (strncasecmp(cp, "sha1:", 5) == 0) {
2154 				cp += 5;
2155 				cp = cp + strspn(cp, " \t");
2156 				was_sha1 = 1;
2157 			} else {
2158 				/*
2159 				 * Just try to process the line as a key.
2160 				 * Parsing will fail if it isn't.
2161 				 */
2162 			}
2163 			if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2164 				fatal("sshkey_new");
2165 			if ((r = sshkey_read(key, &cp)) != 0)
2166 				fatal("%s:%lu: invalid key: %s",
2167 				    path, lnum, ssh_err(r));
2168 			if (was_explicit_key)
2169 				r = ssh_krl_revoke_key_explicit(krl, key);
2170 			else if (was_sha1)
2171 				r = ssh_krl_revoke_key_sha1(krl, key);
2172 			else
2173 				r = ssh_krl_revoke_key(krl, key);
2174 			if (r != 0)
2175 				fatal("%s: revoke key failed: %s",
2176 				    __func__, ssh_err(r));
2177 			sshkey_free(key);
2178 		}
2179 	}
2180 	if (strcmp(path, "-") != 0)
2181 		fclose(krl_spec);
2182 	free(path);
2183 }
2184 
2185 static void
2186 do_gen_krl(struct passwd *pw, int updating, int argc, char **argv)
2187 {
2188 	struct ssh_krl *krl;
2189 	struct stat sb;
2190 	struct sshkey *ca = NULL;
2191 	int fd, i, r, wild_ca = 0;
2192 	char *tmp;
2193 	struct sshbuf *kbuf;
2194 
2195 	if (*identity_file == '\0')
2196 		fatal("KRL generation requires an output file");
2197 	if (stat(identity_file, &sb) == -1) {
2198 		if (errno != ENOENT)
2199 			fatal("Cannot access KRL \"%s\": %s",
2200 			    identity_file, strerror(errno));
2201 		if (updating)
2202 			fatal("KRL \"%s\" does not exist", identity_file);
2203 	}
2204 	if (ca_key_path != NULL) {
2205 		if (strcasecmp(ca_key_path, "none") == 0)
2206 			wild_ca = 1;
2207 		else {
2208 			tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
2209 			if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
2210 				fatal("Cannot load CA public key %s: %s",
2211 				    tmp, ssh_err(r));
2212 			free(tmp);
2213 		}
2214 	}
2215 
2216 	if (updating)
2217 		load_krl(identity_file, &krl);
2218 	else if ((krl = ssh_krl_init()) == NULL)
2219 		fatal("couldn't create KRL");
2220 
2221 	if (cert_serial != 0)
2222 		ssh_krl_set_version(krl, cert_serial);
2223 	if (identity_comment != NULL)
2224 		ssh_krl_set_comment(krl, identity_comment);
2225 
2226 	for (i = 0; i < argc; i++)
2227 		update_krl_from_file(pw, argv[i], wild_ca, ca, krl);
2228 
2229 	if ((kbuf = sshbuf_new()) == NULL)
2230 		fatal("sshbuf_new failed");
2231 	if (ssh_krl_to_blob(krl, kbuf, NULL, 0) != 0)
2232 		fatal("Couldn't generate KRL");
2233 	if ((fd = open(identity_file, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
2234 		fatal("open %s: %s", identity_file, strerror(errno));
2235 	if (atomicio(vwrite, fd, (void *)sshbuf_ptr(kbuf), sshbuf_len(kbuf)) !=
2236 	    sshbuf_len(kbuf))
2237 		fatal("write %s: %s", identity_file, strerror(errno));
2238 	close(fd);
2239 	sshbuf_free(kbuf);
2240 	ssh_krl_free(krl);
2241 	sshkey_free(ca);
2242 }
2243 
2244 static void
2245 do_check_krl(struct passwd *pw, int argc, char **argv)
2246 {
2247 	int i, r, ret = 0;
2248 	char *comment;
2249 	struct ssh_krl *krl;
2250 	struct sshkey *k;
2251 
2252 	if (*identity_file == '\0')
2253 		fatal("KRL checking requires an input file");
2254 	load_krl(identity_file, &krl);
2255 	for (i = 0; i < argc; i++) {
2256 		if ((r = sshkey_load_public(argv[i], &k, &comment)) != 0)
2257 			fatal("Cannot load public key %s: %s",
2258 			    argv[i], ssh_err(r));
2259 		r = ssh_krl_check_key(krl, k);
2260 		printf("%s%s%s%s: %s\n", argv[i],
2261 		    *comment ? " (" : "", comment, *comment ? ")" : "",
2262 		    r == 0 ? "ok" : "REVOKED");
2263 		if (r != 0)
2264 			ret = 1;
2265 		sshkey_free(k);
2266 		free(comment);
2267 	}
2268 	ssh_krl_free(krl);
2269 	exit(ret);
2270 }
2271 #endif
2272 
2273 static void
2274 usage(void)
2275 {
2276 	fprintf(stderr,
2277 	    "usage: ssh-keygen [-q] [-b bits] [-t dsa | ecdsa | ed25519 | rsa]\n"
2278 	    "                  [-N new_passphrase] [-C comment] [-f output_keyfile]\n"
2279 	    "       ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]\n"
2280 	    "       ssh-keygen -i [-m key_format] [-f input_keyfile]\n"
2281 	    "       ssh-keygen -e [-m key_format] [-f input_keyfile]\n"
2282 	    "       ssh-keygen -y [-f input_keyfile]\n"
2283 	    "       ssh-keygen -c [-P passphrase] [-C comment] [-f keyfile]\n"
2284 	    "       ssh-keygen -l [-v] [-E fingerprint_hash] [-f input_keyfile]\n"
2285 	    "       ssh-keygen -B [-f input_keyfile]\n");
2286 #ifdef ENABLE_PKCS11
2287 	fprintf(stderr,
2288 	    "       ssh-keygen -D pkcs11\n");
2289 #endif
2290 	fprintf(stderr,
2291 	    "       ssh-keygen -F hostname [-f known_hosts_file] [-l]\n"
2292 	    "       ssh-keygen -H [-f known_hosts_file]\n"
2293 	    "       ssh-keygen -R hostname [-f known_hosts_file]\n"
2294 	    "       ssh-keygen -r hostname [-f input_keyfile] [-g]\n"
2295 #ifdef WITH_OPENSSL
2296 	    "       ssh-keygen -G output_file [-v] [-b bits] [-M memory] [-S start_point]\n"
2297 	    "       ssh-keygen -T output_file -f input_file [-v] [-a rounds] [-J num_lines]\n"
2298 	    "                  [-j start_line] [-K checkpt] [-W generator]\n"
2299 #endif
2300 	    "       ssh-keygen -s ca_key -I certificate_identity [-h] [-U]\n"
2301 	    "                  [-D pkcs11_provider] [-n principals] [-O option]\n"
2302 	    "                  [-V validity_interval] [-z serial_number] file ...\n"
2303 	    "       ssh-keygen -L [-f input_keyfile]\n"
2304 	    "       ssh-keygen -A\n"
2305 	    "       ssh-keygen -k -f krl_file [-u] [-s ca_public] [-z version_number]\n"
2306 	    "                  file ...\n"
2307 	    "       ssh-keygen -Q -f krl_file file ...\n");
2308 	exit(1);
2309 }
2310 
2311 /*
2312  * Main program for key management.
2313  */
2314 int
2315 main(int argc, char **argv)
2316 {
2317 	char dotsshdir[PATH_MAX], comment[1024], *passphrase1, *passphrase2;
2318 	char *rr_hostname = NULL, *ep, *fp, *ra;
2319 	struct sshkey *private, *public;
2320 	struct passwd *pw;
2321 	struct stat st;
2322 	int r, opt, type, fd;
2323 	int gen_all_hostkeys = 0, gen_krl = 0, update_krl = 0, check_krl = 0;
2324 	FILE *f;
2325 	const char *errstr;
2326 #ifdef WITH_OPENSSL
2327 	/* Moduli generation/screening */
2328 	char out_file[PATH_MAX], *checkpoint = NULL;
2329 	u_int32_t memory = 0, generator_wanted = 0;
2330 	int do_gen_candidates = 0, do_screen_candidates = 0;
2331 	unsigned long start_lineno = 0, lines_to_process = 0;
2332 	BIGNUM *start = NULL;
2333 #endif
2334 
2335 	extern int optind;
2336 	extern char *optarg;
2337 
2338 	ssh_malloc_init();	/* must be called before any mallocs */
2339 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
2340 	sanitise_stdfd();
2341 
2342 	OpenSSL_add_all_algorithms();
2343 	log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
2344 
2345 	setlocale(LC_CTYPE, "");
2346 
2347 	/* we need this for the home * directory.  */
2348 	pw = getpwuid(getuid());
2349 	if (!pw)
2350 		fatal("No user exists for uid %lu", (u_long)getuid());
2351 	if (gethostname(hostname, sizeof(hostname)) < 0)
2352 		fatal("gethostname: %s", strerror(errno));
2353 
2354 	/* Remaining characters: Ydw */
2355 	while ((opt = getopt(argc, argv, "ABHLQUXceghiklopquvxy"
2356 	    "C:D:E:F:G:I:J:K:M:N:O:P:R:S:T:V:W:Z:"
2357 	    "a:b:f:g:j:m:n:r:s:t:z:")) != -1) {
2358 		switch (opt) {
2359 		case 'A':
2360 			gen_all_hostkeys = 1;
2361 			break;
2362 		case 'b':
2363 			bits = (u_int32_t)strtonum(optarg, 10, 32768, &errstr);
2364 			if (errstr)
2365 				fatal("Bits has bad value %s (%s)",
2366 					optarg, errstr);
2367 			break;
2368 		case 'E':
2369 			fingerprint_hash = ssh_digest_alg_by_name(optarg);
2370 			if (fingerprint_hash == -1)
2371 				fatal("Invalid hash algorithm \"%s\"", optarg);
2372 			break;
2373 		case 'F':
2374 			find_host = 1;
2375 			rr_hostname = optarg;
2376 			break;
2377 		case 'H':
2378 			hash_hosts = 1;
2379 			break;
2380 		case 'I':
2381 			cert_key_id = optarg;
2382 			break;
2383 		case 'R':
2384 			delete_host = 1;
2385 			rr_hostname = optarg;
2386 			break;
2387 		case 'L':
2388 			show_cert = 1;
2389 			break;
2390 		case 'l':
2391 			print_fingerprint = 1;
2392 			break;
2393 		case 'B':
2394 			print_bubblebabble = 1;
2395 			break;
2396 		case 'm':
2397 			if (strcasecmp(optarg, "RFC4716") == 0 ||
2398 			    strcasecmp(optarg, "ssh2") == 0) {
2399 				convert_format = FMT_RFC4716;
2400 				break;
2401 			}
2402 			if (strcasecmp(optarg, "PKCS8") == 0) {
2403 				convert_format = FMT_PKCS8;
2404 				break;
2405 			}
2406 			if (strcasecmp(optarg, "PEM") == 0) {
2407 				convert_format = FMT_PEM;
2408 				break;
2409 			}
2410 			fatal("Unsupported conversion format \"%s\"", optarg);
2411 		case 'n':
2412 			cert_principals = optarg;
2413 			break;
2414 		case 'o':
2415 			use_new_format = 1;
2416 			break;
2417 		case 'p':
2418 			change_passphrase = 1;
2419 			break;
2420 		case 'c':
2421 			change_comment = 1;
2422 			break;
2423 		case 'f':
2424 			if (strlcpy(identity_file, optarg,
2425 			    sizeof(identity_file)) >= sizeof(identity_file))
2426 				fatal("Identity filename too long");
2427 			have_identity = 1;
2428 			break;
2429 		case 'g':
2430 			print_generic = 1;
2431 			break;
2432 		case 'P':
2433 			identity_passphrase = optarg;
2434 			break;
2435 		case 'N':
2436 			identity_new_passphrase = optarg;
2437 			break;
2438 		case 'Q':
2439 			check_krl = 1;
2440 			break;
2441 		case 'O':
2442 			add_cert_option(optarg);
2443 			break;
2444 		case 'Z':
2445 			new_format_cipher = optarg;
2446 			break;
2447 		case 'C':
2448 			identity_comment = optarg;
2449 			break;
2450 		case 'q':
2451 			quiet = 1;
2452 			break;
2453 		case 'e':
2454 		case 'x':
2455 			/* export key */
2456 			convert_to = 1;
2457 			break;
2458 		case 'h':
2459 			cert_key_type = SSH2_CERT_TYPE_HOST;
2460 			certflags_flags = 0;
2461 			break;
2462 		case 'k':
2463 			gen_krl = 1;
2464 			break;
2465 		case 'i':
2466 		case 'X':
2467 			/* import key */
2468 			convert_from = 1;
2469 			break;
2470 		case 'y':
2471 			print_public = 1;
2472 			break;
2473 		case 's':
2474 			ca_key_path = optarg;
2475 			break;
2476 		case 't':
2477 			key_type_name = optarg;
2478 			break;
2479 		case 'D':
2480 			pkcs11provider = optarg;
2481 			break;
2482 		case 'U':
2483 			prefer_agent = 1;
2484 			break;
2485 		case 'u':
2486 			update_krl = 1;
2487 			break;
2488 		case 'v':
2489 			if (log_level == SYSLOG_LEVEL_INFO)
2490 				log_level = SYSLOG_LEVEL_DEBUG1;
2491 			else {
2492 				if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
2493 				    log_level < SYSLOG_LEVEL_DEBUG3)
2494 					log_level++;
2495 			}
2496 			break;
2497 		case 'r':
2498 			rr_hostname = optarg;
2499 			break;
2500 		case 'a':
2501 			rounds = (int)strtonum(optarg, 1, INT_MAX, &errstr);
2502 			if (errstr)
2503 				fatal("Invalid number: %s (%s)",
2504 					optarg, errstr);
2505 			break;
2506 		case 'V':
2507 			parse_cert_times(optarg);
2508 			break;
2509 		case 'z':
2510 			errno = 0;
2511 			cert_serial = strtoull(optarg, &ep, 10);
2512 			if (*optarg < '0' || *optarg > '9' || *ep != '\0' ||
2513 			    (errno == ERANGE && cert_serial == ULLONG_MAX))
2514 				fatal("Invalid serial number \"%s\"", optarg);
2515 			break;
2516 #ifdef WITH_OPENSSL
2517 		/* Moduli generation/screening */
2518 		case 'G':
2519 			do_gen_candidates = 1;
2520 			if (strlcpy(out_file, optarg, sizeof(out_file)) >=
2521 			    sizeof(out_file))
2522 				fatal("Output filename too long");
2523 			break;
2524 		case 'J':
2525 			lines_to_process = strtoul(optarg, NULL, 10);
2526 			break;
2527 		case 'j':
2528 			start_lineno = strtoul(optarg, NULL, 10);
2529 			break;
2530 		case 'K':
2531 			if (strlen(optarg) >= PATH_MAX)
2532 				fatal("Checkpoint filename too long");
2533 			checkpoint = xstrdup(optarg);
2534 			break;
2535 		case 'M':
2536 			memory = (u_int32_t)strtonum(optarg, 1, UINT_MAX,
2537 			    &errstr);
2538 			if (errstr)
2539 				fatal("Memory limit is %s: %s", errstr, optarg);
2540 			break;
2541 		case 'S':
2542 			/* XXX - also compare length against bits */
2543 			if (BN_hex2bn(&start, optarg) == 0)
2544 				fatal("Invalid start point.");
2545 			break;
2546 		case 'T':
2547 			do_screen_candidates = 1;
2548 			if (strlcpy(out_file, optarg, sizeof(out_file)) >=
2549 			    sizeof(out_file))
2550 				fatal("Output filename too long");
2551 			break;
2552 		case 'W':
2553 			generator_wanted = (u_int32_t)strtonum(optarg, 1,
2554 			    UINT_MAX, &errstr);
2555 			if (errstr != NULL)
2556 				fatal("Desired generator invalid: %s (%s)",
2557 				    optarg, errstr);
2558 			break;
2559 #endif /* WITH_OPENSSL */
2560 		case '?':
2561 		default:
2562 			usage();
2563 		}
2564 	}
2565 
2566 	/* reinit */
2567 	log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
2568 
2569 	argv += optind;
2570 	argc -= optind;
2571 
2572 	if (ca_key_path != NULL) {
2573 		if (argc < 1 && !gen_krl) {
2574 			error("Too few arguments.");
2575 			usage();
2576 		}
2577 	} else if (argc > 0 && !gen_krl && !check_krl) {
2578 		error("Too many arguments.");
2579 		usage();
2580 	}
2581 	if (change_passphrase && change_comment) {
2582 		error("Can only have one of -p and -c.");
2583 		usage();
2584 	}
2585 	if (print_fingerprint && (delete_host || hash_hosts)) {
2586 		error("Cannot use -l with -H or -R.");
2587 		usage();
2588 	}
2589 #ifdef WITH_OPENSSL
2590 	if (gen_krl) {
2591 		do_gen_krl(pw, update_krl, argc, argv);
2592 		return (0);
2593 	}
2594 	if (check_krl) {
2595 		do_check_krl(pw, argc, argv);
2596 		return (0);
2597 	}
2598 #endif
2599 	if (ca_key_path != NULL) {
2600 		if (cert_key_id == NULL)
2601 			fatal("Must specify key id (-I) when certifying");
2602 		do_ca_sign(pw, argc, argv);
2603 	}
2604 	if (show_cert)
2605 		do_show_cert(pw);
2606 	if (delete_host || hash_hosts || find_host)
2607 		do_known_hosts(pw, rr_hostname);
2608 	if (pkcs11provider != NULL)
2609 		do_download(pw);
2610 	if (print_fingerprint || print_bubblebabble)
2611 		do_fingerprint(pw);
2612 	if (change_passphrase)
2613 		do_change_passphrase(pw);
2614 	if (change_comment)
2615 		do_change_comment(pw);
2616 #ifdef WITH_OPENSSL
2617 	if (convert_to)
2618 		do_convert_to(pw);
2619 	if (convert_from)
2620 		do_convert_from(pw);
2621 #endif
2622 	if (print_public)
2623 		do_print_public(pw);
2624 	if (rr_hostname != NULL) {
2625 		unsigned int n = 0;
2626 
2627 		if (have_identity) {
2628 			n = do_print_resource_record(pw,
2629 			    identity_file, rr_hostname);
2630 			if (n == 0)
2631 				fatal("%s: %s", identity_file, strerror(errno));
2632 			exit(0);
2633 		} else {
2634 
2635 			n += do_print_resource_record(pw,
2636 			    _PATH_HOST_RSA_KEY_FILE, rr_hostname);
2637 			n += do_print_resource_record(pw,
2638 			    _PATH_HOST_DSA_KEY_FILE, rr_hostname);
2639 			n += do_print_resource_record(pw,
2640 			    _PATH_HOST_ECDSA_KEY_FILE, rr_hostname);
2641 			n += do_print_resource_record(pw,
2642 			    _PATH_HOST_ED25519_KEY_FILE, rr_hostname);
2643 			n += do_print_resource_record(pw,
2644 			    _PATH_HOST_XMSS_KEY_FILE, rr_hostname);
2645 			if (n == 0)
2646 				fatal("no keys found.");
2647 			exit(0);
2648 		}
2649 	}
2650 
2651 #ifdef WITH_OPENSSL
2652 	if (do_gen_candidates) {
2653 		FILE *out = fopen(out_file, "w");
2654 
2655 		if (out == NULL) {
2656 			error("Couldn't open modulus candidate file \"%s\": %s",
2657 			    out_file, strerror(errno));
2658 			return (1);
2659 		}
2660 		if (bits == 0)
2661 			bits = DEFAULT_BITS;
2662 		if (gen_candidates(out, memory, bits, start) != 0)
2663 			fatal("modulus candidate generation failed");
2664 
2665 		return (0);
2666 	}
2667 
2668 	if (do_screen_candidates) {
2669 		FILE *in;
2670 		FILE *out = fopen(out_file, "a");
2671 
2672 		if (have_identity && strcmp(identity_file, "-") != 0) {
2673 			if ((in = fopen(identity_file, "r")) == NULL) {
2674 				fatal("Couldn't open modulus candidate "
2675 				    "file \"%s\": %s", identity_file,
2676 				    strerror(errno));
2677 			}
2678 		} else
2679 			in = stdin;
2680 
2681 		if (out == NULL) {
2682 			fatal("Couldn't open moduli file \"%s\": %s",
2683 			    out_file, strerror(errno));
2684 		}
2685 		if (prime_test(in, out, rounds == 0 ? 100 : rounds,
2686 		    generator_wanted, checkpoint,
2687 		    start_lineno, lines_to_process) != 0)
2688 			fatal("modulus screening failed");
2689 		return (0);
2690 	}
2691 #endif
2692 
2693 	if (gen_all_hostkeys) {
2694 		do_gen_all_hostkeys(pw);
2695 		return (0);
2696 	}
2697 
2698 	if (key_type_name == NULL)
2699 		key_type_name = DEFAULT_KEY_TYPE_NAME;
2700 
2701 	type = sshkey_type_from_name(key_type_name);
2702 	type_bits_valid(type, key_type_name, &bits);
2703 
2704 	if (!quiet)
2705 		printf("Generating public/private %s key pair.\n",
2706 		    key_type_name);
2707 	if ((r = sshkey_generate(type, bits, &private)) != 0)
2708 		fatal("sshkey_generate failed");
2709 	if ((r = sshkey_from_private(private, &public)) != 0)
2710 		fatal("sshkey_from_private failed: %s\n", ssh_err(r));
2711 
2712 	if (!have_identity)
2713 		ask_filename(pw, "Enter file in which to save the key");
2714 
2715 	/* Create ~/.ssh directory if it doesn't already exist. */
2716 	snprintf(dotsshdir, sizeof dotsshdir, "%s/%s",
2717 	    pw->pw_dir, _PATH_SSH_USER_DIR);
2718 	if (strstr(identity_file, dotsshdir) != NULL) {
2719 		if (stat(dotsshdir, &st) < 0) {
2720 			if (errno != ENOENT) {
2721 				error("Could not stat %s: %s", dotsshdir,
2722 				    strerror(errno));
2723 			} else if (mkdir(dotsshdir, 0700) < 0) {
2724 				error("Could not create directory '%s': %s",
2725 				    dotsshdir, strerror(errno));
2726 			} else if (!quiet)
2727 				printf("Created directory '%s'.\n", dotsshdir);
2728 		}
2729 	}
2730 	/* If the file already exists, ask the user to confirm. */
2731 	if (stat(identity_file, &st) >= 0) {
2732 		char yesno[3];
2733 		printf("%s already exists.\n", identity_file);
2734 		printf("Overwrite (y/n)? ");
2735 		fflush(stdout);
2736 		if (fgets(yesno, sizeof(yesno), stdin) == NULL)
2737 			exit(1);
2738 		if (yesno[0] != 'y' && yesno[0] != 'Y')
2739 			exit(1);
2740 	}
2741 	/* Ask for a passphrase (twice). */
2742 	if (identity_passphrase)
2743 		passphrase1 = xstrdup(identity_passphrase);
2744 	else if (identity_new_passphrase)
2745 		passphrase1 = xstrdup(identity_new_passphrase);
2746 	else {
2747 passphrase_again:
2748 		passphrase1 =
2749 			read_passphrase("Enter passphrase (empty for no "
2750 			    "passphrase): ", RP_ALLOW_STDIN);
2751 		passphrase2 = read_passphrase("Enter same passphrase again: ",
2752 		    RP_ALLOW_STDIN);
2753 		if (strcmp(passphrase1, passphrase2) != 0) {
2754 			/*
2755 			 * The passphrases do not match.  Clear them and
2756 			 * retry.
2757 			 */
2758 			explicit_bzero(passphrase1, strlen(passphrase1));
2759 			explicit_bzero(passphrase2, strlen(passphrase2));
2760 			free(passphrase1);
2761 			free(passphrase2);
2762 			printf("Passphrases do not match.  Try again.\n");
2763 			goto passphrase_again;
2764 		}
2765 		/* Clear the other copy of the passphrase. */
2766 		explicit_bzero(passphrase2, strlen(passphrase2));
2767 		free(passphrase2);
2768 	}
2769 
2770 	if (identity_comment) {
2771 		strlcpy(comment, identity_comment, sizeof(comment));
2772 	} else {
2773 		/* Create default comment field for the passphrase. */
2774 		snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
2775 	}
2776 
2777 	/* Save the key with the given passphrase and comment. */
2778 	if ((r = sshkey_save_private(private, identity_file, passphrase1,
2779 	    comment, use_new_format, new_format_cipher, rounds)) != 0) {
2780 		error("Saving key \"%s\" failed: %s",
2781 		    identity_file, ssh_err(r));
2782 		explicit_bzero(passphrase1, strlen(passphrase1));
2783 		free(passphrase1);
2784 		exit(1);
2785 	}
2786 	/* Clear the passphrase. */
2787 	explicit_bzero(passphrase1, strlen(passphrase1));
2788 	free(passphrase1);
2789 
2790 	/* Clear the private key and the random number generator. */
2791 	sshkey_free(private);
2792 
2793 	if (!quiet)
2794 		printf("Your identification has been saved in %s.\n", identity_file);
2795 
2796 	strlcat(identity_file, ".pub", sizeof(identity_file));
2797 	if ((fd = open(identity_file, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
2798 		fatal("Unable to save public key to %s: %s",
2799 		    identity_file, strerror(errno));
2800 	if ((f = fdopen(fd, "w")) == NULL)
2801 		fatal("fdopen %s failed: %s", identity_file, strerror(errno));
2802 	if ((r = sshkey_write(public, f)) != 0)
2803 		error("write key failed: %s", ssh_err(r));
2804 	fprintf(f, " %s\n", comment);
2805 	if (ferror(f) || fclose(f) != 0)
2806 		fatal("write public failed: %s", strerror(errno));
2807 
2808 	if (!quiet) {
2809 		fp = sshkey_fingerprint(public, fingerprint_hash,
2810 		    SSH_FP_DEFAULT);
2811 		ra = sshkey_fingerprint(public, fingerprint_hash,
2812 		    SSH_FP_RANDOMART);
2813 		if (fp == NULL || ra == NULL)
2814 			fatal("sshkey_fingerprint failed");
2815 		printf("Your public key has been saved in %s.\n",
2816 		    identity_file);
2817 		printf("The key fingerprint is:\n");
2818 		printf("%s %s\n", fp, comment);
2819 		printf("The key's randomart image is:\n");
2820 		printf("%s\n", ra);
2821 		free(ra);
2822 		free(fp);
2823 	}
2824 
2825 	sshkey_free(public);
2826 	exit(0);
2827 }
2828