1/* $OpenBSD: ssh-keygen.c,v 1.472 2024/01/11 01:45:36 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
21#ifdef WITH_OPENSSL
22#include <openssl/evp.h>
23#include <openssl/pem.h>
24#include "openbsd-compat/openssl-compat.h"
25#endif
26
27#ifdef HAVE_STDINT_H
28# include <stdint.h>
29#endif
30#include <errno.h>
31#include <fcntl.h>
32#include <netdb.h>
33#ifdef HAVE_PATHS_H
34# include <paths.h>
35#endif
36#include <pwd.h>
37#include <stdarg.h>
38#include <stdio.h>
39#include <stdlib.h>
40#include <string.h>
41#include <unistd.h>
42#include <limits.h>
43#include <locale.h>
44#include <time.h>
45
46#include "xmalloc.h"
47#include "sshkey.h"
48#include "authfile.h"
49#include "sshbuf.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 "ssherr.h"
59#include "ssh-pkcs11.h"
60#include "atomicio.h"
61#include "krl.h"
62#include "digest.h"
63#include "utf8.h"
64#include "authfd.h"
65#include "sshsig.h"
66#include "ssh-sk.h"
67#include "sk-api.h" /* XXX for SSH_SK_USER_PRESENCE_REQD; remove */
68#include "cipher.h"
69
70#define DEFAULT_KEY_TYPE_NAME "ed25519"
71
72/*
73 * Default number of bits in the RSA, DSA and ECDSA keys.  These value can be
74 * overridden on the command line.
75 *
76 * These values, with the exception of DSA, provide security equivalent to at
77 * least 128 bits of security according to NIST Special Publication 800-57:
78 * Recommendation for Key Management Part 1 rev 4 section 5.6.1.
79 * For DSA it (and FIPS-186-4 section 4.2) specifies that the only size for
80 * which a 160bit hash is acceptable is 1kbit, and since ssh-dss specifies only
81 * SHA1 we limit the DSA key size 1k bits.
82 */
83#define DEFAULT_BITS		3072
84#define DEFAULT_BITS_DSA	1024
85#define DEFAULT_BITS_ECDSA	256
86
87static int quiet = 0;
88
89/* Flag indicating that we just want to see the key fingerprint */
90static int print_fingerprint = 0;
91static int print_bubblebabble = 0;
92
93/* Hash algorithm to use for fingerprints. */
94static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
95
96/* The identity file name, given on the command line or entered by the user. */
97static char identity_file[PATH_MAX];
98static int have_identity = 0;
99
100/* This is set to the passphrase if given on the command line. */
101static char *identity_passphrase = NULL;
102
103/* This is set to the new passphrase if given on the command line. */
104static char *identity_new_passphrase = NULL;
105
106/* Key type when certifying */
107static u_int cert_key_type = SSH2_CERT_TYPE_USER;
108
109/* "key ID" of signed key */
110static char *cert_key_id = NULL;
111
112/* Comma-separated list of principal names for certifying keys */
113static char *cert_principals = NULL;
114
115/* Validity period for certificates */
116static u_int64_t cert_valid_from = 0;
117static u_int64_t cert_valid_to = ~0ULL;
118
119/* Certificate options */
120#define CERTOPT_X_FWD				(1)
121#define CERTOPT_AGENT_FWD			(1<<1)
122#define CERTOPT_PORT_FWD			(1<<2)
123#define CERTOPT_PTY				(1<<3)
124#define CERTOPT_USER_RC				(1<<4)
125#define CERTOPT_NO_REQUIRE_USER_PRESENCE	(1<<5)
126#define CERTOPT_REQUIRE_VERIFY			(1<<6)
127#define CERTOPT_DEFAULT	(CERTOPT_X_FWD|CERTOPT_AGENT_FWD| \
128			 CERTOPT_PORT_FWD|CERTOPT_PTY|CERTOPT_USER_RC)
129static u_int32_t certflags_flags = CERTOPT_DEFAULT;
130static char *certflags_command = NULL;
131static char *certflags_src_addr = NULL;
132
133/* Arbitrary extensions specified by user */
134struct cert_ext {
135	char *key;
136	char *val;
137	int crit;
138};
139static struct cert_ext *cert_ext;
140static size_t ncert_ext;
141
142/* Conversion to/from various formats */
143enum {
144	FMT_RFC4716,
145	FMT_PKCS8,
146	FMT_PEM
147} convert_format = FMT_RFC4716;
148
149static char *key_type_name = NULL;
150
151/* Load key from this PKCS#11 provider */
152static char *pkcs11provider = NULL;
153
154/* FIDO/U2F provider to use */
155static char *sk_provider = NULL;
156
157/* Format for writing private keys */
158static int private_key_format = SSHKEY_PRIVATE_OPENSSH;
159
160/* Cipher for new-format private keys */
161static char *openssh_format_cipher = NULL;
162
163/* Number of KDF rounds to derive new format keys. */
164static int rounds = 0;
165
166/* argv0 */
167extern char *__progname;
168
169static char hostname[NI_MAXHOST];
170
171#ifdef WITH_OPENSSL
172/* moduli.c */
173int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
174int prime_test(FILE *, FILE *, u_int32_t, u_int32_t, char *, unsigned long,
175    unsigned long);
176#endif
177
178static void
179type_bits_valid(int type, const char *name, u_int32_t *bitsp)
180{
181	if (type == KEY_UNSPEC)
182		fatal("unknown key type %s", key_type_name);
183	if (*bitsp == 0) {
184#ifdef WITH_OPENSSL
185		int nid;
186
187		switch(type) {
188		case KEY_DSA:
189			*bitsp = DEFAULT_BITS_DSA;
190			break;
191		case KEY_ECDSA:
192			if (name != NULL &&
193			    (nid = sshkey_ecdsa_nid_from_name(name)) > 0)
194				*bitsp = sshkey_curve_nid_to_bits(nid);
195			if (*bitsp == 0)
196				*bitsp = DEFAULT_BITS_ECDSA;
197			break;
198		case KEY_RSA:
199			*bitsp = DEFAULT_BITS;
200			break;
201		}
202#endif
203	}
204#ifdef WITH_OPENSSL
205	switch (type) {
206	case KEY_DSA:
207		if (*bitsp != 1024)
208			fatal("Invalid DSA key length: must be 1024 bits");
209		break;
210	case KEY_RSA:
211		if (*bitsp < SSH_RSA_MINIMUM_MODULUS_SIZE)
212			fatal("Invalid RSA key length: minimum is %d bits",
213			    SSH_RSA_MINIMUM_MODULUS_SIZE);
214		else if (*bitsp > OPENSSL_RSA_MAX_MODULUS_BITS)
215			fatal("Invalid RSA key length: maximum is %d bits",
216			    OPENSSL_RSA_MAX_MODULUS_BITS);
217		break;
218	case KEY_ECDSA:
219		if (sshkey_ecdsa_bits_to_nid(*bitsp) == -1)
220#ifdef OPENSSL_HAS_NISTP521
221			fatal("Invalid ECDSA key length: valid lengths are "
222			    "256, 384 or 521 bits");
223#else
224			fatal("Invalid ECDSA key length: valid lengths are "
225			    "256 or 384 bits");
226#endif
227	}
228#endif
229}
230
231/*
232 * Checks whether a file exists and, if so, asks the user whether they wish
233 * to overwrite it.
234 * Returns nonzero if the file does not already exist or if the user agrees to
235 * overwrite, or zero otherwise.
236 */
237static int
238confirm_overwrite(const char *filename)
239{
240	char yesno[3];
241	struct stat st;
242
243	if (stat(filename, &st) != 0)
244		return 1;
245	printf("%s already exists.\n", filename);
246	printf("Overwrite (y/n)? ");
247	fflush(stdout);
248	if (fgets(yesno, sizeof(yesno), stdin) == NULL)
249		return 0;
250	if (yesno[0] != 'y' && yesno[0] != 'Y')
251		return 0;
252	return 1;
253}
254
255static void
256ask_filename(struct passwd *pw, const char *prompt)
257{
258	char buf[1024];
259	char *name = NULL;
260
261	if (key_type_name == NULL)
262		name = _PATH_SSH_CLIENT_ID_ED25519;
263	else {
264		switch (sshkey_type_from_name(key_type_name)) {
265#ifdef WITH_DSA
266		case KEY_DSA_CERT:
267		case KEY_DSA:
268			name = _PATH_SSH_CLIENT_ID_DSA;
269			break;
270#endif
271#ifdef OPENSSL_HAS_ECC
272		case KEY_ECDSA_CERT:
273		case KEY_ECDSA:
274			name = _PATH_SSH_CLIENT_ID_ECDSA;
275			break;
276		case KEY_ECDSA_SK_CERT:
277		case KEY_ECDSA_SK:
278			name = _PATH_SSH_CLIENT_ID_ECDSA_SK;
279			break;
280#endif
281		case KEY_RSA_CERT:
282		case KEY_RSA:
283			name = _PATH_SSH_CLIENT_ID_RSA;
284			break;
285		case KEY_ED25519:
286		case KEY_ED25519_CERT:
287			name = _PATH_SSH_CLIENT_ID_ED25519;
288			break;
289		case KEY_ED25519_SK:
290		case KEY_ED25519_SK_CERT:
291			name = _PATH_SSH_CLIENT_ID_ED25519_SK;
292			break;
293		case KEY_XMSS:
294		case KEY_XMSS_CERT:
295			name = _PATH_SSH_CLIENT_ID_XMSS;
296			break;
297		default:
298			fatal("bad key type");
299		}
300	}
301	snprintf(identity_file, sizeof(identity_file),
302	    "%s/%s", pw->pw_dir, name);
303	printf("%s (%s): ", prompt, identity_file);
304	fflush(stdout);
305	if (fgets(buf, sizeof(buf), stdin) == NULL)
306		exit(1);
307	buf[strcspn(buf, "\n")] = '\0';
308	if (strcmp(buf, "") != 0)
309		strlcpy(identity_file, buf, sizeof(identity_file));
310	have_identity = 1;
311}
312
313static struct sshkey *
314load_identity(const char *filename, char **commentp)
315{
316	char *pass;
317	struct sshkey *prv;
318	int r;
319
320	if (commentp != NULL)
321		*commentp = NULL;
322	if ((r = sshkey_load_private(filename, "", &prv, commentp)) == 0)
323		return prv;
324	if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
325		fatal_r(r, "Load key \"%s\"", filename);
326	if (identity_passphrase)
327		pass = xstrdup(identity_passphrase);
328	else
329		pass = read_passphrase("Enter passphrase: ", RP_ALLOW_STDIN);
330	r = sshkey_load_private(filename, pass, &prv, commentp);
331	freezero(pass, strlen(pass));
332	if (r != 0)
333		fatal_r(r, "Load key \"%s\"", filename);
334	return prv;
335}
336
337#define SSH_COM_PUBLIC_BEGIN		"---- BEGIN SSH2 PUBLIC KEY ----"
338#define SSH_COM_PUBLIC_END		"---- END SSH2 PUBLIC KEY ----"
339#define SSH_COM_PRIVATE_BEGIN		"---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
340#define	SSH_COM_PRIVATE_KEY_MAGIC	0x3f6ff9eb
341
342#ifdef WITH_OPENSSL
343static void
344do_convert_to_ssh2(struct passwd *pw, struct sshkey *k)
345{
346	struct sshbuf *b;
347	char comment[61], *b64;
348	int r;
349
350	if ((b = sshbuf_new()) == NULL)
351		fatal_f("sshbuf_new failed");
352	if ((r = sshkey_putb(k, b)) != 0)
353		fatal_fr(r, "put key");
354	if ((b64 = sshbuf_dtob64_string(b, 1)) == NULL)
355		fatal_f("sshbuf_dtob64_string failed");
356
357	/* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
358	snprintf(comment, sizeof(comment),
359	    "%u-bit %s, converted by %s@%s from OpenSSH",
360	    sshkey_size(k), sshkey_type(k),
361	    pw->pw_name, hostname);
362
363	sshkey_free(k);
364	sshbuf_free(b);
365
366	fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
367	fprintf(stdout, "Comment: \"%s\"\n%s", comment, b64);
368	fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
369	free(b64);
370	exit(0);
371}
372
373static void
374do_convert_to_pkcs8(struct sshkey *k)
375{
376	switch (sshkey_type_plain(k->type)) {
377	case KEY_RSA:
378		if (!PEM_write_RSA_PUBKEY(stdout, k->rsa))
379			fatal("PEM_write_RSA_PUBKEY failed");
380		break;
381#ifdef WITH_DSA
382	case KEY_DSA:
383		if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
384			fatal("PEM_write_DSA_PUBKEY failed");
385		break;
386#endif
387#ifdef OPENSSL_HAS_ECC
388	case KEY_ECDSA:
389		if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
390			fatal("PEM_write_EC_PUBKEY failed");
391		break;
392#endif
393	default:
394		fatal_f("unsupported key type %s", sshkey_type(k));
395	}
396	exit(0);
397}
398
399static void
400do_convert_to_pem(struct sshkey *k)
401{
402	switch (sshkey_type_plain(k->type)) {
403	case KEY_RSA:
404		if (!PEM_write_RSAPublicKey(stdout, k->rsa))
405			fatal("PEM_write_RSAPublicKey failed");
406		break;
407#ifdef WITH_DSA
408	case KEY_DSA:
409		if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
410			fatal("PEM_write_DSA_PUBKEY failed");
411		break;
412#endif
413#ifdef OPENSSL_HAS_ECC
414	case KEY_ECDSA:
415		if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
416			fatal("PEM_write_EC_PUBKEY failed");
417		break;
418#endif
419	default:
420		fatal_f("unsupported key type %s", sshkey_type(k));
421	}
422	exit(0);
423}
424
425static void
426do_convert_to(struct passwd *pw)
427{
428	struct sshkey *k;
429	struct stat st;
430	int r;
431
432	if (!have_identity)
433		ask_filename(pw, "Enter file in which the key is");
434	if (stat(identity_file, &st) == -1)
435		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
436	if ((r = sshkey_load_public(identity_file, &k, NULL)) != 0)
437		k = load_identity(identity_file, NULL);
438	switch (convert_format) {
439	case FMT_RFC4716:
440		do_convert_to_ssh2(pw, k);
441		break;
442	case FMT_PKCS8:
443		do_convert_to_pkcs8(k);
444		break;
445	case FMT_PEM:
446		do_convert_to_pem(k);
447		break;
448	default:
449		fatal_f("unknown key format %d", convert_format);
450	}
451	exit(0);
452}
453
454/*
455 * This is almost exactly the bignum1 encoding, but with 32 bit for length
456 * instead of 16.
457 */
458static void
459buffer_get_bignum_bits(struct sshbuf *b, BIGNUM *value)
460{
461	u_int bytes, bignum_bits;
462	int r;
463
464	if ((r = sshbuf_get_u32(b, &bignum_bits)) != 0)
465		fatal_fr(r, "parse");
466	bytes = (bignum_bits + 7) / 8;
467	if (sshbuf_len(b) < bytes)
468		fatal_f("input buffer too small: need %d have %zu",
469		    bytes, sshbuf_len(b));
470	if (BN_bin2bn(sshbuf_ptr(b), bytes, value) == NULL)
471		fatal_f("BN_bin2bn failed");
472	if ((r = sshbuf_consume(b, bytes)) != 0)
473		fatal_fr(r, "consume");
474}
475
476static struct sshkey *
477do_convert_private_ssh2(struct sshbuf *b)
478{
479	struct sshkey *key = NULL;
480	char *type, *cipher;
481	const char *alg = NULL;
482	u_char e1, e2, e3, *sig = NULL, data[] = "abcde12345";
483	int r, rlen, ktype;
484	u_int magic, i1, i2, i3, i4;
485	size_t slen;
486	u_long e;
487#ifdef WITH_DSA
488	BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL;
489	BIGNUM *dsa_pub_key = NULL, *dsa_priv_key = NULL;
490#endif
491	BIGNUM *rsa_n = NULL, *rsa_e = NULL, *rsa_d = NULL;
492	BIGNUM *rsa_p = NULL, *rsa_q = NULL, *rsa_iqmp = NULL;
493
494	if ((r = sshbuf_get_u32(b, &magic)) != 0)
495		fatal_fr(r, "parse magic");
496
497	if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
498		error("bad magic 0x%x != 0x%x", magic,
499		    SSH_COM_PRIVATE_KEY_MAGIC);
500		return NULL;
501	}
502	if ((r = sshbuf_get_u32(b, &i1)) != 0 ||
503	    (r = sshbuf_get_cstring(b, &type, NULL)) != 0 ||
504	    (r = sshbuf_get_cstring(b, &cipher, NULL)) != 0 ||
505	    (r = sshbuf_get_u32(b, &i2)) != 0 ||
506	    (r = sshbuf_get_u32(b, &i3)) != 0 ||
507	    (r = sshbuf_get_u32(b, &i4)) != 0)
508		fatal_fr(r, "parse");
509	debug("ignore (%d %d %d %d)", i1, i2, i3, i4);
510	if (strcmp(cipher, "none") != 0) {
511		error("unsupported cipher %s", cipher);
512		free(cipher);
513		free(type);
514		return NULL;
515	}
516	free(cipher);
517
518	if (strstr(type, "rsa")) {
519		ktype = KEY_RSA;
520#ifdef WITH_DSA
521	} else if (strstr(type, "dsa")) {
522		ktype = KEY_DSA;
523#endif
524	} else {
525		free(type);
526		return NULL;
527	}
528	if ((key = sshkey_new(ktype)) == NULL)
529		fatal("sshkey_new failed");
530	free(type);
531
532	switch (key->type) {
533#ifdef WITH_DSA
534	case KEY_DSA:
535		if ((dsa_p = BN_new()) == NULL ||
536		    (dsa_q = BN_new()) == NULL ||
537		    (dsa_g = BN_new()) == NULL ||
538		    (dsa_pub_key = BN_new()) == NULL ||
539		    (dsa_priv_key = BN_new()) == NULL)
540			fatal_f("BN_new");
541		buffer_get_bignum_bits(b, dsa_p);
542		buffer_get_bignum_bits(b, dsa_g);
543		buffer_get_bignum_bits(b, dsa_q);
544		buffer_get_bignum_bits(b, dsa_pub_key);
545		buffer_get_bignum_bits(b, dsa_priv_key);
546		if (!DSA_set0_pqg(key->dsa, dsa_p, dsa_q, dsa_g))
547			fatal_f("DSA_set0_pqg failed");
548		dsa_p = dsa_q = dsa_g = NULL; /* transferred */
549		if (!DSA_set0_key(key->dsa, dsa_pub_key, dsa_priv_key))
550			fatal_f("DSA_set0_key failed");
551		dsa_pub_key = dsa_priv_key = NULL; /* transferred */
552		break;
553#endif
554	case KEY_RSA:
555		if ((r = sshbuf_get_u8(b, &e1)) != 0 ||
556		    (e1 < 30 && (r = sshbuf_get_u8(b, &e2)) != 0) ||
557		    (e1 < 30 && (r = sshbuf_get_u8(b, &e3)) != 0))
558			fatal_fr(r, "parse RSA");
559		e = e1;
560		debug("e %lx", e);
561		if (e < 30) {
562			e <<= 8;
563			e += e2;
564			debug("e %lx", e);
565			e <<= 8;
566			e += e3;
567			debug("e %lx", e);
568		}
569		if ((rsa_e = BN_new()) == NULL)
570			fatal_f("BN_new");
571		if (!BN_set_word(rsa_e, e)) {
572			BN_clear_free(rsa_e);
573			sshkey_free(key);
574			return NULL;
575		}
576		if ((rsa_n = BN_new()) == NULL ||
577		    (rsa_d = BN_new()) == NULL ||
578		    (rsa_p = BN_new()) == NULL ||
579		    (rsa_q = BN_new()) == NULL ||
580		    (rsa_iqmp = BN_new()) == NULL)
581			fatal_f("BN_new");
582		buffer_get_bignum_bits(b, rsa_d);
583		buffer_get_bignum_bits(b, rsa_n);
584		buffer_get_bignum_bits(b, rsa_iqmp);
585		buffer_get_bignum_bits(b, rsa_q);
586		buffer_get_bignum_bits(b, rsa_p);
587		if (!RSA_set0_key(key->rsa, rsa_n, rsa_e, rsa_d))
588			fatal_f("RSA_set0_key failed");
589		rsa_n = rsa_e = rsa_d = NULL; /* transferred */
590		if (!RSA_set0_factors(key->rsa, rsa_p, rsa_q))
591			fatal_f("RSA_set0_factors failed");
592		rsa_p = rsa_q = NULL; /* transferred */
593		if ((r = ssh_rsa_complete_crt_parameters(key, rsa_iqmp)) != 0)
594			fatal_fr(r, "generate RSA parameters");
595		BN_clear_free(rsa_iqmp);
596		alg = "rsa-sha2-256";
597		break;
598	}
599	rlen = sshbuf_len(b);
600	if (rlen != 0)
601		error_f("remaining bytes in key blob %d", rlen);
602
603	/* try the key */
604	if ((r = sshkey_sign(key, &sig, &slen, data, sizeof(data),
605	    alg, NULL, NULL, 0)) != 0)
606		error_fr(r, "signing with converted key failed");
607	else if ((r = sshkey_verify(key, sig, slen, data, sizeof(data),
608	    alg, 0, NULL)) != 0)
609		error_fr(r, "verification with converted key failed");
610	if (r != 0) {
611		sshkey_free(key);
612		free(sig);
613		return NULL;
614	}
615	free(sig);
616	return key;
617}
618
619static int
620get_line(FILE *fp, char *line, size_t len)
621{
622	int c;
623	size_t pos = 0;
624
625	line[0] = '\0';
626	while ((c = fgetc(fp)) != EOF) {
627		if (pos >= len - 1)
628			fatal("input line too long.");
629		switch (c) {
630		case '\r':
631			c = fgetc(fp);
632			if (c != EOF && c != '\n' && ungetc(c, fp) == EOF)
633				fatal("unget: %s", strerror(errno));
634			return pos;
635		case '\n':
636			return pos;
637		}
638		line[pos++] = c;
639		line[pos] = '\0';
640	}
641	/* We reached EOF */
642	return -1;
643}
644
645static void
646do_convert_from_ssh2(struct passwd *pw, struct sshkey **k, int *private)
647{
648	int r, blen, escaped = 0;
649	u_int len;
650	char line[1024];
651	struct sshbuf *buf;
652	char encoded[8096];
653	FILE *fp;
654
655	if ((buf = sshbuf_new()) == NULL)
656		fatal("sshbuf_new failed");
657	if ((fp = fopen(identity_file, "r")) == NULL)
658		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
659	encoded[0] = '\0';
660	while ((blen = get_line(fp, line, sizeof(line))) != -1) {
661		if (blen > 0 && line[blen - 1] == '\\')
662			escaped++;
663		if (strncmp(line, "----", 4) == 0 ||
664		    strstr(line, ": ") != NULL) {
665			if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
666				*private = 1;
667			if (strstr(line, " END ") != NULL) {
668				break;
669			}
670			/* fprintf(stderr, "ignore: %s", line); */
671			continue;
672		}
673		if (escaped) {
674			escaped--;
675			/* fprintf(stderr, "escaped: %s", line); */
676			continue;
677		}
678		strlcat(encoded, line, sizeof(encoded));
679	}
680	len = strlen(encoded);
681	if (((len % 4) == 3) &&
682	    (encoded[len-1] == '=') &&
683	    (encoded[len-2] == '=') &&
684	    (encoded[len-3] == '='))
685		encoded[len-3] = '\0';
686	if ((r = sshbuf_b64tod(buf, encoded)) != 0)
687		fatal_fr(r, "base64 decode");
688	if (*private) {
689		if ((*k = do_convert_private_ssh2(buf)) == NULL)
690			fatal_f("private key conversion failed");
691	} else if ((r = sshkey_fromb(buf, k)) != 0)
692		fatal_fr(r, "parse key");
693	sshbuf_free(buf);
694	fclose(fp);
695}
696
697static void
698do_convert_from_pkcs8(struct sshkey **k, int *private)
699{
700	EVP_PKEY *pubkey;
701	FILE *fp;
702
703	if ((fp = fopen(identity_file, "r")) == NULL)
704		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
705	if ((pubkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL)) == NULL) {
706		fatal_f("%s is not a recognised public key format",
707		    identity_file);
708	}
709	fclose(fp);
710	switch (EVP_PKEY_base_id(pubkey)) {
711	case EVP_PKEY_RSA:
712		if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
713			fatal("sshkey_new failed");
714		(*k)->type = KEY_RSA;
715		(*k)->rsa = EVP_PKEY_get1_RSA(pubkey);
716		break;
717#ifdef WITH_DSA
718	case EVP_PKEY_DSA:
719		if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
720			fatal("sshkey_new failed");
721		(*k)->type = KEY_DSA;
722		(*k)->dsa = EVP_PKEY_get1_DSA(pubkey);
723		break;
724#endif
725#ifdef OPENSSL_HAS_ECC
726	case EVP_PKEY_EC:
727		if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
728			fatal("sshkey_new failed");
729		(*k)->type = KEY_ECDSA;
730		(*k)->ecdsa = EVP_PKEY_get1_EC_KEY(pubkey);
731		(*k)->ecdsa_nid = sshkey_ecdsa_key_to_nid((*k)->ecdsa);
732		break;
733#endif
734	default:
735		fatal_f("unsupported pubkey type %d",
736		    EVP_PKEY_base_id(pubkey));
737	}
738	EVP_PKEY_free(pubkey);
739	return;
740}
741
742static void
743do_convert_from_pem(struct sshkey **k, int *private)
744{
745	FILE *fp;
746	RSA *rsa;
747
748	if ((fp = fopen(identity_file, "r")) == NULL)
749		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
750	if ((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
751		if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
752			fatal("sshkey_new failed");
753		(*k)->type = KEY_RSA;
754		(*k)->rsa = rsa;
755		fclose(fp);
756		return;
757	}
758	fatal_f("unrecognised raw private key format");
759}
760
761static void
762do_convert_from(struct passwd *pw)
763{
764	struct sshkey *k = NULL;
765	int r, private = 0, ok = 0;
766	struct stat st;
767
768	if (!have_identity)
769		ask_filename(pw, "Enter file in which the key is");
770	if (stat(identity_file, &st) == -1)
771		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
772
773	switch (convert_format) {
774	case FMT_RFC4716:
775		do_convert_from_ssh2(pw, &k, &private);
776		break;
777	case FMT_PKCS8:
778		do_convert_from_pkcs8(&k, &private);
779		break;
780	case FMT_PEM:
781		do_convert_from_pem(&k, &private);
782		break;
783	default:
784		fatal_f("unknown key format %d", convert_format);
785	}
786
787	if (!private) {
788		if ((r = sshkey_write(k, stdout)) == 0)
789			ok = 1;
790		if (ok)
791			fprintf(stdout, "\n");
792	} else {
793		switch (k->type) {
794#ifdef WITH_DSA
795		case KEY_DSA:
796			ok = PEM_write_DSAPrivateKey(stdout, k->dsa, NULL,
797			    NULL, 0, NULL, NULL);
798			break;
799#endif
800#ifdef OPENSSL_HAS_ECC
801		case KEY_ECDSA:
802			ok = PEM_write_ECPrivateKey(stdout, k->ecdsa, NULL,
803			    NULL, 0, NULL, NULL);
804			break;
805#endif
806		case KEY_RSA:
807			ok = PEM_write_RSAPrivateKey(stdout, k->rsa, NULL,
808			    NULL, 0, NULL, NULL);
809			break;
810		default:
811			fatal_f("unsupported key type %s", sshkey_type(k));
812		}
813	}
814
815	if (!ok)
816		fatal("key write failed");
817	sshkey_free(k);
818	exit(0);
819}
820#endif
821
822static void
823do_print_public(struct passwd *pw)
824{
825	struct sshkey *prv;
826	struct stat st;
827	int r;
828	char *comment = NULL;
829
830	if (!have_identity)
831		ask_filename(pw, "Enter file in which the key is");
832	if (stat(identity_file, &st) == -1)
833		fatal("%s: %s", identity_file, strerror(errno));
834	prv = load_identity(identity_file, &comment);
835	if ((r = sshkey_write(prv, stdout)) != 0)
836		fatal_fr(r, "write key");
837	if (comment != NULL && *comment != '\0')
838		fprintf(stdout, " %s", comment);
839	fprintf(stdout, "\n");
840	if (sshkey_is_sk(prv)) {
841		debug("sk_application: \"%s\", sk_flags 0x%02x",
842			prv->sk_application, prv->sk_flags);
843	}
844	sshkey_free(prv);
845	free(comment);
846	exit(0);
847}
848
849static void
850do_download(struct passwd *pw)
851{
852#ifdef ENABLE_PKCS11
853	struct sshkey **keys = NULL;
854	int i, nkeys;
855	enum sshkey_fp_rep rep;
856	int fptype;
857	char *fp, *ra, **comments = NULL;
858
859	fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
860	rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
861
862	pkcs11_init(1);
863	nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys, &comments);
864	if (nkeys <= 0)
865		fatal("cannot read public key from pkcs11");
866	for (i = 0; i < nkeys; i++) {
867		if (print_fingerprint) {
868			fp = sshkey_fingerprint(keys[i], fptype, rep);
869			ra = sshkey_fingerprint(keys[i], fingerprint_hash,
870			    SSH_FP_RANDOMART);
871			if (fp == NULL || ra == NULL)
872				fatal_f("sshkey_fingerprint fail");
873			printf("%u %s %s (PKCS11 key)\n", sshkey_size(keys[i]),
874			    fp, sshkey_type(keys[i]));
875			if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
876				printf("%s\n", ra);
877			free(ra);
878			free(fp);
879		} else {
880			(void) sshkey_write(keys[i], stdout); /* XXX check */
881			fprintf(stdout, "%s%s\n",
882			    *(comments[i]) == '\0' ? "" : " ", comments[i]);
883		}
884		free(comments[i]);
885		sshkey_free(keys[i]);
886	}
887	free(comments);
888	free(keys);
889	pkcs11_terminate();
890	exit(0);
891#else
892	fatal("no pkcs11 support");
893#endif /* ENABLE_PKCS11 */
894}
895
896static struct sshkey *
897try_read_key(char **cpp)
898{
899	struct sshkey *ret;
900	int r;
901
902	if ((ret = sshkey_new(KEY_UNSPEC)) == NULL)
903		fatal("sshkey_new failed");
904	if ((r = sshkey_read(ret, cpp)) == 0)
905		return ret;
906	/* Not a key */
907	sshkey_free(ret);
908	return NULL;
909}
910
911static void
912fingerprint_one_key(const struct sshkey *public, const char *comment)
913{
914	char *fp = NULL, *ra = NULL;
915	enum sshkey_fp_rep rep;
916	int fptype;
917
918	fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
919	rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
920	fp = sshkey_fingerprint(public, fptype, rep);
921	ra = sshkey_fingerprint(public, fingerprint_hash, SSH_FP_RANDOMART);
922	if (fp == NULL || ra == NULL)
923		fatal_f("sshkey_fingerprint failed");
924	mprintf("%u %s %s (%s)\n", sshkey_size(public), fp,
925	    comment ? comment : "no comment", sshkey_type(public));
926	if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
927		printf("%s\n", ra);
928	free(ra);
929	free(fp);
930}
931
932static void
933fingerprint_private(const char *path)
934{
935	struct stat st;
936	char *comment = NULL;
937	struct sshkey *privkey = NULL, *pubkey = NULL;
938	int r;
939
940	if (stat(identity_file, &st) == -1)
941		fatal("%s: %s", path, strerror(errno));
942	if ((r = sshkey_load_public(path, &pubkey, &comment)) != 0)
943		debug_r(r, "load public \"%s\"", path);
944	if (pubkey == NULL || comment == NULL || *comment == '\0') {
945		free(comment);
946		if ((r = sshkey_load_private(path, NULL,
947		    &privkey, &comment)) != 0)
948			debug_r(r, "load private \"%s\"", path);
949	}
950	if (pubkey == NULL && privkey == NULL)
951		fatal("%s is not a key file.", path);
952
953	fingerprint_one_key(pubkey == NULL ? privkey : pubkey, comment);
954	sshkey_free(pubkey);
955	sshkey_free(privkey);
956	free(comment);
957}
958
959static void
960do_fingerprint(struct passwd *pw)
961{
962	FILE *f;
963	struct sshkey *public = NULL;
964	char *comment = NULL, *cp, *ep, *line = NULL;
965	size_t linesize = 0;
966	int i, invalid = 1;
967	const char *path;
968	u_long lnum = 0;
969
970	if (!have_identity)
971		ask_filename(pw, "Enter file in which the key is");
972	path = identity_file;
973
974	if (strcmp(identity_file, "-") == 0) {
975		f = stdin;
976		path = "(stdin)";
977	} else if ((f = fopen(path, "r")) == NULL)
978		fatal("%s: %s: %s", __progname, path, strerror(errno));
979
980	while (getline(&line, &linesize, f) != -1) {
981		lnum++;
982		cp = line;
983		cp[strcspn(cp, "\n")] = '\0';
984		/* Trim leading space and comments */
985		cp = line + strspn(line, " \t");
986		if (*cp == '#' || *cp == '\0')
987			continue;
988
989		/*
990		 * Input may be plain keys, private keys, authorized_keys
991		 * or known_hosts.
992		 */
993
994		/*
995		 * Try private keys first. Assume a key is private if
996		 * "SSH PRIVATE KEY" appears on the first line and we're
997		 * not reading from stdin (XXX support private keys on stdin).
998		 */
999		if (lnum == 1 && strcmp(identity_file, "-") != 0 &&
1000		    strstr(cp, "PRIVATE KEY") != NULL) {
1001			free(line);
1002			fclose(f);
1003			fingerprint_private(path);
1004			exit(0);
1005		}
1006
1007		/*
1008		 * If it's not a private key, then this must be prepared to
1009		 * accept a public key prefixed with a hostname or options.
1010		 * Try a bare key first, otherwise skip the leading stuff.
1011		 */
1012		comment = NULL;
1013		if ((public = try_read_key(&cp)) == NULL) {
1014			i = strtol(cp, &ep, 10);
1015			if (i == 0 || ep == NULL ||
1016			    (*ep != ' ' && *ep != '\t')) {
1017				int quoted = 0;
1018
1019				comment = cp;
1020				for (; *cp && (quoted || (*cp != ' ' &&
1021				    *cp != '\t')); cp++) {
1022					if (*cp == '\\' && cp[1] == '"')
1023						cp++;	/* Skip both */
1024					else if (*cp == '"')
1025						quoted = !quoted;
1026				}
1027				if (!*cp)
1028					continue;
1029				*cp++ = '\0';
1030			}
1031		}
1032		/* Retry after parsing leading hostname/key options */
1033		if (public == NULL && (public = try_read_key(&cp)) == NULL) {
1034			debug("%s:%lu: not a public key", path, lnum);
1035			continue;
1036		}
1037
1038		/* Find trailing comment, if any */
1039		for (; *cp == ' ' || *cp == '\t'; cp++)
1040			;
1041		if (*cp != '\0' && *cp != '#')
1042			comment = cp;
1043
1044		fingerprint_one_key(public, comment);
1045		sshkey_free(public);
1046		invalid = 0; /* One good key in the file is sufficient */
1047	}
1048	fclose(f);
1049	free(line);
1050
1051	if (invalid)
1052		fatal("%s is not a public key file.", path);
1053	exit(0);
1054}
1055
1056static void
1057do_gen_all_hostkeys(struct passwd *pw)
1058{
1059	struct {
1060		char *key_type;
1061		char *key_type_display;
1062		char *path;
1063	} key_types[] = {
1064#ifdef WITH_OPENSSL
1065		{ "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE },
1066#ifdef OPENSSL_HAS_ECC
1067		{ "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE },
1068#endif /* OPENSSL_HAS_ECC */
1069#endif /* WITH_OPENSSL */
1070		{ "ed25519", "ED25519",_PATH_HOST_ED25519_KEY_FILE },
1071#ifdef WITH_XMSS
1072		{ "xmss", "XMSS",_PATH_HOST_XMSS_KEY_FILE },
1073#endif /* WITH_XMSS */
1074		{ NULL, NULL, NULL }
1075	};
1076
1077	u_int32_t bits = 0;
1078	int first = 0;
1079	struct stat st;
1080	struct sshkey *private, *public;
1081	char comment[1024], *prv_tmp, *pub_tmp, *prv_file, *pub_file;
1082	int i, type, fd, r;
1083
1084	for (i = 0; key_types[i].key_type; i++) {
1085		public = private = NULL;
1086		prv_tmp = pub_tmp = prv_file = pub_file = NULL;
1087
1088		xasprintf(&prv_file, "%s%s",
1089		    identity_file, key_types[i].path);
1090
1091		/* Check whether private key exists and is not zero-length */
1092		if (stat(prv_file, &st) == 0) {
1093			if (st.st_size != 0)
1094				goto next;
1095		} else if (errno != ENOENT) {
1096			error("Could not stat %s: %s", key_types[i].path,
1097			    strerror(errno));
1098			goto failnext;
1099		}
1100
1101		/*
1102		 * Private key doesn't exist or is invalid; proceed with
1103		 * key generation.
1104		 */
1105		xasprintf(&prv_tmp, "%s%s.XXXXXXXXXX",
1106		    identity_file, key_types[i].path);
1107		xasprintf(&pub_tmp, "%s%s.pub.XXXXXXXXXX",
1108		    identity_file, key_types[i].path);
1109		xasprintf(&pub_file, "%s%s.pub",
1110		    identity_file, key_types[i].path);
1111
1112		if (first == 0) {
1113			first = 1;
1114			printf("%s: generating new host keys: ", __progname);
1115		}
1116		printf("%s ", key_types[i].key_type_display);
1117		fflush(stdout);
1118		type = sshkey_type_from_name(key_types[i].key_type);
1119		if ((fd = mkstemp(prv_tmp)) == -1) {
1120			error("Could not save your private key in %s: %s",
1121			    prv_tmp, strerror(errno));
1122			goto failnext;
1123		}
1124		(void)close(fd); /* just using mkstemp() to reserve a name */
1125		bits = 0;
1126		type_bits_valid(type, NULL, &bits);
1127		if ((r = sshkey_generate(type, bits, &private)) != 0) {
1128			error_r(r, "sshkey_generate failed");
1129			goto failnext;
1130		}
1131		if ((r = sshkey_from_private(private, &public)) != 0)
1132			fatal_fr(r, "sshkey_from_private");
1133		snprintf(comment, sizeof comment, "%s@%s", pw->pw_name,
1134		    hostname);
1135		if ((r = sshkey_save_private(private, prv_tmp, "",
1136		    comment, private_key_format, openssh_format_cipher,
1137		    rounds)) != 0) {
1138			error_r(r, "Saving key \"%s\" failed", prv_tmp);
1139			goto failnext;
1140		}
1141		if ((fd = mkstemp(pub_tmp)) == -1) {
1142			error("Could not save your public key in %s: %s",
1143			    pub_tmp, strerror(errno));
1144			goto failnext;
1145		}
1146		(void)fchmod(fd, 0644);
1147		(void)close(fd);
1148		if ((r = sshkey_save_public(public, pub_tmp, comment)) != 0) {
1149			error_r(r, "Unable to save public key to %s",
1150			    identity_file);
1151			goto failnext;
1152		}
1153
1154		/* Rename temporary files to their permanent locations. */
1155		if (rename(pub_tmp, pub_file) != 0) {
1156			error("Unable to move %s into position: %s",
1157			    pub_file, strerror(errno));
1158			goto failnext;
1159		}
1160		if (rename(prv_tmp, prv_file) != 0) {
1161			error("Unable to move %s into position: %s",
1162			    key_types[i].path, strerror(errno));
1163 failnext:
1164			first = 0;
1165			goto next;
1166		}
1167 next:
1168		sshkey_free(private);
1169		sshkey_free(public);
1170		free(prv_tmp);
1171		free(pub_tmp);
1172		free(prv_file);
1173		free(pub_file);
1174	}
1175	if (first != 0)
1176		printf("\n");
1177}
1178
1179struct known_hosts_ctx {
1180	const char *host;	/* Hostname searched for in find/delete case */
1181	FILE *out;		/* Output file, stdout for find_hosts case */
1182	int has_unhashed;	/* When hashing, original had unhashed hosts */
1183	int found_key;		/* For find/delete, host was found */
1184	int invalid;		/* File contained invalid items; don't delete */
1185	int hash_hosts;		/* Hash hostnames as we go */
1186	int find_host;		/* Search for specific hostname */
1187	int delete_host;	/* Delete host from known_hosts */
1188};
1189
1190static int
1191known_hosts_hash(struct hostkey_foreach_line *l, void *_ctx)
1192{
1193	struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1194	char *hashed, *cp, *hosts, *ohosts;
1195	int has_wild = l->hosts && strcspn(l->hosts, "*?!") != strlen(l->hosts);
1196	int was_hashed = l->hosts && l->hosts[0] == HASH_DELIM;
1197
1198	switch (l->status) {
1199	case HKF_STATUS_OK:
1200	case HKF_STATUS_MATCHED:
1201		/*
1202		 * Don't hash hosts already hashed, with wildcard
1203		 * characters or a CA/revocation marker.
1204		 */
1205		if (was_hashed || has_wild || l->marker != MRK_NONE) {
1206			fprintf(ctx->out, "%s\n", l->line);
1207			if (has_wild && !ctx->find_host) {
1208				logit("%s:%lu: ignoring host name "
1209				    "with wildcard: %.64s", l->path,
1210				    l->linenum, l->hosts);
1211			}
1212			return 0;
1213		}
1214		/*
1215		 * Split any comma-separated hostnames from the host list,
1216		 * hash and store separately.
1217		 */
1218		ohosts = hosts = xstrdup(l->hosts);
1219		while ((cp = strsep(&hosts, ",")) != NULL && *cp != '\0') {
1220			lowercase(cp);
1221			if ((hashed = host_hash(cp, NULL, 0)) == NULL)
1222				fatal("hash_host failed");
1223			fprintf(ctx->out, "%s %s\n", hashed, l->rawkey);
1224			free(hashed);
1225			ctx->has_unhashed = 1;
1226		}
1227		free(ohosts);
1228		return 0;
1229	case HKF_STATUS_INVALID:
1230		/* Retain invalid lines, but mark file as invalid. */
1231		ctx->invalid = 1;
1232		logit("%s:%lu: invalid line", l->path, l->linenum);
1233		/* FALLTHROUGH */
1234	default:
1235		fprintf(ctx->out, "%s\n", l->line);
1236		return 0;
1237	}
1238	/* NOTREACHED */
1239	return -1;
1240}
1241
1242static int
1243known_hosts_find_delete(struct hostkey_foreach_line *l, void *_ctx)
1244{
1245	struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1246	enum sshkey_fp_rep rep;
1247	int fptype;
1248	char *fp = NULL, *ra = NULL;
1249
1250	fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
1251	rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1252
1253	if (l->status == HKF_STATUS_MATCHED) {
1254		if (ctx->delete_host) {
1255			if (l->marker != MRK_NONE) {
1256				/* Don't remove CA and revocation lines */
1257				fprintf(ctx->out, "%s\n", l->line);
1258			} else {
1259				/*
1260				 * Hostname matches and has no CA/revoke
1261				 * marker, delete it by *not* writing the
1262				 * line to ctx->out.
1263				 */
1264				ctx->found_key = 1;
1265				if (!quiet)
1266					printf("# Host %s found: line %lu\n",
1267					    ctx->host, l->linenum);
1268			}
1269			return 0;
1270		} else if (ctx->find_host) {
1271			ctx->found_key = 1;
1272			if (!quiet) {
1273				printf("# Host %s found: line %lu %s\n",
1274				    ctx->host,
1275				    l->linenum, l->marker == MRK_CA ? "CA" :
1276				    (l->marker == MRK_REVOKE ? "REVOKED" : ""));
1277			}
1278			if (ctx->hash_hosts)
1279				known_hosts_hash(l, ctx);
1280			else if (print_fingerprint) {
1281				fp = sshkey_fingerprint(l->key, fptype, rep);
1282				ra = sshkey_fingerprint(l->key,
1283				    fingerprint_hash, SSH_FP_RANDOMART);
1284				if (fp == NULL || ra == NULL)
1285					fatal_f("sshkey_fingerprint failed");
1286				mprintf("%s %s %s%s%s\n", ctx->host,
1287				    sshkey_type(l->key), fp,
1288				    l->comment[0] ? " " : "",
1289				    l->comment);
1290				if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
1291					printf("%s\n", ra);
1292				free(ra);
1293				free(fp);
1294			} else
1295				fprintf(ctx->out, "%s\n", l->line);
1296			return 0;
1297		}
1298	} else if (ctx->delete_host) {
1299		/* Retain non-matching hosts when deleting */
1300		if (l->status == HKF_STATUS_INVALID) {
1301			ctx->invalid = 1;
1302			logit("%s:%lu: invalid line", l->path, l->linenum);
1303		}
1304		fprintf(ctx->out, "%s\n", l->line);
1305	}
1306	return 0;
1307}
1308
1309static void
1310do_known_hosts(struct passwd *pw, const char *name, int find_host,
1311    int delete_host, int hash_hosts)
1312{
1313	char *cp, tmp[PATH_MAX], old[PATH_MAX];
1314	int r, fd, oerrno, inplace = 0;
1315	struct known_hosts_ctx ctx;
1316	u_int foreach_options;
1317	struct stat sb;
1318
1319	if (!have_identity) {
1320		cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
1321		if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
1322		    sizeof(identity_file))
1323			fatal("Specified known hosts path too long");
1324		free(cp);
1325		have_identity = 1;
1326	}
1327	if (stat(identity_file, &sb) != 0)
1328		fatal("Cannot stat %s: %s", identity_file, strerror(errno));
1329
1330	memset(&ctx, 0, sizeof(ctx));
1331	ctx.out = stdout;
1332	ctx.host = name;
1333	ctx.hash_hosts = hash_hosts;
1334	ctx.find_host = find_host;
1335	ctx.delete_host = delete_host;
1336
1337	/*
1338	 * Find hosts goes to stdout, hash and deletions happen in-place
1339	 * A corner case is ssh-keygen -HF foo, which should go to stdout
1340	 */
1341	if (!find_host && (hash_hosts || delete_host)) {
1342		if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
1343		    strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
1344		    strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
1345		    strlcat(old, ".old", sizeof(old)) >= sizeof(old))
1346			fatal("known_hosts path too long");
1347		umask(077);
1348		if ((fd = mkstemp(tmp)) == -1)
1349			fatal("mkstemp: %s", strerror(errno));
1350		if ((ctx.out = fdopen(fd, "w")) == NULL) {
1351			oerrno = errno;
1352			unlink(tmp);
1353			fatal("fdopen: %s", strerror(oerrno));
1354		}
1355		(void)fchmod(fd, sb.st_mode & 0644);
1356		inplace = 1;
1357	}
1358	/* XXX support identity_file == "-" for stdin */
1359	foreach_options = find_host ? HKF_WANT_MATCH : 0;
1360	foreach_options |= print_fingerprint ? HKF_WANT_PARSE_KEY : 0;
1361	if ((r = hostkeys_foreach(identity_file, (find_host || !hash_hosts) ?
1362	    known_hosts_find_delete : known_hosts_hash, &ctx, name, NULL,
1363	    foreach_options, 0)) != 0) {
1364		if (inplace)
1365			unlink(tmp);
1366		fatal_fr(r, "hostkeys_foreach");
1367	}
1368
1369	if (inplace)
1370		fclose(ctx.out);
1371
1372	if (ctx.invalid) {
1373		error("%s is not a valid known_hosts file.", identity_file);
1374		if (inplace) {
1375			error("Not replacing existing known_hosts "
1376			    "file because of errors");
1377			unlink(tmp);
1378		}
1379		exit(1);
1380	} else if (delete_host && !ctx.found_key) {
1381		logit("Host %s not found in %s", name, identity_file);
1382		if (inplace)
1383			unlink(tmp);
1384	} else if (inplace) {
1385		/* Backup existing file */
1386		if (unlink(old) == -1 && errno != ENOENT)
1387			fatal("unlink %.100s: %s", old, strerror(errno));
1388		if (link(identity_file, old) == -1)
1389			fatal("link %.100s to %.100s: %s", identity_file, old,
1390			    strerror(errno));
1391		/* Move new one into place */
1392		if (rename(tmp, identity_file) == -1) {
1393			error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
1394			    strerror(errno));
1395			unlink(tmp);
1396			unlink(old);
1397			exit(1);
1398		}
1399
1400		printf("%s updated.\n", identity_file);
1401		printf("Original contents retained as %s\n", old);
1402		if (ctx.has_unhashed) {
1403			logit("WARNING: %s contains unhashed entries", old);
1404			logit("Delete this file to ensure privacy "
1405			    "of hostnames");
1406		}
1407	}
1408
1409	exit (find_host && !ctx.found_key);
1410}
1411
1412/*
1413 * Perform changing a passphrase.  The argument is the passwd structure
1414 * for the current user.
1415 */
1416static void
1417do_change_passphrase(struct passwd *pw)
1418{
1419	char *comment;
1420	char *old_passphrase, *passphrase1, *passphrase2;
1421	struct stat st;
1422	struct sshkey *private;
1423	int r;
1424
1425	if (!have_identity)
1426		ask_filename(pw, "Enter file in which the key is");
1427	if (stat(identity_file, &st) == -1)
1428		fatal("%s: %s", identity_file, strerror(errno));
1429	/* Try to load the file with empty passphrase. */
1430	r = sshkey_load_private(identity_file, "", &private, &comment);
1431	if (r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
1432		if (identity_passphrase)
1433			old_passphrase = xstrdup(identity_passphrase);
1434		else
1435			old_passphrase =
1436			    read_passphrase("Enter old passphrase: ",
1437			    RP_ALLOW_STDIN);
1438		r = sshkey_load_private(identity_file, old_passphrase,
1439		    &private, &comment);
1440		freezero(old_passphrase, strlen(old_passphrase));
1441		if (r != 0)
1442			goto badkey;
1443	} else if (r != 0) {
1444 badkey:
1445		fatal_r(r, "Failed to load key %s", identity_file);
1446	}
1447	if (comment)
1448		mprintf("Key has comment '%s'\n", comment);
1449
1450	/* Ask the new passphrase (twice). */
1451	if (identity_new_passphrase) {
1452		passphrase1 = xstrdup(identity_new_passphrase);
1453		passphrase2 = NULL;
1454	} else {
1455		passphrase1 =
1456			read_passphrase("Enter new passphrase (empty for no "
1457			    "passphrase): ", RP_ALLOW_STDIN);
1458		passphrase2 = read_passphrase("Enter same passphrase again: ",
1459		    RP_ALLOW_STDIN);
1460
1461		/* Verify that they are the same. */
1462		if (strcmp(passphrase1, passphrase2) != 0) {
1463			explicit_bzero(passphrase1, strlen(passphrase1));
1464			explicit_bzero(passphrase2, strlen(passphrase2));
1465			free(passphrase1);
1466			free(passphrase2);
1467			printf("Pass phrases do not match.  Try again.\n");
1468			exit(1);
1469		}
1470		/* Destroy the other copy. */
1471		freezero(passphrase2, strlen(passphrase2));
1472	}
1473
1474	/* Save the file using the new passphrase. */
1475	if ((r = sshkey_save_private(private, identity_file, passphrase1,
1476	    comment, private_key_format, openssh_format_cipher, rounds)) != 0) {
1477		error_r(r, "Saving key \"%s\" failed", identity_file);
1478		freezero(passphrase1, strlen(passphrase1));
1479		sshkey_free(private);
1480		free(comment);
1481		exit(1);
1482	}
1483	/* Destroy the passphrase and the copy of the key in memory. */
1484	freezero(passphrase1, strlen(passphrase1));
1485	sshkey_free(private);		 /* Destroys contents */
1486	free(comment);
1487
1488	printf("Your identification has been saved with the new passphrase.\n");
1489	exit(0);
1490}
1491
1492/*
1493 * Print the SSHFP RR.
1494 */
1495static int
1496do_print_resource_record(struct passwd *pw, char *fname, char *hname,
1497    int print_generic, char * const *opts, size_t nopts)
1498{
1499	struct sshkey *public;
1500	char *comment = NULL;
1501	struct stat st;
1502	int r, hash = -1;
1503	size_t i;
1504
1505	for (i = 0; i < nopts; i++) {
1506		if (strncasecmp(opts[i], "hashalg=", 8) == 0) {
1507			if ((hash = ssh_digest_alg_by_name(opts[i] + 8)) == -1)
1508				fatal("Unsupported hash algorithm");
1509		} else {
1510			error("Invalid option \"%s\"", opts[i]);
1511			return SSH_ERR_INVALID_ARGUMENT;
1512		}
1513	}
1514	if (fname == NULL)
1515		fatal_f("no filename");
1516	if (stat(fname, &st) == -1) {
1517		if (errno == ENOENT)
1518			return 0;
1519		fatal("%s: %s", fname, strerror(errno));
1520	}
1521	if ((r = sshkey_load_public(fname, &public, &comment)) != 0)
1522		fatal_r(r, "Failed to read v2 public key from \"%s\"", fname);
1523	export_dns_rr(hname, public, stdout, print_generic, hash);
1524	sshkey_free(public);
1525	free(comment);
1526	return 1;
1527}
1528
1529/*
1530 * Change the comment of a private key file.
1531 */
1532static void
1533do_change_comment(struct passwd *pw, const char *identity_comment)
1534{
1535	char new_comment[1024], *comment, *passphrase;
1536	struct sshkey *private;
1537	struct sshkey *public;
1538	struct stat st;
1539	int r;
1540
1541	if (!have_identity)
1542		ask_filename(pw, "Enter file in which the key is");
1543	if (stat(identity_file, &st) == -1)
1544		fatal("%s: %s", identity_file, strerror(errno));
1545	if ((r = sshkey_load_private(identity_file, "",
1546	    &private, &comment)) == 0)
1547		passphrase = xstrdup("");
1548	else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
1549		fatal_r(r, "Cannot load private key \"%s\"", identity_file);
1550	else {
1551		if (identity_passphrase)
1552			passphrase = xstrdup(identity_passphrase);
1553		else if (identity_new_passphrase)
1554			passphrase = xstrdup(identity_new_passphrase);
1555		else
1556			passphrase = read_passphrase("Enter passphrase: ",
1557			    RP_ALLOW_STDIN);
1558		/* Try to load using the passphrase. */
1559		if ((r = sshkey_load_private(identity_file, passphrase,
1560		    &private, &comment)) != 0) {
1561			freezero(passphrase, strlen(passphrase));
1562			fatal_r(r, "Cannot load private key \"%s\"",
1563			    identity_file);
1564		}
1565	}
1566
1567	if (private->type != KEY_ED25519 && private->type != KEY_XMSS &&
1568	    private_key_format != SSHKEY_PRIVATE_OPENSSH) {
1569		error("Comments are only supported for keys stored in "
1570		    "the new format (-o).");
1571		explicit_bzero(passphrase, strlen(passphrase));
1572		sshkey_free(private);
1573		exit(1);
1574	}
1575	if (comment)
1576		printf("Old comment: %s\n", comment);
1577	else
1578		printf("No existing comment\n");
1579
1580	if (identity_comment) {
1581		strlcpy(new_comment, identity_comment, sizeof(new_comment));
1582	} else {
1583		printf("New comment: ");
1584		fflush(stdout);
1585		if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1586			explicit_bzero(passphrase, strlen(passphrase));
1587			sshkey_free(private);
1588			exit(1);
1589		}
1590		new_comment[strcspn(new_comment, "\n")] = '\0';
1591	}
1592	if (comment != NULL && strcmp(comment, new_comment) == 0) {
1593		printf("No change to comment\n");
1594		free(passphrase);
1595		sshkey_free(private);
1596		free(comment);
1597		exit(0);
1598	}
1599
1600	/* Save the file using the new passphrase. */
1601	if ((r = sshkey_save_private(private, identity_file, passphrase,
1602	    new_comment, private_key_format, openssh_format_cipher,
1603	    rounds)) != 0) {
1604		error_r(r, "Saving key \"%s\" failed", identity_file);
1605		freezero(passphrase, strlen(passphrase));
1606		sshkey_free(private);
1607		free(comment);
1608		exit(1);
1609	}
1610	freezero(passphrase, strlen(passphrase));
1611	if ((r = sshkey_from_private(private, &public)) != 0)
1612		fatal_fr(r, "sshkey_from_private");
1613	sshkey_free(private);
1614
1615	strlcat(identity_file, ".pub", sizeof(identity_file));
1616	if ((r = sshkey_save_public(public, identity_file, new_comment)) != 0)
1617		fatal_r(r, "Unable to save public key to %s", identity_file);
1618	sshkey_free(public);
1619	free(comment);
1620
1621	if (strlen(new_comment) > 0)
1622		printf("Comment '%s' applied\n", new_comment);
1623	else
1624		printf("Comment removed\n");
1625
1626	exit(0);
1627}
1628
1629static void
1630cert_ext_add(const char *key, const char *value, int iscrit)
1631{
1632	cert_ext = xreallocarray(cert_ext, ncert_ext + 1, sizeof(*cert_ext));
1633	cert_ext[ncert_ext].key = xstrdup(key);
1634	cert_ext[ncert_ext].val = value == NULL ? NULL : xstrdup(value);
1635	cert_ext[ncert_ext].crit = iscrit;
1636	ncert_ext++;
1637}
1638
1639/* qsort(3) comparison function for certificate extensions */
1640static int
1641cert_ext_cmp(const void *_a, const void *_b)
1642{
1643	const struct cert_ext *a = (const struct cert_ext *)_a;
1644	const struct cert_ext *b = (const struct cert_ext *)_b;
1645	int r;
1646
1647	if (a->crit != b->crit)
1648		return (a->crit < b->crit) ? -1 : 1;
1649	if ((r = strcmp(a->key, b->key)) != 0)
1650		return r;
1651	if ((a->val == NULL) != (b->val == NULL))
1652		return (a->val == NULL) ? -1 : 1;
1653	if (a->val != NULL && (r = strcmp(a->val, b->val)) != 0)
1654		return r;
1655	return 0;
1656}
1657
1658#define OPTIONS_CRITICAL	1
1659#define OPTIONS_EXTENSIONS	2
1660static void
1661prepare_options_buf(struct sshbuf *c, int which)
1662{
1663	struct sshbuf *b;
1664	size_t i;
1665	int r;
1666	const struct cert_ext *ext;
1667
1668	if ((b = sshbuf_new()) == NULL)
1669		fatal_f("sshbuf_new failed");
1670	sshbuf_reset(c);
1671	for (i = 0; i < ncert_ext; i++) {
1672		ext = &cert_ext[i];
1673		if ((ext->crit && (which & OPTIONS_EXTENSIONS)) ||
1674		    (!ext->crit && (which & OPTIONS_CRITICAL)))
1675			continue;
1676		if (ext->val == NULL) {
1677			/* flag option */
1678			debug3_f("%s", ext->key);
1679			if ((r = sshbuf_put_cstring(c, ext->key)) != 0 ||
1680			    (r = sshbuf_put_string(c, NULL, 0)) != 0)
1681				fatal_fr(r, "prepare flag");
1682		} else {
1683			/* key/value option */
1684			debug3_f("%s=%s", ext->key, ext->val);
1685			sshbuf_reset(b);
1686			if ((r = sshbuf_put_cstring(c, ext->key)) != 0 ||
1687			    (r = sshbuf_put_cstring(b, ext->val)) != 0 ||
1688			    (r = sshbuf_put_stringb(c, b)) != 0)
1689				fatal_fr(r, "prepare k/v");
1690		}
1691	}
1692	sshbuf_free(b);
1693}
1694
1695static void
1696finalise_cert_exts(void)
1697{
1698	/* critical options */
1699	if (certflags_command != NULL)
1700		cert_ext_add("force-command", certflags_command, 1);
1701	if (certflags_src_addr != NULL)
1702		cert_ext_add("source-address", certflags_src_addr, 1);
1703	if ((certflags_flags & CERTOPT_REQUIRE_VERIFY) != 0)
1704		cert_ext_add("verify-required", NULL, 1);
1705	/* extensions */
1706	if ((certflags_flags & CERTOPT_X_FWD) != 0)
1707		cert_ext_add("permit-X11-forwarding", NULL, 0);
1708	if ((certflags_flags & CERTOPT_AGENT_FWD) != 0)
1709		cert_ext_add("permit-agent-forwarding", NULL, 0);
1710	if ((certflags_flags & CERTOPT_PORT_FWD) != 0)
1711		cert_ext_add("permit-port-forwarding", NULL, 0);
1712	if ((certflags_flags & CERTOPT_PTY) != 0)
1713		cert_ext_add("permit-pty", NULL, 0);
1714	if ((certflags_flags & CERTOPT_USER_RC) != 0)
1715		cert_ext_add("permit-user-rc", NULL, 0);
1716	if ((certflags_flags & CERTOPT_NO_REQUIRE_USER_PRESENCE) != 0)
1717		cert_ext_add("no-touch-required", NULL, 0);
1718	/* order lexically by key */
1719	if (ncert_ext > 0)
1720		qsort(cert_ext, ncert_ext, sizeof(*cert_ext), cert_ext_cmp);
1721}
1722
1723static struct sshkey *
1724load_pkcs11_key(char *path)
1725{
1726#ifdef ENABLE_PKCS11
1727	struct sshkey **keys = NULL, *public, *private = NULL;
1728	int r, i, nkeys;
1729
1730	if ((r = sshkey_load_public(path, &public, NULL)) != 0)
1731		fatal_r(r, "Couldn't load CA public key \"%s\"", path);
1732
1733	nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase,
1734	    &keys, NULL);
1735	debug3_f("%d keys", nkeys);
1736	if (nkeys <= 0)
1737		fatal("cannot read public key from pkcs11");
1738	for (i = 0; i < nkeys; i++) {
1739		if (sshkey_equal_public(public, keys[i])) {
1740			private = keys[i];
1741			continue;
1742		}
1743		sshkey_free(keys[i]);
1744	}
1745	free(keys);
1746	sshkey_free(public);
1747	return private;
1748#else
1749	fatal("no pkcs11 support");
1750#endif /* ENABLE_PKCS11 */
1751}
1752
1753/* Signer for sshkey_certify_custom that uses the agent */
1754static int
1755agent_signer(struct sshkey *key, u_char **sigp, size_t *lenp,
1756    const u_char *data, size_t datalen,
1757    const char *alg, const char *provider, const char *pin,
1758    u_int compat, void *ctx)
1759{
1760	int *agent_fdp = (int *)ctx;
1761
1762	return ssh_agent_sign(*agent_fdp, key, sigp, lenp,
1763	    data, datalen, alg, compat);
1764}
1765
1766static void
1767do_ca_sign(struct passwd *pw, const char *ca_key_path, int prefer_agent,
1768    unsigned long long cert_serial, int cert_serial_autoinc,
1769    int argc, char **argv)
1770{
1771	int r, i, found, agent_fd = -1;
1772	u_int n;
1773	struct sshkey *ca, *public;
1774	char valid[64], *otmp, *tmp, *cp, *out, *comment;
1775	char *ca_fp = NULL, **plist = NULL, *pin = NULL;
1776	struct ssh_identitylist *agent_ids;
1777	size_t j;
1778	struct notifier_ctx *notifier = NULL;
1779
1780#ifdef ENABLE_PKCS11
1781	pkcs11_init(1);
1782#endif
1783	tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
1784	if (pkcs11provider != NULL) {
1785		/* If a PKCS#11 token was specified then try to use it */
1786		if ((ca = load_pkcs11_key(tmp)) == NULL)
1787			fatal("No PKCS#11 key matching %s found", ca_key_path);
1788	} else if (prefer_agent) {
1789		/*
1790		 * Agent signature requested. Try to use agent after making
1791		 * sure the public key specified is actually present in the
1792		 * agent.
1793		 */
1794		if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
1795			fatal_r(r, "Cannot load CA public key %s", tmp);
1796		if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
1797			fatal_r(r, "Cannot use public key for CA signature");
1798		if ((r = ssh_fetch_identitylist(agent_fd, &agent_ids)) != 0)
1799			fatal_r(r, "Retrieve agent key list");
1800		found = 0;
1801		for (j = 0; j < agent_ids->nkeys; j++) {
1802			if (sshkey_equal(ca, agent_ids->keys[j])) {
1803				found = 1;
1804				break;
1805			}
1806		}
1807		if (!found)
1808			fatal("CA key %s not found in agent", tmp);
1809		ssh_free_identitylist(agent_ids);
1810		ca->flags |= SSHKEY_FLAG_EXT;
1811	} else {
1812		/* CA key is assumed to be a private key on the filesystem */
1813		ca = load_identity(tmp, NULL);
1814		if (sshkey_is_sk(ca) &&
1815		    (ca->sk_flags & SSH_SK_USER_VERIFICATION_REQD)) {
1816			if ((pin = read_passphrase("Enter PIN for CA key: ",
1817			    RP_ALLOW_STDIN)) == NULL)
1818				fatal_f("couldn't read PIN");
1819		}
1820	}
1821	free(tmp);
1822
1823	if (key_type_name != NULL) {
1824		if (sshkey_type_from_name(key_type_name) != ca->type) {
1825			fatal("CA key type %s doesn't match specified %s",
1826			    sshkey_ssh_name(ca), key_type_name);
1827		}
1828	} else if (ca->type == KEY_RSA) {
1829		/* Default to a good signature algorithm */
1830		key_type_name = "rsa-sha2-512";
1831	}
1832	ca_fp = sshkey_fingerprint(ca, fingerprint_hash, SSH_FP_DEFAULT);
1833
1834	finalise_cert_exts();
1835	for (i = 0; i < argc; i++) {
1836		/* Split list of principals */
1837		n = 0;
1838		if (cert_principals != NULL) {
1839			otmp = tmp = xstrdup(cert_principals);
1840			plist = NULL;
1841			for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1842				plist = xreallocarray(plist, n + 1, sizeof(*plist));
1843				if (*(plist[n] = xstrdup(cp)) == '\0')
1844					fatal("Empty principal name");
1845			}
1846			free(otmp);
1847		}
1848		if (n > SSHKEY_CERT_MAX_PRINCIPALS)
1849			fatal("Too many certificate principals specified");
1850
1851		tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1852		if ((r = sshkey_load_public(tmp, &public, &comment)) != 0)
1853			fatal_r(r, "load pubkey \"%s\"", tmp);
1854		if (sshkey_is_cert(public))
1855			fatal_f("key \"%s\" type %s cannot be certified",
1856			    tmp, sshkey_type(public));
1857
1858		/* Prepare certificate to sign */
1859		if ((r = sshkey_to_certified(public)) != 0)
1860			fatal_r(r, "Could not upgrade key %s to certificate", tmp);
1861		public->cert->type = cert_key_type;
1862		public->cert->serial = (u_int64_t)cert_serial;
1863		public->cert->key_id = xstrdup(cert_key_id);
1864		public->cert->nprincipals = n;
1865		public->cert->principals = plist;
1866		public->cert->valid_after = cert_valid_from;
1867		public->cert->valid_before = cert_valid_to;
1868		prepare_options_buf(public->cert->critical, OPTIONS_CRITICAL);
1869		prepare_options_buf(public->cert->extensions,
1870		    OPTIONS_EXTENSIONS);
1871		if ((r = sshkey_from_private(ca,
1872		    &public->cert->signature_key)) != 0)
1873			fatal_r(r, "sshkey_from_private (ca key)");
1874
1875		if (agent_fd != -1 && (ca->flags & SSHKEY_FLAG_EXT) != 0) {
1876			if ((r = sshkey_certify_custom(public, ca,
1877			    key_type_name, sk_provider, NULL, agent_signer,
1878			    &agent_fd)) != 0)
1879				fatal_r(r, "Couldn't certify %s via agent", tmp);
1880		} else {
1881			if (sshkey_is_sk(ca) &&
1882			    (ca->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
1883				notifier = notify_start(0,
1884				    "Confirm user presence for key %s %s",
1885				    sshkey_type(ca), ca_fp);
1886			}
1887			r = sshkey_certify(public, ca, key_type_name,
1888			    sk_provider, pin);
1889			notify_complete(notifier, "User presence confirmed");
1890			if (r != 0)
1891				fatal_r(r, "Couldn't certify key %s", tmp);
1892		}
1893
1894		if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
1895			*cp = '\0';
1896		xasprintf(&out, "%s-cert.pub", tmp);
1897		free(tmp);
1898
1899		if ((r = sshkey_save_public(public, out, comment)) != 0) {
1900			fatal_r(r, "Unable to save public key to %s",
1901			    identity_file);
1902		}
1903
1904		if (!quiet) {
1905			sshkey_format_cert_validity(public->cert,
1906			    valid, sizeof(valid));
1907			logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1908			    "valid %s", sshkey_cert_type(public),
1909			    out, public->cert->key_id,
1910			    (unsigned long long)public->cert->serial,
1911			    cert_principals != NULL ? " for " : "",
1912			    cert_principals != NULL ? cert_principals : "",
1913			    valid);
1914		}
1915
1916		sshkey_free(public);
1917		free(out);
1918		if (cert_serial_autoinc)
1919			cert_serial++;
1920	}
1921	if (pin != NULL)
1922		freezero(pin, strlen(pin));
1923	free(ca_fp);
1924#ifdef ENABLE_PKCS11
1925	pkcs11_terminate();
1926#endif
1927	exit(0);
1928}
1929
1930static u_int64_t
1931parse_relative_time(const char *s, time_t now)
1932{
1933	int64_t mul, secs;
1934
1935	mul = *s == '-' ? -1 : 1;
1936
1937	if ((secs = convtime(s + 1)) == -1)
1938		fatal("Invalid relative certificate time %s", s);
1939	if (mul == -1 && secs > now)
1940		fatal("Certificate time %s cannot be represented", s);
1941	return now + (u_int64_t)(secs * mul);
1942}
1943
1944static void
1945parse_hex_u64(const char *s, uint64_t *up)
1946{
1947	char *ep;
1948	unsigned long long ull;
1949
1950	errno = 0;
1951	ull = strtoull(s, &ep, 16);
1952	if (*s == '\0' || *ep != '\0')
1953		fatal("Invalid certificate time: not a number");
1954	if (errno == ERANGE && ull == ULONG_MAX)
1955		fatal_fr(SSH_ERR_SYSTEM_ERROR, "Invalid certificate time");
1956	*up = (uint64_t)ull;
1957}
1958
1959static void
1960parse_cert_times(char *timespec)
1961{
1962	char *from, *to;
1963	time_t now = time(NULL);
1964	int64_t secs;
1965
1966	/* +timespec relative to now */
1967	if (*timespec == '+' && strchr(timespec, ':') == NULL) {
1968		if ((secs = convtime(timespec + 1)) == -1)
1969			fatal("Invalid relative certificate life %s", timespec);
1970		cert_valid_to = now + secs;
1971		/*
1972		 * Backdate certificate one minute to avoid problems on hosts
1973		 * with poorly-synchronised clocks.
1974		 */
1975		cert_valid_from = ((now - 59)/ 60) * 60;
1976		return;
1977	}
1978
1979	/*
1980	 * from:to, where
1981	 * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | 0x... | "always"
1982	 *   to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | 0x... | "forever"
1983	 */
1984	from = xstrdup(timespec);
1985	to = strchr(from, ':');
1986	if (to == NULL || from == to || *(to + 1) == '\0')
1987		fatal("Invalid certificate life specification %s", timespec);
1988	*to++ = '\0';
1989
1990	if (*from == '-' || *from == '+')
1991		cert_valid_from = parse_relative_time(from, now);
1992	else if (strcmp(from, "always") == 0)
1993		cert_valid_from = 0;
1994	else if (strncmp(from, "0x", 2) == 0)
1995		parse_hex_u64(from, &cert_valid_from);
1996	else if (parse_absolute_time(from, &cert_valid_from) != 0)
1997		fatal("Invalid from time \"%s\"", from);
1998
1999	if (*to == '-' || *to == '+')
2000		cert_valid_to = parse_relative_time(to, now);
2001	else if (strcmp(to, "forever") == 0)
2002		cert_valid_to = ~(u_int64_t)0;
2003	else if (strncmp(to, "0x", 2) == 0)
2004		parse_hex_u64(to, &cert_valid_to);
2005	else if (parse_absolute_time(to, &cert_valid_to) != 0)
2006		fatal("Invalid to time \"%s\"", to);
2007
2008	if (cert_valid_to <= cert_valid_from)
2009		fatal("Empty certificate validity interval");
2010	free(from);
2011}
2012
2013static void
2014add_cert_option(char *opt)
2015{
2016	char *val, *cp;
2017	int iscrit = 0;
2018
2019	if (strcasecmp(opt, "clear") == 0)
2020		certflags_flags = 0;
2021	else if (strcasecmp(opt, "no-x11-forwarding") == 0)
2022		certflags_flags &= ~CERTOPT_X_FWD;
2023	else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
2024		certflags_flags |= CERTOPT_X_FWD;
2025	else if (strcasecmp(opt, "no-agent-forwarding") == 0)
2026		certflags_flags &= ~CERTOPT_AGENT_FWD;
2027	else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
2028		certflags_flags |= CERTOPT_AGENT_FWD;
2029	else if (strcasecmp(opt, "no-port-forwarding") == 0)
2030		certflags_flags &= ~CERTOPT_PORT_FWD;
2031	else if (strcasecmp(opt, "permit-port-forwarding") == 0)
2032		certflags_flags |= CERTOPT_PORT_FWD;
2033	else if (strcasecmp(opt, "no-pty") == 0)
2034		certflags_flags &= ~CERTOPT_PTY;
2035	else if (strcasecmp(opt, "permit-pty") == 0)
2036		certflags_flags |= CERTOPT_PTY;
2037	else if (strcasecmp(opt, "no-user-rc") == 0)
2038		certflags_flags &= ~CERTOPT_USER_RC;
2039	else if (strcasecmp(opt, "permit-user-rc") == 0)
2040		certflags_flags |= CERTOPT_USER_RC;
2041	else if (strcasecmp(opt, "touch-required") == 0)
2042		certflags_flags &= ~CERTOPT_NO_REQUIRE_USER_PRESENCE;
2043	else if (strcasecmp(opt, "no-touch-required") == 0)
2044		certflags_flags |= CERTOPT_NO_REQUIRE_USER_PRESENCE;
2045	else if (strcasecmp(opt, "no-verify-required") == 0)
2046		certflags_flags &= ~CERTOPT_REQUIRE_VERIFY;
2047	else if (strcasecmp(opt, "verify-required") == 0)
2048		certflags_flags |= CERTOPT_REQUIRE_VERIFY;
2049	else if (strncasecmp(opt, "force-command=", 14) == 0) {
2050		val = opt + 14;
2051		if (*val == '\0')
2052			fatal("Empty force-command option");
2053		if (certflags_command != NULL)
2054			fatal("force-command already specified");
2055		certflags_command = xstrdup(val);
2056	} else if (strncasecmp(opt, "source-address=", 15) == 0) {
2057		val = opt + 15;
2058		if (*val == '\0')
2059			fatal("Empty source-address option");
2060		if (certflags_src_addr != NULL)
2061			fatal("source-address already specified");
2062		if (addr_match_cidr_list(NULL, val) != 0)
2063			fatal("Invalid source-address list");
2064		certflags_src_addr = xstrdup(val);
2065	} else if (strncasecmp(opt, "extension:", 10) == 0 ||
2066		    (iscrit = (strncasecmp(opt, "critical:", 9) == 0))) {
2067		val = xstrdup(strchr(opt, ':') + 1);
2068		if ((cp = strchr(val, '=')) != NULL)
2069			*cp++ = '\0';
2070		cert_ext_add(val, cp, iscrit);
2071		free(val);
2072	} else
2073		fatal("Unsupported certificate option \"%s\"", opt);
2074}
2075
2076static void
2077show_options(struct sshbuf *optbuf, int in_critical)
2078{
2079	char *name, *arg, *hex;
2080	struct sshbuf *options, *option = NULL;
2081	int r;
2082
2083	if ((options = sshbuf_fromb(optbuf)) == NULL)
2084		fatal_f("sshbuf_fromb failed");
2085	while (sshbuf_len(options) != 0) {
2086		sshbuf_free(option);
2087		option = NULL;
2088		if ((r = sshbuf_get_cstring(options, &name, NULL)) != 0 ||
2089		    (r = sshbuf_froms(options, &option)) != 0)
2090			fatal_fr(r, "parse option");
2091		printf("                %s", name);
2092		if (!in_critical &&
2093		    (strcmp(name, "permit-X11-forwarding") == 0 ||
2094		    strcmp(name, "permit-agent-forwarding") == 0 ||
2095		    strcmp(name, "permit-port-forwarding") == 0 ||
2096		    strcmp(name, "permit-pty") == 0 ||
2097		    strcmp(name, "permit-user-rc") == 0 ||
2098		    strcmp(name, "no-touch-required") == 0)) {
2099			printf("\n");
2100		} else if (in_critical &&
2101		    (strcmp(name, "force-command") == 0 ||
2102		    strcmp(name, "source-address") == 0)) {
2103			if ((r = sshbuf_get_cstring(option, &arg, NULL)) != 0)
2104				fatal_fr(r, "parse critical");
2105			printf(" %s\n", arg);
2106			free(arg);
2107		} else if (in_critical &&
2108		    strcmp(name, "verify-required") == 0) {
2109			printf("\n");
2110		} else if (sshbuf_len(option) > 0) {
2111			hex = sshbuf_dtob16(option);
2112			printf(" UNKNOWN OPTION: %s (len %zu)\n",
2113			    hex, sshbuf_len(option));
2114			sshbuf_reset(option);
2115			free(hex);
2116		} else
2117			printf(" UNKNOWN FLAG OPTION\n");
2118		free(name);
2119		if (sshbuf_len(option) != 0)
2120			fatal("Option corrupt: extra data at end");
2121	}
2122	sshbuf_free(option);
2123	sshbuf_free(options);
2124}
2125
2126static void
2127print_cert(struct sshkey *key)
2128{
2129	char valid[64], *key_fp, *ca_fp;
2130	u_int i;
2131
2132	key_fp = sshkey_fingerprint(key, fingerprint_hash, SSH_FP_DEFAULT);
2133	ca_fp = sshkey_fingerprint(key->cert->signature_key,
2134	    fingerprint_hash, SSH_FP_DEFAULT);
2135	if (key_fp == NULL || ca_fp == NULL)
2136		fatal_f("sshkey_fingerprint fail");
2137	sshkey_format_cert_validity(key->cert, valid, sizeof(valid));
2138
2139	printf("        Type: %s %s certificate\n", sshkey_ssh_name(key),
2140	    sshkey_cert_type(key));
2141	printf("        Public key: %s %s\n", sshkey_type(key), key_fp);
2142	printf("        Signing CA: %s %s (using %s)\n",
2143	    sshkey_type(key->cert->signature_key), ca_fp,
2144	    key->cert->signature_type);
2145	printf("        Key ID: \"%s\"\n", key->cert->key_id);
2146	printf("        Serial: %llu\n", (unsigned long long)key->cert->serial);
2147	printf("        Valid: %s\n", valid);
2148	printf("        Principals: ");
2149	if (key->cert->nprincipals == 0)
2150		printf("(none)\n");
2151	else {
2152		for (i = 0; i < key->cert->nprincipals; i++)
2153			printf("\n                %s",
2154			    key->cert->principals[i]);
2155		printf("\n");
2156	}
2157	printf("        Critical Options: ");
2158	if (sshbuf_len(key->cert->critical) == 0)
2159		printf("(none)\n");
2160	else {
2161		printf("\n");
2162		show_options(key->cert->critical, 1);
2163	}
2164	printf("        Extensions: ");
2165	if (sshbuf_len(key->cert->extensions) == 0)
2166		printf("(none)\n");
2167	else {
2168		printf("\n");
2169		show_options(key->cert->extensions, 0);
2170	}
2171}
2172
2173static void
2174do_show_cert(struct passwd *pw)
2175{
2176	struct sshkey *key = NULL;
2177	struct stat st;
2178	int r, is_stdin = 0, ok = 0;
2179	FILE *f;
2180	char *cp, *line = NULL;
2181	const char *path;
2182	size_t linesize = 0;
2183	u_long lnum = 0;
2184
2185	if (!have_identity)
2186		ask_filename(pw, "Enter file in which the key is");
2187	if (strcmp(identity_file, "-") != 0 && stat(identity_file, &st) == -1)
2188		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
2189
2190	path = identity_file;
2191	if (strcmp(path, "-") == 0) {
2192		f = stdin;
2193		path = "(stdin)";
2194		is_stdin = 1;
2195	} else if ((f = fopen(identity_file, "r")) == NULL)
2196		fatal("fopen %s: %s", identity_file, strerror(errno));
2197
2198	while (getline(&line, &linesize, f) != -1) {
2199		lnum++;
2200		sshkey_free(key);
2201		key = NULL;
2202		/* Trim leading space and comments */
2203		cp = line + strspn(line, " \t");
2204		if (*cp == '#' || *cp == '\0')
2205			continue;
2206		if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2207			fatal("sshkey_new");
2208		if ((r = sshkey_read(key, &cp)) != 0) {
2209			error_r(r, "%s:%lu: invalid key", path, lnum);
2210			continue;
2211		}
2212		if (!sshkey_is_cert(key)) {
2213			error("%s:%lu is not a certificate", path, lnum);
2214			continue;
2215		}
2216		ok = 1;
2217		if (!is_stdin && lnum == 1)
2218			printf("%s:\n", path);
2219		else
2220			printf("%s:%lu:\n", path, lnum);
2221		print_cert(key);
2222	}
2223	free(line);
2224	sshkey_free(key);
2225	fclose(f);
2226	exit(ok ? 0 : 1);
2227}
2228
2229static void
2230load_krl(const char *path, struct ssh_krl **krlp)
2231{
2232	struct sshbuf *krlbuf;
2233	int r;
2234
2235	if ((r = sshbuf_load_file(path, &krlbuf)) != 0)
2236		fatal_r(r, "Unable to load KRL %s", path);
2237	/* XXX check sigs */
2238	if ((r = ssh_krl_from_blob(krlbuf, krlp)) != 0 ||
2239	    *krlp == NULL)
2240		fatal_r(r, "Invalid KRL file %s", path);
2241	sshbuf_free(krlbuf);
2242}
2243
2244static void
2245hash_to_blob(const char *cp, u_char **blobp, size_t *lenp,
2246    const char *file, u_long lnum)
2247{
2248	char *tmp;
2249	size_t tlen;
2250	struct sshbuf *b;
2251	int r;
2252
2253	if (strncmp(cp, "SHA256:", 7) != 0)
2254		fatal("%s:%lu: unsupported hash algorithm", file, lnum);
2255	cp += 7;
2256
2257	/*
2258	 * OpenSSH base64 hashes omit trailing '='
2259	 * characters; put them back for decode.
2260	 */
2261	if ((tlen = strlen(cp)) >= SIZE_MAX - 5)
2262		fatal_f("hash too long: %zu bytes", tlen);
2263	tmp = xmalloc(tlen + 4 + 1);
2264	strlcpy(tmp, cp, tlen + 1);
2265	while ((tlen % 4) != 0) {
2266		tmp[tlen++] = '=';
2267		tmp[tlen] = '\0';
2268	}
2269	if ((b = sshbuf_new()) == NULL)
2270		fatal_f("sshbuf_new failed");
2271	if ((r = sshbuf_b64tod(b, tmp)) != 0)
2272		fatal_r(r, "%s:%lu: decode hash failed", file, lnum);
2273	free(tmp);
2274	*lenp = sshbuf_len(b);
2275	*blobp = xmalloc(*lenp);
2276	memcpy(*blobp, sshbuf_ptr(b), *lenp);
2277	sshbuf_free(b);
2278}
2279
2280static void
2281update_krl_from_file(struct passwd *pw, const char *file, int wild_ca,
2282    const struct sshkey *ca, struct ssh_krl *krl)
2283{
2284	struct sshkey *key = NULL;
2285	u_long lnum = 0;
2286	char *path, *cp, *ep, *line = NULL;
2287	u_char *blob = NULL;
2288	size_t blen = 0, linesize = 0;
2289	unsigned long long serial, serial2;
2290	int i, was_explicit_key, was_sha1, was_sha256, was_hash, r;
2291	FILE *krl_spec;
2292
2293	path = tilde_expand_filename(file, pw->pw_uid);
2294	if (strcmp(path, "-") == 0) {
2295		krl_spec = stdin;
2296		free(path);
2297		path = xstrdup("(standard input)");
2298	} else if ((krl_spec = fopen(path, "r")) == NULL)
2299		fatal("fopen %s: %s", path, strerror(errno));
2300
2301	if (!quiet)
2302		printf("Revoking from %s\n", path);
2303	while (getline(&line, &linesize, krl_spec) != -1) {
2304		if (linesize >= INT_MAX) {
2305			fatal_f("%s contains unparsable line, len=%zu",
2306			    path, linesize);
2307		}
2308		lnum++;
2309		was_explicit_key = was_sha1 = was_sha256 = was_hash = 0;
2310		cp = line + strspn(line, " \t");
2311		/* Trim trailing space, comments and strip \n */
2312		for (i = 0, r = -1; cp[i] != '\0'; i++) {
2313			if (cp[i] == '#' || cp[i] == '\n') {
2314				cp[i] = '\0';
2315				break;
2316			}
2317			if (cp[i] == ' ' || cp[i] == '\t') {
2318				/* Remember the start of a span of whitespace */
2319				if (r == -1)
2320					r = i;
2321			} else
2322				r = -1;
2323		}
2324		if (r != -1)
2325			cp[r] = '\0';
2326		if (*cp == '\0')
2327			continue;
2328		if (strncasecmp(cp, "serial:", 7) == 0) {
2329			if (ca == NULL && !wild_ca) {
2330				fatal("revoking certificates by serial number "
2331				    "requires specification of a CA key");
2332			}
2333			cp += 7;
2334			cp = cp + strspn(cp, " \t");
2335			errno = 0;
2336			serial = strtoull(cp, &ep, 0);
2337			if (*cp == '\0' || (*ep != '\0' && *ep != '-'))
2338				fatal("%s:%lu: invalid serial \"%s\"",
2339				    path, lnum, cp);
2340			if (errno == ERANGE && serial == ULLONG_MAX)
2341				fatal("%s:%lu: serial out of range",
2342				    path, lnum);
2343			serial2 = serial;
2344			if (*ep == '-') {
2345				cp = ep + 1;
2346				errno = 0;
2347				serial2 = strtoull(cp, &ep, 0);
2348				if (*cp == '\0' || *ep != '\0')
2349					fatal("%s:%lu: invalid serial \"%s\"",
2350					    path, lnum, cp);
2351				if (errno == ERANGE && serial2 == ULLONG_MAX)
2352					fatal("%s:%lu: serial out of range",
2353					    path, lnum);
2354				if (serial2 <= serial)
2355					fatal("%s:%lu: invalid serial range "
2356					    "%llu:%llu", path, lnum,
2357					    (unsigned long long)serial,
2358					    (unsigned long long)serial2);
2359			}
2360			if (ssh_krl_revoke_cert_by_serial_range(krl,
2361			    ca, serial, serial2) != 0) {
2362				fatal_f("revoke serial failed");
2363			}
2364		} else if (strncasecmp(cp, "id:", 3) == 0) {
2365			if (ca == NULL && !wild_ca) {
2366				fatal("revoking certificates by key ID "
2367				    "requires specification of a CA key");
2368			}
2369			cp += 3;
2370			cp = cp + strspn(cp, " \t");
2371			if (ssh_krl_revoke_cert_by_key_id(krl, ca, cp) != 0)
2372				fatal_f("revoke key ID failed");
2373		} else if (strncasecmp(cp, "hash:", 5) == 0) {
2374			cp += 5;
2375			cp = cp + strspn(cp, " \t");
2376			hash_to_blob(cp, &blob, &blen, file, lnum);
2377			r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2378			if (r != 0)
2379				fatal_fr(r, "revoke key failed");
2380		} else {
2381			if (strncasecmp(cp, "key:", 4) == 0) {
2382				cp += 4;
2383				cp = cp + strspn(cp, " \t");
2384				was_explicit_key = 1;
2385			} else if (strncasecmp(cp, "sha1:", 5) == 0) {
2386				cp += 5;
2387				cp = cp + strspn(cp, " \t");
2388				was_sha1 = 1;
2389			} else if (strncasecmp(cp, "sha256:", 7) == 0) {
2390				cp += 7;
2391				cp = cp + strspn(cp, " \t");
2392				was_sha256 = 1;
2393				/*
2394				 * Just try to process the line as a key.
2395				 * Parsing will fail if it isn't.
2396				 */
2397			}
2398			if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2399				fatal("sshkey_new");
2400			if ((r = sshkey_read(key, &cp)) != 0)
2401				fatal_r(r, "%s:%lu: invalid key", path, lnum);
2402			if (was_explicit_key)
2403				r = ssh_krl_revoke_key_explicit(krl, key);
2404			else if (was_sha1) {
2405				if (sshkey_fingerprint_raw(key,
2406				    SSH_DIGEST_SHA1, &blob, &blen) != 0) {
2407					fatal("%s:%lu: fingerprint failed",
2408					    file, lnum);
2409				}
2410				r = ssh_krl_revoke_key_sha1(krl, blob, blen);
2411			} else if (was_sha256) {
2412				if (sshkey_fingerprint_raw(key,
2413				    SSH_DIGEST_SHA256, &blob, &blen) != 0) {
2414					fatal("%s:%lu: fingerprint failed",
2415					    file, lnum);
2416				}
2417				r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2418			} else
2419				r = ssh_krl_revoke_key(krl, key);
2420			if (r != 0)
2421				fatal_fr(r, "revoke key failed");
2422			freezero(blob, blen);
2423			blob = NULL;
2424			blen = 0;
2425			sshkey_free(key);
2426		}
2427	}
2428	if (strcmp(path, "-") != 0)
2429		fclose(krl_spec);
2430	free(line);
2431	free(path);
2432}
2433
2434static void
2435do_gen_krl(struct passwd *pw, int updating, const char *ca_key_path,
2436    unsigned long long krl_version, const char *krl_comment,
2437    int argc, char **argv)
2438{
2439	struct ssh_krl *krl;
2440	struct stat sb;
2441	struct sshkey *ca = NULL;
2442	int i, r, wild_ca = 0;
2443	char *tmp;
2444	struct sshbuf *kbuf;
2445
2446	if (*identity_file == '\0')
2447		fatal("KRL generation requires an output file");
2448	if (stat(identity_file, &sb) == -1) {
2449		if (errno != ENOENT)
2450			fatal("Cannot access KRL \"%s\": %s",
2451			    identity_file, strerror(errno));
2452		if (updating)
2453			fatal("KRL \"%s\" does not exist", identity_file);
2454	}
2455	if (ca_key_path != NULL) {
2456		if (strcasecmp(ca_key_path, "none") == 0)
2457			wild_ca = 1;
2458		else {
2459			tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
2460			if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
2461				fatal_r(r, "Cannot load CA public key %s", tmp);
2462			free(tmp);
2463		}
2464	}
2465
2466	if (updating)
2467		load_krl(identity_file, &krl);
2468	else if ((krl = ssh_krl_init()) == NULL)
2469		fatal("couldn't create KRL");
2470
2471	if (krl_version != 0)
2472		ssh_krl_set_version(krl, krl_version);
2473	if (krl_comment != NULL)
2474		ssh_krl_set_comment(krl, krl_comment);
2475
2476	for (i = 0; i < argc; i++)
2477		update_krl_from_file(pw, argv[i], wild_ca, ca, krl);
2478
2479	if ((kbuf = sshbuf_new()) == NULL)
2480		fatal("sshbuf_new failed");
2481	if (ssh_krl_to_blob(krl, kbuf) != 0)
2482		fatal("Couldn't generate KRL");
2483	if ((r = sshbuf_write_file(identity_file, kbuf)) != 0)
2484		fatal("write %s: %s", identity_file, strerror(errno));
2485	sshbuf_free(kbuf);
2486	ssh_krl_free(krl);
2487	sshkey_free(ca);
2488}
2489
2490static void
2491do_check_krl(struct passwd *pw, int print_krl, int argc, char **argv)
2492{
2493	int i, r, ret = 0;
2494	char *comment;
2495	struct ssh_krl *krl;
2496	struct sshkey *k;
2497
2498	if (*identity_file == '\0')
2499		fatal("KRL checking requires an input file");
2500	load_krl(identity_file, &krl);
2501	if (print_krl)
2502		krl_dump(krl, stdout);
2503	for (i = 0; i < argc; i++) {
2504		if ((r = sshkey_load_public(argv[i], &k, &comment)) != 0)
2505			fatal_r(r, "Cannot load public key %s", argv[i]);
2506		r = ssh_krl_check_key(krl, k);
2507		printf("%s%s%s%s: %s\n", argv[i],
2508		    *comment ? " (" : "", comment, *comment ? ")" : "",
2509		    r == 0 ? "ok" : "REVOKED");
2510		if (r != 0)
2511			ret = 1;
2512		sshkey_free(k);
2513		free(comment);
2514	}
2515	ssh_krl_free(krl);
2516	exit(ret);
2517}
2518
2519static struct sshkey *
2520load_sign_key(const char *keypath, const struct sshkey *pubkey)
2521{
2522	size_t i, slen, plen = strlen(keypath);
2523	char *privpath = xstrdup(keypath);
2524	static const char * const suffixes[] = { "-cert.pub", ".pub", NULL };
2525	struct sshkey *ret = NULL, *privkey = NULL;
2526	int r, waspub = 0;
2527	struct stat st;
2528
2529	/*
2530	 * If passed a public key filename, then try to locate the corresponding
2531	 * private key. This lets us specify certificates on the command-line
2532	 * and have ssh-keygen find the appropriate private key.
2533	 */
2534	for (i = 0; suffixes[i]; i++) {
2535		slen = strlen(suffixes[i]);
2536		if (plen <= slen ||
2537		    strcmp(privpath + plen - slen, suffixes[i]) != 0)
2538			continue;
2539		privpath[plen - slen] = '\0';
2540		debug_f("%s looks like a public key, using private key "
2541		    "path %s instead", keypath, privpath);
2542		waspub = 1;
2543	}
2544	if (waspub && stat(privpath, &st) != 0 && errno == ENOENT)
2545		fatal("No private key found for public key \"%s\"", keypath);
2546	if ((r = sshkey_load_private(privpath, "", &privkey, NULL)) != 0 &&
2547	    (r != SSH_ERR_KEY_WRONG_PASSPHRASE)) {
2548		debug_fr(r, "load private key \"%s\"", privpath);
2549		fatal("No private key found for \"%s\"", privpath);
2550	} else if (privkey == NULL)
2551		privkey = load_identity(privpath, NULL);
2552
2553	if (!sshkey_equal_public(pubkey, privkey)) {
2554		error("Public key %s doesn't match private %s",
2555		    keypath, privpath);
2556		goto done;
2557	}
2558	if (sshkey_is_cert(pubkey) && !sshkey_is_cert(privkey)) {
2559		/*
2560		 * Graft the certificate onto the private key to make
2561		 * it capable of signing.
2562		 */
2563		if ((r = sshkey_to_certified(privkey)) != 0) {
2564			error_fr(r, "sshkey_to_certified");
2565			goto done;
2566		}
2567		if ((r = sshkey_cert_copy(pubkey, privkey)) != 0) {
2568			error_fr(r, "sshkey_cert_copy");
2569			goto done;
2570		}
2571	}
2572	/* success */
2573	ret = privkey;
2574	privkey = NULL;
2575 done:
2576	sshkey_free(privkey);
2577	free(privpath);
2578	return ret;
2579}
2580
2581static int
2582sign_one(struct sshkey *signkey, const char *filename, int fd,
2583    const char *sig_namespace, const char *hashalg, sshsig_signer *signer,
2584    void *signer_ctx)
2585{
2586	struct sshbuf *sigbuf = NULL, *abuf = NULL;
2587	int r = SSH_ERR_INTERNAL_ERROR, wfd = -1, oerrno;
2588	char *wfile = NULL, *asig = NULL, *fp = NULL;
2589	char *pin = NULL, *prompt = NULL;
2590
2591	if (!quiet) {
2592		if (fd == STDIN_FILENO)
2593			fprintf(stderr, "Signing data on standard input\n");
2594		else
2595			fprintf(stderr, "Signing file %s\n", filename);
2596	}
2597	if (signer == NULL && sshkey_is_sk(signkey)) {
2598		if ((signkey->sk_flags & SSH_SK_USER_VERIFICATION_REQD)) {
2599			xasprintf(&prompt, "Enter PIN for %s key: ",
2600			    sshkey_type(signkey));
2601			if ((pin = read_passphrase(prompt,
2602			    RP_ALLOW_STDIN)) == NULL)
2603				fatal_f("couldn't read PIN");
2604		}
2605		if ((signkey->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
2606			if ((fp = sshkey_fingerprint(signkey, fingerprint_hash,
2607			    SSH_FP_DEFAULT)) == NULL)
2608				fatal_f("fingerprint failed");
2609			fprintf(stderr, "Confirm user presence for key %s %s\n",
2610			    sshkey_type(signkey), fp);
2611			free(fp);
2612		}
2613	}
2614	if ((r = sshsig_sign_fd(signkey, hashalg, sk_provider, pin,
2615	    fd, sig_namespace, &sigbuf, signer, signer_ctx)) != 0) {
2616		error_r(r, "Signing %s failed", filename);
2617		goto out;
2618	}
2619	if ((r = sshsig_armor(sigbuf, &abuf)) != 0) {
2620		error_fr(r, "sshsig_armor");
2621		goto out;
2622	}
2623	if ((asig = sshbuf_dup_string(abuf)) == NULL) {
2624		error_f("buffer error");
2625		r = SSH_ERR_ALLOC_FAIL;
2626		goto out;
2627	}
2628
2629	if (fd == STDIN_FILENO) {
2630		fputs(asig, stdout);
2631		fflush(stdout);
2632	} else {
2633		xasprintf(&wfile, "%s.sig", filename);
2634		if (confirm_overwrite(wfile)) {
2635			if ((wfd = open(wfile, O_WRONLY|O_CREAT|O_TRUNC,
2636			    0666)) == -1) {
2637				oerrno = errno;
2638				error("Cannot open %s: %s",
2639				    wfile, strerror(errno));
2640				errno = oerrno;
2641				r = SSH_ERR_SYSTEM_ERROR;
2642				goto out;
2643			}
2644			if (atomicio(vwrite, wfd, asig,
2645			    strlen(asig)) != strlen(asig)) {
2646				oerrno = errno;
2647				error("Cannot write to %s: %s",
2648				    wfile, strerror(errno));
2649				errno = oerrno;
2650				r = SSH_ERR_SYSTEM_ERROR;
2651				goto out;
2652			}
2653			if (!quiet) {
2654				fprintf(stderr, "Write signature to %s\n",
2655				    wfile);
2656			}
2657		}
2658	}
2659	/* success */
2660	r = 0;
2661 out:
2662	free(wfile);
2663	free(prompt);
2664	free(asig);
2665	if (pin != NULL)
2666		freezero(pin, strlen(pin));
2667	sshbuf_free(abuf);
2668	sshbuf_free(sigbuf);
2669	if (wfd != -1)
2670		close(wfd);
2671	return r;
2672}
2673
2674static int
2675sig_process_opts(char * const *opts, size_t nopts, char **hashalgp,
2676    uint64_t *verify_timep, int *print_pubkey)
2677{
2678	size_t i;
2679	time_t now;
2680
2681	if (verify_timep != NULL)
2682		*verify_timep = 0;
2683	if (print_pubkey != NULL)
2684		*print_pubkey = 0;
2685	if (hashalgp != NULL)
2686		*hashalgp = NULL;
2687	for (i = 0; i < nopts; i++) {
2688		if (hashalgp != NULL &&
2689		    strncasecmp(opts[i], "hashalg=", 8) == 0) {
2690			*hashalgp = xstrdup(opts[i] + 8);
2691		} else if (verify_timep &&
2692		    strncasecmp(opts[i], "verify-time=", 12) == 0) {
2693			if (parse_absolute_time(opts[i] + 12,
2694			    verify_timep) != 0 || *verify_timep == 0) {
2695				error("Invalid \"verify-time\" option");
2696				return SSH_ERR_INVALID_ARGUMENT;
2697			}
2698		} else if (print_pubkey &&
2699		    strcasecmp(opts[i], "print-pubkey") == 0) {
2700			*print_pubkey = 1;
2701		} else {
2702			error("Invalid option \"%s\"", opts[i]);
2703			return SSH_ERR_INVALID_ARGUMENT;
2704		}
2705	}
2706	if (verify_timep && *verify_timep == 0) {
2707		if ((now = time(NULL)) < 0) {
2708			error("Time is before epoch");
2709			return SSH_ERR_INVALID_ARGUMENT;
2710		}
2711		*verify_timep = (uint64_t)now;
2712	}
2713	return 0;
2714}
2715
2716
2717static int
2718sig_sign(const char *keypath, const char *sig_namespace, int require_agent,
2719    int argc, char **argv, char * const *opts, size_t nopts)
2720{
2721	int i, fd = -1, r, ret = -1;
2722	int agent_fd = -1;
2723	struct sshkey *pubkey = NULL, *privkey = NULL, *signkey = NULL;
2724	sshsig_signer *signer = NULL;
2725	char *hashalg = NULL;
2726
2727	/* Check file arguments. */
2728	for (i = 0; i < argc; i++) {
2729		if (strcmp(argv[i], "-") != 0)
2730			continue;
2731		if (i > 0 || argc > 1)
2732			fatal("Cannot sign mix of paths and standard input");
2733	}
2734
2735	if (sig_process_opts(opts, nopts, &hashalg, NULL, NULL) != 0)
2736		goto done; /* error already logged */
2737
2738	if ((r = sshkey_load_public(keypath, &pubkey, NULL)) != 0) {
2739		error_r(r, "Couldn't load public key %s", keypath);
2740		goto done;
2741	}
2742
2743	if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) {
2744		if (require_agent)
2745			fatal("Couldn't get agent socket");
2746		debug_r(r, "Couldn't get agent socket");
2747	} else {
2748		if ((r = ssh_agent_has_key(agent_fd, pubkey)) == 0)
2749			signer = agent_signer;
2750		else {
2751			if (require_agent)
2752				fatal("Couldn't find key in agent");
2753			debug_r(r, "Couldn't find key in agent");
2754		}
2755	}
2756
2757	if (signer == NULL) {
2758		/* Not using agent - try to load private key */
2759		if ((privkey = load_sign_key(keypath, pubkey)) == NULL)
2760			goto done;
2761		signkey = privkey;
2762	} else {
2763		/* Will use key in agent */
2764		signkey = pubkey;
2765	}
2766
2767	if (argc == 0) {
2768		if ((r = sign_one(signkey, "(stdin)", STDIN_FILENO,
2769		    sig_namespace, hashalg, signer, &agent_fd)) != 0)
2770			goto done;
2771	} else {
2772		for (i = 0; i < argc; i++) {
2773			if (strcmp(argv[i], "-") == 0)
2774				fd = STDIN_FILENO;
2775			else if ((fd = open(argv[i], O_RDONLY)) == -1) {
2776				error("Cannot open %s for signing: %s",
2777				    argv[i], strerror(errno));
2778				goto done;
2779			}
2780			if ((r = sign_one(signkey, argv[i], fd, sig_namespace,
2781			    hashalg, signer, &agent_fd)) != 0)
2782				goto done;
2783			if (fd != STDIN_FILENO)
2784				close(fd);
2785			fd = -1;
2786		}
2787	}
2788
2789	ret = 0;
2790done:
2791	if (fd != -1 && fd != STDIN_FILENO)
2792		close(fd);
2793	sshkey_free(pubkey);
2794	sshkey_free(privkey);
2795	free(hashalg);
2796	return ret;
2797}
2798
2799static int
2800sig_verify(const char *signature, const char *sig_namespace,
2801    const char *principal, const char *allowed_keys, const char *revoked_keys,
2802    char * const *opts, size_t nopts)
2803{
2804	int r, ret = -1;
2805	int print_pubkey = 0;
2806	struct sshbuf *sigbuf = NULL, *abuf = NULL;
2807	struct sshkey *sign_key = NULL;
2808	char *fp = NULL;
2809	struct sshkey_sig_details *sig_details = NULL;
2810	uint64_t verify_time = 0;
2811
2812	if (sig_process_opts(opts, nopts, NULL, &verify_time,
2813	    &print_pubkey) != 0)
2814		goto done; /* error already logged */
2815
2816	memset(&sig_details, 0, sizeof(sig_details));
2817	if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
2818		error_r(r, "Couldn't read signature file");
2819		goto done;
2820	}
2821
2822	if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
2823		error_fr(r, "sshsig_armor");
2824		goto done;
2825	}
2826	if ((r = sshsig_verify_fd(sigbuf, STDIN_FILENO, sig_namespace,
2827	    &sign_key, &sig_details)) != 0)
2828		goto done; /* sshsig_verify() prints error */
2829
2830	if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
2831	    SSH_FP_DEFAULT)) == NULL)
2832		fatal_f("sshkey_fingerprint failed");
2833	debug("Valid (unverified) signature from key %s", fp);
2834	if (sig_details != NULL) {
2835		debug2_f("signature details: counter = %u, flags = 0x%02x",
2836		    sig_details->sk_counter, sig_details->sk_flags);
2837	}
2838	free(fp);
2839	fp = NULL;
2840
2841	if (revoked_keys != NULL) {
2842		if ((r = sshkey_check_revoked(sign_key, revoked_keys)) != 0) {
2843			debug3_fr(r, "sshkey_check_revoked");
2844			goto done;
2845		}
2846	}
2847
2848	if (allowed_keys != NULL && (r = sshsig_check_allowed_keys(allowed_keys,
2849	    sign_key, principal, sig_namespace, verify_time)) != 0) {
2850		debug3_fr(r, "sshsig_check_allowed_keys");
2851		goto done;
2852	}
2853	/* success */
2854	ret = 0;
2855done:
2856	if (!quiet) {
2857		if (ret == 0) {
2858			if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
2859			    SSH_FP_DEFAULT)) == NULL)
2860				fatal_f("sshkey_fingerprint failed");
2861			if (principal == NULL) {
2862				printf("Good \"%s\" signature with %s key %s\n",
2863				    sig_namespace, sshkey_type(sign_key), fp);
2864
2865			} else {
2866				printf("Good \"%s\" signature for %s with %s key %s\n",
2867				    sig_namespace, principal,
2868				    sshkey_type(sign_key), fp);
2869			}
2870		} else {
2871			printf("Could not verify signature.\n");
2872		}
2873	}
2874	/* Print the signature key if requested */
2875	if (ret == 0 && print_pubkey && sign_key != NULL) {
2876		if ((r = sshkey_write(sign_key, stdout)) == 0)
2877			fputc('\n', stdout);
2878		else {
2879			error_r(r, "Could not print public key.\n");
2880			ret = -1;
2881		}
2882	}
2883	sshbuf_free(sigbuf);
2884	sshbuf_free(abuf);
2885	sshkey_free(sign_key);
2886	sshkey_sig_details_free(sig_details);
2887	free(fp);
2888	return ret;
2889}
2890
2891static int
2892sig_find_principals(const char *signature, const char *allowed_keys,
2893    char * const *opts, size_t nopts)
2894{
2895	int r, ret = -1;
2896	struct sshbuf *sigbuf = NULL, *abuf = NULL;
2897	struct sshkey *sign_key = NULL;
2898	char *principals = NULL, *cp, *tmp;
2899	uint64_t verify_time = 0;
2900
2901	if (sig_process_opts(opts, nopts, NULL, &verify_time, NULL) != 0)
2902		goto done; /* error already logged */
2903
2904	if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
2905		error_r(r, "Couldn't read signature file");
2906		goto done;
2907	}
2908	if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
2909		error_fr(r, "sshsig_armor");
2910		goto done;
2911	}
2912	if ((r = sshsig_get_pubkey(sigbuf, &sign_key)) != 0) {
2913		error_fr(r, "sshsig_get_pubkey");
2914		goto done;
2915	}
2916	if ((r = sshsig_find_principals(allowed_keys, sign_key,
2917	    verify_time, &principals)) != 0) {
2918		if (r != SSH_ERR_KEY_NOT_FOUND)
2919			error_fr(r, "sshsig_find_principal");
2920		goto done;
2921	}
2922	ret = 0;
2923done:
2924	if (ret == 0 ) {
2925		/* Emit matching principals one per line */
2926		tmp = principals;
2927		while ((cp = strsep(&tmp, ",")) != NULL && *cp != '\0')
2928			puts(cp);
2929	} else {
2930		fprintf(stderr, "No principal matched.\n");
2931	}
2932	sshbuf_free(sigbuf);
2933	sshbuf_free(abuf);
2934	sshkey_free(sign_key);
2935	free(principals);
2936	return ret;
2937}
2938
2939static int
2940sig_match_principals(const char *allowed_keys, char *principal,
2941	char * const *opts, size_t nopts)
2942{
2943	int r;
2944	char **principals = NULL;
2945	size_t i, nprincipals = 0;
2946
2947	if ((r = sig_process_opts(opts, nopts, NULL, NULL, NULL)) != 0)
2948		return r; /* error already logged */
2949
2950	if ((r = sshsig_match_principals(allowed_keys, principal,
2951	    &principals, &nprincipals)) != 0) {
2952		debug_f("match: %s", ssh_err(r));
2953		fprintf(stderr, "No principal matched.\n");
2954		return r;
2955	}
2956	for (i = 0; i < nprincipals; i++) {
2957		printf("%s\n", principals[i]);
2958		free(principals[i]);
2959	}
2960	free(principals);
2961
2962	return 0;
2963}
2964
2965static void
2966do_moduli_gen(const char *out_file, char **opts, size_t nopts)
2967{
2968#ifdef WITH_OPENSSL
2969	/* Moduli generation/screening */
2970	u_int32_t memory = 0;
2971	BIGNUM *start = NULL;
2972	int moduli_bits = 0;
2973	FILE *out;
2974	size_t i;
2975	const char *errstr;
2976
2977	/* Parse options */
2978	for (i = 0; i < nopts; i++) {
2979		if (strncmp(opts[i], "memory=", 7) == 0) {
2980			memory = (u_int32_t)strtonum(opts[i]+7, 1,
2981			    UINT_MAX, &errstr);
2982			if (errstr) {
2983				fatal("Memory limit is %s: %s",
2984				    errstr, opts[i]+7);
2985			}
2986		} else if (strncmp(opts[i], "start=", 6) == 0) {
2987			/* XXX - also compare length against bits */
2988			if (BN_hex2bn(&start, opts[i]+6) == 0)
2989				fatal("Invalid start point.");
2990		} else if (strncmp(opts[i], "bits=", 5) == 0) {
2991			moduli_bits = (int)strtonum(opts[i]+5, 1,
2992			    INT_MAX, &errstr);
2993			if (errstr) {
2994				fatal("Invalid number: %s (%s)",
2995					opts[i]+12, errstr);
2996			}
2997		} else {
2998			fatal("Option \"%s\" is unsupported for moduli "
2999			    "generation", opts[i]);
3000		}
3001	}
3002
3003	if ((out = fopen(out_file, "w")) == NULL) {
3004		fatal("Couldn't open modulus candidate file \"%s\": %s",
3005		    out_file, strerror(errno));
3006	}
3007	setvbuf(out, NULL, _IOLBF, 0);
3008
3009	if (moduli_bits == 0)
3010		moduli_bits = DEFAULT_BITS;
3011	if (gen_candidates(out, memory, moduli_bits, start) != 0)
3012		fatal("modulus candidate generation failed");
3013#else /* WITH_OPENSSL */
3014	fatal("Moduli generation is not supported");
3015#endif /* WITH_OPENSSL */
3016}
3017
3018static void
3019do_moduli_screen(const char *out_file, char **opts, size_t nopts)
3020{
3021#ifdef WITH_OPENSSL
3022	/* Moduli generation/screening */
3023	char *checkpoint = NULL;
3024	u_int32_t generator_wanted = 0;
3025	unsigned long start_lineno = 0, lines_to_process = 0;
3026	int prime_tests = 0;
3027	FILE *out, *in = stdin;
3028	size_t i;
3029	const char *errstr;
3030
3031	/* Parse options */
3032	for (i = 0; i < nopts; i++) {
3033		if (strncmp(opts[i], "lines=", 6) == 0) {
3034			lines_to_process = strtoul(opts[i]+6, NULL, 10);
3035		} else if (strncmp(opts[i], "start-line=", 11) == 0) {
3036			start_lineno = strtoul(opts[i]+11, NULL, 10);
3037		} else if (strncmp(opts[i], "checkpoint=", 11) == 0) {
3038			free(checkpoint);
3039			checkpoint = xstrdup(opts[i]+11);
3040		} else if (strncmp(opts[i], "generator=", 10) == 0) {
3041			generator_wanted = (u_int32_t)strtonum(
3042			    opts[i]+10, 1, UINT_MAX, &errstr);
3043			if (errstr != NULL) {
3044				fatal("Generator invalid: %s (%s)",
3045				    opts[i]+10, errstr);
3046			}
3047		} else if (strncmp(opts[i], "prime-tests=", 12) == 0) {
3048			prime_tests = (int)strtonum(opts[i]+12, 1,
3049			    INT_MAX, &errstr);
3050			if (errstr) {
3051				fatal("Invalid number: %s (%s)",
3052					opts[i]+12, errstr);
3053			}
3054		} else {
3055			fatal("Option \"%s\" is unsupported for moduli "
3056			    "screening", opts[i]);
3057		}
3058	}
3059
3060	if (have_identity && strcmp(identity_file, "-") != 0) {
3061		if ((in = fopen(identity_file, "r")) == NULL) {
3062			fatal("Couldn't open modulus candidate "
3063			    "file \"%s\": %s", identity_file,
3064			    strerror(errno));
3065		}
3066	}
3067
3068	if ((out = fopen(out_file, "a")) == NULL) {
3069		fatal("Couldn't open moduli file \"%s\": %s",
3070		    out_file, strerror(errno));
3071	}
3072	setvbuf(out, NULL, _IOLBF, 0);
3073	if (prime_test(in, out, prime_tests == 0 ? 100 : prime_tests,
3074	    generator_wanted, checkpoint,
3075	    start_lineno, lines_to_process) != 0)
3076		fatal("modulus screening failed");
3077	if (in != stdin)
3078		(void)fclose(in);
3079	free(checkpoint);
3080#else /* WITH_OPENSSL */
3081	fatal("Moduli screening is not supported");
3082#endif /* WITH_OPENSSL */
3083}
3084
3085/* Read and confirm a passphrase */
3086static char *
3087read_check_passphrase(const char *prompt1, const char *prompt2,
3088    const char *retry_prompt)
3089{
3090	char *passphrase1, *passphrase2;
3091
3092	for (;;) {
3093		passphrase1 = read_passphrase(prompt1, RP_ALLOW_STDIN);
3094		passphrase2 = read_passphrase(prompt2, RP_ALLOW_STDIN);
3095		if (strcmp(passphrase1, passphrase2) == 0) {
3096			freezero(passphrase2, strlen(passphrase2));
3097			return passphrase1;
3098		}
3099		/* The passphrases do not match. Clear them and retry. */
3100		freezero(passphrase1, strlen(passphrase1));
3101		freezero(passphrase2, strlen(passphrase2));
3102		fputs(retry_prompt, stdout);
3103		fputc('\n', stdout);
3104		fflush(stdout);
3105	}
3106	/* NOTREACHED */
3107	return NULL;
3108}
3109
3110static char *
3111private_key_passphrase(void)
3112{
3113	if (identity_passphrase)
3114		return xstrdup(identity_passphrase);
3115	if (identity_new_passphrase)
3116		return xstrdup(identity_new_passphrase);
3117
3118	return read_check_passphrase(
3119	    "Enter passphrase (empty for no passphrase): ",
3120	    "Enter same passphrase again: ",
3121	    "Passphrases do not match.  Try again.");
3122}
3123
3124static char *
3125sk_suffix(const char *application, const uint8_t *user, size_t userlen)
3126{
3127	char *ret, *cp;
3128	size_t slen, i;
3129
3130	/* Trim off URL-like preamble */
3131	if (strncmp(application, "ssh://", 6) == 0)
3132		ret =  xstrdup(application + 6);
3133	else if (strncmp(application, "ssh:", 4) == 0)
3134		ret =  xstrdup(application + 4);
3135	else
3136		ret = xstrdup(application);
3137
3138	/* Count trailing zeros in user */
3139	for (i = 0; i < userlen; i++) {
3140		if (user[userlen - i - 1] != 0)
3141			break;
3142	}
3143	if (i >= userlen)
3144		return ret; /* user-id was default all-zeros */
3145
3146	/* Append user-id, escaping non-UTF-8 characters */
3147	slen = userlen - i;
3148	if (asmprintf(&cp, INT_MAX, NULL, "%.*s", (int)slen, user) == -1)
3149		fatal_f("asmprintf failed");
3150	/* Don't emit a user-id that contains path or control characters */
3151	if (strchr(cp, '/') != NULL || strstr(cp, "..") != NULL ||
3152	    strchr(cp, '\\') != NULL) {
3153		free(cp);
3154		cp = tohex(user, slen);
3155	}
3156	xextendf(&ret, "_", "%s", cp);
3157	free(cp);
3158	return ret;
3159}
3160
3161static int
3162do_download_sk(const char *skprovider, const char *device)
3163{
3164	struct sshsk_resident_key **srks;
3165	size_t nsrks, i;
3166	int r, ret = -1;
3167	char *fp, *pin = NULL, *pass = NULL, *path, *pubpath;
3168	const char *ext;
3169	struct sshkey *key;
3170
3171	if (skprovider == NULL)
3172		fatal("Cannot download keys without provider");
3173
3174	pin = read_passphrase("Enter PIN for authenticator: ", RP_ALLOW_STDIN);
3175	if (!quiet) {
3176		printf("You may need to touch your authenticator "
3177		    "to authorize key download.\n");
3178	}
3179	if ((r = sshsk_load_resident(skprovider, device, pin, 0,
3180	    &srks, &nsrks)) != 0) {
3181		if (pin != NULL)
3182			freezero(pin, strlen(pin));
3183		error_r(r, "Unable to load resident keys");
3184		return -1;
3185	}
3186	if (nsrks == 0)
3187		logit("No keys to download");
3188	if (pin != NULL)
3189		freezero(pin, strlen(pin));
3190
3191	for (i = 0; i < nsrks; i++) {
3192		key = srks[i]->key;
3193		if (key->type != KEY_ECDSA_SK && key->type != KEY_ED25519_SK) {
3194			error("Unsupported key type %s (%d)",
3195			    sshkey_type(key), key->type);
3196			continue;
3197		}
3198		if ((fp = sshkey_fingerprint(key, fingerprint_hash,
3199		    SSH_FP_DEFAULT)) == NULL)
3200			fatal_f("sshkey_fingerprint failed");
3201		debug_f("key %zu: %s %s %s (flags 0x%02x)", i,
3202		    sshkey_type(key), fp, key->sk_application, key->sk_flags);
3203		ext = sk_suffix(key->sk_application,
3204		    srks[i]->user_id, srks[i]->user_id_len);
3205		xasprintf(&path, "id_%s_rk%s%s",
3206		    key->type == KEY_ECDSA_SK ? "ecdsa_sk" : "ed25519_sk",
3207		    *ext == '\0' ? "" : "_", ext);
3208
3209		/* If the file already exists, ask the user to confirm. */
3210		if (!confirm_overwrite(path)) {
3211			free(path);
3212			break;
3213		}
3214
3215		/* Save the key with the application string as the comment */
3216		if (pass == NULL)
3217			pass = private_key_passphrase();
3218		if ((r = sshkey_save_private(key, path, pass,
3219		    key->sk_application, private_key_format,
3220		    openssh_format_cipher, rounds)) != 0) {
3221			error_r(r, "Saving key \"%s\" failed", path);
3222			free(path);
3223			break;
3224		}
3225		if (!quiet) {
3226			printf("Saved %s key%s%s to %s\n", sshkey_type(key),
3227			    *ext != '\0' ? " " : "",
3228			    *ext != '\0' ? key->sk_application : "",
3229			    path);
3230		}
3231
3232		/* Save public key too */
3233		xasprintf(&pubpath, "%s.pub", path);
3234		free(path);
3235		if ((r = sshkey_save_public(key, pubpath,
3236		    key->sk_application)) != 0) {
3237			error_r(r, "Saving public key \"%s\" failed", pubpath);
3238			free(pubpath);
3239			break;
3240		}
3241		free(pubpath);
3242	}
3243
3244	if (i >= nsrks)
3245		ret = 0; /* success */
3246	if (pass != NULL)
3247		freezero(pass, strlen(pass));
3248	sshsk_free_resident_keys(srks, nsrks);
3249	return ret;
3250}
3251
3252static void
3253save_attestation(struct sshbuf *attest, const char *path)
3254{
3255	mode_t omask;
3256	int r;
3257
3258	if (path == NULL)
3259		return; /* nothing to do */
3260	if (attest == NULL || sshbuf_len(attest) == 0)
3261		fatal("Enrollment did not return attestation data");
3262	omask = umask(077);
3263	r = sshbuf_write_file(path, attest);
3264	umask(omask);
3265	if (r != 0)
3266		fatal_r(r, "Unable to write attestation data \"%s\"", path);
3267	if (!quiet)
3268		printf("Your FIDO attestation certificate has been saved in "
3269		    "%s\n", path);
3270}
3271
3272static int
3273confirm_sk_overwrite(const char *application, const char *user)
3274{
3275	char yesno[3];
3276
3277	printf("A resident key scoped to '%s' with user id '%s' already "
3278	    "exists.\n", application == NULL ? "ssh:" : application,
3279	    user == NULL ? "null" : user);
3280	printf("Overwrite key in token (y/n)? ");
3281	fflush(stdout);
3282	if (fgets(yesno, sizeof(yesno), stdin) == NULL)
3283		return 0;
3284	if (yesno[0] != 'y' && yesno[0] != 'Y')
3285		return 0;
3286	return 1;
3287}
3288
3289static void
3290usage(void)
3291{
3292	fprintf(stderr,
3293	    "usage: ssh-keygen [-q] [-a rounds] [-b bits] [-C comment] [-f output_keyfile]\n"
3294	    "                  [-m format] [-N new_passphrase] [-O option]\n"
3295	    "                  [-t dsa | ecdsa | ecdsa-sk | ed25519 | ed25519-sk | rsa]\n"
3296	    "                  [-w provider] [-Z cipher]\n"
3297	    "       ssh-keygen -p [-a rounds] [-f keyfile] [-m format] [-N new_passphrase]\n"
3298	    "                   [-P old_passphrase] [-Z cipher]\n"
3299#ifdef WITH_OPENSSL
3300	    "       ssh-keygen -i [-f input_keyfile] [-m key_format]\n"
3301	    "       ssh-keygen -e [-f input_keyfile] [-m key_format]\n"
3302#endif
3303	    "       ssh-keygen -y [-f input_keyfile]\n"
3304	    "       ssh-keygen -c [-a rounds] [-C comment] [-f keyfile] [-P passphrase]\n"
3305	    "       ssh-keygen -l [-v] [-E fingerprint_hash] [-f input_keyfile]\n"
3306	    "       ssh-keygen -B [-f input_keyfile]\n");
3307#ifdef ENABLE_PKCS11
3308	fprintf(stderr,
3309	    "       ssh-keygen -D pkcs11\n");
3310#endif
3311	fprintf(stderr,
3312	    "       ssh-keygen -F hostname [-lv] [-f known_hosts_file]\n"
3313	    "       ssh-keygen -H [-f known_hosts_file]\n"
3314	    "       ssh-keygen -K [-a rounds] [-w provider]\n"
3315	    "       ssh-keygen -R hostname [-f known_hosts_file]\n"
3316	    "       ssh-keygen -r hostname [-g] [-f input_keyfile]\n"
3317#ifdef WITH_OPENSSL
3318	    "       ssh-keygen -M generate [-O option] output_file\n"
3319	    "       ssh-keygen -M screen [-f input_file] [-O option] output_file\n"
3320#endif
3321	    "       ssh-keygen -I certificate_identity -s ca_key [-hU] [-D pkcs11_provider]\n"
3322	    "                  [-n principals] [-O option] [-V validity_interval]\n"
3323	    "                  [-z serial_number] file ...\n"
3324	    "       ssh-keygen -L [-f input_keyfile]\n"
3325	    "       ssh-keygen -A [-a rounds] [-f prefix_path]\n"
3326	    "       ssh-keygen -k -f krl_file [-u] [-s ca_public] [-z version_number]\n"
3327	    "                  file ...\n"
3328	    "       ssh-keygen -Q [-l] -f krl_file [file ...]\n"
3329	    "       ssh-keygen -Y find-principals -s signature_file -f allowed_signers_file\n"
3330	    "       ssh-keygen -Y match-principals -I signer_identity -f allowed_signers_file\n"
3331	    "       ssh-keygen -Y check-novalidate -n namespace -s signature_file\n"
3332	    "       ssh-keygen -Y sign -f key_file -n namespace file [-O option] ...\n"
3333	    "       ssh-keygen -Y verify -f allowed_signers_file -I signer_identity\n"
3334	    "                  -n namespace -s signature_file [-r krl_file] [-O option]\n");
3335	exit(1);
3336}
3337
3338/*
3339 * Main program for key management.
3340 */
3341int
3342main(int argc, char **argv)
3343{
3344	char comment[1024], *passphrase = NULL;
3345	char *rr_hostname = NULL, *ep, *fp, *ra;
3346	struct sshkey *private, *public;
3347	struct passwd *pw;
3348	int r, opt, type;
3349	int change_passphrase = 0, change_comment = 0, show_cert = 0;
3350	int find_host = 0, delete_host = 0, hash_hosts = 0;
3351	int gen_all_hostkeys = 0, gen_krl = 0, update_krl = 0, check_krl = 0;
3352	int prefer_agent = 0, convert_to = 0, convert_from = 0;
3353	int print_public = 0, print_generic = 0, cert_serial_autoinc = 0;
3354	int do_gen_candidates = 0, do_screen_candidates = 0, download_sk = 0;
3355	unsigned long long cert_serial = 0;
3356	char *identity_comment = NULL, *ca_key_path = NULL, **opts = NULL;
3357	char *sk_application = NULL, *sk_device = NULL, *sk_user = NULL;
3358	char *sk_attestation_path = NULL;
3359	struct sshbuf *challenge = NULL, *attest = NULL;
3360	size_t i, nopts = 0;
3361	u_int32_t bits = 0;
3362	uint8_t sk_flags = SSH_SK_USER_PRESENCE_REQD;
3363	const char *errstr;
3364	int log_level = SYSLOG_LEVEL_INFO;
3365	char *sign_op = NULL;
3366
3367	extern int optind;
3368	extern char *optarg;
3369
3370	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
3371	sanitise_stdfd();
3372
3373	__progname = ssh_get_progname(argv[0]);
3374
3375	seed_rng();
3376
3377	log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
3378
3379	msetlocale();
3380
3381	/* we need this for the home * directory.  */
3382	pw = getpwuid(getuid());
3383	if (!pw)
3384		fatal("No user exists for uid %lu", (u_long)getuid());
3385	pw = pwcopy(pw);
3386	if (gethostname(hostname, sizeof(hostname)) == -1)
3387		fatal("gethostname: %s", strerror(errno));
3388
3389	sk_provider = getenv("SSH_SK_PROVIDER");
3390
3391	/* Remaining characters: dGjJSTWx */
3392	while ((opt = getopt(argc, argv, "ABHKLQUXceghiklopquvy"
3393	    "C:D:E:F:I:M:N:O:P:R:V:Y:Z:"
3394	    "a:b:f:g:m:n:r:s:t:w:z:")) != -1) {
3395		switch (opt) {
3396		case 'A':
3397			gen_all_hostkeys = 1;
3398			break;
3399		case 'b':
3400			bits = (u_int32_t)strtonum(optarg, 1, UINT32_MAX,
3401			    &errstr);
3402			if (errstr)
3403				fatal("Bits has bad value %s (%s)",
3404					optarg, errstr);
3405			break;
3406		case 'E':
3407			fingerprint_hash = ssh_digest_alg_by_name(optarg);
3408			if (fingerprint_hash == -1)
3409				fatal("Invalid hash algorithm \"%s\"", optarg);
3410			break;
3411		case 'F':
3412			find_host = 1;
3413			rr_hostname = optarg;
3414			break;
3415		case 'H':
3416			hash_hosts = 1;
3417			break;
3418		case 'I':
3419			cert_key_id = optarg;
3420			break;
3421		case 'R':
3422			delete_host = 1;
3423			rr_hostname = optarg;
3424			break;
3425		case 'L':
3426			show_cert = 1;
3427			break;
3428		case 'l':
3429			print_fingerprint = 1;
3430			break;
3431		case 'B':
3432			print_bubblebabble = 1;
3433			break;
3434		case 'm':
3435			if (strcasecmp(optarg, "RFC4716") == 0 ||
3436			    strcasecmp(optarg, "ssh2") == 0) {
3437				convert_format = FMT_RFC4716;
3438				break;
3439			}
3440			if (strcasecmp(optarg, "PKCS8") == 0) {
3441				convert_format = FMT_PKCS8;
3442				private_key_format = SSHKEY_PRIVATE_PKCS8;
3443				break;
3444			}
3445			if (strcasecmp(optarg, "PEM") == 0) {
3446				convert_format = FMT_PEM;
3447				private_key_format = SSHKEY_PRIVATE_PEM;
3448				break;
3449			}
3450			fatal("Unsupported conversion format \"%s\"", optarg);
3451		case 'n':
3452			cert_principals = optarg;
3453			break;
3454		case 'o':
3455			/* no-op; new format is already the default */
3456			break;
3457		case 'p':
3458			change_passphrase = 1;
3459			break;
3460		case 'c':
3461			change_comment = 1;
3462			break;
3463		case 'f':
3464			if (strlcpy(identity_file, optarg,
3465			    sizeof(identity_file)) >= sizeof(identity_file))
3466				fatal("Identity filename too long");
3467			have_identity = 1;
3468			break;
3469		case 'g':
3470			print_generic = 1;
3471			break;
3472		case 'K':
3473			download_sk = 1;
3474			break;
3475		case 'P':
3476			identity_passphrase = optarg;
3477			break;
3478		case 'N':
3479			identity_new_passphrase = optarg;
3480			break;
3481		case 'Q':
3482			check_krl = 1;
3483			break;
3484		case 'O':
3485			opts = xrecallocarray(opts, nopts, nopts + 1,
3486			    sizeof(*opts));
3487			opts[nopts++] = xstrdup(optarg);
3488			break;
3489		case 'Z':
3490			openssh_format_cipher = optarg;
3491			if (cipher_by_name(openssh_format_cipher) == NULL)
3492				fatal("Invalid OpenSSH-format cipher '%s'",
3493				    openssh_format_cipher);
3494			break;
3495		case 'C':
3496			identity_comment = optarg;
3497			break;
3498		case 'q':
3499			quiet = 1;
3500			break;
3501		case 'e':
3502			/* export key */
3503			convert_to = 1;
3504			break;
3505		case 'h':
3506			cert_key_type = SSH2_CERT_TYPE_HOST;
3507			certflags_flags = 0;
3508			break;
3509		case 'k':
3510			gen_krl = 1;
3511			break;
3512		case 'i':
3513		case 'X':
3514			/* import key */
3515			convert_from = 1;
3516			break;
3517		case 'y':
3518			print_public = 1;
3519			break;
3520		case 's':
3521			ca_key_path = optarg;
3522			break;
3523		case 't':
3524			key_type_name = optarg;
3525			break;
3526		case 'D':
3527			pkcs11provider = optarg;
3528			break;
3529		case 'U':
3530			prefer_agent = 1;
3531			break;
3532		case 'u':
3533			update_krl = 1;
3534			break;
3535		case 'v':
3536			if (log_level == SYSLOG_LEVEL_INFO)
3537				log_level = SYSLOG_LEVEL_DEBUG1;
3538			else {
3539				if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
3540				    log_level < SYSLOG_LEVEL_DEBUG3)
3541					log_level++;
3542			}
3543			break;
3544		case 'r':
3545			rr_hostname = optarg;
3546			break;
3547		case 'a':
3548			rounds = (int)strtonum(optarg, 1, INT_MAX, &errstr);
3549			if (errstr)
3550				fatal("Invalid number: %s (%s)",
3551					optarg, errstr);
3552			break;
3553		case 'V':
3554			parse_cert_times(optarg);
3555			break;
3556		case 'Y':
3557			sign_op = optarg;
3558			break;
3559		case 'w':
3560			sk_provider = optarg;
3561			break;
3562		case 'z':
3563			errno = 0;
3564			if (*optarg == '+') {
3565				cert_serial_autoinc = 1;
3566				optarg++;
3567			}
3568			cert_serial = strtoull(optarg, &ep, 10);
3569			if (*optarg < '0' || *optarg > '9' || *ep != '\0' ||
3570			    (errno == ERANGE && cert_serial == ULLONG_MAX))
3571				fatal("Invalid serial number \"%s\"", optarg);
3572			break;
3573		case 'M':
3574			if (strcmp(optarg, "generate") == 0)
3575				do_gen_candidates = 1;
3576			else if (strcmp(optarg, "screen") == 0)
3577				do_screen_candidates = 1;
3578			else
3579				fatal("Unsupported moduli option %s", optarg);
3580			break;
3581		default:
3582			usage();
3583		}
3584	}
3585
3586#ifdef ENABLE_SK_INTERNAL
3587	if (sk_provider == NULL)
3588		sk_provider = "internal";
3589#endif
3590
3591	/* reinit */
3592	log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
3593
3594	argv += optind;
3595	argc -= optind;
3596
3597	if (sign_op != NULL) {
3598		if (strncmp(sign_op, "find-principals", 15) == 0) {
3599			if (ca_key_path == NULL) {
3600				error("Too few arguments for find-principals:"
3601				    "missing signature file");
3602				exit(1);
3603			}
3604			if (!have_identity) {
3605				error("Too few arguments for find-principals:"
3606				    "missing allowed keys file");
3607				exit(1);
3608			}
3609			return sig_find_principals(ca_key_path, identity_file,
3610			    opts, nopts);
3611		} else if (strncmp(sign_op, "match-principals", 16) == 0) {
3612			if (!have_identity) {
3613				error("Too few arguments for match-principals:"
3614				    "missing allowed keys file");
3615				exit(1);
3616			}
3617			if (cert_key_id == NULL) {
3618				error("Too few arguments for match-principals: "
3619				    "missing principal ID");
3620				exit(1);
3621			}
3622			return sig_match_principals(identity_file, cert_key_id,
3623			    opts, nopts);
3624		} else if (strncmp(sign_op, "sign", 4) == 0) {
3625			/* NB. cert_principals is actually namespace, via -n */
3626			if (cert_principals == NULL ||
3627			    *cert_principals == '\0') {
3628				error("Too few arguments for sign: "
3629				    "missing namespace");
3630				exit(1);
3631			}
3632			if (!have_identity) {
3633				error("Too few arguments for sign: "
3634				    "missing key");
3635				exit(1);
3636			}
3637			return sig_sign(identity_file, cert_principals,
3638			    prefer_agent, argc, argv, opts, nopts);
3639		} else if (strncmp(sign_op, "check-novalidate", 16) == 0) {
3640			/* NB. cert_principals is actually namespace, via -n */
3641			if (cert_principals == NULL ||
3642			    *cert_principals == '\0') {
3643				error("Too few arguments for check-novalidate: "
3644				    "missing namespace");
3645				exit(1);
3646			}
3647			if (ca_key_path == NULL) {
3648				error("Too few arguments for check-novalidate: "
3649				    "missing signature file");
3650				exit(1);
3651			}
3652			return sig_verify(ca_key_path, cert_principals,
3653			    NULL, NULL, NULL, opts, nopts);
3654		} else if (strncmp(sign_op, "verify", 6) == 0) {
3655			/* NB. cert_principals is actually namespace, via -n */
3656			if (cert_principals == NULL ||
3657			    *cert_principals == '\0') {
3658				error("Too few arguments for verify: "
3659				    "missing namespace");
3660				exit(1);
3661			}
3662			if (ca_key_path == NULL) {
3663				error("Too few arguments for verify: "
3664				    "missing signature file");
3665				exit(1);
3666			}
3667			if (!have_identity) {
3668				error("Too few arguments for sign: "
3669				    "missing allowed keys file");
3670				exit(1);
3671			}
3672			if (cert_key_id == NULL) {
3673				error("Too few arguments for verify: "
3674				    "missing principal identity");
3675				exit(1);
3676			}
3677			return sig_verify(ca_key_path, cert_principals,
3678			    cert_key_id, identity_file, rr_hostname,
3679			    opts, nopts);
3680		}
3681		error("Unsupported operation for -Y: \"%s\"", sign_op);
3682		usage();
3683		/* NOTREACHED */
3684	}
3685
3686	if (ca_key_path != NULL) {
3687		if (argc < 1 && !gen_krl) {
3688			error("Too few arguments.");
3689			usage();
3690		}
3691	} else if (argc > 0 && !gen_krl && !check_krl &&
3692	    !do_gen_candidates && !do_screen_candidates) {
3693		error("Too many arguments.");
3694		usage();
3695	}
3696	if (change_passphrase && change_comment) {
3697		error("Can only have one of -p and -c.");
3698		usage();
3699	}
3700	if (print_fingerprint && (delete_host || hash_hosts)) {
3701		error("Cannot use -l with -H or -R.");
3702		usage();
3703	}
3704	if (gen_krl) {
3705		do_gen_krl(pw, update_krl, ca_key_path,
3706		    cert_serial, identity_comment, argc, argv);
3707		return (0);
3708	}
3709	if (check_krl) {
3710		do_check_krl(pw, print_fingerprint, argc, argv);
3711		return (0);
3712	}
3713	if (ca_key_path != NULL) {
3714		if (cert_key_id == NULL)
3715			fatal("Must specify key id (-I) when certifying");
3716		for (i = 0; i < nopts; i++)
3717			add_cert_option(opts[i]);
3718		do_ca_sign(pw, ca_key_path, prefer_agent,
3719		    cert_serial, cert_serial_autoinc, argc, argv);
3720	}
3721	if (show_cert)
3722		do_show_cert(pw);
3723	if (delete_host || hash_hosts || find_host) {
3724		do_known_hosts(pw, rr_hostname, find_host,
3725		    delete_host, hash_hosts);
3726	}
3727	if (pkcs11provider != NULL)
3728		do_download(pw);
3729	if (download_sk) {
3730		for (i = 0; i < nopts; i++) {
3731			if (strncasecmp(opts[i], "device=", 7) == 0) {
3732				sk_device = xstrdup(opts[i] + 7);
3733			} else {
3734				fatal("Option \"%s\" is unsupported for "
3735				    "FIDO authenticator download", opts[i]);
3736			}
3737		}
3738		return do_download_sk(sk_provider, sk_device);
3739	}
3740	if (print_fingerprint || print_bubblebabble)
3741		do_fingerprint(pw);
3742	if (change_passphrase)
3743		do_change_passphrase(pw);
3744	if (change_comment)
3745		do_change_comment(pw, identity_comment);
3746#ifdef WITH_OPENSSL
3747	if (convert_to)
3748		do_convert_to(pw);
3749	if (convert_from)
3750		do_convert_from(pw);
3751#else /* WITH_OPENSSL */
3752	if (convert_to || convert_from)
3753		fatal("key conversion disabled at compile time");
3754#endif /* WITH_OPENSSL */
3755	if (print_public)
3756		do_print_public(pw);
3757	if (rr_hostname != NULL) {
3758		unsigned int n = 0;
3759
3760		if (have_identity) {
3761			n = do_print_resource_record(pw, identity_file,
3762			    rr_hostname, print_generic, opts, nopts);
3763			if (n == 0)
3764				fatal("%s: %s", identity_file, strerror(errno));
3765			exit(0);
3766		} else {
3767
3768			n += do_print_resource_record(pw,
3769			    _PATH_HOST_RSA_KEY_FILE, rr_hostname,
3770			    print_generic, opts, nopts);
3771#ifdef WITH_DSA
3772			n += do_print_resource_record(pw,
3773			    _PATH_HOST_DSA_KEY_FILE, rr_hostname,
3774			    print_generic, opts, nopts);
3775#endif
3776			n += do_print_resource_record(pw,
3777			    _PATH_HOST_ECDSA_KEY_FILE, rr_hostname,
3778			    print_generic, opts, nopts);
3779			n += do_print_resource_record(pw,
3780			    _PATH_HOST_ED25519_KEY_FILE, rr_hostname,
3781			    print_generic, opts, nopts);
3782			n += do_print_resource_record(pw,
3783			    _PATH_HOST_XMSS_KEY_FILE, rr_hostname,
3784			    print_generic, opts, nopts);
3785			if (n == 0)
3786				fatal("no keys found.");
3787			exit(0);
3788		}
3789	}
3790
3791	if (do_gen_candidates || do_screen_candidates) {
3792		if (argc <= 0)
3793			fatal("No output file specified");
3794		else if (argc > 1)
3795			fatal("Too many output files specified");
3796	}
3797	if (do_gen_candidates) {
3798		do_moduli_gen(argv[0], opts, nopts);
3799		return 0;
3800	}
3801	if (do_screen_candidates) {
3802		do_moduli_screen(argv[0], opts, nopts);
3803		return 0;
3804	}
3805
3806	if (gen_all_hostkeys) {
3807		do_gen_all_hostkeys(pw);
3808		return (0);
3809	}
3810
3811	if (key_type_name == NULL)
3812		key_type_name = DEFAULT_KEY_TYPE_NAME;
3813
3814	type = sshkey_type_from_name(key_type_name);
3815	type_bits_valid(type, key_type_name, &bits);
3816
3817	if (!quiet)
3818		printf("Generating public/private %s key pair.\n",
3819		    key_type_name);
3820	switch (type) {
3821	case KEY_ECDSA_SK:
3822	case KEY_ED25519_SK:
3823		for (i = 0; i < nopts; i++) {
3824			if (strcasecmp(opts[i], "no-touch-required") == 0) {
3825				sk_flags &= ~SSH_SK_USER_PRESENCE_REQD;
3826			} else if (strcasecmp(opts[i], "verify-required") == 0) {
3827				sk_flags |= SSH_SK_USER_VERIFICATION_REQD;
3828			} else if (strcasecmp(opts[i], "resident") == 0) {
3829				sk_flags |= SSH_SK_RESIDENT_KEY;
3830			} else if (strncasecmp(opts[i], "device=", 7) == 0) {
3831				sk_device = xstrdup(opts[i] + 7);
3832			} else if (strncasecmp(opts[i], "user=", 5) == 0) {
3833				sk_user = xstrdup(opts[i] + 5);
3834			} else if (strncasecmp(opts[i], "challenge=", 10) == 0) {
3835				if ((r = sshbuf_load_file(opts[i] + 10,
3836				    &challenge)) != 0) {
3837					fatal_r(r, "Unable to load FIDO "
3838					    "enrollment challenge \"%s\"",
3839					    opts[i] + 10);
3840				}
3841			} else if (strncasecmp(opts[i],
3842			    "write-attestation=", 18) == 0) {
3843				sk_attestation_path = opts[i] + 18;
3844			} else if (strncasecmp(opts[i],
3845			    "application=", 12) == 0) {
3846				sk_application = xstrdup(opts[i] + 12);
3847				if (strncmp(sk_application, "ssh:", 4) != 0) {
3848					fatal("FIDO application string must "
3849					    "begin with \"ssh:\"");
3850				}
3851			} else {
3852				fatal("Option \"%s\" is unsupported for "
3853				    "FIDO authenticator enrollment", opts[i]);
3854			}
3855		}
3856		if ((attest = sshbuf_new()) == NULL)
3857			fatal("sshbuf_new failed");
3858		r = 0;
3859		for (i = 0 ;;) {
3860			if (!quiet) {
3861				printf("You may need to touch your "
3862				    "authenticator%s to authorize key "
3863				    "generation.\n",
3864				    r == 0 ? "" : " again");
3865			}
3866			fflush(stdout);
3867			r = sshsk_enroll(type, sk_provider, sk_device,
3868			    sk_application == NULL ? "ssh:" : sk_application,
3869			    sk_user, sk_flags, passphrase, challenge,
3870			    &private, attest);
3871			if (r == 0)
3872				break;
3873			if (r == SSH_ERR_KEY_BAD_PERMISSIONS &&
3874			    (sk_flags & SSH_SK_RESIDENT_KEY) != 0 &&
3875			    (sk_flags & SSH_SK_FORCE_OPERATION) == 0 &&
3876			    confirm_sk_overwrite(sk_application, sk_user)) {
3877				sk_flags |= SSH_SK_FORCE_OPERATION;
3878				continue;
3879			}
3880			if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
3881				fatal_r(r, "Key enrollment failed");
3882			else if (passphrase != NULL) {
3883				error("PIN incorrect");
3884				freezero(passphrase, strlen(passphrase));
3885				passphrase = NULL;
3886			}
3887			if (++i >= 3)
3888				fatal("Too many incorrect PINs");
3889			passphrase = read_passphrase("Enter PIN for "
3890			    "authenticator: ", RP_ALLOW_STDIN);
3891		}
3892		if (passphrase != NULL) {
3893			freezero(passphrase, strlen(passphrase));
3894			passphrase = NULL;
3895		}
3896		break;
3897	default:
3898		if ((r = sshkey_generate(type, bits, &private)) != 0)
3899			fatal("sshkey_generate failed");
3900		break;
3901	}
3902	if ((r = sshkey_from_private(private, &public)) != 0)
3903		fatal_r(r, "sshkey_from_private");
3904
3905	if (!have_identity)
3906		ask_filename(pw, "Enter file in which to save the key");
3907
3908	/* Create ~/.ssh directory if it doesn't already exist. */
3909	hostfile_create_user_ssh_dir(identity_file, !quiet);
3910
3911	/* If the file already exists, ask the user to confirm. */
3912	if (!confirm_overwrite(identity_file))
3913		exit(1);
3914
3915	/* Determine the passphrase for the private key */
3916	passphrase = private_key_passphrase();
3917	if (identity_comment) {
3918		strlcpy(comment, identity_comment, sizeof(comment));
3919	} else {
3920		/* Create default comment field for the passphrase. */
3921		snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
3922	}
3923
3924	/* Save the key with the given passphrase and comment. */
3925	if ((r = sshkey_save_private(private, identity_file, passphrase,
3926	    comment, private_key_format, openssh_format_cipher, rounds)) != 0) {
3927		error_r(r, "Saving key \"%s\" failed", identity_file);
3928		freezero(passphrase, strlen(passphrase));
3929		exit(1);
3930	}
3931	freezero(passphrase, strlen(passphrase));
3932	sshkey_free(private);
3933
3934	if (!quiet) {
3935		printf("Your identification has been saved in %s\n",
3936		    identity_file);
3937	}
3938
3939	strlcat(identity_file, ".pub", sizeof(identity_file));
3940	if ((r = sshkey_save_public(public, identity_file, comment)) != 0)
3941		fatal_r(r, "Unable to save public key to %s", identity_file);
3942
3943	if (!quiet) {
3944		fp = sshkey_fingerprint(public, fingerprint_hash,
3945		    SSH_FP_DEFAULT);
3946		ra = sshkey_fingerprint(public, fingerprint_hash,
3947		    SSH_FP_RANDOMART);
3948		if (fp == NULL || ra == NULL)
3949			fatal("sshkey_fingerprint failed");
3950		printf("Your public key has been saved in %s\n",
3951		    identity_file);
3952		printf("The key fingerprint is:\n");
3953		printf("%s %s\n", fp, comment);
3954		printf("The key's randomart image is:\n");
3955		printf("%s\n", ra);
3956		free(ra);
3957		free(fp);
3958	}
3959
3960	if (sk_attestation_path != NULL)
3961		save_attestation(attest, sk_attestation_path);
3962
3963	sshbuf_free(attest);
3964	sshkey_free(public);
3965
3966	exit(0);
3967}
3968