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