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