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