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