xref: /netbsd-src/crypto/external/bsd/openssh/dist/ssh-keygen.c (revision b757af438b42b93f8c6571f026d8b8ef3eaf5fc9)
1 /*	$NetBSD: ssh-keygen.c,v 1.8 2011/09/16 15:36:18 joerg Exp $	*/
2 /* $OpenBSD: ssh-keygen.c,v 1.210 2011/04/18 00:46:05 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.8 2011/09/16 15:36:18 joerg 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 "ssh2.h"
47 
48 #ifdef ENABLE_PKCS11
49 #include "ssh-pkcs11.h"
50 #endif
51 
52 /* Number of bits in the RSA/DSA key.  This value can be set on the command line. */
53 #define DEFAULT_BITS		2048
54 #define DEFAULT_BITS_DSA	1024
55 #define DEFAULT_BITS_ECDSA	256
56 u_int32_t bits = 0;
57 
58 /*
59  * Flag indicating that we just want to change the passphrase.  This can be
60  * set on the command line.
61  */
62 int change_passphrase = 0;
63 
64 /*
65  * Flag indicating that we just want to change the comment.  This can be set
66  * on the command line.
67  */
68 int change_comment = 0;
69 
70 int quiet = 0;
71 
72 int log_level = SYSLOG_LEVEL_INFO;
73 
74 /* Flag indicating that we want to hash a known_hosts file */
75 int hash_hosts = 0;
76 /* Flag indicating that we want lookup a host in known_hosts file */
77 int find_host = 0;
78 /* Flag indicating that we want to delete a host from a known_hosts file */
79 int delete_host = 0;
80 
81 /* Flag indicating that we want to show the contents of a certificate */
82 int show_cert = 0;
83 
84 /* Flag indicating that we just want to see the key fingerprint */
85 int print_fingerprint = 0;
86 int print_bubblebabble = 0;
87 
88 /* The identity file name, given on the command line or entered by the user. */
89 char identity_file[1024];
90 int have_identity = 0;
91 
92 /* This is set to the passphrase if given on the command line. */
93 char *identity_passphrase = NULL;
94 
95 /* This is set to the new passphrase if given on the command line. */
96 char *identity_new_passphrase = NULL;
97 
98 /* This is set to the new comment if given on the command line. */
99 char *identity_comment = NULL;
100 
101 /* Path to CA key when certifying keys. */
102 char *ca_key_path = NULL;
103 
104 /* Certificate serial number */
105 long long cert_serial = 0;
106 
107 /* Key type when certifying */
108 u_int cert_key_type = SSH2_CERT_TYPE_USER;
109 
110 /* "key ID" of signed key */
111 char *cert_key_id = NULL;
112 
113 /* Comma-separated list of principal names for certifying keys */
114 char *cert_principals = NULL;
115 
116 /* Validity period for certificates */
117 u_int64_t cert_valid_from = 0;
118 u_int64_t cert_valid_to = ~0ULL;
119 
120 /* Certificate options */
121 #define CERTOPT_X_FWD	(1)
122 #define CERTOPT_AGENT_FWD	(1<<1)
123 #define CERTOPT_PORT_FWD	(1<<2)
124 #define CERTOPT_PTY		(1<<3)
125 #define CERTOPT_USER_RC	(1<<4)
126 #define CERTOPT_DEFAULT	(CERTOPT_X_FWD|CERTOPT_AGENT_FWD| \
127 			 CERTOPT_PORT_FWD|CERTOPT_PTY|CERTOPT_USER_RC)
128 u_int32_t certflags_flags = CERTOPT_DEFAULT;
129 char *certflags_command = NULL;
130 char *certflags_src_addr = NULL;
131 
132 /* Conversion to/from various formats */
133 int convert_to = 0;
134 int convert_from = 0;
135 enum {
136 	FMT_RFC4716,
137 	FMT_PKCS8,
138 	FMT_PEM
139 } convert_format = FMT_RFC4716;
140 int print_public = 0;
141 int print_generic = 0;
142 
143 const char *key_type_name = NULL;
144 
145 /* Load key from this PKCS#11 provider */
146 char *pkcs11provider = NULL;
147 
148 /* argv0 */
149 extern char *__progname;
150 
151 char hostname[MAXHOSTNAMELEN];
152 
153 /* moduli.c */
154 int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
155 int prime_test(FILE *, FILE *, u_int32_t, u_int32_t);
156 
157 static void
158 type_bits_valid(int type, u_int32_t *bitsp)
159 {
160 	u_int maxbits;
161 
162 	if (type == KEY_UNSPEC) {
163 		fprintf(stderr, "unknown key type %s\n", key_type_name);
164 		exit(1);
165 	}
166 	if (*bitsp == 0) {
167 		if (type == KEY_DSA)
168 			*bitsp = DEFAULT_BITS_DSA;
169 		else if (type == KEY_ECDSA)
170 			*bitsp = DEFAULT_BITS_ECDSA;
171 		else
172 			*bitsp = DEFAULT_BITS;
173 	}
174 	maxbits = (type == KEY_DSA) ?
175 	    OPENSSL_DSA_MAX_MODULUS_BITS : OPENSSL_RSA_MAX_MODULUS_BITS;
176 	if (*bitsp > maxbits) {
177 		fprintf(stderr, "key bits exceeds maximum %d\n", maxbits);
178 		exit(1);
179 	}
180 	if (type == KEY_DSA && *bitsp != 1024)
181 		fatal("DSA keys must be 1024 bits");
182 	else if (type != KEY_ECDSA && *bitsp < 768)
183 		fatal("Key must at least be 768 bits");
184 	else if (type == KEY_ECDSA && key_ecdsa_bits_to_nid(*bitsp) == -1)
185 		fatal("Invalid ECDSA key length - valid lengths are "
186 		    "256, 384 or 521 bits");
187 }
188 
189 static void
190 ask_filename(struct passwd *pw, const char *prompt)
191 {
192 	char buf[1024];
193 	const char *name = NULL;
194 
195 	if (key_type_name == NULL)
196 		name = _PATH_SSH_CLIENT_ID_RSA;
197 	else {
198 		switch (key_type_from_name(key_type_name)) {
199 		case KEY_RSA1:
200 			name = _PATH_SSH_CLIENT_IDENTITY;
201 			break;
202 		case KEY_DSA_CERT:
203 		case KEY_DSA_CERT_V00:
204 		case KEY_DSA:
205 			name = _PATH_SSH_CLIENT_ID_DSA;
206 			break;
207 		case KEY_ECDSA_CERT:
208 		case KEY_ECDSA:
209 			name = _PATH_SSH_CLIENT_ID_ECDSA;
210 			break;
211 		case KEY_RSA_CERT:
212 		case KEY_RSA_CERT_V00:
213 		case KEY_RSA:
214 			name = _PATH_SSH_CLIENT_ID_RSA;
215 			break;
216 		default:
217 			fprintf(stderr, "bad key type\n");
218 			exit(1);
219 			break;
220 		}
221 	}
222 	snprintf(identity_file, sizeof(identity_file), "%s/%s", pw->pw_dir, name);
223 	fprintf(stderr, "%s (%s): ", prompt, identity_file);
224 	if (fgets(buf, sizeof(buf), stdin) == NULL)
225 		exit(1);
226 	buf[strcspn(buf, "\n")] = '\0';
227 	if (strcmp(buf, "") != 0)
228 		strlcpy(identity_file, buf, sizeof(identity_file));
229 	have_identity = 1;
230 }
231 
232 static Key *
233 load_identity(char *filename)
234 {
235 	char *pass;
236 	Key *prv;
237 
238 	prv = key_load_private(filename, "", NULL);
239 	if (prv == NULL) {
240 		if (identity_passphrase)
241 			pass = xstrdup(identity_passphrase);
242 		else
243 			pass = read_passphrase("Enter passphrase: ",
244 			    RP_ALLOW_STDIN);
245 		prv = key_load_private(filename, pass, NULL);
246 		memset(pass, 0, strlen(pass));
247 		xfree(pass);
248 	}
249 	return prv;
250 }
251 
252 #define SSH_COM_PUBLIC_BEGIN		"---- BEGIN SSH2 PUBLIC KEY ----"
253 #define SSH_COM_PUBLIC_END		"---- END SSH2 PUBLIC KEY ----"
254 #define SSH_COM_PRIVATE_BEGIN		"---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
255 #define	SSH_COM_PRIVATE_KEY_MAGIC	0x3f6ff9eb
256 
257 __dead static void
258 do_convert_to_ssh2(struct passwd *pw, Key *k)
259 {
260 	u_int len;
261 	u_char *blob;
262 	char comment[61];
263 
264 	if (key_to_blob(k, &blob, &len) <= 0) {
265 		fprintf(stderr, "key_to_blob failed\n");
266 		exit(1);
267 	}
268 	/* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
269 	snprintf(comment, sizeof(comment),
270 	    "%u-bit %s, converted by %s@%s from OpenSSH",
271 	    key_size(k), key_type(k),
272 	    pw->pw_name, hostname);
273 
274 	fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
275 	fprintf(stdout, "Comment: \"%s\"\n", comment);
276 	dump_base64(stdout, blob, len);
277 	fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
278 	key_free(k);
279 	xfree(blob);
280 	exit(0);
281 }
282 
283 __dead static void
284 do_convert_to_pkcs8(Key *k)
285 {
286 	switch (key_type_plain(k->type)) {
287 	case KEY_RSA:
288 		if (!PEM_write_RSA_PUBKEY(stdout, k->rsa))
289 			fatal("PEM_write_RSA_PUBKEY failed");
290 		break;
291 	case KEY_DSA:
292 		if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
293 			fatal("PEM_write_DSA_PUBKEY failed");
294 		break;
295 	case KEY_ECDSA:
296 		if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
297 			fatal("PEM_write_EC_PUBKEY failed");
298 		break;
299 	default:
300 		fatal("%s: unsupported key type %s", __func__, key_type(k));
301 	}
302 	exit(0);
303 }
304 
305 __dead static void
306 do_convert_to_pem(Key *k)
307 {
308 	switch (key_type_plain(k->type)) {
309 	case KEY_RSA:
310 		if (!PEM_write_RSAPublicKey(stdout, k->rsa))
311 			fatal("PEM_write_RSAPublicKey failed");
312 		break;
313 #if notyet /* OpenSSH 0.9.8 lacks this function */
314 	case KEY_DSA:
315 		if (!PEM_write_DSAPublicKey(stdout, k->dsa))
316 			fatal("PEM_write_DSAPublicKey failed");
317 		break;
318 #endif
319 	/* XXX ECDSA? */
320 	default:
321 		fatal("%s: unsupported key type %s", __func__, key_type(k));
322 	}
323 	exit(0);
324 }
325 
326 __dead static void
327 do_convert_to(struct passwd *pw)
328 {
329 	Key *k;
330 	struct stat st;
331 
332 	if (!have_identity)
333 		ask_filename(pw, "Enter file in which the key is");
334 	if (stat(identity_file, &st) < 0)
335 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
336 	if ((k = key_load_public(identity_file, NULL)) == NULL) {
337 		if ((k = load_identity(identity_file)) == NULL) {
338 			fprintf(stderr, "load failed\n");
339 			exit(1);
340 		}
341 	}
342 	if (k->type == KEY_RSA1) {
343 		fprintf(stderr, "version 1 keys are not supported\n");
344 		exit(1);
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 __dead 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 __dead 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 __dead 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 __dead 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 		const char *key_type;
844 		const char *key_type_display;
845 		const 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 __dead 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 && !c && !ca)
1077 					printhost(out, cp, pub, ca, 0);
1078 			} else if (hash_hosts)
1079 				printhost(out, cp, pub, ca, 0);
1080 		} else {
1081 			if (find_host || delete_host) {
1082 				c = (match_hostname(name, cp,
1083 				    strlen(cp)) == 1);
1084 				if (find_host && c) {
1085 					printf("# Host %s found: "
1086 					    "line %d type %s%s\n", name,
1087 					    num, key_type(pub),
1088 					    ca ? " (CA key)" : "");
1089 					printhost(out, name, pub,
1090 					    ca, hash_hosts && !ca);
1091 				}
1092 				if (delete_host && !c && !ca)
1093 					printhost(out, cp, pub, ca, 0);
1094 			} else if (hash_hosts) {
1095 				for (cp2 = strsep(&cp, ",");
1096 				    cp2 != NULL && *cp2 != '\0';
1097 				    cp2 = strsep(&cp, ",")) {
1098 					if (ca) {
1099 						fprintf(stderr, "Warning: "
1100 						    "ignoring CA key for host: "
1101 						    "%.64s\n", cp2);
1102 						printhost(out, cp2, pub, ca, 0);
1103 					} else if (strcspn(cp2, "*?!") !=
1104 					    strlen(cp2)) {
1105 						fprintf(stderr, "Warning: "
1106 						    "ignoring host name with "
1107 						    "metacharacters: %.64s\n",
1108 						    cp2);
1109 						printhost(out, cp2, pub, ca, 0);
1110 					} else
1111 						printhost(out, cp2, pub, ca, 1);
1112 				}
1113 				has_unhashed = 1;
1114 			}
1115 		}
1116 		key_free(pub);
1117 	}
1118 	fclose(in);
1119 
1120 	if (invalid) {
1121 		fprintf(stderr, "%s is not a valid known_hosts file.\n",
1122 		    identity_file);
1123 		if (inplace) {
1124 			fprintf(stderr, "Not replacing existing known_hosts "
1125 			    "file because of errors\n");
1126 			fclose(out);
1127 			unlink(tmp);
1128 		}
1129 		exit(1);
1130 	}
1131 
1132 	if (inplace) {
1133 		fclose(out);
1134 
1135 		/* Backup existing file */
1136 		if (unlink(old) == -1 && errno != ENOENT)
1137 			fatal("unlink %.100s: %s", old, strerror(errno));
1138 		if (link(identity_file, old) == -1)
1139 			fatal("link %.100s to %.100s: %s", identity_file, old,
1140 			    strerror(errno));
1141 		/* Move new one into place */
1142 		if (rename(tmp, identity_file) == -1) {
1143 			error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
1144 			    strerror(errno));
1145 			unlink(tmp);
1146 			unlink(old);
1147 			exit(1);
1148 		}
1149 
1150 		fprintf(stderr, "%s updated.\n", identity_file);
1151 		fprintf(stderr, "Original contents retained as %s\n", old);
1152 		if (has_unhashed) {
1153 			fprintf(stderr, "WARNING: %s contains unhashed "
1154 			    "entries\n", old);
1155 			fprintf(stderr, "Delete this file to ensure privacy "
1156 			    "of hostnames\n");
1157 		}
1158 	}
1159 
1160 	exit(0);
1161 }
1162 
1163 /*
1164  * Perform changing a passphrase.  The argument is the passwd structure
1165  * for the current user.
1166  */
1167 __dead static void
1168 do_change_passphrase(struct passwd *pw)
1169 {
1170 	char *comment;
1171 	char *old_passphrase, *passphrase1, *passphrase2;
1172 	struct stat st;
1173 	Key *private;
1174 
1175 	if (!have_identity)
1176 		ask_filename(pw, "Enter file in which the key is");
1177 	if (stat(identity_file, &st) < 0) {
1178 		perror(identity_file);
1179 		exit(1);
1180 	}
1181 	/* Try to load the file with empty passphrase. */
1182 	private = key_load_private(identity_file, "", &comment);
1183 	if (private == NULL) {
1184 		if (identity_passphrase)
1185 			old_passphrase = xstrdup(identity_passphrase);
1186 		else
1187 			old_passphrase =
1188 			    read_passphrase("Enter old passphrase: ",
1189 			    RP_ALLOW_STDIN);
1190 		private = key_load_private(identity_file, old_passphrase,
1191 		    &comment);
1192 		memset(old_passphrase, 0, strlen(old_passphrase));
1193 		xfree(old_passphrase);
1194 		if (private == NULL) {
1195 			printf("Bad passphrase.\n");
1196 			exit(1);
1197 		}
1198 	}
1199 	printf("Key has comment '%s'\n", comment);
1200 
1201 	/* Ask the new passphrase (twice). */
1202 	if (identity_new_passphrase) {
1203 		passphrase1 = xstrdup(identity_new_passphrase);
1204 		passphrase2 = NULL;
1205 	} else {
1206 		passphrase1 =
1207 			read_passphrase("Enter new passphrase (empty for no "
1208 			    "passphrase): ", RP_ALLOW_STDIN);
1209 		passphrase2 = read_passphrase("Enter same passphrase again: ",
1210 		    RP_ALLOW_STDIN);
1211 
1212 		/* Verify that they are the same. */
1213 		if (strcmp(passphrase1, passphrase2) != 0) {
1214 			memset(passphrase1, 0, strlen(passphrase1));
1215 			memset(passphrase2, 0, strlen(passphrase2));
1216 			xfree(passphrase1);
1217 			xfree(passphrase2);
1218 			printf("Pass phrases do not match.  Try again.\n");
1219 			exit(1);
1220 		}
1221 		/* Destroy the other copy. */
1222 		memset(passphrase2, 0, strlen(passphrase2));
1223 		xfree(passphrase2);
1224 	}
1225 
1226 	/* Save the file using the new passphrase. */
1227 	if (!key_save_private(private, identity_file, passphrase1, comment)) {
1228 		printf("Saving the key failed: %s.\n", identity_file);
1229 		memset(passphrase1, 0, strlen(passphrase1));
1230 		xfree(passphrase1);
1231 		key_free(private);
1232 		xfree(comment);
1233 		exit(1);
1234 	}
1235 	/* Destroy the passphrase and the copy of the key in memory. */
1236 	memset(passphrase1, 0, strlen(passphrase1));
1237 	xfree(passphrase1);
1238 	key_free(private);		 /* Destroys contents */
1239 	xfree(comment);
1240 
1241 	printf("Your identification has been saved with the new passphrase.\n");
1242 	exit(0);
1243 }
1244 
1245 /*
1246  * Print the SSHFP RR.
1247  */
1248 static int
1249 do_print_resource_record(struct passwd *pw, const char *fname,
1250     const char *hname)
1251 {
1252 	Key *public;
1253 	char *comment = NULL;
1254 	struct stat st;
1255 
1256 	if (fname == NULL)
1257 		ask_filename(pw, "Enter file in which the key is");
1258 	if (stat(fname, &st) < 0) {
1259 		if (errno == ENOENT)
1260 			return 0;
1261 		perror(fname);
1262 		exit(1);
1263 	}
1264 	public = key_load_public(fname, &comment);
1265 	if (public != NULL) {
1266 		export_dns_rr(hname, public, stdout, print_generic);
1267 		key_free(public);
1268 		xfree(comment);
1269 		return 1;
1270 	}
1271 	if (comment)
1272 		xfree(comment);
1273 
1274 	printf("failed to read v2 public key from %s.\n", fname);
1275 	exit(1);
1276 }
1277 
1278 /*
1279  * Change the comment of a private key file.
1280  */
1281 __dead static void
1282 do_change_comment(struct passwd *pw)
1283 {
1284 	char new_comment[1024], *comment, *passphrase;
1285 	Key *private;
1286 	Key *public;
1287 	struct stat st;
1288 	FILE *f;
1289 	int fd;
1290 
1291 	if (!have_identity)
1292 		ask_filename(pw, "Enter file in which the key is");
1293 	if (stat(identity_file, &st) < 0) {
1294 		perror(identity_file);
1295 		exit(1);
1296 	}
1297 	private = key_load_private(identity_file, "", &comment);
1298 	if (private == NULL) {
1299 		if (identity_passphrase)
1300 			passphrase = xstrdup(identity_passphrase);
1301 		else if (identity_new_passphrase)
1302 			passphrase = xstrdup(identity_new_passphrase);
1303 		else
1304 			passphrase = read_passphrase("Enter passphrase: ",
1305 			    RP_ALLOW_STDIN);
1306 		/* Try to load using the passphrase. */
1307 		private = key_load_private(identity_file, passphrase, &comment);
1308 		if (private == NULL) {
1309 			memset(passphrase, 0, strlen(passphrase));
1310 			xfree(passphrase);
1311 			printf("Bad passphrase.\n");
1312 			exit(1);
1313 		}
1314 	} else {
1315 		passphrase = xstrdup("");
1316 	}
1317 	if (private->type != KEY_RSA1) {
1318 		fprintf(stderr, "Comments are only supported for RSA1 keys.\n");
1319 		key_free(private);
1320 		exit(1);
1321 	}
1322 	printf("Key now has comment '%s'\n", comment);
1323 
1324 	if (identity_comment) {
1325 		strlcpy(new_comment, identity_comment, sizeof(new_comment));
1326 	} else {
1327 		printf("Enter new comment: ");
1328 		fflush(stdout);
1329 		if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1330 			memset(passphrase, 0, strlen(passphrase));
1331 			key_free(private);
1332 			exit(1);
1333 		}
1334 		new_comment[strcspn(new_comment, "\n")] = '\0';
1335 	}
1336 
1337 	/* Save the file using the new passphrase. */
1338 	if (!key_save_private(private, identity_file, passphrase, new_comment)) {
1339 		printf("Saving the key failed: %s.\n", identity_file);
1340 		memset(passphrase, 0, strlen(passphrase));
1341 		xfree(passphrase);
1342 		key_free(private);
1343 		xfree(comment);
1344 		exit(1);
1345 	}
1346 	memset(passphrase, 0, strlen(passphrase));
1347 	xfree(passphrase);
1348 	public = key_from_private(private);
1349 	key_free(private);
1350 
1351 	strlcat(identity_file, ".pub", sizeof(identity_file));
1352 	fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1353 	if (fd == -1) {
1354 		printf("Could not save your public key in %s\n", identity_file);
1355 		exit(1);
1356 	}
1357 	f = fdopen(fd, "w");
1358 	if (f == NULL) {
1359 		printf("fdopen %s failed\n", identity_file);
1360 		exit(1);
1361 	}
1362 	if (!key_write(public, f))
1363 		fprintf(stderr, "write key failed\n");
1364 	key_free(public);
1365 	fprintf(f, " %s\n", new_comment);
1366 	fclose(f);
1367 
1368 	xfree(comment);
1369 
1370 	printf("The comment in your key file has been changed.\n");
1371 	exit(0);
1372 }
1373 
1374 static const char *
1375 fmt_validity(u_int64_t valid_from, u_int64_t valid_to)
1376 {
1377 	char from[32], to[32];
1378 	static char ret[64];
1379 	time_t tt;
1380 	struct tm *tm;
1381 
1382 	*from = *to = '\0';
1383 	if (valid_from == 0 && valid_to == 0xffffffffffffffffULL)
1384 		return "forever";
1385 
1386 	if (valid_from != 0) {
1387 		/* XXX revisit INT_MAX in 2038 :) */
1388 		tt = valid_from > INT_MAX ? INT_MAX : valid_from;
1389 		tm = localtime(&tt);
1390 		strftime(from, sizeof(from), "%Y-%m-%dT%H:%M:%S", tm);
1391 	}
1392 	if (valid_to != 0xffffffffffffffffULL) {
1393 		/* XXX revisit INT_MAX in 2038 :) */
1394 		tt = valid_to > INT_MAX ? INT_MAX : valid_to;
1395 		tm = localtime(&tt);
1396 		strftime(to, sizeof(to), "%Y-%m-%dT%H:%M:%S", tm);
1397 	}
1398 
1399 	if (valid_from == 0) {
1400 		snprintf(ret, sizeof(ret), "before %s", to);
1401 		return ret;
1402 	}
1403 	if (valid_to == 0xffffffffffffffffULL) {
1404 		snprintf(ret, sizeof(ret), "after %s", from);
1405 		return ret;
1406 	}
1407 
1408 	snprintf(ret, sizeof(ret), "from %s to %s", from, to);
1409 	return ret;
1410 }
1411 
1412 static void
1413 add_flag_option(Buffer *c, const char *name)
1414 {
1415 	debug3("%s: %s", __func__, name);
1416 	buffer_put_cstring(c, name);
1417 	buffer_put_string(c, NULL, 0);
1418 }
1419 
1420 static void
1421 add_string_option(Buffer *c, const char *name, const char *value)
1422 {
1423 	Buffer b;
1424 
1425 	debug3("%s: %s=%s", __func__, name, value);
1426 	buffer_init(&b);
1427 	buffer_put_cstring(&b, value);
1428 
1429 	buffer_put_cstring(c, name);
1430 	buffer_put_string(c, buffer_ptr(&b), buffer_len(&b));
1431 
1432 	buffer_free(&b);
1433 }
1434 
1435 #define OPTIONS_CRITICAL	1
1436 #define OPTIONS_EXTENSIONS	2
1437 static void
1438 prepare_options_buf(Buffer *c, int which)
1439 {
1440 	buffer_clear(c);
1441 	if ((which & OPTIONS_CRITICAL) != 0 &&
1442 	    certflags_command != NULL)
1443 		add_string_option(c, "force-command", certflags_command);
1444 	if ((which & OPTIONS_EXTENSIONS) != 0 &&
1445 	    (certflags_flags & CERTOPT_X_FWD) != 0)
1446 		add_flag_option(c, "permit-X11-forwarding");
1447 	if ((which & OPTIONS_EXTENSIONS) != 0 &&
1448 	    (certflags_flags & CERTOPT_AGENT_FWD) != 0)
1449 		add_flag_option(c, "permit-agent-forwarding");
1450 	if ((which & OPTIONS_EXTENSIONS) != 0 &&
1451 	    (certflags_flags & CERTOPT_PORT_FWD) != 0)
1452 		add_flag_option(c, "permit-port-forwarding");
1453 	if ((which & OPTIONS_EXTENSIONS) != 0 &&
1454 	    (certflags_flags & CERTOPT_PTY) != 0)
1455 		add_flag_option(c, "permit-pty");
1456 	if ((which & OPTIONS_EXTENSIONS) != 0 &&
1457 	    (certflags_flags & CERTOPT_USER_RC) != 0)
1458 		add_flag_option(c, "permit-user-rc");
1459 	if ((which & OPTIONS_CRITICAL) != 0 &&
1460 	    certflags_src_addr != NULL)
1461 		add_string_option(c, "source-address", certflags_src_addr);
1462 }
1463 
1464 static Key *
1465 load_pkcs11_key(char *path)
1466 {
1467 #ifdef ENABLE_PKCS11
1468 	Key **keys = NULL, *public, *private = NULL;
1469 	int i, nkeys;
1470 
1471 	if ((public = key_load_public(path, NULL)) == NULL)
1472 		fatal("Couldn't load CA public key \"%s\"", path);
1473 
1474 	nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase, &keys);
1475 	debug3("%s: %d keys", __func__, nkeys);
1476 	if (nkeys <= 0)
1477 		fatal("cannot read public key from pkcs11");
1478 	for (i = 0; i < nkeys; i++) {
1479 		if (key_equal_public(public, keys[i])) {
1480 			private = keys[i];
1481 			continue;
1482 		}
1483 		key_free(keys[i]);
1484 	}
1485 	xfree(keys);
1486 	key_free(public);
1487 	return private;
1488 #else
1489 	fatal("no pkcs11 support");
1490 #endif /* ENABLE_PKCS11 */
1491 }
1492 
1493 __dead static void
1494 do_ca_sign(struct passwd *pw, int argc, char **argv)
1495 {
1496 	int i, fd;
1497 	u_int n;
1498 	Key *ca, *public;
1499 	char *otmp, *tmp, *cp, *out, *comment, **plist = NULL;
1500 	FILE *f;
1501 	int v00 = 0; /* legacy keys */
1502 
1503 	if (key_type_name != NULL) {
1504 		switch (key_type_from_name(key_type_name)) {
1505 		case KEY_RSA_CERT_V00:
1506 		case KEY_DSA_CERT_V00:
1507 			v00 = 1;
1508 			break;
1509 		case KEY_UNSPEC:
1510 			if (strcasecmp(key_type_name, "v00") == 0) {
1511 				v00 = 1;
1512 				break;
1513 			} else if (strcasecmp(key_type_name, "v01") == 0)
1514 				break;
1515 			/* FALLTHROUGH */
1516 		default:
1517 			fprintf(stderr, "unknown key type %s\n", key_type_name);
1518 			exit(1);
1519 		}
1520 	}
1521 
1522 	pkcs11_init(1);
1523 	tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
1524 	if (pkcs11provider != NULL) {
1525 		if ((ca = load_pkcs11_key(tmp)) == NULL)
1526 			fatal("No PKCS#11 key matching %s found", ca_key_path);
1527 	} else if ((ca = load_identity(tmp)) == NULL)
1528 		fatal("Couldn't load CA key \"%s\"", tmp);
1529 	xfree(tmp);
1530 
1531 	for (i = 0; i < argc; i++) {
1532 		/* Split list of principals */
1533 		n = 0;
1534 		if (cert_principals != NULL) {
1535 			otmp = tmp = xstrdup(cert_principals);
1536 			plist = NULL;
1537 			for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1538 				plist = xrealloc(plist, n + 1, sizeof(*plist));
1539 				if (*(plist[n] = xstrdup(cp)) == '\0')
1540 					fatal("Empty principal name");
1541 			}
1542 			xfree(otmp);
1543 		}
1544 
1545 		tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1546 		if ((public = key_load_public(tmp, &comment)) == NULL)
1547 			fatal("%s: unable to open \"%s\"", __func__, tmp);
1548 		if (public->type != KEY_RSA && public->type != KEY_DSA &&
1549 		    public->type != KEY_ECDSA)
1550 			fatal("%s: key \"%s\" type %s cannot be certified",
1551 			    __func__, tmp, key_type(public));
1552 
1553 		/* Prepare certificate to sign */
1554 		if (key_to_certified(public, v00) != 0)
1555 			fatal("Could not upgrade key %s to certificate", tmp);
1556 		public->cert->type = cert_key_type;
1557 		public->cert->serial = (u_int64_t)cert_serial;
1558 		public->cert->key_id = xstrdup(cert_key_id);
1559 		public->cert->nprincipals = n;
1560 		public->cert->principals = plist;
1561 		public->cert->valid_after = cert_valid_from;
1562 		public->cert->valid_before = cert_valid_to;
1563 		if (v00) {
1564 			prepare_options_buf(&public->cert->critical,
1565 			    OPTIONS_CRITICAL|OPTIONS_EXTENSIONS);
1566 		} else {
1567 			prepare_options_buf(&public->cert->critical,
1568 			    OPTIONS_CRITICAL);
1569 			prepare_options_buf(&public->cert->extensions,
1570 			    OPTIONS_EXTENSIONS);
1571 		}
1572 		public->cert->signature_key = key_from_private(ca);
1573 
1574 		if (key_certify(public, ca) != 0)
1575 			fatal("Couldn't not certify key %s", tmp);
1576 
1577 		if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
1578 			*cp = '\0';
1579 		xasprintf(&out, "%s-cert.pub", tmp);
1580 		xfree(tmp);
1581 
1582 		if ((fd = open(out, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
1583 			fatal("Could not open \"%s\" for writing: %s", out,
1584 			    strerror(errno));
1585 		if ((f = fdopen(fd, "w")) == NULL)
1586 			fatal("%s: fdopen: %s", __func__, strerror(errno));
1587 		if (!key_write(public, f))
1588 			fatal("Could not write certified key to %s", out);
1589 		fprintf(f, " %s\n", comment);
1590 		fclose(f);
1591 
1592 		if (!quiet) {
1593 			logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1594 			    "valid %s", key_cert_type(public),
1595 			    out, public->cert->key_id,
1596 			    (unsigned long long)public->cert->serial,
1597 			    cert_principals != NULL ? " for " : "",
1598 			    cert_principals != NULL ? cert_principals : "",
1599 			    fmt_validity(cert_valid_from, cert_valid_to));
1600 		}
1601 
1602 		key_free(public);
1603 		xfree(out);
1604 	}
1605 	pkcs11_terminate();
1606 	exit(0);
1607 }
1608 
1609 static u_int64_t
1610 parse_relative_time(const char *s, time_t now)
1611 {
1612 	int64_t mul, secs;
1613 
1614 	mul = *s == '-' ? -1 : 1;
1615 
1616 	if ((secs = convtime(s + 1)) == -1)
1617 		fatal("Invalid relative certificate time %s", s);
1618 	if (mul == -1 && secs > now)
1619 		fatal("Certificate time %s cannot be represented", s);
1620 	return now + (u_int64_t)(secs * mul);
1621 }
1622 
1623 static u_int64_t
1624 parse_absolute_time(const char *s)
1625 {
1626 	struct tm tm;
1627 	time_t tt;
1628 	char buf[32];
1629 	const char *fmt;
1630 
1631 	/*
1632 	 * POSIX strptime says "The application shall ensure that there
1633 	 * is white-space or other non-alphanumeric characters between
1634 	 * any two conversion specifications" so arrange things this way.
1635 	 */
1636 	switch (strlen(s)) {
1637 	case 8:
1638 		fmt = "%Y-%m-%d";
1639 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
1640 		break;
1641 	case 14:
1642 		fmt = "%Y-%m-%dT%H:%M:%S";
1643 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
1644 		    s, s + 4, s + 6, s + 8, s + 10, s + 12);
1645 		break;
1646 	default:
1647 		fatal("Invalid certificate time format %s", s);
1648 	}
1649 
1650 	bzero(&tm, sizeof(tm));
1651 	if (strptime(buf, fmt, &tm) == NULL)
1652 		fatal("Invalid certificate time %s", s);
1653 	if ((tt = mktime(&tm)) < 0)
1654 		fatal("Certificate time %s cannot be represented", s);
1655 	return (u_int64_t)tt;
1656 }
1657 
1658 static void
1659 parse_cert_times(char *timespec)
1660 {
1661 	char *from, *to;
1662 	time_t now = time(NULL);
1663 	int64_t secs;
1664 
1665 	/* +timespec relative to now */
1666 	if (*timespec == '+' && strchr(timespec, ':') == NULL) {
1667 		if ((secs = convtime(timespec + 1)) == -1)
1668 			fatal("Invalid relative certificate life %s", timespec);
1669 		cert_valid_to = now + secs;
1670 		/*
1671 		 * Backdate certificate one minute to avoid problems on hosts
1672 		 * with poorly-synchronised clocks.
1673 		 */
1674 		cert_valid_from = ((now - 59)/ 60) * 60;
1675 		return;
1676 	}
1677 
1678 	/*
1679 	 * from:to, where
1680 	 * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS
1681 	 *   to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS
1682 	 */
1683 	from = xstrdup(timespec);
1684 	to = strchr(from, ':');
1685 	if (to == NULL || from == to || *(to + 1) == '\0')
1686 		fatal("Invalid certificate life specification %s", timespec);
1687 	*to++ = '\0';
1688 
1689 	if (*from == '-' || *from == '+')
1690 		cert_valid_from = parse_relative_time(from, now);
1691 	else
1692 		cert_valid_from = parse_absolute_time(from);
1693 
1694 	if (*to == '-' || *to == '+')
1695 		cert_valid_to = parse_relative_time(to, cert_valid_from);
1696 	else
1697 		cert_valid_to = parse_absolute_time(to);
1698 
1699 	if (cert_valid_to <= cert_valid_from)
1700 		fatal("Empty certificate validity interval");
1701 	xfree(from);
1702 }
1703 
1704 static void
1705 add_cert_option(char *opt)
1706 {
1707 	char *val;
1708 
1709 	if (strcasecmp(opt, "clear") == 0)
1710 		certflags_flags = 0;
1711 	else if (strcasecmp(opt, "no-x11-forwarding") == 0)
1712 		certflags_flags &= ~CERTOPT_X_FWD;
1713 	else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
1714 		certflags_flags |= CERTOPT_X_FWD;
1715 	else if (strcasecmp(opt, "no-agent-forwarding") == 0)
1716 		certflags_flags &= ~CERTOPT_AGENT_FWD;
1717 	else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
1718 		certflags_flags |= CERTOPT_AGENT_FWD;
1719 	else if (strcasecmp(opt, "no-port-forwarding") == 0)
1720 		certflags_flags &= ~CERTOPT_PORT_FWD;
1721 	else if (strcasecmp(opt, "permit-port-forwarding") == 0)
1722 		certflags_flags |= CERTOPT_PORT_FWD;
1723 	else if (strcasecmp(opt, "no-pty") == 0)
1724 		certflags_flags &= ~CERTOPT_PTY;
1725 	else if (strcasecmp(opt, "permit-pty") == 0)
1726 		certflags_flags |= CERTOPT_PTY;
1727 	else if (strcasecmp(opt, "no-user-rc") == 0)
1728 		certflags_flags &= ~CERTOPT_USER_RC;
1729 	else if (strcasecmp(opt, "permit-user-rc") == 0)
1730 		certflags_flags |= CERTOPT_USER_RC;
1731 	else if (strncasecmp(opt, "force-command=", 14) == 0) {
1732 		val = opt + 14;
1733 		if (*val == '\0')
1734 			fatal("Empty force-command option");
1735 		if (certflags_command != NULL)
1736 			fatal("force-command already specified");
1737 		certflags_command = xstrdup(val);
1738 	} else if (strncasecmp(opt, "source-address=", 15) == 0) {
1739 		val = opt + 15;
1740 		if (*val == '\0')
1741 			fatal("Empty source-address option");
1742 		if (certflags_src_addr != NULL)
1743 			fatal("source-address already specified");
1744 		if (addr_match_cidr_list(NULL, val) != 0)
1745 			fatal("Invalid source-address list");
1746 		certflags_src_addr = xstrdup(val);
1747 	} else
1748 		fatal("Unsupported certificate option \"%s\"", opt);
1749 }
1750 
1751 static void
1752 show_options(const Buffer *optbuf, int v00, int in_critical)
1753 {
1754 	u_char *name, *data;
1755 	u_int dlen;
1756 	Buffer options, option;
1757 
1758 	buffer_init(&options);
1759 	buffer_append(&options, buffer_ptr(optbuf), buffer_len(optbuf));
1760 
1761 	buffer_init(&option);
1762 	while (buffer_len(&options) != 0) {
1763 		name = buffer_get_string(&options, NULL);
1764 		data = buffer_get_string_ptr(&options, &dlen);
1765 		buffer_append(&option, data, dlen);
1766 		printf("                %s", name);
1767 		if ((v00 || !in_critical) &&
1768 		    (strcmp(name, "permit-X11-forwarding") == 0 ||
1769 		    strcmp(name, "permit-agent-forwarding") == 0 ||
1770 		    strcmp(name, "permit-port-forwarding") == 0 ||
1771 		    strcmp(name, "permit-pty") == 0 ||
1772 		    strcmp(name, "permit-user-rc") == 0))
1773 			printf("\n");
1774 		else if ((v00 || in_critical) &&
1775 		    (strcmp(name, "force-command") == 0 ||
1776 		    strcmp(name, "source-address") == 0)) {
1777 			data = buffer_get_string(&option, NULL);
1778 			printf(" %s\n", data);
1779 			xfree(data);
1780 		} else {
1781 			printf(" UNKNOWN OPTION (len %u)\n",
1782 			    buffer_len(&option));
1783 			buffer_clear(&option);
1784 		}
1785 		xfree(name);
1786 		if (buffer_len(&option) != 0)
1787 			fatal("Option corrupt: extra data at end");
1788 	}
1789 	buffer_free(&option);
1790 	buffer_free(&options);
1791 }
1792 
1793 __dead static void
1794 do_show_cert(struct passwd *pw)
1795 {
1796 	Key *key;
1797 	struct stat st;
1798 	char *key_fp, *ca_fp;
1799 	u_int i, v00;
1800 
1801 	if (!have_identity)
1802 		ask_filename(pw, "Enter file in which the key is");
1803 	if (stat(identity_file, &st) < 0)
1804 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
1805 	if ((key = key_load_public(identity_file, NULL)) == NULL)
1806 		fatal("%s is not a public key", identity_file);
1807 	if (!key_is_cert(key))
1808 		fatal("%s is not a certificate", identity_file);
1809 	v00 = key->type == KEY_RSA_CERT_V00 || key->type == KEY_DSA_CERT_V00;
1810 
1811 	key_fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
1812 	ca_fp = key_fingerprint(key->cert->signature_key,
1813 	    SSH_FP_MD5, SSH_FP_HEX);
1814 
1815 	printf("%s:\n", identity_file);
1816 	printf("        Type: %s %s certificate\n", key_ssh_name(key),
1817 	    key_cert_type(key));
1818 	printf("        Public key: %s %s\n", key_type(key), key_fp);
1819 	printf("        Signing CA: %s %s\n",
1820 	    key_type(key->cert->signature_key), ca_fp);
1821 	printf("        Key ID: \"%s\"\n", key->cert->key_id);
1822 	if (!v00) {
1823 		printf("        Serial: %llu\n",
1824 		    (unsigned long long)key->cert->serial);
1825 	}
1826 	printf("        Valid: %s\n",
1827 	    fmt_validity(key->cert->valid_after, key->cert->valid_before));
1828 	printf("        Principals: ");
1829 	if (key->cert->nprincipals == 0)
1830 		printf("(none)\n");
1831 	else {
1832 		for (i = 0; i < key->cert->nprincipals; i++)
1833 			printf("\n                %s",
1834 			    key->cert->principals[i]);
1835 		printf("\n");
1836 	}
1837 	printf("        Critical Options: ");
1838 	if (buffer_len(&key->cert->critical) == 0)
1839 		printf("(none)\n");
1840 	else {
1841 		printf("\n");
1842 		show_options(&key->cert->critical, v00, 1);
1843 	}
1844 	if (!v00) {
1845 		printf("        Extensions: ");
1846 		if (buffer_len(&key->cert->extensions) == 0)
1847 			printf("(none)\n");
1848 		else {
1849 			printf("\n");
1850 			show_options(&key->cert->extensions, v00, 0);
1851 		}
1852 	}
1853 	exit(0);
1854 }
1855 
1856 __dead static void
1857 usage(void)
1858 {
1859 	fprintf(stderr, "usage: %s [options]\n", __progname);
1860 	fprintf(stderr, "Options:\n");
1861 	fprintf(stderr, "  -A          Generate non-existent host keys for all key types.\n");
1862 	fprintf(stderr, "  -a trials   Number of trials for screening DH-GEX moduli.\n");
1863 	fprintf(stderr, "  -B          Show bubblebabble digest of key file.\n");
1864 	fprintf(stderr, "  -b bits     Number of bits in the key to create.\n");
1865 	fprintf(stderr, "  -C comment  Provide new comment.\n");
1866 	fprintf(stderr, "  -c          Change comment in private and public key files.\n");
1867 #ifdef ENABLE_PKCS11
1868 	fprintf(stderr, "  -D pkcs11   Download public key from pkcs11 token.\n");
1869 #endif
1870 	fprintf(stderr, "  -e          Export OpenSSH to foreign format key file.\n");
1871 	fprintf(stderr, "  -F hostname Find hostname in known hosts file.\n");
1872 	fprintf(stderr, "  -f filename Filename of the key file.\n");
1873 	fprintf(stderr, "  -G file     Generate candidates for DH-GEX moduli.\n");
1874 	fprintf(stderr, "  -g          Use generic DNS resource record format.\n");
1875 	fprintf(stderr, "  -H          Hash names in known_hosts file.\n");
1876 	fprintf(stderr, "  -h          Generate host certificate instead of a user certificate.\n");
1877 	fprintf(stderr, "  -I key_id   Key identifier to include in certificate.\n");
1878 	fprintf(stderr, "  -i          Import foreign format to OpenSSH key file.\n");
1879 	fprintf(stderr, "  -L          Print the contents of a certificate.\n");
1880 	fprintf(stderr, "  -l          Show fingerprint of key file.\n");
1881 	fprintf(stderr, "  -M memory   Amount of memory (MB) to use for generating DH-GEX moduli.\n");
1882 	fprintf(stderr, "  -m key_fmt  Conversion format for -e/-i (PEM|PKCS8|RFC4716).\n");
1883 	fprintf(stderr, "  -N phrase   Provide new passphrase.\n");
1884 	fprintf(stderr, "  -n name,... User/host principal names to include in certificate\n");
1885 	fprintf(stderr, "  -O option   Specify a certificate option.\n");
1886 	fprintf(stderr, "  -P phrase   Provide old passphrase.\n");
1887 	fprintf(stderr, "  -p          Change passphrase of private key file.\n");
1888 	fprintf(stderr, "  -q          Quiet.\n");
1889 	fprintf(stderr, "  -R hostname Remove host from known_hosts file.\n");
1890 	fprintf(stderr, "  -r hostname Print DNS resource record.\n");
1891 	fprintf(stderr, "  -S start    Start point (hex) for generating DH-GEX moduli.\n");
1892 	fprintf(stderr, "  -s ca_key   Certify keys with CA key.\n");
1893 	fprintf(stderr, "  -T file     Screen candidates for DH-GEX moduli.\n");
1894 	fprintf(stderr, "  -t type     Specify type of key to create.\n");
1895 	fprintf(stderr, "  -V from:to  Specify certificate validity interval.\n");
1896 	fprintf(stderr, "  -v          Verbose.\n");
1897 	fprintf(stderr, "  -W gen      Generator to use for generating DH-GEX moduli.\n");
1898 	fprintf(stderr, "  -y          Read private key file and print public key.\n");
1899 	fprintf(stderr, "  -z serial   Specify a serial number.\n");
1900 
1901 	exit(1);
1902 }
1903 
1904 /*
1905  * Main program for key management.
1906  */
1907 int
1908 main(int argc, char **argv)
1909 {
1910 	char dotsshdir[MAXPATHLEN], comment[1024], *passphrase1, *passphrase2;
1911 	char out_file[MAXPATHLEN], *rr_hostname = NULL;
1912 	Key *private, *public;
1913 	struct passwd *pw;
1914 	struct stat st;
1915 	int opt, type, fd;
1916 	u_int32_t memory = 0, generator_wanted = 0, trials = 100;
1917 	int do_gen_candidates = 0, do_screen_candidates = 0;
1918 	int gen_all_hostkeys = 0;
1919 	BIGNUM *start = NULL;
1920 	FILE *f;
1921 	const char *errstr;
1922 
1923 	extern int optind;
1924 	extern char *optarg;
1925 
1926 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1927 	sanitise_stdfd();
1928 
1929 	OpenSSL_add_all_algorithms();
1930 	log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
1931 
1932 	/* we need this for the home * directory.  */
1933 	pw = getpwuid(getuid());
1934 	if (!pw) {
1935 		printf("You don't exist, go away!\n");
1936 		exit(1);
1937 	}
1938 	if (gethostname(hostname, sizeof(hostname)) < 0) {
1939 		perror("gethostname");
1940 		exit(1);
1941 	}
1942 
1943 	while ((opt = getopt(argc, argv, "AegiqpclBHLhvxXyF:b:f:t:D:I:P:m:N:n:"
1944 	    "O:C:r:g:R:T:G:M:S:s:a:V:W:z:")) != -1) {
1945 		switch (opt) {
1946 		case 'A':
1947 			gen_all_hostkeys = 1;
1948 			break;
1949 		case 'b':
1950 			bits = (u_int32_t)strtonum(optarg, 256, 32768, &errstr);
1951 			if (errstr)
1952 				fatal("Bits has bad value %s (%s)",
1953 					optarg, errstr);
1954 			break;
1955 		case 'F':
1956 			find_host = 1;
1957 			rr_hostname = optarg;
1958 			break;
1959 		case 'H':
1960 			hash_hosts = 1;
1961 			break;
1962 		case 'I':
1963 			cert_key_id = optarg;
1964 			break;
1965 		case 'R':
1966 			delete_host = 1;
1967 			rr_hostname = optarg;
1968 			break;
1969 		case 'L':
1970 			show_cert = 1;
1971 			break;
1972 		case 'l':
1973 			print_fingerprint = 1;
1974 			break;
1975 		case 'B':
1976 			print_bubblebabble = 1;
1977 			break;
1978 		case 'm':
1979 			if (strcasecmp(optarg, "RFC4716") == 0 ||
1980 			    strcasecmp(optarg, "ssh2") == 0) {
1981 				convert_format = FMT_RFC4716;
1982 				break;
1983 			}
1984 			if (strcasecmp(optarg, "PKCS8") == 0) {
1985 				convert_format = FMT_PKCS8;
1986 				break;
1987 			}
1988 			if (strcasecmp(optarg, "PEM") == 0) {
1989 				convert_format = FMT_PEM;
1990 				break;
1991 			}
1992 			fatal("Unsupported conversion format \"%s\"", optarg);
1993 		case 'n':
1994 			cert_principals = optarg;
1995 			break;
1996 		case 'p':
1997 			change_passphrase = 1;
1998 			break;
1999 		case 'c':
2000 			change_comment = 1;
2001 			break;
2002 		case 'f':
2003 			if (strlcpy(identity_file, optarg, sizeof(identity_file)) >=
2004 			    sizeof(identity_file))
2005 				fatal("Identity filename too long");
2006 			have_identity = 1;
2007 			break;
2008 		case 'g':
2009 			print_generic = 1;
2010 			break;
2011 		case 'P':
2012 			identity_passphrase = optarg;
2013 			break;
2014 		case 'N':
2015 			identity_new_passphrase = optarg;
2016 			break;
2017 		case 'O':
2018 			add_cert_option(optarg);
2019 			break;
2020 		case 'C':
2021 			identity_comment = optarg;
2022 			break;
2023 		case 'q':
2024 			quiet = 1;
2025 			break;
2026 		case 'e':
2027 		case 'x':
2028 			/* export key */
2029 			convert_to = 1;
2030 			break;
2031 		case 'h':
2032 			cert_key_type = SSH2_CERT_TYPE_HOST;
2033 			certflags_flags = 0;
2034 			break;
2035 		case 'i':
2036 		case 'X':
2037 			/* import key */
2038 			convert_from = 1;
2039 			break;
2040 		case 'y':
2041 			print_public = 1;
2042 			break;
2043 		case 's':
2044 			ca_key_path = optarg;
2045 			break;
2046 		case 't':
2047 			key_type_name = optarg;
2048 			break;
2049 		case 'D':
2050 			pkcs11provider = optarg;
2051 			break;
2052 		case 'v':
2053 			if (log_level == SYSLOG_LEVEL_INFO)
2054 				log_level = SYSLOG_LEVEL_DEBUG1;
2055 			else {
2056 				if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
2057 				    log_level < SYSLOG_LEVEL_DEBUG3)
2058 					log_level++;
2059 			}
2060 			break;
2061 		case 'r':
2062 			rr_hostname = optarg;
2063 			break;
2064 		case 'W':
2065 			generator_wanted = (u_int32_t)strtonum(optarg, 1,
2066 			    UINT_MAX, &errstr);
2067 			if (errstr)
2068 				fatal("Desired generator has bad value: %s (%s)",
2069 					optarg, errstr);
2070 			break;
2071 		case 'a':
2072 			trials = (u_int32_t)strtonum(optarg, 1, UINT_MAX, &errstr);
2073 			if (errstr)
2074 				fatal("Invalid number of trials: %s (%s)",
2075 					optarg, errstr);
2076 			break;
2077 		case 'M':
2078 			memory = (u_int32_t)strtonum(optarg, 1, UINT_MAX, &errstr);
2079 			if (errstr)
2080 				fatal("Memory limit is %s: %s", errstr, optarg);
2081 			break;
2082 		case 'G':
2083 			do_gen_candidates = 1;
2084 			if (strlcpy(out_file, optarg, sizeof(out_file)) >=
2085 			    sizeof(out_file))
2086 				fatal("Output filename too long");
2087 			break;
2088 		case 'T':
2089 			do_screen_candidates = 1;
2090 			if (strlcpy(out_file, optarg, sizeof(out_file)) >=
2091 			    sizeof(out_file))
2092 				fatal("Output filename too long");
2093 			break;
2094 		case 'S':
2095 			/* XXX - also compare length against bits */
2096 			if (BN_hex2bn(&start, optarg) == 0)
2097 				fatal("Invalid start point.");
2098 			break;
2099 		case 'V':
2100 			parse_cert_times(optarg);
2101 			break;
2102 		case 'z':
2103 			cert_serial = strtonum(optarg, 0, LLONG_MAX, &errstr);
2104 			if (errstr)
2105 				fatal("Invalid serial number: %s", errstr);
2106 			break;
2107 		case '?':
2108 		default:
2109 			usage();
2110 		}
2111 	}
2112 
2113 	/* reinit */
2114 	log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
2115 
2116 	argv += optind;
2117 	argc -= optind;
2118 
2119 	if (ca_key_path != NULL) {
2120 		if (argc < 1) {
2121 			printf("Too few arguments.\n");
2122 			usage();
2123 		}
2124 	} else if (argc > 0) {
2125 		printf("Too many arguments.\n");
2126 		usage();
2127 	}
2128 	if (change_passphrase && change_comment) {
2129 		printf("Can only have one of -p and -c.\n");
2130 		usage();
2131 	}
2132 	if (print_fingerprint && (delete_host || hash_hosts)) {
2133 		printf("Cannot use -l with -D or -R.\n");
2134 		usage();
2135 	}
2136 	if (ca_key_path != NULL) {
2137 		if (cert_key_id == NULL)
2138 			fatal("Must specify key id (-I) when certifying");
2139 		do_ca_sign(pw, argc, argv);
2140 	}
2141 	if (show_cert)
2142 		do_show_cert(pw);
2143 	if (delete_host || hash_hosts || find_host)
2144 		do_known_hosts(pw, rr_hostname);
2145 	if (print_fingerprint || print_bubblebabble)
2146 		do_fingerprint(pw);
2147 	if (change_passphrase)
2148 		do_change_passphrase(pw);
2149 	if (change_comment)
2150 		do_change_comment(pw);
2151 	if (convert_to)
2152 		do_convert_to(pw);
2153 	if (convert_from)
2154 		do_convert_from(pw);
2155 	if (print_public)
2156 		do_print_public(pw);
2157 	if (rr_hostname != NULL) {
2158 		unsigned int n = 0;
2159 
2160 		if (have_identity) {
2161 			n = do_print_resource_record(pw,
2162 			    identity_file, rr_hostname);
2163 			if (n == 0) {
2164 				perror(identity_file);
2165 				exit(1);
2166 			}
2167 			exit(0);
2168 		} else {
2169 
2170 			n += do_print_resource_record(pw,
2171 			    _PATH_HOST_RSA_KEY_FILE, rr_hostname);
2172 			n += do_print_resource_record(pw,
2173 			    _PATH_HOST_DSA_KEY_FILE, rr_hostname);
2174 
2175 			if (n == 0)
2176 				fatal("no keys found.");
2177 			exit(0);
2178 		}
2179 	}
2180 	if (pkcs11provider != NULL)
2181 		do_download(pw);
2182 
2183 	if (do_gen_candidates) {
2184 		FILE *out = fopen(out_file, "w");
2185 
2186 		if (out == NULL) {
2187 			error("Couldn't open modulus candidate file \"%s\": %s",
2188 			    out_file, strerror(errno));
2189 			return (1);
2190 		}
2191 		if (bits == 0)
2192 			bits = DEFAULT_BITS;
2193 		if (gen_candidates(out, memory, bits, start) != 0)
2194 			fatal("modulus candidate generation failed");
2195 
2196 		return (0);
2197 	}
2198 
2199 	if (do_screen_candidates) {
2200 		FILE *in;
2201 		FILE *out = fopen(out_file, "w");
2202 
2203 		if (have_identity && strcmp(identity_file, "-") != 0) {
2204 			if ((in = fopen(identity_file, "r")) == NULL) {
2205 				fatal("Couldn't open modulus candidate "
2206 				    "file \"%s\": %s", identity_file,
2207 				    strerror(errno));
2208 			}
2209 		} else
2210 			in = stdin;
2211 
2212 		if (out == NULL) {
2213 			fatal("Couldn't open moduli file \"%s\": %s",
2214 			    out_file, strerror(errno));
2215 		}
2216 		if (prime_test(in, out, trials, generator_wanted) != 0)
2217 			fatal("modulus screening failed");
2218 		return (0);
2219 	}
2220 
2221 	if (gen_all_hostkeys) {
2222 		do_gen_all_hostkeys(pw);
2223 		return (0);
2224 	}
2225 
2226 	arc4random_stir();
2227 
2228 	if (key_type_name == NULL)
2229 		key_type_name = "rsa";
2230 
2231 	type = key_type_from_name(key_type_name);
2232 	type_bits_valid(type, &bits);
2233 
2234 	if (!quiet)
2235 		printf("Generating public/private %s key pair.\n", key_type_name);
2236 	private = key_generate(type, bits);
2237 	if (private == NULL) {
2238 		fprintf(stderr, "key_generate failed\n");
2239 		exit(1);
2240 	}
2241 	public  = key_from_private(private);
2242 
2243 	if (!have_identity)
2244 		ask_filename(pw, "Enter file in which to save the key");
2245 
2246 	/* Create ~/.ssh directory if it doesn't already exist. */
2247 	snprintf(dotsshdir, sizeof dotsshdir, "%s/%s",
2248 	    pw->pw_dir, _PATH_SSH_USER_DIR);
2249 	if (strstr(identity_file, dotsshdir) != NULL) {
2250 		if (stat(dotsshdir, &st) < 0) {
2251 			if (errno != ENOENT) {
2252 				error("Could not stat %s: %s", dotsshdir,
2253 				    strerror(errno));
2254 			} else if (mkdir(dotsshdir, 0700) < 0) {
2255 				error("Could not create directory '%s': %s",
2256 				    dotsshdir, strerror(errno));
2257 			} else if (!quiet)
2258 				printf("Created directory '%s'.\n", dotsshdir);
2259 		}
2260 	}
2261 	/* If the file already exists, ask the user to confirm. */
2262 	if (stat(identity_file, &st) >= 0) {
2263 		char yesno[3];
2264 		printf("%s already exists.\n", identity_file);
2265 		printf("Overwrite (y/n)? ");
2266 		fflush(stdout);
2267 		if (fgets(yesno, sizeof(yesno), stdin) == NULL)
2268 			exit(1);
2269 		if (yesno[0] != 'y' && yesno[0] != 'Y')
2270 			exit(1);
2271 	}
2272 	/* Ask for a passphrase (twice). */
2273 	if (identity_passphrase)
2274 		passphrase1 = xstrdup(identity_passphrase);
2275 	else if (identity_new_passphrase)
2276 		passphrase1 = xstrdup(identity_new_passphrase);
2277 	else {
2278 passphrase_again:
2279 		passphrase1 =
2280 			read_passphrase("Enter passphrase (empty for no "
2281 			    "passphrase): ", RP_ALLOW_STDIN);
2282 		passphrase2 = read_passphrase("Enter same passphrase again: ",
2283 		    RP_ALLOW_STDIN);
2284 		if (strcmp(passphrase1, passphrase2) != 0) {
2285 			/*
2286 			 * The passphrases do not match.  Clear them and
2287 			 * retry.
2288 			 */
2289 			memset(passphrase1, 0, strlen(passphrase1));
2290 			memset(passphrase2, 0, strlen(passphrase2));
2291 			xfree(passphrase1);
2292 			xfree(passphrase2);
2293 			printf("Passphrases do not match.  Try again.\n");
2294 			goto passphrase_again;
2295 		}
2296 		/* Clear the other copy of the passphrase. */
2297 		memset(passphrase2, 0, strlen(passphrase2));
2298 		xfree(passphrase2);
2299 	}
2300 
2301 	if (identity_comment) {
2302 		strlcpy(comment, identity_comment, sizeof(comment));
2303 	} else {
2304 		/* Create default comment field for the passphrase. */
2305 		snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
2306 	}
2307 
2308 	/* Save the key with the given passphrase and comment. */
2309 	if (!key_save_private(private, identity_file, passphrase1, comment)) {
2310 		printf("Saving the key failed: %s.\n", identity_file);
2311 		memset(passphrase1, 0, strlen(passphrase1));
2312 		xfree(passphrase1);
2313 		exit(1);
2314 	}
2315 	/* Clear the passphrase. */
2316 	memset(passphrase1, 0, strlen(passphrase1));
2317 	xfree(passphrase1);
2318 
2319 	/* Clear the private key and the random number generator. */
2320 	key_free(private);
2321 	arc4random_stir();
2322 
2323 	if (!quiet)
2324 		printf("Your identification has been saved in %s.\n", identity_file);
2325 
2326 	strlcat(identity_file, ".pub", sizeof(identity_file));
2327 	fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
2328 	if (fd == -1) {
2329 		printf("Could not save your public key in %s\n", identity_file);
2330 		exit(1);
2331 	}
2332 	f = fdopen(fd, "w");
2333 	if (f == NULL) {
2334 		printf("fdopen %s failed\n", identity_file);
2335 		exit(1);
2336 	}
2337 	if (!key_write(public, f))
2338 		fprintf(stderr, "write key failed\n");
2339 	fprintf(f, " %s\n", comment);
2340 	fclose(f);
2341 
2342 	if (!quiet) {
2343 		char *fp = key_fingerprint(public, SSH_FP_MD5, SSH_FP_HEX);
2344 		char *ra = key_fingerprint(public, SSH_FP_MD5,
2345 		    SSH_FP_RANDOMART);
2346 		printf("Your public key has been saved in %s.\n",
2347 		    identity_file);
2348 		printf("The key fingerprint is:\n");
2349 		printf("%s %s\n", fp, comment);
2350 		printf("The key's randomart image is:\n");
2351 		printf("%s\n", ra);
2352 		xfree(ra);
2353 		xfree(fp);
2354 	}
2355 
2356 	key_free(public);
2357 	exit(0);
2358 }
2359