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