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