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