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