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