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