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