xref: /netbsd-src/crypto/external/bsd/openssh/dist/ssh-keygen.c (revision 6d322f2f4598f0d8a138f10ea648ec4fabe41f8b)
1 /*	$NetBSD: ssh-keygen.c,v 1.13 2013/11/08 19:18:25 christos Exp $	*/
2 /* $OpenBSD: ssh-keygen.c,v 1.230 2013/07/20 01:44:37 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.13 2013/11/08 19:18:25 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 		free(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 	free(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 		free(cipher);
413 		buffer_free(&b);
414 		free(type);
415 		return NULL;
416 	}
417 	free(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 		free(type);
426 		return NULL;
427 	}
428 	key = key_new_private(ktype);
429 	free(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 	free(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 (blen > 0 && 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 			free(ra);
740 			free(fp);
741 		} else {
742 			key_write(keys[i], stdout);
743 			fprintf(stdout, "\n");
744 		}
745 		key_free(keys[i]);
746 	}
747 	free(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 		free(comment);
785 		free(ra);
786 		free(fp);
787 		exit(0);
788 	}
789 	if (comment) {
790 		free(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 		free(ra);
850 		free(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 		free(ra);
972 		free(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 		free(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 		free(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 			free(passphrase1);
1253 			free(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 		free(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 		free(passphrase1);
1267 		key_free(private);
1268 		free(comment);
1269 		exit(1);
1270 	}
1271 	/* Destroy the passphrase and the copy of the key in memory. */
1272 	memset(passphrase1, 0, strlen(passphrase1));
1273 	free(passphrase1);
1274 	key_free(private);		 /* Destroys contents */
1275 	free(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 		fatal("%s: no filename", __func__);
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 		free(comment);
1305 		return 1;
1306 	}
1307 	if (comment)
1308 		free(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 			free(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 		free(passphrase);
1378 		key_free(private);
1379 		free(comment);
1380 		exit(1);
1381 	}
1382 	memset(passphrase, 0, strlen(passphrase));
1383 	free(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 	free(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 	free(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 	free(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 			free(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 		free(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 		free(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 	free(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 	char *name;
1791 	u_char *data;
1792 	u_int dlen;
1793 	Buffer options, option;
1794 
1795 	buffer_init(&options);
1796 	buffer_append(&options, buffer_ptr(optbuf), buffer_len(optbuf));
1797 
1798 	buffer_init(&option);
1799 	while (buffer_len(&options) != 0) {
1800 		name = buffer_get_string(&options, NULL);
1801 		data = buffer_get_string_ptr(&options, &dlen);
1802 		buffer_append(&option, data, dlen);
1803 		printf("                %s", name);
1804 		if ((v00 || !in_critical) &&
1805 		    (strcmp(name, "permit-X11-forwarding") == 0 ||
1806 		    strcmp(name, "permit-agent-forwarding") == 0 ||
1807 		    strcmp(name, "permit-port-forwarding") == 0 ||
1808 		    strcmp(name, "permit-pty") == 0 ||
1809 		    strcmp(name, "permit-user-rc") == 0))
1810 			printf("\n");
1811 		else if ((v00 || in_critical) &&
1812 		    (strcmp(name, "force-command") == 0 ||
1813 		    strcmp(name, "source-address") == 0)) {
1814 			data = buffer_get_string(&option, NULL);
1815 			printf(" %s\n", data);
1816 			free(data);
1817 		} else {
1818 			printf(" UNKNOWN OPTION (len %u)\n",
1819 			    buffer_len(&option));
1820 			buffer_clear(&option);
1821 		}
1822 		free(name);
1823 		if (buffer_len(&option) != 0)
1824 			fatal("Option corrupt: extra data at end");
1825 	}
1826 	buffer_free(&option);
1827 	buffer_free(&options);
1828 }
1829 
1830 __dead static void
1831 do_show_cert(struct passwd *pw)
1832 {
1833 	Key *key;
1834 	struct stat st;
1835 	char *key_fp, *ca_fp;
1836 	u_int i, v00;
1837 
1838 	if (!have_identity)
1839 		ask_filename(pw, "Enter file in which the key is");
1840 	if (stat(identity_file, &st) < 0)
1841 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
1842 	if ((key = key_load_public(identity_file, NULL)) == NULL)
1843 		fatal("%s is not a public key", identity_file);
1844 	if (!key_is_cert(key))
1845 		fatal("%s is not a certificate", identity_file);
1846 	v00 = key->type == KEY_RSA_CERT_V00 || key->type == KEY_DSA_CERT_V00;
1847 
1848 	key_fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
1849 	ca_fp = key_fingerprint(key->cert->signature_key,
1850 	    SSH_FP_MD5, SSH_FP_HEX);
1851 
1852 	printf("%s:\n", identity_file);
1853 	printf("        Type: %s %s certificate\n", key_ssh_name(key),
1854 	    key_cert_type(key));
1855 	printf("        Public key: %s %s\n", key_type(key), key_fp);
1856 	printf("        Signing CA: %s %s\n",
1857 	    key_type(key->cert->signature_key), ca_fp);
1858 	printf("        Key ID: \"%s\"\n", key->cert->key_id);
1859 	if (!v00) {
1860 		printf("        Serial: %llu\n",
1861 		    (unsigned long long)key->cert->serial);
1862 	}
1863 	printf("        Valid: %s\n",
1864 	    fmt_validity(key->cert->valid_after, key->cert->valid_before));
1865 	printf("        Principals: ");
1866 	if (key->cert->nprincipals == 0)
1867 		printf("(none)\n");
1868 	else {
1869 		for (i = 0; i < key->cert->nprincipals; i++)
1870 			printf("\n                %s",
1871 			    key->cert->principals[i]);
1872 		printf("\n");
1873 	}
1874 	printf("        Critical Options: ");
1875 	if (buffer_len(&key->cert->critical) == 0)
1876 		printf("(none)\n");
1877 	else {
1878 		printf("\n");
1879 		show_options(&key->cert->critical, v00, 1);
1880 	}
1881 	if (!v00) {
1882 		printf("        Extensions: ");
1883 		if (buffer_len(&key->cert->extensions) == 0)
1884 			printf("(none)\n");
1885 		else {
1886 			printf("\n");
1887 			show_options(&key->cert->extensions, v00, 0);
1888 		}
1889 	}
1890 	exit(0);
1891 }
1892 
1893 static void
1894 load_krl(const char *path, struct ssh_krl **krlp)
1895 {
1896 	Buffer krlbuf;
1897 	int fd;
1898 
1899 	buffer_init(&krlbuf);
1900 	if ((fd = open(path, O_RDONLY)) == -1)
1901 		fatal("open %s: %s", path, strerror(errno));
1902 	if (!key_load_file(fd, path, &krlbuf))
1903 		fatal("Unable to load KRL");
1904 	close(fd);
1905 	/* XXX check sigs */
1906 	if (ssh_krl_from_blob(&krlbuf, krlp, NULL, 0) != 0 ||
1907 	    *krlp == NULL)
1908 		fatal("Invalid KRL file");
1909 	buffer_free(&krlbuf);
1910 }
1911 
1912 static void
1913 update_krl_from_file(struct passwd *pw, const char *file, const Key *ca,
1914     struct ssh_krl *krl)
1915 {
1916 	Key *key = NULL;
1917 	u_long lnum = 0;
1918 	char *path, *cp, *ep, line[SSH_MAX_PUBKEY_BYTES];
1919 	unsigned long long serial, serial2;
1920 	int i, was_explicit_key, was_sha1, r;
1921 	FILE *krl_spec;
1922 
1923 	path = tilde_expand_filename(file, pw->pw_uid);
1924 	if (strcmp(path, "-") == 0) {
1925 		krl_spec = stdin;
1926 		free(path);
1927 		path = xstrdup("(standard input)");
1928 	} else if ((krl_spec = fopen(path, "r")) == NULL)
1929 		fatal("fopen %s: %s", path, strerror(errno));
1930 
1931 	if (!quiet)
1932 		printf("Revoking from %s\n", path);
1933 	while (read_keyfile_line(krl_spec, path, line, sizeof(line),
1934 	    &lnum) == 0) {
1935 		was_explicit_key = was_sha1 = 0;
1936 		cp = line + strspn(line, " \t");
1937 		/* Trim trailing space, comments and strip \n */
1938 		for (i = 0, r = -1; cp[i] != '\0'; i++) {
1939 			if (cp[i] == '#' || cp[i] == '\n') {
1940 				cp[i] = '\0';
1941 				break;
1942 			}
1943 			if (cp[i] == ' ' || cp[i] == '\t') {
1944 				/* Remember the start of a span of whitespace */
1945 				if (r == -1)
1946 					r = i;
1947 			} else
1948 				r = -1;
1949 		}
1950 		if (r != -1)
1951 			cp[r] = '\0';
1952 		if (*cp == '\0')
1953 			continue;
1954 		if (strncasecmp(cp, "serial:", 7) == 0) {
1955 			if (ca == NULL) {
1956 				fatal("revoking certificated by serial number "
1957 				    "requires specification of a CA key");
1958 			}
1959 			cp += 7;
1960 			cp = cp + strspn(cp, " \t");
1961 			errno = 0;
1962 			serial = strtoull(cp, &ep, 0);
1963 			if (*cp == '\0' || (*ep != '\0' && *ep != '-'))
1964 				fatal("%s:%lu: invalid serial \"%s\"",
1965 				    path, lnum, cp);
1966 			if (errno == ERANGE && serial == ULLONG_MAX)
1967 				fatal("%s:%lu: serial out of range",
1968 				    path, lnum);
1969 			serial2 = serial;
1970 			if (*ep == '-') {
1971 				cp = ep + 1;
1972 				errno = 0;
1973 				serial2 = strtoull(cp, &ep, 0);
1974 				if (*cp == '\0' || *ep != '\0')
1975 					fatal("%s:%lu: invalid serial \"%s\"",
1976 					    path, lnum, cp);
1977 				if (errno == ERANGE && serial2 == ULLONG_MAX)
1978 					fatal("%s:%lu: serial out of range",
1979 					    path, lnum);
1980 				if (serial2 <= serial)
1981 					fatal("%s:%lu: invalid serial range "
1982 					    "%llu:%llu", path, lnum,
1983 					    (unsigned long long)serial,
1984 					    (unsigned long long)serial2);
1985 			}
1986 			if (ssh_krl_revoke_cert_by_serial_range(krl,
1987 			    ca, serial, serial2) != 0) {
1988 				fatal("%s: revoke serial failed",
1989 				    __func__);
1990 			}
1991 		} else if (strncasecmp(cp, "id:", 3) == 0) {
1992 			if (ca == NULL) {
1993 				fatal("revoking certificated by key ID "
1994 				    "requires specification of a CA key");
1995 			}
1996 			cp += 3;
1997 			cp = cp + strspn(cp, " \t");
1998 			if (ssh_krl_revoke_cert_by_key_id(krl, ca, cp) != 0)
1999 				fatal("%s: revoke key ID failed", __func__);
2000 		} else {
2001 			if (strncasecmp(cp, "key:", 4) == 0) {
2002 				cp += 4;
2003 				cp = cp + strspn(cp, " \t");
2004 				was_explicit_key = 1;
2005 			} else if (strncasecmp(cp, "sha1:", 5) == 0) {
2006 				cp += 5;
2007 				cp = cp + strspn(cp, " \t");
2008 				was_sha1 = 1;
2009 			} else {
2010 				/*
2011 				 * Just try to process the line as a key.
2012 				 * Parsing will fail if it isn't.
2013 				 */
2014 			}
2015 			if ((key = key_new(KEY_UNSPEC)) == NULL)
2016 				fatal("key_new");
2017 			if (key_read(key, &cp) != 1)
2018 				fatal("%s:%lu: invalid key", path, lnum);
2019 			if (was_explicit_key)
2020 				r = ssh_krl_revoke_key_explicit(krl, key);
2021 			else if (was_sha1)
2022 				r = ssh_krl_revoke_key_sha1(krl, key);
2023 			else
2024 				r = ssh_krl_revoke_key(krl, key);
2025 			if (r != 0)
2026 				fatal("%s: revoke key failed", __func__);
2027 			key_free(key);
2028 		}
2029 	}
2030 	if (strcmp(path, "-") != 0)
2031 		fclose(krl_spec);
2032 	free(path);
2033 }
2034 
2035 static void
2036 do_gen_krl(struct passwd *pw, int updating, int argc, char **argv)
2037 {
2038 	struct ssh_krl *krl;
2039 	struct stat sb;
2040 	Key *ca = NULL;
2041 	int fd, i;
2042 	char *tmp;
2043 	Buffer kbuf;
2044 
2045 	if (*identity_file == '\0')
2046 		fatal("KRL generation requires an output file");
2047 	if (stat(identity_file, &sb) == -1) {
2048 		if (errno != ENOENT)
2049 			fatal("Cannot access KRL \"%s\": %s",
2050 			    identity_file, strerror(errno));
2051 		if (updating)
2052 			fatal("KRL \"%s\" does not exist", identity_file);
2053 	}
2054 	if (ca_key_path != NULL) {
2055 		tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
2056 		if ((ca = key_load_public(tmp, NULL)) == NULL)
2057 			fatal("Cannot load CA public key %s", tmp);
2058 		free(tmp);
2059 	}
2060 
2061 	if (updating)
2062 		load_krl(identity_file, &krl);
2063 	else if ((krl = ssh_krl_init()) == NULL)
2064 		fatal("couldn't create KRL");
2065 
2066 	if (cert_serial != 0)
2067 		ssh_krl_set_version(krl, cert_serial);
2068 	if (identity_comment != NULL)
2069 		ssh_krl_set_comment(krl, identity_comment);
2070 
2071 	for (i = 0; i < argc; i++)
2072 		update_krl_from_file(pw, argv[i], ca, krl);
2073 
2074 	buffer_init(&kbuf);
2075 	if (ssh_krl_to_blob(krl, &kbuf, NULL, 0) != 0)
2076 		fatal("Couldn't generate KRL");
2077 	if ((fd = open(identity_file, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
2078 		fatal("open %s: %s", identity_file, strerror(errno));
2079 	if (atomicio(vwrite, fd, buffer_ptr(&kbuf), buffer_len(&kbuf)) !=
2080 	    buffer_len(&kbuf))
2081 		fatal("write %s: %s", identity_file, strerror(errno));
2082 	close(fd);
2083 	buffer_free(&kbuf);
2084 	ssh_krl_free(krl);
2085 	if (ca != NULL)
2086 		key_free(ca);
2087 }
2088 
2089 __dead static void
2090 do_check_krl(struct passwd *pw, int argc, char **argv)
2091 {
2092 	int i, r, ret = 0;
2093 	char *comment;
2094 	struct ssh_krl *krl;
2095 	Key *k;
2096 
2097 	if (*identity_file == '\0')
2098 		fatal("KRL checking requires an input file");
2099 	load_krl(identity_file, &krl);
2100 	for (i = 0; i < argc; i++) {
2101 		if ((k = key_load_public(argv[i], &comment)) == NULL)
2102 			fatal("Cannot load public key %s", argv[i]);
2103 		r = ssh_krl_check_key(krl, k);
2104 		printf("%s%s%s%s: %s\n", argv[i],
2105 		    *comment ? " (" : "", comment, *comment ? ")" : "",
2106 		    r == 0 ? "ok" : "REVOKED");
2107 		if (r != 0)
2108 			ret = 1;
2109 		key_free(k);
2110 		free(comment);
2111 	}
2112 	ssh_krl_free(krl);
2113 	exit(ret);
2114 }
2115 
2116 __dead static void
2117 usage(void)
2118 {
2119 	fprintf(stderr, "usage: %s [options]\n", __progname);
2120 	fprintf(stderr, "Options:\n");
2121 	fprintf(stderr, "  -A          Generate non-existent host keys for all key types.\n");
2122 	fprintf(stderr, "  -a trials   Number of trials for screening DH-GEX moduli.\n");
2123 	fprintf(stderr, "  -B          Show bubblebabble digest of key file.\n");
2124 	fprintf(stderr, "  -b bits     Number of bits in the key to create.\n");
2125 	fprintf(stderr, "  -C comment  Provide new comment.\n");
2126 	fprintf(stderr, "  -c          Change comment in private and public key files.\n");
2127 #ifdef ENABLE_PKCS11
2128 	fprintf(stderr, "  -D pkcs11   Download public key from pkcs11 token.\n");
2129 #endif
2130 	fprintf(stderr, "  -e          Export OpenSSH to foreign format key file.\n");
2131 	fprintf(stderr, "  -F hostname Find hostname in known hosts file.\n");
2132 	fprintf(stderr, "  -f filename Filename of the key file.\n");
2133 	fprintf(stderr, "  -G file     Generate candidates for DH-GEX moduli.\n");
2134 	fprintf(stderr, "  -g          Use generic DNS resource record format.\n");
2135 	fprintf(stderr, "  -H          Hash names in known_hosts file.\n");
2136 	fprintf(stderr, "  -h          Generate host certificate instead of a user certificate.\n");
2137 	fprintf(stderr, "  -I key_id   Key identifier to include in certificate.\n");
2138 	fprintf(stderr, "  -i          Import foreign format to OpenSSH key file.\n");
2139 	fprintf(stderr, "  -J number   Screen this number of moduli lines.\n");
2140 	fprintf(stderr, "  -j number   Start screening moduli at specified line.\n");
2141 	fprintf(stderr, "  -K checkpt  Write checkpoints to this file.\n");
2142 	fprintf(stderr, "  -k          Generate a KRL file.\n");
2143 	fprintf(stderr, "  -L          Print the contents of a certificate.\n");
2144 	fprintf(stderr, "  -l          Show fingerprint of key file.\n");
2145 	fprintf(stderr, "  -M memory   Amount of memory (MB) to use for generating DH-GEX moduli.\n");
2146 	fprintf(stderr, "  -m key_fmt  Conversion format for -e/-i (PEM|PKCS8|RFC4716).\n");
2147 	fprintf(stderr, "  -N phrase   Provide new passphrase.\n");
2148 	fprintf(stderr, "  -n name,... User/host principal names to include in certificate\n");
2149 	fprintf(stderr, "  -O option   Specify a certificate option.\n");
2150 	fprintf(stderr, "  -P phrase   Provide old passphrase.\n");
2151 	fprintf(stderr, "  -p          Change passphrase of private key file.\n");
2152 	fprintf(stderr, "  -Q          Test whether key(s) are revoked in KRL.\n");
2153 	fprintf(stderr, "  -q          Quiet.\n");
2154 	fprintf(stderr, "  -R hostname Remove host from known_hosts file.\n");
2155 	fprintf(stderr, "  -r hostname Print DNS resource record.\n");
2156 	fprintf(stderr, "  -S start    Start point (hex) for generating DH-GEX moduli.\n");
2157 	fprintf(stderr, "  -s ca_key   Certify keys with CA key.\n");
2158 	fprintf(stderr, "  -T file     Screen candidates for DH-GEX moduli.\n");
2159 	fprintf(stderr, "  -t type     Specify type of key to create.\n");
2160 	fprintf(stderr, "  -u          Update KRL rather than creating a new one.\n");
2161 	fprintf(stderr, "  -V from:to  Specify certificate validity interval.\n");
2162 	fprintf(stderr, "  -v          Verbose.\n");
2163 	fprintf(stderr, "  -W gen      Generator to use for generating DH-GEX moduli.\n");
2164 	fprintf(stderr, "  -y          Read private key file and print public key.\n");
2165 	fprintf(stderr, "  -z serial   Specify a serial number.\n");
2166 
2167 	exit(1);
2168 }
2169 
2170 /*
2171  * Main program for key management.
2172  */
2173 int
2174 main(int argc, char **argv)
2175 {
2176 	char dotsshdir[MAXPATHLEN], comment[1024], *passphrase1, *passphrase2;
2177 	char *checkpoint = NULL;
2178 	char out_file[MAXPATHLEN], *ep, *rr_hostname = NULL;
2179 	Key *private, *public;
2180 	struct passwd *pw;
2181 	struct stat st;
2182 	int opt, type, fd;
2183 	u_int32_t memory = 0, generator_wanted = 0, trials = 100;
2184 	int do_gen_candidates = 0, do_screen_candidates = 0;
2185 	int gen_all_hostkeys = 0, gen_krl = 0, update_krl = 0, check_krl = 0;
2186 	unsigned long start_lineno = 0, lines_to_process = 0;
2187 	BIGNUM *start = NULL;
2188 	FILE *f;
2189 	const char *errstr;
2190 
2191 	extern int optind;
2192 	extern char *optarg;
2193 
2194 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
2195 	sanitise_stdfd();
2196 
2197 	OpenSSL_add_all_algorithms();
2198 	log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
2199 
2200 	/* we need this for the home * directory.  */
2201 	pw = getpwuid(getuid());
2202 	if (!pw) {
2203 		printf("No user exists for uid %lu\n", (u_long)getuid());
2204 		exit(1);
2205 	}
2206 	if (gethostname(hostname, sizeof(hostname)) < 0) {
2207 		perror("gethostname");
2208 		exit(1);
2209 	}
2210 
2211 	while ((opt = getopt(argc, argv, "ABHLQXceghiklpquvxy"
2212 	    "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) {
2213 		switch (opt) {
2214 		case 'A':
2215 			gen_all_hostkeys = 1;
2216 			break;
2217 		case 'b':
2218 			bits = (u_int32_t)strtonum(optarg, 256, 32768, &errstr);
2219 			if (errstr)
2220 				fatal("Bits has bad value %s (%s)",
2221 					optarg, errstr);
2222 			break;
2223 		case 'F':
2224 			find_host = 1;
2225 			rr_hostname = optarg;
2226 			break;
2227 		case 'H':
2228 			hash_hosts = 1;
2229 			break;
2230 		case 'I':
2231 			cert_key_id = optarg;
2232 			break;
2233 		case 'J':
2234 			lines_to_process = strtoul(optarg, NULL, 10);
2235                         break;
2236 		case 'j':
2237 			start_lineno = strtoul(optarg, NULL, 10);
2238                         break;
2239 		case 'R':
2240 			delete_host = 1;
2241 			rr_hostname = optarg;
2242 			break;
2243 		case 'L':
2244 			show_cert = 1;
2245 			break;
2246 		case 'l':
2247 			print_fingerprint = 1;
2248 			break;
2249 		case 'B':
2250 			print_bubblebabble = 1;
2251 			break;
2252 		case 'm':
2253 			if (strcasecmp(optarg, "RFC4716") == 0 ||
2254 			    strcasecmp(optarg, "ssh2") == 0) {
2255 				convert_format = FMT_RFC4716;
2256 				break;
2257 			}
2258 			if (strcasecmp(optarg, "PKCS8") == 0) {
2259 				convert_format = FMT_PKCS8;
2260 				break;
2261 			}
2262 			if (strcasecmp(optarg, "PEM") == 0) {
2263 				convert_format = FMT_PEM;
2264 				break;
2265 			}
2266 			fatal("Unsupported conversion format \"%s\"", optarg);
2267 		case 'n':
2268 			cert_principals = optarg;
2269 			break;
2270 		case 'p':
2271 			change_passphrase = 1;
2272 			break;
2273 		case 'c':
2274 			change_comment = 1;
2275 			break;
2276 		case 'f':
2277 			if (strlcpy(identity_file, optarg, sizeof(identity_file)) >=
2278 			    sizeof(identity_file))
2279 				fatal("Identity filename too long");
2280 			have_identity = 1;
2281 			break;
2282 		case 'g':
2283 			print_generic = 1;
2284 			break;
2285 		case 'P':
2286 			identity_passphrase = optarg;
2287 			break;
2288 		case 'N':
2289 			identity_new_passphrase = optarg;
2290 			break;
2291 		case 'Q':
2292 			check_krl = 1;
2293 			break;
2294 		case 'O':
2295 			add_cert_option(optarg);
2296 			break;
2297 		case 'C':
2298 			identity_comment = optarg;
2299 			break;
2300 		case 'q':
2301 			quiet = 1;
2302 			break;
2303 		case 'e':
2304 		case 'x':
2305 			/* export key */
2306 			convert_to = 1;
2307 			break;
2308 		case 'h':
2309 			cert_key_type = SSH2_CERT_TYPE_HOST;
2310 			certflags_flags = 0;
2311 			break;
2312 		case 'k':
2313 			gen_krl = 1;
2314 			break;
2315 		case 'i':
2316 		case 'X':
2317 			/* import key */
2318 			convert_from = 1;
2319 			break;
2320 		case 'y':
2321 			print_public = 1;
2322 			break;
2323 		case 's':
2324 			ca_key_path = optarg;
2325 			break;
2326 		case 't':
2327 			key_type_name = optarg;
2328 			break;
2329 		case 'D':
2330 			pkcs11provider = optarg;
2331 			break;
2332 		case 'u':
2333 			update_krl = 1;
2334 			break;
2335 		case 'v':
2336 			if (log_level == SYSLOG_LEVEL_INFO)
2337 				log_level = SYSLOG_LEVEL_DEBUG1;
2338 			else {
2339 				if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
2340 				    log_level < SYSLOG_LEVEL_DEBUG3)
2341 					log_level++;
2342 			}
2343 			break;
2344 		case 'r':
2345 			rr_hostname = optarg;
2346 			break;
2347 		case 'W':
2348 			generator_wanted = (u_int32_t)strtonum(optarg, 1,
2349 			    UINT_MAX, &errstr);
2350 			if (errstr)
2351 				fatal("Desired generator has bad value: %s (%s)",
2352 					optarg, errstr);
2353 			break;
2354 		case 'a':
2355 			trials = (u_int32_t)strtonum(optarg, 1, UINT_MAX, &errstr);
2356 			if (errstr)
2357 				fatal("Invalid number of trials: %s (%s)",
2358 					optarg, errstr);
2359 			break;
2360 		case 'M':
2361 			memory = (u_int32_t)strtonum(optarg, 1, UINT_MAX, &errstr);
2362 			if (errstr)
2363 				fatal("Memory limit is %s: %s", errstr, optarg);
2364 			break;
2365 		case 'G':
2366 			do_gen_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 'T':
2372 			do_screen_candidates = 1;
2373 			if (strlcpy(out_file, optarg, sizeof(out_file)) >=
2374 			    sizeof(out_file))
2375 				fatal("Output filename too long");
2376 			break;
2377 		case 'K':
2378 			if (strlen(optarg) >= MAXPATHLEN)
2379 				fatal("Checkpoint filename too long");
2380 			checkpoint = xstrdup(optarg);
2381 			break;
2382 		case 'S':
2383 			/* XXX - also compare length against bits */
2384 			if (BN_hex2bn(&start, optarg) == 0)
2385 				fatal("Invalid start point.");
2386 			break;
2387 		case 'V':
2388 			parse_cert_times(optarg);
2389 			break;
2390 		case 'z':
2391 			errno = 0;
2392 			cert_serial = strtoull(optarg, &ep, 10);
2393 			if (*optarg < '0' || *optarg > '9' || *ep != '\0' ||
2394 			    (errno == ERANGE && cert_serial == ULLONG_MAX))
2395 				fatal("Invalid serial number \"%s\"", optarg);
2396 			break;
2397 		case '?':
2398 		default:
2399 			usage();
2400 		}
2401 	}
2402 
2403 	/* reinit */
2404 	log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
2405 
2406 	argv += optind;
2407 	argc -= optind;
2408 
2409 	if (ca_key_path != NULL) {
2410 		if (argc < 1 && !gen_krl) {
2411 			printf("Too few arguments.\n");
2412 			usage();
2413 		}
2414 	} else if (argc > 0 && !gen_krl && !check_krl) {
2415 		printf("Too many arguments.\n");
2416 		usage();
2417 	}
2418 	if (change_passphrase && change_comment) {
2419 		printf("Can only have one of -p and -c.\n");
2420 		usage();
2421 	}
2422 	if (print_fingerprint && (delete_host || hash_hosts)) {
2423 		printf("Cannot use -l with -H or -R.\n");
2424 		usage();
2425 	}
2426 	if (gen_krl) {
2427 		do_gen_krl(pw, update_krl, argc, argv);
2428 		return (0);
2429 	}
2430 	if (check_krl) {
2431 		do_check_krl(pw, argc, argv);
2432 		return (0);
2433 	}
2434 	if (ca_key_path != NULL) {
2435 		if (cert_key_id == NULL)
2436 			fatal("Must specify key id (-I) when certifying");
2437 		do_ca_sign(pw, argc, argv);
2438 	}
2439 	if (show_cert)
2440 		do_show_cert(pw);
2441 	if (delete_host || hash_hosts || find_host)
2442 		do_known_hosts(pw, rr_hostname);
2443 	if (pkcs11provider != NULL)
2444 		do_download(pw);
2445 	if (print_fingerprint || print_bubblebabble)
2446 		do_fingerprint(pw);
2447 	if (change_passphrase)
2448 		do_change_passphrase(pw);
2449 	if (change_comment)
2450 		do_change_comment(pw);
2451 	if (convert_to)
2452 		do_convert_to(pw);
2453 	if (convert_from)
2454 		do_convert_from(pw);
2455 	if (print_public)
2456 		do_print_public(pw);
2457 	if (rr_hostname != NULL) {
2458 		unsigned int n = 0;
2459 
2460 		if (have_identity) {
2461 			n = do_print_resource_record(pw,
2462 			    identity_file, rr_hostname);
2463 			if (n == 0) {
2464 				perror(identity_file);
2465 				exit(1);
2466 			}
2467 			exit(0);
2468 		} else {
2469 
2470 			n += do_print_resource_record(pw,
2471 			    _PATH_HOST_RSA_KEY_FILE, rr_hostname);
2472 			n += do_print_resource_record(pw,
2473 			    _PATH_HOST_DSA_KEY_FILE, rr_hostname);
2474 			n += do_print_resource_record(pw,
2475 			    _PATH_HOST_ECDSA_KEY_FILE, rr_hostname);
2476 
2477 			if (n == 0)
2478 				fatal("no keys found.");
2479 			exit(0);
2480 		}
2481 	}
2482 
2483 	if (do_gen_candidates) {
2484 		FILE *out = fopen(out_file, "w");
2485 
2486 		if (out == NULL) {
2487 			error("Couldn't open modulus candidate file \"%s\": %s",
2488 			    out_file, strerror(errno));
2489 			return (1);
2490 		}
2491 		if (bits == 0)
2492 			bits = DEFAULT_BITS;
2493 		if (gen_candidates(out, memory, bits, start) != 0)
2494 			fatal("modulus candidate generation failed");
2495 
2496 		return (0);
2497 	}
2498 
2499 	if (do_screen_candidates) {
2500 		FILE *in;
2501 		FILE *out = fopen(out_file, "a");
2502 
2503 		if (have_identity && strcmp(identity_file, "-") != 0) {
2504 			if ((in = fopen(identity_file, "r")) == NULL) {
2505 				fatal("Couldn't open modulus candidate "
2506 				    "file \"%s\": %s", identity_file,
2507 				    strerror(errno));
2508 			}
2509 		} else
2510 			in = stdin;
2511 
2512 		if (out == NULL) {
2513 			fatal("Couldn't open moduli file \"%s\": %s",
2514 			    out_file, strerror(errno));
2515 		}
2516 		if (prime_test(in, out, trials, generator_wanted, checkpoint,
2517 		    start_lineno, lines_to_process) != 0)
2518 			fatal("modulus screening failed");
2519 		return (0);
2520 	}
2521 
2522 	if (gen_all_hostkeys) {
2523 		do_gen_all_hostkeys(pw);
2524 		return (0);
2525 	}
2526 
2527 	arc4random_stir();
2528 
2529 	if (key_type_name == NULL)
2530 		key_type_name = "rsa";
2531 
2532 	type = key_type_from_name(key_type_name);
2533 	type_bits_valid(type, &bits);
2534 
2535 	if (!quiet)
2536 		printf("Generating public/private %s key pair.\n", key_type_name);
2537 	private = key_generate(type, bits);
2538 	if (private == NULL) {
2539 		fprintf(stderr, "key_generate failed\n");
2540 		exit(1);
2541 	}
2542 	public  = key_from_private(private);
2543 
2544 	if (!have_identity)
2545 		ask_filename(pw, "Enter file in which to save the key");
2546 
2547 	/* Create ~/.ssh directory if it doesn't already exist. */
2548 	snprintf(dotsshdir, sizeof dotsshdir, "%s/%s",
2549 	    pw->pw_dir, _PATH_SSH_USER_DIR);
2550 	if (strstr(identity_file, dotsshdir) != NULL) {
2551 		if (stat(dotsshdir, &st) < 0) {
2552 			if (errno != ENOENT) {
2553 				error("Could not stat %s: %s", dotsshdir,
2554 				    strerror(errno));
2555 			} else if (mkdir(dotsshdir, 0700) < 0) {
2556 				error("Could not create directory '%s': %s",
2557 				    dotsshdir, strerror(errno));
2558 			} else if (!quiet)
2559 				printf("Created directory '%s'.\n", dotsshdir);
2560 		}
2561 	}
2562 	/* If the file already exists, ask the user to confirm. */
2563 	if (stat(identity_file, &st) >= 0) {
2564 		char yesno[3];
2565 		printf("%s already exists.\n", identity_file);
2566 		printf("Overwrite (y/n)? ");
2567 		fflush(stdout);
2568 		if (fgets(yesno, sizeof(yesno), stdin) == NULL)
2569 			exit(1);
2570 		if (yesno[0] != 'y' && yesno[0] != 'Y')
2571 			exit(1);
2572 	}
2573 	/* Ask for a passphrase (twice). */
2574 	if (identity_passphrase)
2575 		passphrase1 = xstrdup(identity_passphrase);
2576 	else if (identity_new_passphrase)
2577 		passphrase1 = xstrdup(identity_new_passphrase);
2578 	else {
2579 passphrase_again:
2580 		passphrase1 =
2581 			read_passphrase("Enter passphrase (empty for no "
2582 			    "passphrase): ", RP_ALLOW_STDIN);
2583 		passphrase2 = read_passphrase("Enter same passphrase again: ",
2584 		    RP_ALLOW_STDIN);
2585 		if (strcmp(passphrase1, passphrase2) != 0) {
2586 			/*
2587 			 * The passphrases do not match.  Clear them and
2588 			 * retry.
2589 			 */
2590 			memset(passphrase1, 0, strlen(passphrase1));
2591 			memset(passphrase2, 0, strlen(passphrase2));
2592 			free(passphrase1);
2593 			free(passphrase2);
2594 			printf("Passphrases do not match.  Try again.\n");
2595 			goto passphrase_again;
2596 		}
2597 		/* Clear the other copy of the passphrase. */
2598 		memset(passphrase2, 0, strlen(passphrase2));
2599 		free(passphrase2);
2600 	}
2601 
2602 	if (identity_comment) {
2603 		strlcpy(comment, identity_comment, sizeof(comment));
2604 	} else {
2605 		/* Create default comment field for the passphrase. */
2606 		snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
2607 	}
2608 
2609 	/* Save the key with the given passphrase and comment. */
2610 	if (!key_save_private(private, identity_file, passphrase1, comment)) {
2611 		printf("Saving the key failed: %s.\n", identity_file);
2612 		memset(passphrase1, 0, strlen(passphrase1));
2613 		free(passphrase1);
2614 		exit(1);
2615 	}
2616 	/* Clear the passphrase. */
2617 	memset(passphrase1, 0, strlen(passphrase1));
2618 	free(passphrase1);
2619 
2620 	/* Clear the private key and the random number generator. */
2621 	key_free(private);
2622 	arc4random_stir();
2623 
2624 	if (!quiet)
2625 		printf("Your identification has been saved in %s.\n", identity_file);
2626 
2627 	strlcat(identity_file, ".pub", sizeof(identity_file));
2628 	fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
2629 	if (fd == -1) {
2630 		printf("Could not save your public key in %s\n", identity_file);
2631 		exit(1);
2632 	}
2633 	f = fdopen(fd, "w");
2634 	if (f == NULL) {
2635 		printf("fdopen %s failed\n", identity_file);
2636 		exit(1);
2637 	}
2638 	if (!key_write(public, f))
2639 		fprintf(stderr, "write key failed\n");
2640 	fprintf(f, " %s\n", comment);
2641 	fclose(f);
2642 
2643 	if (!quiet) {
2644 		char *fp = key_fingerprint(public, SSH_FP_MD5, SSH_FP_HEX);
2645 		char *ra = key_fingerprint(public, SSH_FP_MD5,
2646 		    SSH_FP_RANDOMART);
2647 		printf("Your public key has been saved in %s.\n",
2648 		    identity_file);
2649 		printf("The key fingerprint is:\n");
2650 		printf("%s %s\n", fp, comment);
2651 		printf("The key's randomart image is:\n");
2652 		printf("%s\n", ra);
2653 		free(ra);
2654 		free(fp);
2655 	}
2656 
2657 	key_free(public);
2658 	exit(0);
2659 }
2660