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