xref: /openssh-portable/ssh-keygen.c (revision d081f017)
1 /* $OpenBSD: ssh-keygen.c,v 1.404 2020/03/13 03:17:07 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 
69 #ifdef WITH_OPENSSL
70 # define DEFAULT_KEY_TYPE_NAME "rsa"
71 #else
72 # define DEFAULT_KEY_TYPE_NAME "ed25519"
73 #endif
74 
75 /*
76  * Default number of bits in the RSA, DSA and ECDSA keys.  These value can be
77  * overridden on the command line.
78  *
79  * These values, with the exception of DSA, provide security equivalent to at
80  * least 128 bits of security according to NIST Special Publication 800-57:
81  * Recommendation for Key Management Part 1 rev 4 section 5.6.1.
82  * For DSA it (and FIPS-186-4 section 4.2) specifies that the only size for
83  * which a 160bit hash is acceptable is 1kbit, and since ssh-dss specifies only
84  * SHA1 we limit the DSA key size 1k bits.
85  */
86 #define DEFAULT_BITS		3072
87 #define DEFAULT_BITS_DSA	1024
88 #define DEFAULT_BITS_ECDSA	256
89 
90 static int quiet = 0;
91 
92 /* Flag indicating that we just want to see the key fingerprint */
93 static int print_fingerprint = 0;
94 static int print_bubblebabble = 0;
95 
96 /* Hash algorithm to use for fingerprints. */
97 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
98 
99 /* The identity file name, given on the command line or entered by the user. */
100 static char identity_file[PATH_MAX];
101 static int have_identity = 0;
102 
103 /* This is set to the passphrase if given on the command line. */
104 static char *identity_passphrase = NULL;
105 
106 /* This is set to the new passphrase if given on the command line. */
107 static char *identity_new_passphrase = NULL;
108 
109 /* Key type when certifying */
110 static u_int cert_key_type = SSH2_CERT_TYPE_USER;
111 
112 /* "key ID" of signed key */
113 static char *cert_key_id = NULL;
114 
115 /* Comma-separated list of principal names for certifying keys */
116 static char *cert_principals = NULL;
117 
118 /* Validity period for certificates */
119 static u_int64_t cert_valid_from = 0;
120 static u_int64_t cert_valid_to = ~0ULL;
121 
122 /* Certificate options */
123 #define CERTOPT_X_FWD				(1)
124 #define CERTOPT_AGENT_FWD			(1<<1)
125 #define CERTOPT_PORT_FWD			(1<<2)
126 #define CERTOPT_PTY				(1<<3)
127 #define CERTOPT_USER_RC				(1<<4)
128 #define CERTOPT_NO_REQUIRE_USER_PRESENCE	(1<<5)
129 #define CERTOPT_DEFAULT	(CERTOPT_X_FWD|CERTOPT_AGENT_FWD| \
130 			 CERTOPT_PORT_FWD|CERTOPT_PTY|CERTOPT_USER_RC)
131 static u_int32_t certflags_flags = CERTOPT_DEFAULT;
132 static char *certflags_command = NULL;
133 static char *certflags_src_addr = NULL;
134 
135 /* Arbitrary extensions specified by user */
136 struct cert_userext {
137 	char *key;
138 	char *val;
139 	int crit;
140 };
141 static struct cert_userext *cert_userext;
142 static size_t ncert_userext;
143 
144 /* Conversion to/from various formats */
145 enum {
146 	FMT_RFC4716,
147 	FMT_PKCS8,
148 	FMT_PEM
149 } convert_format = FMT_RFC4716;
150 
151 static char *key_type_name = NULL;
152 
153 /* Load key from this PKCS#11 provider */
154 static char *pkcs11provider = NULL;
155 
156 /* FIDO/U2F provider to use */
157 static char *sk_provider = NULL;
158 
159 /* Format for writing private keys */
160 static int private_key_format = SSHKEY_PRIVATE_OPENSSH;
161 
162 /* Cipher for new-format private keys */
163 static char *openssh_format_cipher = NULL;
164 
165 /* Number of KDF rounds to derive new format keys. */
166 static int rounds = 0;
167 
168 /* argv0 */
169 extern char *__progname;
170 
171 static char hostname[NI_MAXHOST];
172 
173 #ifdef WITH_OPENSSL
174 /* moduli.c */
175 int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
176 int prime_test(FILE *, FILE *, u_int32_t, u_int32_t, char *, unsigned long,
177     unsigned long);
178 #endif
179 
180 static void
type_bits_valid(int type,const char * name,u_int32_t * bitsp)181 type_bits_valid(int type, const char *name, u_int32_t *bitsp)
182 {
183 	if (type == KEY_UNSPEC)
184 		fatal("unknown key type %s", key_type_name);
185 	if (*bitsp == 0) {
186 #ifdef WITH_OPENSSL
187 		u_int nid;
188 
189 		switch(type) {
190 		case KEY_DSA:
191 			*bitsp = DEFAULT_BITS_DSA;
192 			break;
193 		case KEY_ECDSA:
194 			if (name != NULL &&
195 			    (nid = sshkey_ecdsa_nid_from_name(name)) > 0)
196 				*bitsp = sshkey_curve_nid_to_bits(nid);
197 			if (*bitsp == 0)
198 				*bitsp = DEFAULT_BITS_ECDSA;
199 			break;
200 		case KEY_RSA:
201 			*bitsp = DEFAULT_BITS;
202 			break;
203 		}
204 #endif
205 	}
206 #ifdef WITH_OPENSSL
207 	switch (type) {
208 	case KEY_DSA:
209 		if (*bitsp != 1024)
210 			fatal("Invalid DSA key length: must be 1024 bits");
211 		break;
212 	case KEY_RSA:
213 		if (*bitsp < SSH_RSA_MINIMUM_MODULUS_SIZE)
214 			fatal("Invalid RSA key length: minimum is %d bits",
215 			    SSH_RSA_MINIMUM_MODULUS_SIZE);
216 		else if (*bitsp > OPENSSL_RSA_MAX_MODULUS_BITS)
217 			fatal("Invalid RSA key length: maximum is %d bits",
218 			    OPENSSL_RSA_MAX_MODULUS_BITS);
219 		break;
220 	case KEY_ECDSA:
221 		if (sshkey_ecdsa_bits_to_nid(*bitsp) == -1)
222 			fatal("Invalid ECDSA key length: valid lengths are "
223 #ifdef OPENSSL_HAS_NISTP521
224 			    "256, 384 or 521 bits");
225 #else
226 			    "256 or 384 bits");
227 #endif
228 	}
229 #endif
230 }
231 
232 /*
233  * Checks whether a file exists and, if so, asks the user whether they wish
234  * to overwrite it.
235  * Returns nonzero if the file does not already exist or if the user agrees to
236  * overwrite, or zero otherwise.
237  */
238 static int
confirm_overwrite(const char * filename)239 confirm_overwrite(const char *filename)
240 {
241 	char yesno[3];
242 	struct stat st;
243 
244 	if (stat(filename, &st) != 0)
245 		return 1;
246 	printf("%s already exists.\n", filename);
247 	printf("Overwrite (y/n)? ");
248 	fflush(stdout);
249 	if (fgets(yesno, sizeof(yesno), stdin) == NULL)
250 		return 0;
251 	if (yesno[0] != 'y' && yesno[0] != 'Y')
252 		return 0;
253 	return 1;
254 }
255 
256 static void
ask_filename(struct passwd * pw,const char * prompt)257 ask_filename(struct passwd *pw, const char *prompt)
258 {
259 	char buf[1024];
260 	char *name = NULL;
261 
262 	if (key_type_name == NULL)
263 		name = _PATH_SSH_CLIENT_ID_RSA;
264 	else {
265 		switch (sshkey_type_from_name(key_type_name)) {
266 		case KEY_DSA_CERT:
267 		case KEY_DSA:
268 			name = _PATH_SSH_CLIENT_ID_DSA;
269 			break;
270 #ifdef OPENSSL_HAS_ECC
271 		case KEY_ECDSA_CERT:
272 		case KEY_ECDSA:
273 			name = _PATH_SSH_CLIENT_ID_ECDSA;
274 			break;
275 		case KEY_ECDSA_SK_CERT:
276 		case KEY_ECDSA_SK:
277 			name = _PATH_SSH_CLIENT_ID_ECDSA_SK;
278 			break;
279 #endif
280 		case KEY_RSA_CERT:
281 		case KEY_RSA:
282 			name = _PATH_SSH_CLIENT_ID_RSA;
283 			break;
284 		case KEY_ED25519:
285 		case KEY_ED25519_CERT:
286 			name = _PATH_SSH_CLIENT_ID_ED25519;
287 			break;
288 		case KEY_ED25519_SK:
289 		case KEY_ED25519_SK_CERT:
290 			name = _PATH_SSH_CLIENT_ID_ED25519_SK;
291 			break;
292 		case KEY_XMSS:
293 		case KEY_XMSS_CERT:
294 			name = _PATH_SSH_CLIENT_ID_XMSS;
295 			break;
296 		default:
297 			fatal("bad key type");
298 		}
299 	}
300 	snprintf(identity_file, sizeof(identity_file),
301 	    "%s/%s", pw->pw_dir, name);
302 	printf("%s (%s): ", prompt, identity_file);
303 	fflush(stdout);
304 	if (fgets(buf, sizeof(buf), stdin) == NULL)
305 		exit(1);
306 	buf[strcspn(buf, "\n")] = '\0';
307 	if (strcmp(buf, "") != 0)
308 		strlcpy(identity_file, buf, sizeof(identity_file));
309 	have_identity = 1;
310 }
311 
312 static struct sshkey *
load_identity(const char * filename,char ** commentp)313 load_identity(const char *filename, char **commentp)
314 {
315 	char *pass;
316 	struct sshkey *prv;
317 	int r;
318 
319 	if (commentp != NULL)
320 		*commentp = NULL;
321 	if ((r = sshkey_load_private(filename, "", &prv, commentp)) == 0)
322 		return prv;
323 	if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
324 		fatal("Load key \"%s\": %s", filename, ssh_err(r));
325 	if (identity_passphrase)
326 		pass = xstrdup(identity_passphrase);
327 	else
328 		pass = read_passphrase("Enter passphrase: ", RP_ALLOW_STDIN);
329 	r = sshkey_load_private(filename, pass, &prv, commentp);
330 	freezero(pass, strlen(pass));
331 	if (r != 0)
332 		fatal("Load key \"%s\": %s", filename, ssh_err(r));
333 	return prv;
334 }
335 
336 #define SSH_COM_PUBLIC_BEGIN		"---- BEGIN SSH2 PUBLIC KEY ----"
337 #define SSH_COM_PUBLIC_END		"---- END SSH2 PUBLIC KEY ----"
338 #define SSH_COM_PRIVATE_BEGIN		"---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
339 #define	SSH_COM_PRIVATE_KEY_MAGIC	0x3f6ff9eb
340 
341 #ifdef WITH_OPENSSL
342 static void
do_convert_to_ssh2(struct passwd * pw,struct sshkey * k)343 do_convert_to_ssh2(struct passwd *pw, struct sshkey *k)
344 {
345 	struct sshbuf *b;
346 	char comment[61], *b64;
347 	int r;
348 
349 	if ((b = sshbuf_new()) == NULL)
350 		fatal("%s: sshbuf_new failed", __func__);
351 	if ((r = sshkey_putb(k, b)) != 0)
352 		fatal("key_to_blob failed: %s", ssh_err(r));
353 	if ((b64 = sshbuf_dtob64_string(b, 1)) == NULL)
354 		fatal("%s: sshbuf_dtob64_string failed", __func__);
355 
356 	/* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
357 	snprintf(comment, sizeof(comment),
358 	    "%u-bit %s, converted by %s@%s from OpenSSH",
359 	    sshkey_size(k), sshkey_type(k),
360 	    pw->pw_name, hostname);
361 
362 	sshkey_free(k);
363 	sshbuf_free(b);
364 
365 	fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
366 	fprintf(stdout, "Comment: \"%s\"\n%s", comment, b64);
367 	fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
368 	free(b64);
369 	exit(0);
370 }
371 
372 static void
do_convert_to_pkcs8(struct sshkey * k)373 do_convert_to_pkcs8(struct sshkey *k)
374 {
375 	switch (sshkey_type_plain(k->type)) {
376 	case KEY_RSA:
377 		if (!PEM_write_RSA_PUBKEY(stdout, k->rsa))
378 			fatal("PEM_write_RSA_PUBKEY failed");
379 		break;
380 	case KEY_DSA:
381 		if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
382 			fatal("PEM_write_DSA_PUBKEY failed");
383 		break;
384 #ifdef OPENSSL_HAS_ECC
385 	case KEY_ECDSA:
386 		if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
387 			fatal("PEM_write_EC_PUBKEY failed");
388 		break;
389 #endif
390 	default:
391 		fatal("%s: unsupported key type %s", __func__, sshkey_type(k));
392 	}
393 	exit(0);
394 }
395 
396 static void
do_convert_to_pem(struct sshkey * k)397 do_convert_to_pem(struct sshkey *k)
398 {
399 	switch (sshkey_type_plain(k->type)) {
400 	case KEY_RSA:
401 		if (!PEM_write_RSAPublicKey(stdout, k->rsa))
402 			fatal("PEM_write_RSAPublicKey failed");
403 		break;
404 	case KEY_DSA:
405 		if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
406 			fatal("PEM_write_DSA_PUBKEY failed");
407 		break;
408 #ifdef OPENSSL_HAS_ECC
409 	case KEY_ECDSA:
410 		if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
411 			fatal("PEM_write_EC_PUBKEY failed");
412 		break;
413 #endif
414 	default:
415 		fatal("%s: unsupported key type %s", __func__, sshkey_type(k));
416 	}
417 	exit(0);
418 }
419 
420 static void
do_convert_to(struct passwd * pw)421 do_convert_to(struct passwd *pw)
422 {
423 	struct sshkey *k;
424 	struct stat st;
425 	int r;
426 
427 	if (!have_identity)
428 		ask_filename(pw, "Enter file in which the key is");
429 	if (stat(identity_file, &st) == -1)
430 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
431 	if ((r = sshkey_load_public(identity_file, &k, NULL)) != 0)
432 		k = load_identity(identity_file, NULL);
433 	switch (convert_format) {
434 	case FMT_RFC4716:
435 		do_convert_to_ssh2(pw, k);
436 		break;
437 	case FMT_PKCS8:
438 		do_convert_to_pkcs8(k);
439 		break;
440 	case FMT_PEM:
441 		do_convert_to_pem(k);
442 		break;
443 	default:
444 		fatal("%s: unknown key format %d", __func__, convert_format);
445 	}
446 	exit(0);
447 }
448 
449 /*
450  * This is almost exactly the bignum1 encoding, but with 32 bit for length
451  * instead of 16.
452  */
453 static void
buffer_get_bignum_bits(struct sshbuf * b,BIGNUM * value)454 buffer_get_bignum_bits(struct sshbuf *b, BIGNUM *value)
455 {
456 	u_int bytes, bignum_bits;
457 	int r;
458 
459 	if ((r = sshbuf_get_u32(b, &bignum_bits)) != 0)
460 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
461 	bytes = (bignum_bits + 7) / 8;
462 	if (sshbuf_len(b) < bytes)
463 		fatal("%s: input buffer too small: need %d have %zu",
464 		    __func__, bytes, sshbuf_len(b));
465 	if (BN_bin2bn(sshbuf_ptr(b), bytes, value) == NULL)
466 		fatal("%s: BN_bin2bn failed", __func__);
467 	if ((r = sshbuf_consume(b, bytes)) != 0)
468 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
469 }
470 
471 static struct sshkey *
do_convert_private_ssh2(struct sshbuf * b)472 do_convert_private_ssh2(struct sshbuf *b)
473 {
474 	struct sshkey *key = NULL;
475 	char *type, *cipher;
476 	u_char e1, e2, e3, *sig = NULL, data[] = "abcde12345";
477 	int r, rlen, ktype;
478 	u_int magic, i1, i2, i3, i4;
479 	size_t slen;
480 	u_long e;
481 	BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL;
482 	BIGNUM *dsa_pub_key = NULL, *dsa_priv_key = NULL;
483 	BIGNUM *rsa_n = NULL, *rsa_e = NULL, *rsa_d = NULL;
484 	BIGNUM *rsa_p = NULL, *rsa_q = NULL, *rsa_iqmp = NULL;
485 
486 	if ((r = sshbuf_get_u32(b, &magic)) != 0)
487 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
488 
489 	if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
490 		error("bad magic 0x%x != 0x%x", magic,
491 		    SSH_COM_PRIVATE_KEY_MAGIC);
492 		return NULL;
493 	}
494 	if ((r = sshbuf_get_u32(b, &i1)) != 0 ||
495 	    (r = sshbuf_get_cstring(b, &type, NULL)) != 0 ||
496 	    (r = sshbuf_get_cstring(b, &cipher, NULL)) != 0 ||
497 	    (r = sshbuf_get_u32(b, &i2)) != 0 ||
498 	    (r = sshbuf_get_u32(b, &i3)) != 0 ||
499 	    (r = sshbuf_get_u32(b, &i4)) != 0)
500 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
501 	debug("ignore (%d %d %d %d)", i1, i2, i3, i4);
502 	if (strcmp(cipher, "none") != 0) {
503 		error("unsupported cipher %s", cipher);
504 		free(cipher);
505 		free(type);
506 		return NULL;
507 	}
508 	free(cipher);
509 
510 	if (strstr(type, "dsa")) {
511 		ktype = KEY_DSA;
512 	} else if (strstr(type, "rsa")) {
513 		ktype = KEY_RSA;
514 	} else {
515 		free(type);
516 		return NULL;
517 	}
518 	if ((key = sshkey_new(ktype)) == NULL)
519 		fatal("sshkey_new failed");
520 	free(type);
521 
522 	switch (key->type) {
523 	case KEY_DSA:
524 		if ((dsa_p = BN_new()) == NULL ||
525 		    (dsa_q = BN_new()) == NULL ||
526 		    (dsa_g = BN_new()) == NULL ||
527 		    (dsa_pub_key = BN_new()) == NULL ||
528 		    (dsa_priv_key = BN_new()) == NULL)
529 			fatal("%s: BN_new", __func__);
530 		buffer_get_bignum_bits(b, dsa_p);
531 		buffer_get_bignum_bits(b, dsa_g);
532 		buffer_get_bignum_bits(b, dsa_q);
533 		buffer_get_bignum_bits(b, dsa_pub_key);
534 		buffer_get_bignum_bits(b, dsa_priv_key);
535 		if (!DSA_set0_pqg(key->dsa, dsa_p, dsa_q, dsa_g))
536 			fatal("%s: DSA_set0_pqg failed", __func__);
537 		dsa_p = dsa_q = dsa_g = NULL; /* transferred */
538 		if (!DSA_set0_key(key->dsa, dsa_pub_key, dsa_priv_key))
539 			fatal("%s: DSA_set0_key failed", __func__);
540 		dsa_pub_key = dsa_priv_key = NULL; /* transferred */
541 		break;
542 	case KEY_RSA:
543 		if ((r = sshbuf_get_u8(b, &e1)) != 0 ||
544 		    (e1 < 30 && (r = sshbuf_get_u8(b, &e2)) != 0) ||
545 		    (e1 < 30 && (r = sshbuf_get_u8(b, &e3)) != 0))
546 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
547 		e = e1;
548 		debug("e %lx", e);
549 		if (e < 30) {
550 			e <<= 8;
551 			e += e2;
552 			debug("e %lx", e);
553 			e <<= 8;
554 			e += e3;
555 			debug("e %lx", e);
556 		}
557 		if ((rsa_e = BN_new()) == NULL)
558 			fatal("%s: BN_new", __func__);
559 		if (!BN_set_word(rsa_e, e)) {
560 			BN_clear_free(rsa_e);
561 			sshkey_free(key);
562 			return NULL;
563 		}
564 		if ((rsa_n = BN_new()) == NULL ||
565 		    (rsa_d = BN_new()) == NULL ||
566 		    (rsa_p = BN_new()) == NULL ||
567 		    (rsa_q = BN_new()) == NULL ||
568 		    (rsa_iqmp = BN_new()) == NULL)
569 			fatal("%s: BN_new", __func__);
570 		buffer_get_bignum_bits(b, rsa_d);
571 		buffer_get_bignum_bits(b, rsa_n);
572 		buffer_get_bignum_bits(b, rsa_iqmp);
573 		buffer_get_bignum_bits(b, rsa_q);
574 		buffer_get_bignum_bits(b, rsa_p);
575 		if (!RSA_set0_key(key->rsa, rsa_n, rsa_e, rsa_d))
576 			fatal("%s: RSA_set0_key failed", __func__);
577 		rsa_n = rsa_e = rsa_d = NULL; /* transferred */
578 		if (!RSA_set0_factors(key->rsa, rsa_p, rsa_q))
579 			fatal("%s: RSA_set0_factors failed", __func__);
580 		rsa_p = rsa_q = NULL; /* transferred */
581 		if ((r = ssh_rsa_complete_crt_parameters(key, rsa_iqmp)) != 0)
582 			fatal("generate RSA parameters failed: %s", ssh_err(r));
583 		BN_clear_free(rsa_iqmp);
584 		break;
585 	}
586 	rlen = sshbuf_len(b);
587 	if (rlen != 0)
588 		error("%s: remaining bytes in key blob %d", __func__, rlen);
589 
590 	/* try the key */
591 	if (sshkey_sign(key, &sig, &slen, data, sizeof(data),
592 	    NULL, NULL, 0) != 0 ||
593 	    sshkey_verify(key, sig, slen, data, sizeof(data),
594 	    NULL, 0, NULL) != 0) {
595 		sshkey_free(key);
596 		free(sig);
597 		return NULL;
598 	}
599 	free(sig);
600 	return key;
601 }
602 
603 static int
get_line(FILE * fp,char * line,size_t len)604 get_line(FILE *fp, char *line, size_t len)
605 {
606 	int c;
607 	size_t pos = 0;
608 
609 	line[0] = '\0';
610 	while ((c = fgetc(fp)) != EOF) {
611 		if (pos >= len - 1)
612 			fatal("input line too long.");
613 		switch (c) {
614 		case '\r':
615 			c = fgetc(fp);
616 			if (c != EOF && c != '\n' && ungetc(c, fp) == EOF)
617 				fatal("unget: %s", strerror(errno));
618 			return pos;
619 		case '\n':
620 			return pos;
621 		}
622 		line[pos++] = c;
623 		line[pos] = '\0';
624 	}
625 	/* We reached EOF */
626 	return -1;
627 }
628 
629 static void
do_convert_from_ssh2(struct passwd * pw,struct sshkey ** k,int * private)630 do_convert_from_ssh2(struct passwd *pw, struct sshkey **k, int *private)
631 {
632 	int r, blen, escaped = 0;
633 	u_int len;
634 	char line[1024];
635 	struct sshbuf *buf;
636 	char encoded[8096];
637 	FILE *fp;
638 
639 	if ((buf = sshbuf_new()) == NULL)
640 		fatal("sshbuf_new failed");
641 	if ((fp = fopen(identity_file, "r")) == NULL)
642 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
643 	encoded[0] = '\0';
644 	while ((blen = get_line(fp, line, sizeof(line))) != -1) {
645 		if (blen > 0 && line[blen - 1] == '\\')
646 			escaped++;
647 		if (strncmp(line, "----", 4) == 0 ||
648 		    strstr(line, ": ") != NULL) {
649 			if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
650 				*private = 1;
651 			if (strstr(line, " END ") != NULL) {
652 				break;
653 			}
654 			/* fprintf(stderr, "ignore: %s", line); */
655 			continue;
656 		}
657 		if (escaped) {
658 			escaped--;
659 			/* fprintf(stderr, "escaped: %s", line); */
660 			continue;
661 		}
662 		strlcat(encoded, line, sizeof(encoded));
663 	}
664 	len = strlen(encoded);
665 	if (((len % 4) == 3) &&
666 	    (encoded[len-1] == '=') &&
667 	    (encoded[len-2] == '=') &&
668 	    (encoded[len-3] == '='))
669 		encoded[len-3] = '\0';
670 	if ((r = sshbuf_b64tod(buf, encoded)) != 0)
671 		fatal("%s: base64 decoding failed: %s", __func__, ssh_err(r));
672 	if (*private)
673 		*k = do_convert_private_ssh2(buf);
674 	else if ((r = sshkey_fromb(buf, k)) != 0)
675 		fatal("decode blob failed: %s", ssh_err(r));
676 	sshbuf_free(buf);
677 	fclose(fp);
678 }
679 
680 static void
do_convert_from_pkcs8(struct sshkey ** k,int * private)681 do_convert_from_pkcs8(struct sshkey **k, int *private)
682 {
683 	EVP_PKEY *pubkey;
684 	FILE *fp;
685 
686 	if ((fp = fopen(identity_file, "r")) == NULL)
687 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
688 	if ((pubkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL)) == NULL) {
689 		fatal("%s: %s is not a recognised public key format", __func__,
690 		    identity_file);
691 	}
692 	fclose(fp);
693 	switch (EVP_PKEY_base_id(pubkey)) {
694 	case EVP_PKEY_RSA:
695 		if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
696 			fatal("sshkey_new failed");
697 		(*k)->type = KEY_RSA;
698 		(*k)->rsa = EVP_PKEY_get1_RSA(pubkey);
699 		break;
700 	case EVP_PKEY_DSA:
701 		if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
702 			fatal("sshkey_new failed");
703 		(*k)->type = KEY_DSA;
704 		(*k)->dsa = EVP_PKEY_get1_DSA(pubkey);
705 		break;
706 #ifdef OPENSSL_HAS_ECC
707 	case EVP_PKEY_EC:
708 		if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
709 			fatal("sshkey_new failed");
710 		(*k)->type = KEY_ECDSA;
711 		(*k)->ecdsa = EVP_PKEY_get1_EC_KEY(pubkey);
712 		(*k)->ecdsa_nid = sshkey_ecdsa_key_to_nid((*k)->ecdsa);
713 		break;
714 #endif
715 	default:
716 		fatal("%s: unsupported pubkey type %d", __func__,
717 		    EVP_PKEY_base_id(pubkey));
718 	}
719 	EVP_PKEY_free(pubkey);
720 	return;
721 }
722 
723 static void
do_convert_from_pem(struct sshkey ** k,int * private)724 do_convert_from_pem(struct sshkey **k, int *private)
725 {
726 	FILE *fp;
727 	RSA *rsa;
728 
729 	if ((fp = fopen(identity_file, "r")) == NULL)
730 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
731 	if ((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
732 		if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
733 			fatal("sshkey_new failed");
734 		(*k)->type = KEY_RSA;
735 		(*k)->rsa = rsa;
736 		fclose(fp);
737 		return;
738 	}
739 	fatal("%s: unrecognised raw private key format", __func__);
740 }
741 
742 static void
do_convert_from(struct passwd * pw)743 do_convert_from(struct passwd *pw)
744 {
745 	struct sshkey *k = NULL;
746 	int r, private = 0, ok = 0;
747 	struct stat st;
748 
749 	if (!have_identity)
750 		ask_filename(pw, "Enter file in which the key is");
751 	if (stat(identity_file, &st) == -1)
752 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
753 
754 	switch (convert_format) {
755 	case FMT_RFC4716:
756 		do_convert_from_ssh2(pw, &k, &private);
757 		break;
758 	case FMT_PKCS8:
759 		do_convert_from_pkcs8(&k, &private);
760 		break;
761 	case FMT_PEM:
762 		do_convert_from_pem(&k, &private);
763 		break;
764 	default:
765 		fatal("%s: unknown key format %d", __func__, convert_format);
766 	}
767 
768 	if (!private) {
769 		if ((r = sshkey_write(k, stdout)) == 0)
770 			ok = 1;
771 		if (ok)
772 			fprintf(stdout, "\n");
773 	} else {
774 		switch (k->type) {
775 		case KEY_DSA:
776 			ok = PEM_write_DSAPrivateKey(stdout, k->dsa, NULL,
777 			    NULL, 0, NULL, NULL);
778 			break;
779 #ifdef OPENSSL_HAS_ECC
780 		case KEY_ECDSA:
781 			ok = PEM_write_ECPrivateKey(stdout, k->ecdsa, NULL,
782 			    NULL, 0, NULL, NULL);
783 			break;
784 #endif
785 		case KEY_RSA:
786 			ok = PEM_write_RSAPrivateKey(stdout, k->rsa, NULL,
787 			    NULL, 0, NULL, NULL);
788 			break;
789 		default:
790 			fatal("%s: unsupported key type %s", __func__,
791 			    sshkey_type(k));
792 		}
793 	}
794 
795 	if (!ok)
796 		fatal("key write failed");
797 	sshkey_free(k);
798 	exit(0);
799 }
800 #endif
801 
802 static void
do_print_public(struct passwd * pw)803 do_print_public(struct passwd *pw)
804 {
805 	struct sshkey *prv;
806 	struct stat st;
807 	int r;
808 	char *comment = NULL;
809 
810 	if (!have_identity)
811 		ask_filename(pw, "Enter file in which the key is");
812 	if (stat(identity_file, &st) == -1)
813 		fatal("%s: %s", identity_file, strerror(errno));
814 	prv = load_identity(identity_file, &comment);
815 	if ((r = sshkey_write(prv, stdout)) != 0)
816 		error("sshkey_write failed: %s", ssh_err(r));
817 	sshkey_free(prv);
818 	if (comment != NULL && *comment != '\0')
819 		fprintf(stdout, " %s", comment);
820 	fprintf(stdout, "\n");
821 	free(comment);
822 	exit(0);
823 }
824 
825 static void
do_download(struct passwd * pw)826 do_download(struct passwd *pw)
827 {
828 #ifdef ENABLE_PKCS11
829 	struct sshkey **keys = NULL;
830 	int i, nkeys;
831 	enum sshkey_fp_rep rep;
832 	int fptype;
833 	char *fp, *ra, **comments = NULL;
834 
835 	fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
836 	rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
837 
838 	pkcs11_init(1);
839 	nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys, &comments);
840 	if (nkeys <= 0)
841 		fatal("cannot read public key from pkcs11");
842 	for (i = 0; i < nkeys; i++) {
843 		if (print_fingerprint) {
844 			fp = sshkey_fingerprint(keys[i], fptype, rep);
845 			ra = sshkey_fingerprint(keys[i], fingerprint_hash,
846 			    SSH_FP_RANDOMART);
847 			if (fp == NULL || ra == NULL)
848 				fatal("%s: sshkey_fingerprint fail", __func__);
849 			printf("%u %s %s (PKCS11 key)\n", sshkey_size(keys[i]),
850 			    fp, sshkey_type(keys[i]));
851 			if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
852 				printf("%s\n", ra);
853 			free(ra);
854 			free(fp);
855 		} else {
856 			(void) sshkey_write(keys[i], stdout); /* XXX check */
857 			fprintf(stdout, "%s%s\n",
858 			    *(comments[i]) == '\0' ? "" : " ", comments[i]);
859 		}
860 		free(comments[i]);
861 		sshkey_free(keys[i]);
862 	}
863 	free(comments);
864 	free(keys);
865 	pkcs11_terminate();
866 	exit(0);
867 #else
868 	fatal("no pkcs11 support");
869 #endif /* ENABLE_PKCS11 */
870 }
871 
872 static struct sshkey *
try_read_key(char ** cpp)873 try_read_key(char **cpp)
874 {
875 	struct sshkey *ret;
876 	int r;
877 
878 	if ((ret = sshkey_new(KEY_UNSPEC)) == NULL)
879 		fatal("sshkey_new failed");
880 	if ((r = sshkey_read(ret, cpp)) == 0)
881 		return ret;
882 	/* Not a key */
883 	sshkey_free(ret);
884 	return NULL;
885 }
886 
887 static void
fingerprint_one_key(const struct sshkey * public,const char * comment)888 fingerprint_one_key(const struct sshkey *public, const char *comment)
889 {
890 	char *fp = NULL, *ra = NULL;
891 	enum sshkey_fp_rep rep;
892 	int fptype;
893 
894 	fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
895 	rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
896 	fp = sshkey_fingerprint(public, fptype, rep);
897 	ra = sshkey_fingerprint(public, fingerprint_hash, SSH_FP_RANDOMART);
898 	if (fp == NULL || ra == NULL)
899 		fatal("%s: sshkey_fingerprint failed", __func__);
900 	mprintf("%u %s %s (%s)\n", sshkey_size(public), fp,
901 	    comment ? comment : "no comment", sshkey_type(public));
902 	if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
903 		printf("%s\n", ra);
904 	free(ra);
905 	free(fp);
906 }
907 
908 static void
fingerprint_private(const char * path)909 fingerprint_private(const char *path)
910 {
911 	struct stat st;
912 	char *comment = NULL;
913 	struct sshkey *public = NULL;
914 	int r;
915 
916 	if (stat(identity_file, &st) == -1)
917 		fatal("%s: %s", path, strerror(errno));
918 	if ((r = sshkey_load_public(path, &public, &comment)) != 0) {
919 		debug("load public \"%s\": %s", path, ssh_err(r));
920 		if ((r = sshkey_load_private(path, NULL,
921 		    &public, &comment)) != 0) {
922 			debug("load private \"%s\": %s", path, ssh_err(r));
923 			fatal("%s is not a key file.", path);
924 		}
925 	}
926 
927 	fingerprint_one_key(public, comment);
928 	sshkey_free(public);
929 	free(comment);
930 }
931 
932 static void
do_fingerprint(struct passwd * pw)933 do_fingerprint(struct passwd *pw)
934 {
935 	FILE *f;
936 	struct sshkey *public = NULL;
937 	char *comment = NULL, *cp, *ep, *line = NULL;
938 	size_t linesize = 0;
939 	int i, invalid = 1;
940 	const char *path;
941 	u_long lnum = 0;
942 
943 	if (!have_identity)
944 		ask_filename(pw, "Enter file in which the key is");
945 	path = identity_file;
946 
947 	if (strcmp(identity_file, "-") == 0) {
948 		f = stdin;
949 		path = "(stdin)";
950 	} else if ((f = fopen(path, "r")) == NULL)
951 		fatal("%s: %s: %s", __progname, path, strerror(errno));
952 
953 	while (getline(&line, &linesize, f) != -1) {
954 		lnum++;
955 		cp = line;
956 		cp[strcspn(cp, "\n")] = '\0';
957 		/* Trim leading space and comments */
958 		cp = line + strspn(line, " \t");
959 		if (*cp == '#' || *cp == '\0')
960 			continue;
961 
962 		/*
963 		 * Input may be plain keys, private keys, authorized_keys
964 		 * or known_hosts.
965 		 */
966 
967 		/*
968 		 * Try private keys first. Assume a key is private if
969 		 * "SSH PRIVATE KEY" appears on the first line and we're
970 		 * not reading from stdin (XXX support private keys on stdin).
971 		 */
972 		if (lnum == 1 && strcmp(identity_file, "-") != 0 &&
973 		    strstr(cp, "PRIVATE KEY") != NULL) {
974 			free(line);
975 			fclose(f);
976 			fingerprint_private(path);
977 			exit(0);
978 		}
979 
980 		/*
981 		 * If it's not a private key, then this must be prepared to
982 		 * accept a public key prefixed with a hostname or options.
983 		 * Try a bare key first, otherwise skip the leading stuff.
984 		 */
985 		if ((public = try_read_key(&cp)) == NULL) {
986 			i = strtol(cp, &ep, 10);
987 			if (i == 0 || ep == NULL ||
988 			    (*ep != ' ' && *ep != '\t')) {
989 				int quoted = 0;
990 
991 				comment = cp;
992 				for (; *cp && (quoted || (*cp != ' ' &&
993 				    *cp != '\t')); cp++) {
994 					if (*cp == '\\' && cp[1] == '"')
995 						cp++;	/* Skip both */
996 					else if (*cp == '"')
997 						quoted = !quoted;
998 				}
999 				if (!*cp)
1000 					continue;
1001 				*cp++ = '\0';
1002 			}
1003 		}
1004 		/* Retry after parsing leading hostname/key options */
1005 		if (public == NULL && (public = try_read_key(&cp)) == NULL) {
1006 			debug("%s:%lu: not a public key", path, lnum);
1007 			continue;
1008 		}
1009 
1010 		/* Find trailing comment, if any */
1011 		for (; *cp == ' ' || *cp == '\t'; cp++)
1012 			;
1013 		if (*cp != '\0' && *cp != '#')
1014 			comment = cp;
1015 
1016 		fingerprint_one_key(public, comment);
1017 		sshkey_free(public);
1018 		invalid = 0; /* One good key in the file is sufficient */
1019 	}
1020 	fclose(f);
1021 	free(line);
1022 
1023 	if (invalid)
1024 		fatal("%s is not a public key file.", path);
1025 	exit(0);
1026 }
1027 
1028 static void
do_gen_all_hostkeys(struct passwd * pw)1029 do_gen_all_hostkeys(struct passwd *pw)
1030 {
1031 	struct {
1032 		char *key_type;
1033 		char *key_type_display;
1034 		char *path;
1035 	} key_types[] = {
1036 #ifdef WITH_OPENSSL
1037 		{ "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE },
1038 		{ "dsa", "DSA", _PATH_HOST_DSA_KEY_FILE },
1039 #ifdef OPENSSL_HAS_ECC
1040 		{ "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE },
1041 #endif /* OPENSSL_HAS_ECC */
1042 #endif /* WITH_OPENSSL */
1043 		{ "ed25519", "ED25519",_PATH_HOST_ED25519_KEY_FILE },
1044 #ifdef WITH_XMSS
1045 		{ "xmss", "XMSS",_PATH_HOST_XMSS_KEY_FILE },
1046 #endif /* WITH_XMSS */
1047 		{ NULL, NULL, NULL }
1048 	};
1049 
1050 	u_int32_t bits = 0;
1051 	int first = 0;
1052 	struct stat st;
1053 	struct sshkey *private, *public;
1054 	char comment[1024], *prv_tmp, *pub_tmp, *prv_file, *pub_file;
1055 	int i, type, fd, r;
1056 	FILE *f;
1057 
1058 	for (i = 0; key_types[i].key_type; i++) {
1059 		public = private = NULL;
1060 		prv_tmp = pub_tmp = prv_file = pub_file = NULL;
1061 
1062 		xasprintf(&prv_file, "%s%s",
1063 		    identity_file, key_types[i].path);
1064 
1065 		/* Check whether private key exists and is not zero-length */
1066 		if (stat(prv_file, &st) == 0) {
1067 			if (st.st_size != 0)
1068 				goto next;
1069 		} else if (errno != ENOENT) {
1070 			error("Could not stat %s: %s", key_types[i].path,
1071 			    strerror(errno));
1072 			goto failnext;
1073 		}
1074 
1075 		/*
1076 		 * Private key doesn't exist or is invalid; proceed with
1077 		 * key generation.
1078 		 */
1079 		xasprintf(&prv_tmp, "%s%s.XXXXXXXXXX",
1080 		    identity_file, key_types[i].path);
1081 		xasprintf(&pub_tmp, "%s%s.pub.XXXXXXXXXX",
1082 		    identity_file, key_types[i].path);
1083 		xasprintf(&pub_file, "%s%s.pub",
1084 		    identity_file, key_types[i].path);
1085 
1086 		if (first == 0) {
1087 			first = 1;
1088 			printf("%s: generating new host keys: ", __progname);
1089 		}
1090 		printf("%s ", key_types[i].key_type_display);
1091 		fflush(stdout);
1092 		type = sshkey_type_from_name(key_types[i].key_type);
1093 		if ((fd = mkstemp(prv_tmp)) == -1) {
1094 			error("Could not save your public key in %s: %s",
1095 			    prv_tmp, strerror(errno));
1096 			goto failnext;
1097 		}
1098 		close(fd); /* just using mkstemp() to generate/reserve a name */
1099 		bits = 0;
1100 		type_bits_valid(type, NULL, &bits);
1101 		if ((r = sshkey_generate(type, bits, &private)) != 0) {
1102 			error("sshkey_generate failed: %s", ssh_err(r));
1103 			goto failnext;
1104 		}
1105 		if ((r = sshkey_from_private(private, &public)) != 0)
1106 			fatal("sshkey_from_private failed: %s", ssh_err(r));
1107 		snprintf(comment, sizeof comment, "%s@%s", pw->pw_name,
1108 		    hostname);
1109 		if ((r = sshkey_save_private(private, prv_tmp, "",
1110 		    comment, private_key_format, openssh_format_cipher,
1111 		    rounds)) != 0) {
1112 			error("Saving key \"%s\" failed: %s",
1113 			    prv_tmp, ssh_err(r));
1114 			goto failnext;
1115 		}
1116 		if ((fd = mkstemp(pub_tmp)) == -1) {
1117 			error("Could not save your public key in %s: %s",
1118 			    pub_tmp, strerror(errno));
1119 			goto failnext;
1120 		}
1121 		(void)fchmod(fd, 0644);
1122 		f = fdopen(fd, "w");
1123 		if (f == NULL) {
1124 			error("fdopen %s failed: %s", pub_tmp, strerror(errno));
1125 			close(fd);
1126 			goto failnext;
1127 		}
1128 		if ((r = sshkey_write(public, f)) != 0) {
1129 			error("write key failed: %s", ssh_err(r));
1130 			fclose(f);
1131 			goto failnext;
1132 		}
1133 		fprintf(f, " %s\n", comment);
1134 		if (ferror(f) != 0) {
1135 			error("write key failed: %s", strerror(errno));
1136 			fclose(f);
1137 			goto failnext;
1138 		}
1139 		if (fclose(f) != 0) {
1140 			error("key close failed: %s", strerror(errno));
1141 			goto failnext;
1142 		}
1143 
1144 		/* Rename temporary files to their permanent locations. */
1145 		if (rename(pub_tmp, pub_file) != 0) {
1146 			error("Unable to move %s into position: %s",
1147 			    pub_file, strerror(errno));
1148 			goto failnext;
1149 		}
1150 		if (rename(prv_tmp, prv_file) != 0) {
1151 			error("Unable to move %s into position: %s",
1152 			    key_types[i].path, strerror(errno));
1153  failnext:
1154 			first = 0;
1155 			goto next;
1156 		}
1157  next:
1158 		sshkey_free(private);
1159 		sshkey_free(public);
1160 		free(prv_tmp);
1161 		free(pub_tmp);
1162 		free(prv_file);
1163 		free(pub_file);
1164 	}
1165 	if (first != 0)
1166 		printf("\n");
1167 }
1168 
1169 struct known_hosts_ctx {
1170 	const char *host;	/* Hostname searched for in find/delete case */
1171 	FILE *out;		/* Output file, stdout for find_hosts case */
1172 	int has_unhashed;	/* When hashing, original had unhashed hosts */
1173 	int found_key;		/* For find/delete, host was found */
1174 	int invalid;		/* File contained invalid items; don't delete */
1175 	int hash_hosts;		/* Hash hostnames as we go */
1176 	int find_host;		/* Search for specific hostname */
1177 	int delete_host;	/* Delete host from known_hosts */
1178 };
1179 
1180 static int
known_hosts_hash(struct hostkey_foreach_line * l,void * _ctx)1181 known_hosts_hash(struct hostkey_foreach_line *l, void *_ctx)
1182 {
1183 	struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1184 	char *hashed, *cp, *hosts, *ohosts;
1185 	int has_wild = l->hosts && strcspn(l->hosts, "*?!") != strlen(l->hosts);
1186 	int was_hashed = l->hosts && l->hosts[0] == HASH_DELIM;
1187 
1188 	switch (l->status) {
1189 	case HKF_STATUS_OK:
1190 	case HKF_STATUS_MATCHED:
1191 		/*
1192 		 * Don't hash hosts already already hashed, with wildcard
1193 		 * characters or a CA/revocation marker.
1194 		 */
1195 		if (was_hashed || has_wild || l->marker != MRK_NONE) {
1196 			fprintf(ctx->out, "%s\n", l->line);
1197 			if (has_wild && !ctx->find_host) {
1198 				logit("%s:%lu: ignoring host name "
1199 				    "with wildcard: %.64s", l->path,
1200 				    l->linenum, l->hosts);
1201 			}
1202 			return 0;
1203 		}
1204 		/*
1205 		 * Split any comma-separated hostnames from the host list,
1206 		 * hash and store separately.
1207 		 */
1208 		ohosts = hosts = xstrdup(l->hosts);
1209 		while ((cp = strsep(&hosts, ",")) != NULL && *cp != '\0') {
1210 			lowercase(cp);
1211 			if ((hashed = host_hash(cp, NULL, 0)) == NULL)
1212 				fatal("hash_host failed");
1213 			fprintf(ctx->out, "%s %s\n", hashed, l->rawkey);
1214 			ctx->has_unhashed = 1;
1215 		}
1216 		free(ohosts);
1217 		return 0;
1218 	case HKF_STATUS_INVALID:
1219 		/* Retain invalid lines, but mark file as invalid. */
1220 		ctx->invalid = 1;
1221 		logit("%s:%lu: invalid line", l->path, l->linenum);
1222 		/* FALLTHROUGH */
1223 	default:
1224 		fprintf(ctx->out, "%s\n", l->line);
1225 		return 0;
1226 	}
1227 	/* NOTREACHED */
1228 	return -1;
1229 }
1230 
1231 static int
known_hosts_find_delete(struct hostkey_foreach_line * l,void * _ctx)1232 known_hosts_find_delete(struct hostkey_foreach_line *l, void *_ctx)
1233 {
1234 	struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1235 	enum sshkey_fp_rep rep;
1236 	int fptype;
1237 	char *fp = NULL, *ra = NULL;
1238 
1239 	fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
1240 	rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1241 
1242 	if (l->status == HKF_STATUS_MATCHED) {
1243 		if (ctx->delete_host) {
1244 			if (l->marker != MRK_NONE) {
1245 				/* Don't remove CA and revocation lines */
1246 				fprintf(ctx->out, "%s\n", l->line);
1247 			} else {
1248 				/*
1249 				 * Hostname matches and has no CA/revoke
1250 				 * marker, delete it by *not* writing the
1251 				 * line to ctx->out.
1252 				 */
1253 				ctx->found_key = 1;
1254 				if (!quiet)
1255 					printf("# Host %s found: line %lu\n",
1256 					    ctx->host, l->linenum);
1257 			}
1258 			return 0;
1259 		} else if (ctx->find_host) {
1260 			ctx->found_key = 1;
1261 			if (!quiet) {
1262 				printf("# Host %s found: line %lu %s\n",
1263 				    ctx->host,
1264 				    l->linenum, l->marker == MRK_CA ? "CA" :
1265 				    (l->marker == MRK_REVOKE ? "REVOKED" : ""));
1266 			}
1267 			if (ctx->hash_hosts)
1268 				known_hosts_hash(l, ctx);
1269 			else if (print_fingerprint) {
1270 				fp = sshkey_fingerprint(l->key, fptype, rep);
1271 				ra = sshkey_fingerprint(l->key,
1272 				    fingerprint_hash, SSH_FP_RANDOMART);
1273 				if (fp == NULL || ra == NULL)
1274 					fatal("%s: sshkey_fingerprint failed",
1275 					    __func__);
1276 				mprintf("%s %s %s%s%s\n", ctx->host,
1277 				    sshkey_type(l->key), fp,
1278 				    l->comment[0] ? " " : "",
1279 				    l->comment);
1280 				if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
1281 					printf("%s\n", ra);
1282 				free(ra);
1283 				free(fp);
1284 			} else
1285 				fprintf(ctx->out, "%s\n", l->line);
1286 			return 0;
1287 		}
1288 	} else if (ctx->delete_host) {
1289 		/* Retain non-matching hosts when deleting */
1290 		if (l->status == HKF_STATUS_INVALID) {
1291 			ctx->invalid = 1;
1292 			logit("%s:%lu: invalid line", l->path, l->linenum);
1293 		}
1294 		fprintf(ctx->out, "%s\n", l->line);
1295 	}
1296 	return 0;
1297 }
1298 
1299 static void
do_known_hosts(struct passwd * pw,const char * name,int find_host,int delete_host,int hash_hosts)1300 do_known_hosts(struct passwd *pw, const char *name, int find_host,
1301     int delete_host, int hash_hosts)
1302 {
1303 	char *cp, tmp[PATH_MAX], old[PATH_MAX];
1304 	int r, fd, oerrno, inplace = 0;
1305 	struct known_hosts_ctx ctx;
1306 	u_int foreach_options;
1307 
1308 	if (!have_identity) {
1309 		cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
1310 		if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
1311 		    sizeof(identity_file))
1312 			fatal("Specified known hosts path too long");
1313 		free(cp);
1314 		have_identity = 1;
1315 	}
1316 
1317 	memset(&ctx, 0, sizeof(ctx));
1318 	ctx.out = stdout;
1319 	ctx.host = name;
1320 	ctx.hash_hosts = hash_hosts;
1321 	ctx.find_host = find_host;
1322 	ctx.delete_host = delete_host;
1323 
1324 	/*
1325 	 * Find hosts goes to stdout, hash and deletions happen in-place
1326 	 * A corner case is ssh-keygen -HF foo, which should go to stdout
1327 	 */
1328 	if (!find_host && (hash_hosts || delete_host)) {
1329 		if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
1330 		    strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
1331 		    strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
1332 		    strlcat(old, ".old", sizeof(old)) >= sizeof(old))
1333 			fatal("known_hosts path too long");
1334 		umask(077);
1335 		if ((fd = mkstemp(tmp)) == -1)
1336 			fatal("mkstemp: %s", strerror(errno));
1337 		if ((ctx.out = fdopen(fd, "w")) == NULL) {
1338 			oerrno = errno;
1339 			unlink(tmp);
1340 			fatal("fdopen: %s", strerror(oerrno));
1341 		}
1342 		inplace = 1;
1343 	}
1344 	/* XXX support identity_file == "-" for stdin */
1345 	foreach_options = find_host ? HKF_WANT_MATCH : 0;
1346 	foreach_options |= print_fingerprint ? HKF_WANT_PARSE_KEY : 0;
1347 	if ((r = hostkeys_foreach(identity_file, (find_host || !hash_hosts) ?
1348 	    known_hosts_find_delete : known_hosts_hash, &ctx, name, NULL,
1349 	    foreach_options)) != 0) {
1350 		if (inplace)
1351 			unlink(tmp);
1352 		fatal("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
1353 	}
1354 
1355 	if (inplace)
1356 		fclose(ctx.out);
1357 
1358 	if (ctx.invalid) {
1359 		error("%s is not a valid known_hosts file.", identity_file);
1360 		if (inplace) {
1361 			error("Not replacing existing known_hosts "
1362 			    "file because of errors");
1363 			unlink(tmp);
1364 		}
1365 		exit(1);
1366 	} else if (delete_host && !ctx.found_key) {
1367 		logit("Host %s not found in %s", name, identity_file);
1368 		if (inplace)
1369 			unlink(tmp);
1370 	} else if (inplace) {
1371 		/* Backup existing file */
1372 		if (unlink(old) == -1 && errno != ENOENT)
1373 			fatal("unlink %.100s: %s", old, strerror(errno));
1374 		if (link(identity_file, old) == -1)
1375 			fatal("link %.100s to %.100s: %s", identity_file, old,
1376 			    strerror(errno));
1377 		/* Move new one into place */
1378 		if (rename(tmp, identity_file) == -1) {
1379 			error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
1380 			    strerror(errno));
1381 			unlink(tmp);
1382 			unlink(old);
1383 			exit(1);
1384 		}
1385 
1386 		printf("%s updated.\n", identity_file);
1387 		printf("Original contents retained as %s\n", old);
1388 		if (ctx.has_unhashed) {
1389 			logit("WARNING: %s contains unhashed entries", old);
1390 			logit("Delete this file to ensure privacy "
1391 			    "of hostnames");
1392 		}
1393 	}
1394 
1395 	exit (find_host && !ctx.found_key);
1396 }
1397 
1398 /*
1399  * Perform changing a passphrase.  The argument is the passwd structure
1400  * for the current user.
1401  */
1402 static void
do_change_passphrase(struct passwd * pw)1403 do_change_passphrase(struct passwd *pw)
1404 {
1405 	char *comment;
1406 	char *old_passphrase, *passphrase1, *passphrase2;
1407 	struct stat st;
1408 	struct sshkey *private;
1409 	int r;
1410 
1411 	if (!have_identity)
1412 		ask_filename(pw, "Enter file in which the key is");
1413 	if (stat(identity_file, &st) == -1)
1414 		fatal("%s: %s", identity_file, strerror(errno));
1415 	/* Try to load the file with empty passphrase. */
1416 	r = sshkey_load_private(identity_file, "", &private, &comment);
1417 	if (r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
1418 		if (identity_passphrase)
1419 			old_passphrase = xstrdup(identity_passphrase);
1420 		else
1421 			old_passphrase =
1422 			    read_passphrase("Enter old passphrase: ",
1423 			    RP_ALLOW_STDIN);
1424 		r = sshkey_load_private(identity_file, old_passphrase,
1425 		    &private, &comment);
1426 		freezero(old_passphrase, strlen(old_passphrase));
1427 		if (r != 0)
1428 			goto badkey;
1429 	} else if (r != 0) {
1430  badkey:
1431 		fatal("Failed to load key %s: %s", identity_file, ssh_err(r));
1432 	}
1433 	if (comment)
1434 		mprintf("Key has comment '%s'\n", comment);
1435 
1436 	/* Ask the new passphrase (twice). */
1437 	if (identity_new_passphrase) {
1438 		passphrase1 = xstrdup(identity_new_passphrase);
1439 		passphrase2 = NULL;
1440 	} else {
1441 		passphrase1 =
1442 			read_passphrase("Enter new passphrase (empty for no "
1443 			    "passphrase): ", RP_ALLOW_STDIN);
1444 		passphrase2 = read_passphrase("Enter same passphrase again: ",
1445 		    RP_ALLOW_STDIN);
1446 
1447 		/* Verify that they are the same. */
1448 		if (strcmp(passphrase1, passphrase2) != 0) {
1449 			explicit_bzero(passphrase1, strlen(passphrase1));
1450 			explicit_bzero(passphrase2, strlen(passphrase2));
1451 			free(passphrase1);
1452 			free(passphrase2);
1453 			printf("Pass phrases do not match.  Try again.\n");
1454 			exit(1);
1455 		}
1456 		/* Destroy the other copy. */
1457 		freezero(passphrase2, strlen(passphrase2));
1458 	}
1459 
1460 	/* Save the file using the new passphrase. */
1461 	if ((r = sshkey_save_private(private, identity_file, passphrase1,
1462 	    comment, private_key_format, openssh_format_cipher, rounds)) != 0) {
1463 		error("Saving key \"%s\" failed: %s.",
1464 		    identity_file, ssh_err(r));
1465 		freezero(passphrase1, strlen(passphrase1));
1466 		sshkey_free(private);
1467 		free(comment);
1468 		exit(1);
1469 	}
1470 	/* Destroy the passphrase and the copy of the key in memory. */
1471 	freezero(passphrase1, strlen(passphrase1));
1472 	sshkey_free(private);		 /* Destroys contents */
1473 	free(comment);
1474 
1475 	printf("Your identification has been saved with the new passphrase.\n");
1476 	exit(0);
1477 }
1478 
1479 /*
1480  * Print the SSHFP RR.
1481  */
1482 static int
do_print_resource_record(struct passwd * pw,char * fname,char * hname,int print_generic)1483 do_print_resource_record(struct passwd *pw, char *fname, char *hname,
1484     int print_generic)
1485 {
1486 	struct sshkey *public;
1487 	char *comment = NULL;
1488 	struct stat st;
1489 	int r;
1490 
1491 	if (fname == NULL)
1492 		fatal("%s: no filename", __func__);
1493 	if (stat(fname, &st) == -1) {
1494 		if (errno == ENOENT)
1495 			return 0;
1496 		fatal("%s: %s", fname, strerror(errno));
1497 	}
1498 	if ((r = sshkey_load_public(fname, &public, &comment)) != 0)
1499 		fatal("Failed to read v2 public key from \"%s\": %s.",
1500 		    fname, ssh_err(r));
1501 	export_dns_rr(hname, public, stdout, print_generic);
1502 	sshkey_free(public);
1503 	free(comment);
1504 	return 1;
1505 }
1506 
1507 /*
1508  * Change the comment of a private key file.
1509  */
1510 static void
do_change_comment(struct passwd * pw,const char * identity_comment)1511 do_change_comment(struct passwd *pw, const char *identity_comment)
1512 {
1513 	char new_comment[1024], *comment, *passphrase;
1514 	struct sshkey *private;
1515 	struct sshkey *public;
1516 	struct stat st;
1517 	FILE *f;
1518 	int r, fd;
1519 
1520 	if (!have_identity)
1521 		ask_filename(pw, "Enter file in which the key is");
1522 	if (stat(identity_file, &st) == -1)
1523 		fatal("%s: %s", identity_file, strerror(errno));
1524 	if ((r = sshkey_load_private(identity_file, "",
1525 	    &private, &comment)) == 0)
1526 		passphrase = xstrdup("");
1527 	else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
1528 		fatal("Cannot load private key \"%s\": %s.",
1529 		    identity_file, ssh_err(r));
1530 	else {
1531 		if (identity_passphrase)
1532 			passphrase = xstrdup(identity_passphrase);
1533 		else if (identity_new_passphrase)
1534 			passphrase = xstrdup(identity_new_passphrase);
1535 		else
1536 			passphrase = read_passphrase("Enter passphrase: ",
1537 			    RP_ALLOW_STDIN);
1538 		/* Try to load using the passphrase. */
1539 		if ((r = sshkey_load_private(identity_file, passphrase,
1540 		    &private, &comment)) != 0) {
1541 			freezero(passphrase, strlen(passphrase));
1542 			fatal("Cannot load private key \"%s\": %s.",
1543 			    identity_file, ssh_err(r));
1544 		}
1545 	}
1546 
1547 	if (private->type != KEY_ED25519 && private->type != KEY_XMSS &&
1548 	    private_key_format != SSHKEY_PRIVATE_OPENSSH) {
1549 		error("Comments are only supported for keys stored in "
1550 		    "the new format (-o).");
1551 		explicit_bzero(passphrase, strlen(passphrase));
1552 		sshkey_free(private);
1553 		exit(1);
1554 	}
1555 	if (comment)
1556 		printf("Old comment: %s\n", comment);
1557 	else
1558 		printf("No existing comment\n");
1559 
1560 	if (identity_comment) {
1561 		strlcpy(new_comment, identity_comment, sizeof(new_comment));
1562 	} else {
1563 		printf("New comment: ");
1564 		fflush(stdout);
1565 		if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1566 			explicit_bzero(passphrase, strlen(passphrase));
1567 			sshkey_free(private);
1568 			exit(1);
1569 		}
1570 		new_comment[strcspn(new_comment, "\n")] = '\0';
1571 	}
1572 	if (comment != NULL && strcmp(comment, new_comment) == 0) {
1573 		printf("No change to comment\n");
1574 		free(passphrase);
1575 		sshkey_free(private);
1576 		free(comment);
1577 		exit(0);
1578 	}
1579 
1580 	/* Save the file using the new passphrase. */
1581 	if ((r = sshkey_save_private(private, identity_file, passphrase,
1582 	    new_comment, private_key_format, openssh_format_cipher,
1583 	    rounds)) != 0) {
1584 		error("Saving key \"%s\" failed: %s",
1585 		    identity_file, ssh_err(r));
1586 		freezero(passphrase, strlen(passphrase));
1587 		sshkey_free(private);
1588 		free(comment);
1589 		exit(1);
1590 	}
1591 	freezero(passphrase, strlen(passphrase));
1592 	if ((r = sshkey_from_private(private, &public)) != 0)
1593 		fatal("sshkey_from_private failed: %s", ssh_err(r));
1594 	sshkey_free(private);
1595 
1596 	strlcat(identity_file, ".pub", sizeof(identity_file));
1597 	fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1598 	if (fd == -1)
1599 		fatal("Could not save your public key in %s", identity_file);
1600 	f = fdopen(fd, "w");
1601 	if (f == NULL)
1602 		fatal("fdopen %s failed: %s", identity_file, strerror(errno));
1603 	if ((r = sshkey_write(public, f)) != 0)
1604 		fatal("write key failed: %s", ssh_err(r));
1605 	sshkey_free(public);
1606 	fprintf(f, " %s\n", new_comment);
1607 	fclose(f);
1608 
1609 	free(comment);
1610 
1611 	if (strlen(new_comment) > 0)
1612 		printf("Comment '%s' applied\n", new_comment);
1613 	else
1614 		printf("Comment removed\n");
1615 
1616 	exit(0);
1617 }
1618 
1619 static void
add_flag_option(struct sshbuf * c,const char * name)1620 add_flag_option(struct sshbuf *c, const char *name)
1621 {
1622 	int r;
1623 
1624 	debug3("%s: %s", __func__, name);
1625 	if ((r = sshbuf_put_cstring(c, name)) != 0 ||
1626 	    (r = sshbuf_put_string(c, NULL, 0)) != 0)
1627 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1628 }
1629 
1630 static void
add_string_option(struct sshbuf * c,const char * name,const char * value)1631 add_string_option(struct sshbuf *c, const char *name, const char *value)
1632 {
1633 	struct sshbuf *b;
1634 	int r;
1635 
1636 	debug3("%s: %s=%s", __func__, name, value);
1637 	if ((b = sshbuf_new()) == NULL)
1638 		fatal("%s: sshbuf_new failed", __func__);
1639 	if ((r = sshbuf_put_cstring(b, value)) != 0 ||
1640 	    (r = sshbuf_put_cstring(c, name)) != 0 ||
1641 	    (r = sshbuf_put_stringb(c, b)) != 0)
1642 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1643 
1644 	sshbuf_free(b);
1645 }
1646 
1647 #define OPTIONS_CRITICAL	1
1648 #define OPTIONS_EXTENSIONS	2
1649 static void
prepare_options_buf(struct sshbuf * c,int which)1650 prepare_options_buf(struct sshbuf *c, int which)
1651 {
1652 	size_t i;
1653 
1654 	sshbuf_reset(c);
1655 	if ((which & OPTIONS_CRITICAL) != 0 &&
1656 	    certflags_command != NULL)
1657 		add_string_option(c, "force-command", certflags_command);
1658 	if ((which & OPTIONS_EXTENSIONS) != 0 &&
1659 	    (certflags_flags & CERTOPT_X_FWD) != 0)
1660 		add_flag_option(c, "permit-X11-forwarding");
1661 	if ((which & OPTIONS_EXTENSIONS) != 0 &&
1662 	    (certflags_flags & CERTOPT_AGENT_FWD) != 0)
1663 		add_flag_option(c, "permit-agent-forwarding");
1664 	if ((which & OPTIONS_EXTENSIONS) != 0 &&
1665 	    (certflags_flags & CERTOPT_PORT_FWD) != 0)
1666 		add_flag_option(c, "permit-port-forwarding");
1667 	if ((which & OPTIONS_EXTENSIONS) != 0 &&
1668 	    (certflags_flags & CERTOPT_PTY) != 0)
1669 		add_flag_option(c, "permit-pty");
1670 	if ((which & OPTIONS_EXTENSIONS) != 0 &&
1671 	    (certflags_flags & CERTOPT_USER_RC) != 0)
1672 		add_flag_option(c, "permit-user-rc");
1673 	if ((which & OPTIONS_EXTENSIONS) != 0 &&
1674 	    (certflags_flags & CERTOPT_NO_REQUIRE_USER_PRESENCE) != 0)
1675 		add_flag_option(c, "no-touch-required");
1676 	if ((which & OPTIONS_CRITICAL) != 0 &&
1677 	    certflags_src_addr != NULL)
1678 		add_string_option(c, "source-address", certflags_src_addr);
1679 	for (i = 0; i < ncert_userext; i++) {
1680 		if ((cert_userext[i].crit && (which & OPTIONS_EXTENSIONS)) ||
1681 		    (!cert_userext[i].crit && (which & OPTIONS_CRITICAL)))
1682 			continue;
1683 		if (cert_userext[i].val == NULL)
1684 			add_flag_option(c, cert_userext[i].key);
1685 		else {
1686 			add_string_option(c, cert_userext[i].key,
1687 			    cert_userext[i].val);
1688 		}
1689 	}
1690 }
1691 
1692 static struct sshkey *
load_pkcs11_key(char * path)1693 load_pkcs11_key(char *path)
1694 {
1695 #ifdef ENABLE_PKCS11
1696 	struct sshkey **keys = NULL, *public, *private = NULL;
1697 	int r, i, nkeys;
1698 
1699 	if ((r = sshkey_load_public(path, &public, NULL)) != 0)
1700 		fatal("Couldn't load CA public key \"%s\": %s",
1701 		    path, ssh_err(r));
1702 
1703 	nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase,
1704 	    &keys, NULL);
1705 	debug3("%s: %d keys", __func__, nkeys);
1706 	if (nkeys <= 0)
1707 		fatal("cannot read public key from pkcs11");
1708 	for (i = 0; i < nkeys; i++) {
1709 		if (sshkey_equal_public(public, keys[i])) {
1710 			private = keys[i];
1711 			continue;
1712 		}
1713 		sshkey_free(keys[i]);
1714 	}
1715 	free(keys);
1716 	sshkey_free(public);
1717 	return private;
1718 #else
1719 	fatal("no pkcs11 support");
1720 #endif /* ENABLE_PKCS11 */
1721 }
1722 
1723 /* Signer for sshkey_certify_custom that uses the agent */
1724 static int
agent_signer(struct sshkey * key,u_char ** sigp,size_t * lenp,const u_char * data,size_t datalen,const char * alg,const char * provider,u_int compat,void * ctx)1725 agent_signer(struct sshkey *key, u_char **sigp, size_t *lenp,
1726     const u_char *data, size_t datalen,
1727     const char *alg, const char *provider, u_int compat, void *ctx)
1728 {
1729 	int *agent_fdp = (int *)ctx;
1730 
1731 	return ssh_agent_sign(*agent_fdp, key, sigp, lenp,
1732 	    data, datalen, alg, compat);
1733 }
1734 
1735 static void
do_ca_sign(struct passwd * pw,const char * ca_key_path,int prefer_agent,unsigned long long cert_serial,int cert_serial_autoinc,int argc,char ** argv)1736 do_ca_sign(struct passwd *pw, const char *ca_key_path, int prefer_agent,
1737     unsigned long long cert_serial, int cert_serial_autoinc,
1738     int argc, char **argv)
1739 {
1740 	int r, i, fd, found, agent_fd = -1;
1741 	u_int n;
1742 	struct sshkey *ca, *public;
1743 	char valid[64], *otmp, *tmp, *cp, *out, *comment;
1744 	char *ca_fp = NULL, **plist = NULL;
1745 	FILE *f;
1746 	struct ssh_identitylist *agent_ids;
1747 	size_t j;
1748 	struct notifier_ctx *notifier = NULL;
1749 
1750 #ifdef ENABLE_PKCS11
1751 	pkcs11_init(1);
1752 #endif
1753 	tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
1754 	if (pkcs11provider != NULL) {
1755 		/* If a PKCS#11 token was specified then try to use it */
1756 		if ((ca = load_pkcs11_key(tmp)) == NULL)
1757 			fatal("No PKCS#11 key matching %s found", ca_key_path);
1758 	} else if (prefer_agent) {
1759 		/*
1760 		 * Agent signature requested. Try to use agent after making
1761 		 * sure the public key specified is actually present in the
1762 		 * agent.
1763 		 */
1764 		if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
1765 			fatal("Cannot load CA public key %s: %s",
1766 			    tmp, ssh_err(r));
1767 		if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
1768 			fatal("Cannot use public key for CA signature: %s",
1769 			    ssh_err(r));
1770 		if ((r = ssh_fetch_identitylist(agent_fd, &agent_ids)) != 0)
1771 			fatal("Retrieve agent key list: %s", ssh_err(r));
1772 		found = 0;
1773 		for (j = 0; j < agent_ids->nkeys; j++) {
1774 			if (sshkey_equal(ca, agent_ids->keys[j])) {
1775 				found = 1;
1776 				break;
1777 			}
1778 		}
1779 		if (!found)
1780 			fatal("CA key %s not found in agent", tmp);
1781 		ssh_free_identitylist(agent_ids);
1782 		ca->flags |= SSHKEY_FLAG_EXT;
1783 	} else {
1784 		/* CA key is assumed to be a private key on the filesystem */
1785 		ca = load_identity(tmp, NULL);
1786 	}
1787 	free(tmp);
1788 
1789 	if (key_type_name != NULL) {
1790 		if (sshkey_type_from_name(key_type_name) != ca->type) {
1791 			fatal("CA key type %s doesn't match specified %s",
1792 			    sshkey_ssh_name(ca), key_type_name);
1793 		}
1794 	} else if (ca->type == KEY_RSA) {
1795 		/* Default to a good signature algorithm */
1796 		key_type_name = "rsa-sha2-512";
1797 	}
1798 	ca_fp = sshkey_fingerprint(ca, fingerprint_hash, SSH_FP_DEFAULT);
1799 
1800 	for (i = 0; i < argc; i++) {
1801 		/* Split list of principals */
1802 		n = 0;
1803 		if (cert_principals != NULL) {
1804 			otmp = tmp = xstrdup(cert_principals);
1805 			plist = NULL;
1806 			for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1807 				plist = xreallocarray(plist, n + 1, sizeof(*plist));
1808 				if (*(plist[n] = xstrdup(cp)) == '\0')
1809 					fatal("Empty principal name");
1810 			}
1811 			free(otmp);
1812 		}
1813 		if (n > SSHKEY_CERT_MAX_PRINCIPALS)
1814 			fatal("Too many certificate principals specified");
1815 
1816 		tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1817 		if ((r = sshkey_load_public(tmp, &public, &comment)) != 0)
1818 			fatal("%s: unable to open \"%s\": %s",
1819 			    __func__, tmp, ssh_err(r));
1820 		if (sshkey_is_cert(public))
1821 			fatal("%s: key \"%s\" type %s cannot be certified",
1822 			    __func__, tmp, sshkey_type(public));
1823 
1824 		/* Prepare certificate to sign */
1825 		if ((r = sshkey_to_certified(public)) != 0)
1826 			fatal("Could not upgrade key %s to certificate: %s",
1827 			    tmp, ssh_err(r));
1828 		public->cert->type = cert_key_type;
1829 		public->cert->serial = (u_int64_t)cert_serial;
1830 		public->cert->key_id = xstrdup(cert_key_id);
1831 		public->cert->nprincipals = n;
1832 		public->cert->principals = plist;
1833 		public->cert->valid_after = cert_valid_from;
1834 		public->cert->valid_before = cert_valid_to;
1835 		prepare_options_buf(public->cert->critical, OPTIONS_CRITICAL);
1836 		prepare_options_buf(public->cert->extensions,
1837 		    OPTIONS_EXTENSIONS);
1838 		if ((r = sshkey_from_private(ca,
1839 		    &public->cert->signature_key)) != 0)
1840 			fatal("sshkey_from_private (ca key): %s", ssh_err(r));
1841 
1842 		if (agent_fd != -1 && (ca->flags & SSHKEY_FLAG_EXT) != 0) {
1843 			if ((r = sshkey_certify_custom(public, ca,
1844 			    key_type_name, sk_provider, agent_signer,
1845 			    &agent_fd)) != 0)
1846 				fatal("Couldn't certify key %s via agent: %s",
1847 				    tmp, ssh_err(r));
1848 		} else {
1849 			if (sshkey_is_sk(ca) &&
1850 			    (ca->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
1851 				notifier = notify_start(0,
1852 				    "Confirm user presence for key %s %s",
1853 				    sshkey_type(ca), ca_fp);
1854 			}
1855 			r = sshkey_certify(public, ca, key_type_name,
1856 			    sk_provider);
1857 			notify_complete(notifier);
1858 			if (r != 0)
1859 				fatal("Couldn't certify key %s: %s",
1860 				    tmp, ssh_err(r));
1861 		}
1862 
1863 		if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
1864 			*cp = '\0';
1865 		xasprintf(&out, "%s-cert.pub", tmp);
1866 		free(tmp);
1867 
1868 		if ((fd = open(out, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
1869 			fatal("Could not open \"%s\" for writing: %s", out,
1870 			    strerror(errno));
1871 		if ((f = fdopen(fd, "w")) == NULL)
1872 			fatal("%s: fdopen: %s", __func__, strerror(errno));
1873 		if ((r = sshkey_write(public, f)) != 0)
1874 			fatal("Could not write certified key to %s: %s",
1875 			    out, ssh_err(r));
1876 		fprintf(f, " %s\n", comment);
1877 		fclose(f);
1878 
1879 		if (!quiet) {
1880 			sshkey_format_cert_validity(public->cert,
1881 			    valid, sizeof(valid));
1882 			logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1883 			    "valid %s", sshkey_cert_type(public),
1884 			    out, public->cert->key_id,
1885 			    (unsigned long long)public->cert->serial,
1886 			    cert_principals != NULL ? " for " : "",
1887 			    cert_principals != NULL ? cert_principals : "",
1888 			    valid);
1889 		}
1890 
1891 		sshkey_free(public);
1892 		free(out);
1893 		if (cert_serial_autoinc)
1894 			cert_serial++;
1895 	}
1896 	free(ca_fp);
1897 #ifdef ENABLE_PKCS11
1898 	pkcs11_terminate();
1899 #endif
1900 	exit(0);
1901 }
1902 
1903 static u_int64_t
parse_relative_time(const char * s,time_t now)1904 parse_relative_time(const char *s, time_t now)
1905 {
1906 	int64_t mul, secs;
1907 
1908 	mul = *s == '-' ? -1 : 1;
1909 
1910 	if ((secs = convtime(s + 1)) == -1)
1911 		fatal("Invalid relative certificate time %s", s);
1912 	if (mul == -1 && secs > now)
1913 		fatal("Certificate time %s cannot be represented", s);
1914 	return now + (u_int64_t)(secs * mul);
1915 }
1916 
1917 static void
parse_cert_times(char * timespec)1918 parse_cert_times(char *timespec)
1919 {
1920 	char *from, *to;
1921 	time_t now = time(NULL);
1922 	int64_t secs;
1923 
1924 	/* +timespec relative to now */
1925 	if (*timespec == '+' && strchr(timespec, ':') == NULL) {
1926 		if ((secs = convtime(timespec + 1)) == -1)
1927 			fatal("Invalid relative certificate life %s", timespec);
1928 		cert_valid_to = now + secs;
1929 		/*
1930 		 * Backdate certificate one minute to avoid problems on hosts
1931 		 * with poorly-synchronised clocks.
1932 		 */
1933 		cert_valid_from = ((now - 59)/ 60) * 60;
1934 		return;
1935 	}
1936 
1937 	/*
1938 	 * from:to, where
1939 	 * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "always"
1940 	 *   to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "forever"
1941 	 */
1942 	from = xstrdup(timespec);
1943 	to = strchr(from, ':');
1944 	if (to == NULL || from == to || *(to + 1) == '\0')
1945 		fatal("Invalid certificate life specification %s", timespec);
1946 	*to++ = '\0';
1947 
1948 	if (*from == '-' || *from == '+')
1949 		cert_valid_from = parse_relative_time(from, now);
1950 	else if (strcmp(from, "always") == 0)
1951 		cert_valid_from = 0;
1952 	else if (parse_absolute_time(from, &cert_valid_from) != 0)
1953 		fatal("Invalid from time \"%s\"", from);
1954 
1955 	if (*to == '-' || *to == '+')
1956 		cert_valid_to = parse_relative_time(to, now);
1957 	else if (strcmp(to, "forever") == 0)
1958 		cert_valid_to = ~(u_int64_t)0;
1959 	else if (parse_absolute_time(to, &cert_valid_to) != 0)
1960 		fatal("Invalid to time \"%s\"", to);
1961 
1962 	if (cert_valid_to <= cert_valid_from)
1963 		fatal("Empty certificate validity interval");
1964 	free(from);
1965 }
1966 
1967 static void
add_cert_option(char * opt)1968 add_cert_option(char *opt)
1969 {
1970 	char *val, *cp;
1971 	int iscrit = 0;
1972 
1973 	if (strcasecmp(opt, "clear") == 0)
1974 		certflags_flags = 0;
1975 	else if (strcasecmp(opt, "no-x11-forwarding") == 0)
1976 		certflags_flags &= ~CERTOPT_X_FWD;
1977 	else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
1978 		certflags_flags |= CERTOPT_X_FWD;
1979 	else if (strcasecmp(opt, "no-agent-forwarding") == 0)
1980 		certflags_flags &= ~CERTOPT_AGENT_FWD;
1981 	else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
1982 		certflags_flags |= CERTOPT_AGENT_FWD;
1983 	else if (strcasecmp(opt, "no-port-forwarding") == 0)
1984 		certflags_flags &= ~CERTOPT_PORT_FWD;
1985 	else if (strcasecmp(opt, "permit-port-forwarding") == 0)
1986 		certflags_flags |= CERTOPT_PORT_FWD;
1987 	else if (strcasecmp(opt, "no-pty") == 0)
1988 		certflags_flags &= ~CERTOPT_PTY;
1989 	else if (strcasecmp(opt, "permit-pty") == 0)
1990 		certflags_flags |= CERTOPT_PTY;
1991 	else if (strcasecmp(opt, "no-user-rc") == 0)
1992 		certflags_flags &= ~CERTOPT_USER_RC;
1993 	else if (strcasecmp(opt, "permit-user-rc") == 0)
1994 		certflags_flags |= CERTOPT_USER_RC;
1995 	else if (strcasecmp(opt, "touch-required") == 0)
1996 		certflags_flags &= ~CERTOPT_NO_REQUIRE_USER_PRESENCE;
1997 	else if (strcasecmp(opt, "no-touch-required") == 0)
1998 		certflags_flags |= CERTOPT_NO_REQUIRE_USER_PRESENCE;
1999 	else if (strncasecmp(opt, "force-command=", 14) == 0) {
2000 		val = opt + 14;
2001 		if (*val == '\0')
2002 			fatal("Empty force-command option");
2003 		if (certflags_command != NULL)
2004 			fatal("force-command already specified");
2005 		certflags_command = xstrdup(val);
2006 	} else if (strncasecmp(opt, "source-address=", 15) == 0) {
2007 		val = opt + 15;
2008 		if (*val == '\0')
2009 			fatal("Empty source-address option");
2010 		if (certflags_src_addr != NULL)
2011 			fatal("source-address already specified");
2012 		if (addr_match_cidr_list(NULL, val) != 0)
2013 			fatal("Invalid source-address list");
2014 		certflags_src_addr = xstrdup(val);
2015 	} else if (strncasecmp(opt, "extension:", 10) == 0 ||
2016 		   (iscrit = (strncasecmp(opt, "critical:", 9) == 0))) {
2017 		val = xstrdup(strchr(opt, ':') + 1);
2018 		if ((cp = strchr(val, '=')) != NULL)
2019 			*cp++ = '\0';
2020 		cert_userext = xreallocarray(cert_userext, ncert_userext + 1,
2021 		    sizeof(*cert_userext));
2022 		cert_userext[ncert_userext].key = val;
2023 		cert_userext[ncert_userext].val = cp == NULL ?
2024 		    NULL : xstrdup(cp);
2025 		cert_userext[ncert_userext].crit = iscrit;
2026 		ncert_userext++;
2027 	} else
2028 		fatal("Unsupported certificate option \"%s\"", opt);
2029 }
2030 
2031 static void
show_options(struct sshbuf * optbuf,int in_critical)2032 show_options(struct sshbuf *optbuf, int in_critical)
2033 {
2034 	char *name, *arg;
2035 	struct sshbuf *options, *option = NULL;
2036 	int r;
2037 
2038 	if ((options = sshbuf_fromb(optbuf)) == NULL)
2039 		fatal("%s: sshbuf_fromb failed", __func__);
2040 	while (sshbuf_len(options) != 0) {
2041 		sshbuf_free(option);
2042 		option = NULL;
2043 		if ((r = sshbuf_get_cstring(options, &name, NULL)) != 0 ||
2044 		    (r = sshbuf_froms(options, &option)) != 0)
2045 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
2046 		printf("                %s", name);
2047 		if (!in_critical &&
2048 		    (strcmp(name, "permit-X11-forwarding") == 0 ||
2049 		    strcmp(name, "permit-agent-forwarding") == 0 ||
2050 		    strcmp(name, "permit-port-forwarding") == 0 ||
2051 		    strcmp(name, "permit-pty") == 0 ||
2052 		    strcmp(name, "permit-user-rc") == 0 ||
2053 		    strcmp(name, "no-touch-required") == 0)) {
2054 			printf("\n");
2055 		} else if (in_critical &&
2056 		    (strcmp(name, "force-command") == 0 ||
2057 		    strcmp(name, "source-address") == 0)) {
2058 			if ((r = sshbuf_get_cstring(option, &arg, NULL)) != 0)
2059 				fatal("%s: buffer error: %s",
2060 				    __func__, ssh_err(r));
2061 			printf(" %s\n", arg);
2062 			free(arg);
2063 		} else {
2064 			printf(" UNKNOWN OPTION (len %zu)\n",
2065 			    sshbuf_len(option));
2066 			sshbuf_reset(option);
2067 		}
2068 		free(name);
2069 		if (sshbuf_len(option) != 0)
2070 			fatal("Option corrupt: extra data at end");
2071 	}
2072 	sshbuf_free(option);
2073 	sshbuf_free(options);
2074 }
2075 
2076 static void
print_cert(struct sshkey * key)2077 print_cert(struct sshkey *key)
2078 {
2079 	char valid[64], *key_fp, *ca_fp;
2080 	u_int i;
2081 
2082 	key_fp = sshkey_fingerprint(key, fingerprint_hash, SSH_FP_DEFAULT);
2083 	ca_fp = sshkey_fingerprint(key->cert->signature_key,
2084 	    fingerprint_hash, SSH_FP_DEFAULT);
2085 	if (key_fp == NULL || ca_fp == NULL)
2086 		fatal("%s: sshkey_fingerprint fail", __func__);
2087 	sshkey_format_cert_validity(key->cert, valid, sizeof(valid));
2088 
2089 	printf("        Type: %s %s certificate\n", sshkey_ssh_name(key),
2090 	    sshkey_cert_type(key));
2091 	printf("        Public key: %s %s\n", sshkey_type(key), key_fp);
2092 	printf("        Signing CA: %s %s (using %s)\n",
2093 	    sshkey_type(key->cert->signature_key), ca_fp,
2094 	    key->cert->signature_type);
2095 	printf("        Key ID: \"%s\"\n", key->cert->key_id);
2096 	printf("        Serial: %llu\n", (unsigned long long)key->cert->serial);
2097 	printf("        Valid: %s\n", valid);
2098 	printf("        Principals: ");
2099 	if (key->cert->nprincipals == 0)
2100 		printf("(none)\n");
2101 	else {
2102 		for (i = 0; i < key->cert->nprincipals; i++)
2103 			printf("\n                %s",
2104 			    key->cert->principals[i]);
2105 		printf("\n");
2106 	}
2107 	printf("        Critical Options: ");
2108 	if (sshbuf_len(key->cert->critical) == 0)
2109 		printf("(none)\n");
2110 	else {
2111 		printf("\n");
2112 		show_options(key->cert->critical, 1);
2113 	}
2114 	printf("        Extensions: ");
2115 	if (sshbuf_len(key->cert->extensions) == 0)
2116 		printf("(none)\n");
2117 	else {
2118 		printf("\n");
2119 		show_options(key->cert->extensions, 0);
2120 	}
2121 }
2122 
2123 static void
do_show_cert(struct passwd * pw)2124 do_show_cert(struct passwd *pw)
2125 {
2126 	struct sshkey *key = NULL;
2127 	struct stat st;
2128 	int r, is_stdin = 0, ok = 0;
2129 	FILE *f;
2130 	char *cp, *line = NULL;
2131 	const char *path;
2132 	size_t linesize = 0;
2133 	u_long lnum = 0;
2134 
2135 	if (!have_identity)
2136 		ask_filename(pw, "Enter file in which the key is");
2137 	if (strcmp(identity_file, "-") != 0 && stat(identity_file, &st) == -1)
2138 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
2139 
2140 	path = identity_file;
2141 	if (strcmp(path, "-") == 0) {
2142 		f = stdin;
2143 		path = "(stdin)";
2144 		is_stdin = 1;
2145 	} else if ((f = fopen(identity_file, "r")) == NULL)
2146 		fatal("fopen %s: %s", identity_file, strerror(errno));
2147 
2148 	while (getline(&line, &linesize, f) != -1) {
2149 		lnum++;
2150 		sshkey_free(key);
2151 		key = NULL;
2152 		/* Trim leading space and comments */
2153 		cp = line + strspn(line, " \t");
2154 		if (*cp == '#' || *cp == '\0')
2155 			continue;
2156 		if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2157 			fatal("sshkey_new");
2158 		if ((r = sshkey_read(key, &cp)) != 0) {
2159 			error("%s:%lu: invalid key: %s", path,
2160 			    lnum, ssh_err(r));
2161 			continue;
2162 		}
2163 		if (!sshkey_is_cert(key)) {
2164 			error("%s:%lu is not a certificate", path, lnum);
2165 			continue;
2166 		}
2167 		ok = 1;
2168 		if (!is_stdin && lnum == 1)
2169 			printf("%s:\n", path);
2170 		else
2171 			printf("%s:%lu:\n", path, lnum);
2172 		print_cert(key);
2173 	}
2174 	free(line);
2175 	sshkey_free(key);
2176 	fclose(f);
2177 	exit(ok ? 0 : 1);
2178 }
2179 
2180 static void
load_krl(const char * path,struct ssh_krl ** krlp)2181 load_krl(const char *path, struct ssh_krl **krlp)
2182 {
2183 	struct sshbuf *krlbuf;
2184 	int r;
2185 
2186 	if ((r = sshbuf_load_file(path, &krlbuf)) != 0)
2187 		fatal("Unable to load KRL: %s", ssh_err(r));
2188 	/* XXX check sigs */
2189 	if ((r = ssh_krl_from_blob(krlbuf, krlp, NULL, 0)) != 0 ||
2190 	    *krlp == NULL)
2191 		fatal("Invalid KRL file: %s", ssh_err(r));
2192 	sshbuf_free(krlbuf);
2193 }
2194 
2195 static void
hash_to_blob(const char * cp,u_char ** blobp,size_t * lenp,const char * file,u_long lnum)2196 hash_to_blob(const char *cp, u_char **blobp, size_t *lenp,
2197     const char *file, u_long lnum)
2198 {
2199 	char *tmp;
2200 	size_t tlen;
2201 	struct sshbuf *b;
2202 	int r;
2203 
2204 	if (strncmp(cp, "SHA256:", 7) != 0)
2205 		fatal("%s:%lu: unsupported hash algorithm", file, lnum);
2206 	cp += 7;
2207 
2208 	/*
2209 	 * OpenSSH base64 hashes omit trailing '='
2210 	 * characters; put them back for decode.
2211 	 */
2212 	tlen = strlen(cp);
2213 	tmp = xmalloc(tlen + 4 + 1);
2214 	strlcpy(tmp, cp, tlen + 1);
2215 	while ((tlen % 4) != 0) {
2216 		tmp[tlen++] = '=';
2217 		tmp[tlen] = '\0';
2218 	}
2219 	if ((b = sshbuf_new()) == NULL)
2220 		fatal("%s: sshbuf_new failed", __func__);
2221 	if ((r = sshbuf_b64tod(b, tmp)) != 0)
2222 		fatal("%s:%lu: decode hash failed: %s", file, lnum, ssh_err(r));
2223 	free(tmp);
2224 	*lenp = sshbuf_len(b);
2225 	*blobp = xmalloc(*lenp);
2226 	memcpy(*blobp, sshbuf_ptr(b), *lenp);
2227 	sshbuf_free(b);
2228 }
2229 
2230 static void
update_krl_from_file(struct passwd * pw,const char * file,int wild_ca,const struct sshkey * ca,struct ssh_krl * krl)2231 update_krl_from_file(struct passwd *pw, const char *file, int wild_ca,
2232     const struct sshkey *ca, struct ssh_krl *krl)
2233 {
2234 	struct sshkey *key = NULL;
2235 	u_long lnum = 0;
2236 	char *path, *cp, *ep, *line = NULL;
2237 	u_char *blob = NULL;
2238 	size_t blen = 0, linesize = 0;
2239 	unsigned long long serial, serial2;
2240 	int i, was_explicit_key, was_sha1, was_sha256, was_hash, r;
2241 	FILE *krl_spec;
2242 
2243 	path = tilde_expand_filename(file, pw->pw_uid);
2244 	if (strcmp(path, "-") == 0) {
2245 		krl_spec = stdin;
2246 		free(path);
2247 		path = xstrdup("(standard input)");
2248 	} else if ((krl_spec = fopen(path, "r")) == NULL)
2249 		fatal("fopen %s: %s", path, strerror(errno));
2250 
2251 	if (!quiet)
2252 		printf("Revoking from %s\n", path);
2253 	while (getline(&line, &linesize, krl_spec) != -1) {
2254 		lnum++;
2255 		was_explicit_key = was_sha1 = was_sha256 = was_hash = 0;
2256 		cp = line + strspn(line, " \t");
2257 		/* Trim trailing space, comments and strip \n */
2258 		for (i = 0, r = -1; cp[i] != '\0'; i++) {
2259 			if (cp[i] == '#' || cp[i] == '\n') {
2260 				cp[i] = '\0';
2261 				break;
2262 			}
2263 			if (cp[i] == ' ' || cp[i] == '\t') {
2264 				/* Remember the start of a span of whitespace */
2265 				if (r == -1)
2266 					r = i;
2267 			} else
2268 				r = -1;
2269 		}
2270 		if (r != -1)
2271 			cp[r] = '\0';
2272 		if (*cp == '\0')
2273 			continue;
2274 		if (strncasecmp(cp, "serial:", 7) == 0) {
2275 			if (ca == NULL && !wild_ca) {
2276 				fatal("revoking certificates by serial number "
2277 				    "requires specification of a CA key");
2278 			}
2279 			cp += 7;
2280 			cp = cp + strspn(cp, " \t");
2281 			errno = 0;
2282 			serial = strtoull(cp, &ep, 0);
2283 			if (*cp == '\0' || (*ep != '\0' && *ep != '-'))
2284 				fatal("%s:%lu: invalid serial \"%s\"",
2285 				    path, lnum, cp);
2286 			if (errno == ERANGE && serial == ULLONG_MAX)
2287 				fatal("%s:%lu: serial out of range",
2288 				    path, lnum);
2289 			serial2 = serial;
2290 			if (*ep == '-') {
2291 				cp = ep + 1;
2292 				errno = 0;
2293 				serial2 = strtoull(cp, &ep, 0);
2294 				if (*cp == '\0' || *ep != '\0')
2295 					fatal("%s:%lu: invalid serial \"%s\"",
2296 					    path, lnum, cp);
2297 				if (errno == ERANGE && serial2 == ULLONG_MAX)
2298 					fatal("%s:%lu: serial out of range",
2299 					    path, lnum);
2300 				if (serial2 <= serial)
2301 					fatal("%s:%lu: invalid serial range "
2302 					    "%llu:%llu", path, lnum,
2303 					    (unsigned long long)serial,
2304 					    (unsigned long long)serial2);
2305 			}
2306 			if (ssh_krl_revoke_cert_by_serial_range(krl,
2307 			    ca, serial, serial2) != 0) {
2308 				fatal("%s: revoke serial failed",
2309 				    __func__);
2310 			}
2311 		} else if (strncasecmp(cp, "id:", 3) == 0) {
2312 			if (ca == NULL && !wild_ca) {
2313 				fatal("revoking certificates by key ID "
2314 				    "requires specification of a CA key");
2315 			}
2316 			cp += 3;
2317 			cp = cp + strspn(cp, " \t");
2318 			if (ssh_krl_revoke_cert_by_key_id(krl, ca, cp) != 0)
2319 				fatal("%s: revoke key ID failed", __func__);
2320 		} else if (strncasecmp(cp, "hash:", 5) == 0) {
2321 			cp += 5;
2322 			cp = cp + strspn(cp, " \t");
2323 			hash_to_blob(cp, &blob, &blen, file, lnum);
2324 			r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2325 			if (r != 0)
2326 				fatal("%s: revoke key failed: %s",
2327 				    __func__, ssh_err(r));
2328 		} else {
2329 			if (strncasecmp(cp, "key:", 4) == 0) {
2330 				cp += 4;
2331 				cp = cp + strspn(cp, " \t");
2332 				was_explicit_key = 1;
2333 			} else if (strncasecmp(cp, "sha1:", 5) == 0) {
2334 				cp += 5;
2335 				cp = cp + strspn(cp, " \t");
2336 				was_sha1 = 1;
2337 			} else if (strncasecmp(cp, "sha256:", 7) == 0) {
2338 				cp += 7;
2339 				cp = cp + strspn(cp, " \t");
2340 				was_sha256 = 1;
2341 				/*
2342 				 * Just try to process the line as a key.
2343 				 * Parsing will fail if it isn't.
2344 				 */
2345 			}
2346 			if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2347 				fatal("sshkey_new");
2348 			if ((r = sshkey_read(key, &cp)) != 0)
2349 				fatal("%s:%lu: invalid key: %s",
2350 				    path, lnum, ssh_err(r));
2351 			if (was_explicit_key)
2352 				r = ssh_krl_revoke_key_explicit(krl, key);
2353 			else if (was_sha1) {
2354 				if (sshkey_fingerprint_raw(key,
2355 				    SSH_DIGEST_SHA1, &blob, &blen) != 0) {
2356 					fatal("%s:%lu: fingerprint failed",
2357 					    file, lnum);
2358 				}
2359 				r = ssh_krl_revoke_key_sha1(krl, blob, blen);
2360 			} else if (was_sha256) {
2361 				if (sshkey_fingerprint_raw(key,
2362 				    SSH_DIGEST_SHA256, &blob, &blen) != 0) {
2363 					fatal("%s:%lu: fingerprint failed",
2364 					    file, lnum);
2365 				}
2366 				r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2367 			} else
2368 				r = ssh_krl_revoke_key(krl, key);
2369 			if (r != 0)
2370 				fatal("%s: revoke key failed: %s",
2371 				    __func__, ssh_err(r));
2372 			freezero(blob, blen);
2373 			blob = NULL;
2374 			blen = 0;
2375 			sshkey_free(key);
2376 		}
2377 	}
2378 	if (strcmp(path, "-") != 0)
2379 		fclose(krl_spec);
2380 	free(line);
2381 	free(path);
2382 }
2383 
2384 static void
do_gen_krl(struct passwd * pw,int updating,const char * ca_key_path,unsigned long long krl_version,const char * krl_comment,int argc,char ** argv)2385 do_gen_krl(struct passwd *pw, int updating, const char *ca_key_path,
2386     unsigned long long krl_version, const char *krl_comment,
2387     int argc, char **argv)
2388 {
2389 	struct ssh_krl *krl;
2390 	struct stat sb;
2391 	struct sshkey *ca = NULL;
2392 	int i, r, wild_ca = 0;
2393 	char *tmp;
2394 	struct sshbuf *kbuf;
2395 
2396 	if (*identity_file == '\0')
2397 		fatal("KRL generation requires an output file");
2398 	if (stat(identity_file, &sb) == -1) {
2399 		if (errno != ENOENT)
2400 			fatal("Cannot access KRL \"%s\": %s",
2401 			    identity_file, strerror(errno));
2402 		if (updating)
2403 			fatal("KRL \"%s\" does not exist", identity_file);
2404 	}
2405 	if (ca_key_path != NULL) {
2406 		if (strcasecmp(ca_key_path, "none") == 0)
2407 			wild_ca = 1;
2408 		else {
2409 			tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
2410 			if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
2411 				fatal("Cannot load CA public key %s: %s",
2412 				    tmp, ssh_err(r));
2413 			free(tmp);
2414 		}
2415 	}
2416 
2417 	if (updating)
2418 		load_krl(identity_file, &krl);
2419 	else if ((krl = ssh_krl_init()) == NULL)
2420 		fatal("couldn't create KRL");
2421 
2422 	if (krl_version != 0)
2423 		ssh_krl_set_version(krl, krl_version);
2424 	if (krl_comment != NULL)
2425 		ssh_krl_set_comment(krl, krl_comment);
2426 
2427 	for (i = 0; i < argc; i++)
2428 		update_krl_from_file(pw, argv[i], wild_ca, ca, krl);
2429 
2430 	if ((kbuf = sshbuf_new()) == NULL)
2431 		fatal("sshbuf_new failed");
2432 	if (ssh_krl_to_blob(krl, kbuf, NULL, 0) != 0)
2433 		fatal("Couldn't generate KRL");
2434 	if ((r = sshbuf_write_file(identity_file, kbuf)) != 0)
2435 		fatal("write %s: %s", identity_file, strerror(errno));
2436 	sshbuf_free(kbuf);
2437 	ssh_krl_free(krl);
2438 	sshkey_free(ca);
2439 }
2440 
2441 static void
do_check_krl(struct passwd * pw,int argc,char ** argv)2442 do_check_krl(struct passwd *pw, int argc, char **argv)
2443 {
2444 	int i, r, ret = 0;
2445 	char *comment;
2446 	struct ssh_krl *krl;
2447 	struct sshkey *k;
2448 
2449 	if (*identity_file == '\0')
2450 		fatal("KRL checking requires an input file");
2451 	load_krl(identity_file, &krl);
2452 	for (i = 0; i < argc; i++) {
2453 		if ((r = sshkey_load_public(argv[i], &k, &comment)) != 0)
2454 			fatal("Cannot load public key %s: %s",
2455 			    argv[i], ssh_err(r));
2456 		r = ssh_krl_check_key(krl, k);
2457 		printf("%s%s%s%s: %s\n", argv[i],
2458 		    *comment ? " (" : "", comment, *comment ? ")" : "",
2459 		    r == 0 ? "ok" : "REVOKED");
2460 		if (r != 0)
2461 			ret = 1;
2462 		sshkey_free(k);
2463 		free(comment);
2464 	}
2465 	ssh_krl_free(krl);
2466 	exit(ret);
2467 }
2468 
2469 static struct sshkey *
load_sign_key(const char * keypath,const struct sshkey * pubkey)2470 load_sign_key(const char *keypath, const struct sshkey *pubkey)
2471 {
2472 	size_t i, slen, plen = strlen(keypath);
2473 	char *privpath = xstrdup(keypath);
2474 	const char *suffixes[] = { "-cert.pub", ".pub", NULL };
2475 	struct sshkey *ret = NULL, *privkey = NULL;
2476 	int r;
2477 
2478 	/*
2479 	 * If passed a public key filename, then try to locate the corresponding
2480 	 * private key. This lets us specify certificates on the command-line
2481 	 * and have ssh-keygen find the appropriate private key.
2482 	 */
2483 	for (i = 0; suffixes[i]; i++) {
2484 		slen = strlen(suffixes[i]);
2485 		if (plen <= slen ||
2486 		    strcmp(privpath + plen - slen, suffixes[i]) != 0)
2487 			continue;
2488 		privpath[plen - slen] = '\0';
2489 		debug("%s: %s looks like a public key, using private key "
2490 		    "path %s instead", __func__, keypath, privpath);
2491 	}
2492 	if ((privkey = load_identity(privpath, NULL)) == NULL) {
2493 		error("Couldn't load identity %s", keypath);
2494 		goto done;
2495 	}
2496 	if (!sshkey_equal_public(pubkey, privkey)) {
2497 		error("Public key %s doesn't match private %s",
2498 		    keypath, privpath);
2499 		goto done;
2500 	}
2501 	if (sshkey_is_cert(pubkey) && !sshkey_is_cert(privkey)) {
2502 		/*
2503 		 * Graft the certificate onto the private key to make
2504 		 * it capable of signing.
2505 		 */
2506 		if ((r = sshkey_to_certified(privkey)) != 0) {
2507 			error("%s: sshkey_to_certified: %s", __func__,
2508 			    ssh_err(r));
2509 			goto done;
2510 		}
2511 		if ((r = sshkey_cert_copy(pubkey, privkey)) != 0) {
2512 			error("%s: sshkey_cert_copy: %s", __func__, ssh_err(r));
2513 			goto done;
2514 		}
2515 	}
2516 	/* success */
2517 	ret = privkey;
2518 	privkey = NULL;
2519  done:
2520 	sshkey_free(privkey);
2521 	free(privpath);
2522 	return ret;
2523 }
2524 
2525 static int
sign_one(struct sshkey * signkey,const char * filename,int fd,const char * sig_namespace,sshsig_signer * signer,void * signer_ctx)2526 sign_one(struct sshkey *signkey, const char *filename, int fd,
2527     const char *sig_namespace, sshsig_signer *signer, void *signer_ctx)
2528 {
2529 	struct sshbuf *sigbuf = NULL, *abuf = NULL;
2530 	int r = SSH_ERR_INTERNAL_ERROR, wfd = -1, oerrno;
2531 	char *wfile = NULL, *asig = NULL, *fp = NULL;
2532 
2533 	if (!quiet) {
2534 		if (fd == STDIN_FILENO)
2535 			fprintf(stderr, "Signing data on standard input\n");
2536 		else
2537 			fprintf(stderr, "Signing file %s\n", filename);
2538 	}
2539 	if (signer == NULL && sshkey_is_sk(signkey) &&
2540 	    (signkey->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
2541 		if ((fp = sshkey_fingerprint(signkey, fingerprint_hash,
2542 		    SSH_FP_DEFAULT)) == NULL)
2543 			fatal("%s: sshkey_fingerprint failed", __func__);
2544 		fprintf(stderr, "Confirm user presence for key %s %s\n",
2545 		    sshkey_type(signkey), fp);
2546 		free(fp);
2547 	}
2548 	if ((r = sshsig_sign_fd(signkey, NULL, sk_provider, fd, sig_namespace,
2549 	    &sigbuf, signer, signer_ctx)) != 0) {
2550 		error("Signing %s failed: %s", filename, ssh_err(r));
2551 		goto out;
2552 	}
2553 	if ((r = sshsig_armor(sigbuf, &abuf)) != 0) {
2554 		error("%s: sshsig_armor: %s", __func__, ssh_err(r));
2555 		goto out;
2556 	}
2557 	if ((asig = sshbuf_dup_string(abuf)) == NULL) {
2558 		error("%s: buffer error", __func__);
2559 		r = SSH_ERR_ALLOC_FAIL;
2560 		goto out;
2561 	}
2562 
2563 	if (fd == STDIN_FILENO) {
2564 		fputs(asig, stdout);
2565 		fflush(stdout);
2566 	} else {
2567 		xasprintf(&wfile, "%s.sig", filename);
2568 		if (confirm_overwrite(wfile)) {
2569 			if ((wfd = open(wfile, O_WRONLY|O_CREAT|O_TRUNC,
2570 			    0666)) == -1) {
2571 				oerrno = errno;
2572 				error("Cannot open %s: %s",
2573 				    wfile, strerror(errno));
2574 				errno = oerrno;
2575 				r = SSH_ERR_SYSTEM_ERROR;
2576 				goto out;
2577 			}
2578 			if (atomicio(vwrite, wfd, asig,
2579 			    strlen(asig)) != strlen(asig)) {
2580 				oerrno = errno;
2581 				error("Cannot write to %s: %s",
2582 				    wfile, strerror(errno));
2583 				errno = oerrno;
2584 				r = SSH_ERR_SYSTEM_ERROR;
2585 				goto out;
2586 			}
2587 			if (!quiet) {
2588 				fprintf(stderr, "Write signature to %s\n",
2589 				    wfile);
2590 			}
2591 		}
2592 	}
2593 	/* success */
2594 	r = 0;
2595  out:
2596 	free(wfile);
2597 	free(asig);
2598 	sshbuf_free(abuf);
2599 	sshbuf_free(sigbuf);
2600 	if (wfd != -1)
2601 		close(wfd);
2602 	return r;
2603 }
2604 
2605 static int
sig_sign(const char * keypath,const char * sig_namespace,int argc,char ** argv)2606 sig_sign(const char *keypath, const char *sig_namespace, int argc, char **argv)
2607 {
2608 	int i, fd = -1, r, ret = -1;
2609 	int agent_fd = -1;
2610 	struct sshkey *pubkey = NULL, *privkey = NULL, *signkey = NULL;
2611 	sshsig_signer *signer = NULL;
2612 
2613 	/* Check file arguments. */
2614 	for (i = 0; i < argc; i++) {
2615 		if (strcmp(argv[i], "-") != 0)
2616 			continue;
2617 		if (i > 0 || argc > 1)
2618 			fatal("Cannot sign mix of paths and standard input");
2619 	}
2620 
2621 	if ((r = sshkey_load_public(keypath, &pubkey, NULL)) != 0) {
2622 		error("Couldn't load public key %s: %s", keypath, ssh_err(r));
2623 		goto done;
2624 	}
2625 
2626 	if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
2627 		debug("Couldn't get agent socket: %s", ssh_err(r));
2628 	else {
2629 		if ((r = ssh_agent_has_key(agent_fd, pubkey)) == 0)
2630 			signer = agent_signer;
2631 		else
2632 			debug("Couldn't find key in agent: %s", ssh_err(r));
2633 	}
2634 
2635 	if (signer == NULL) {
2636 		/* Not using agent - try to load private key */
2637 		if ((privkey = load_sign_key(keypath, pubkey)) == NULL)
2638 			goto done;
2639 		signkey = privkey;
2640 	} else {
2641 		/* Will use key in agent */
2642 		signkey = pubkey;
2643 	}
2644 
2645 	if (argc == 0) {
2646 		if ((r = sign_one(signkey, "(stdin)", STDIN_FILENO,
2647 		    sig_namespace, signer, &agent_fd)) != 0)
2648 			goto done;
2649 	} else {
2650 		for (i = 0; i < argc; i++) {
2651 			if (strcmp(argv[i], "-") == 0)
2652 				fd = STDIN_FILENO;
2653 			else if ((fd = open(argv[i], O_RDONLY)) == -1) {
2654 				error("Cannot open %s for signing: %s",
2655 				    argv[i], strerror(errno));
2656 				goto done;
2657 			}
2658 			if ((r = sign_one(signkey, argv[i], fd, sig_namespace,
2659 			    signer, &agent_fd)) != 0)
2660 				goto done;
2661 			if (fd != STDIN_FILENO)
2662 				close(fd);
2663 			fd = -1;
2664 		}
2665 	}
2666 
2667 	ret = 0;
2668 done:
2669 	if (fd != -1 && fd != STDIN_FILENO)
2670 		close(fd);
2671 	sshkey_free(pubkey);
2672 	sshkey_free(privkey);
2673 	return ret;
2674 }
2675 
2676 static int
sig_verify(const char * signature,const char * sig_namespace,const char * principal,const char * allowed_keys,const char * revoked_keys)2677 sig_verify(const char *signature, const char *sig_namespace,
2678     const char *principal, const char *allowed_keys, const char *revoked_keys)
2679 {
2680 	int r, ret = -1;
2681 	struct sshbuf *sigbuf = NULL, *abuf = NULL;
2682 	struct sshkey *sign_key = NULL;
2683 	char *fp = NULL;
2684 	struct sshkey_sig_details *sig_details = NULL;
2685 
2686 	memset(&sig_details, 0, sizeof(sig_details));
2687 	if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
2688 		error("Couldn't read signature file: %s", ssh_err(r));
2689 		goto done;
2690 	}
2691 
2692 	if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
2693 		error("%s: sshsig_armor: %s", __func__, ssh_err(r));
2694 		goto done;
2695 	}
2696 	if ((r = sshsig_verify_fd(sigbuf, STDIN_FILENO, sig_namespace,
2697 	    &sign_key, &sig_details)) != 0)
2698 		goto done; /* sshsig_verify() prints error */
2699 
2700 	if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
2701 	    SSH_FP_DEFAULT)) == NULL)
2702 		fatal("%s: sshkey_fingerprint failed", __func__);
2703 	debug("Valid (unverified) signature from key %s", fp);
2704 	if (sig_details != NULL) {
2705 		debug2("%s: signature details: counter = %u, flags = 0x%02x",
2706 		    __func__, sig_details->sk_counter, sig_details->sk_flags);
2707 	}
2708 	free(fp);
2709 	fp = NULL;
2710 
2711 	if (revoked_keys != NULL) {
2712 		if ((r = sshkey_check_revoked(sign_key, revoked_keys)) != 0) {
2713 			debug3("sshkey_check_revoked failed: %s", ssh_err(r));
2714 			goto done;
2715 		}
2716 	}
2717 
2718 	if (allowed_keys != NULL &&
2719 	    (r = sshsig_check_allowed_keys(allowed_keys, sign_key,
2720 					   principal, sig_namespace)) != 0) {
2721 		debug3("sshsig_check_allowed_keys failed: %s", ssh_err(r));
2722 		goto done;
2723 	}
2724 	/* success */
2725 	ret = 0;
2726 done:
2727 	if (!quiet) {
2728 		if (ret == 0) {
2729 			if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
2730 			    SSH_FP_DEFAULT)) == NULL) {
2731 				fatal("%s: sshkey_fingerprint failed",
2732 				    __func__);
2733 			}
2734 			if (principal == NULL) {
2735 				printf("Good \"%s\" signature with %s key %s\n",
2736 				       sig_namespace, sshkey_type(sign_key), fp);
2737 
2738 			} else {
2739 				printf("Good \"%s\" signature for %s with %s key %s\n",
2740 				       sig_namespace, principal,
2741 				       sshkey_type(sign_key), fp);
2742 			}
2743 		} else {
2744 			printf("Could not verify signature.\n");
2745 		}
2746 	}
2747 	sshbuf_free(sigbuf);
2748 	sshbuf_free(abuf);
2749 	sshkey_free(sign_key);
2750 	sshkey_sig_details_free(sig_details);
2751 	free(fp);
2752 	return ret;
2753 }
2754 
2755 static int
sig_find_principals(const char * signature,const char * allowed_keys)2756 sig_find_principals(const char *signature, const char *allowed_keys) {
2757 	int r, ret = -1;
2758 	struct sshbuf *sigbuf = NULL, *abuf = NULL;
2759 	struct sshkey *sign_key = NULL;
2760 	char *principals = NULL, *cp, *tmp;
2761 
2762 	if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
2763 		error("Couldn't read signature file: %s", ssh_err(r));
2764 		goto done;
2765 	}
2766 	if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
2767 		error("%s: sshsig_armor: %s", __func__, ssh_err(r));
2768 		goto done;
2769 	}
2770 	if ((r = sshsig_get_pubkey(sigbuf, &sign_key)) != 0) {
2771 		error("%s: sshsig_get_pubkey: %s",
2772 		    __func__, ssh_err(r));
2773 		goto done;
2774 	}
2775 	if ((r = sshsig_find_principals(allowed_keys, sign_key,
2776 	    &principals)) != 0) {
2777 		error("%s: sshsig_get_principal: %s",
2778 		      __func__, ssh_err(r));
2779 		goto done;
2780 	}
2781 	ret = 0;
2782 done:
2783 	if (ret == 0 ) {
2784 		/* Emit matching principals one per line */
2785 		tmp = principals;
2786 		while ((cp = strsep(&tmp, ",")) != NULL && *cp != '\0')
2787 			puts(cp);
2788 	} else {
2789 		fprintf(stderr, "No principal matched.\n");
2790 	}
2791 	sshbuf_free(sigbuf);
2792 	sshbuf_free(abuf);
2793 	sshkey_free(sign_key);
2794 	free(principals);
2795 	return ret;
2796 }
2797 
2798 static void
do_moduli_gen(const char * out_file,char ** opts,size_t nopts)2799 do_moduli_gen(const char *out_file, char **opts, size_t nopts)
2800 {
2801 #ifdef WITH_OPENSSL
2802 	/* Moduli generation/screening */
2803 	u_int32_t memory = 0;
2804 	BIGNUM *start = NULL;
2805 	int moduli_bits = 0;
2806 	FILE *out;
2807 	size_t i;
2808 	const char *errstr;
2809 
2810 	/* Parse options */
2811 	for (i = 0; i < nopts; i++) {
2812 		if (strncmp(opts[i], "memory=", 7) == 0) {
2813 			memory = (u_int32_t)strtonum(opts[i]+7, 1,
2814 			    UINT_MAX, &errstr);
2815 			if (errstr) {
2816 				fatal("Memory limit is %s: %s",
2817 				    errstr, opts[i]+7);
2818 			}
2819 		} else if (strncmp(opts[i], "start=", 6) == 0) {
2820 			/* XXX - also compare length against bits */
2821 			if (BN_hex2bn(&start, opts[i]+6) == 0)
2822 				fatal("Invalid start point.");
2823 		} else if (strncmp(opts[i], "bits=", 5) == 0) {
2824 			moduli_bits = (int)strtonum(opts[i]+5, 1,
2825 			    INT_MAX, &errstr);
2826 			if (errstr) {
2827 				fatal("Invalid number: %s (%s)",
2828 					opts[i]+12, errstr);
2829 			}
2830 		} else {
2831 			fatal("Option \"%s\" is unsupported for moduli "
2832 			    "generation", opts[i]);
2833 		}
2834 	}
2835 
2836 	if ((out = fopen(out_file, "w")) == NULL) {
2837 		fatal("Couldn't open modulus candidate file \"%s\": %s",
2838 		    out_file, strerror(errno));
2839 	}
2840 	setvbuf(out, NULL, _IOLBF, 0);
2841 
2842 	if (moduli_bits == 0)
2843 		moduli_bits = DEFAULT_BITS;
2844 	if (gen_candidates(out, memory, moduli_bits, start) != 0)
2845 		fatal("modulus candidate generation failed");
2846 #else /* WITH_OPENSSL */
2847 	fatal("Moduli generation is not supported");
2848 #endif /* WITH_OPENSSL */
2849 }
2850 
2851 static void
do_moduli_screen(const char * out_file,char ** opts,size_t nopts)2852 do_moduli_screen(const char *out_file, char **opts, size_t nopts)
2853 {
2854 #ifdef WITH_OPENSSL
2855 	/* Moduli generation/screening */
2856 	char *checkpoint = NULL;
2857 	u_int32_t generator_wanted = 0;
2858 	unsigned long start_lineno = 0, lines_to_process = 0;
2859 	int prime_tests = 0;
2860 	FILE *out, *in = stdin;
2861 	size_t i;
2862 	const char *errstr;
2863 
2864 	/* Parse options */
2865 	for (i = 0; i < nopts; i++) {
2866 		if (strncmp(opts[i], "lines=", 6) == 0) {
2867 			lines_to_process = strtoul(opts[i]+6, NULL, 10);
2868 		} else if (strncmp(opts[i], "start-line=", 11) == 0) {
2869 			start_lineno = strtoul(opts[i]+11, NULL, 10);
2870 		} else if (strncmp(opts[i], "checkpoint=", 11) == 0) {
2871 			checkpoint = xstrdup(opts[i]+11);
2872 		} else if (strncmp(opts[i], "generator=", 10) == 0) {
2873 			generator_wanted = (u_int32_t)strtonum(
2874 			    opts[i]+10, 1, UINT_MAX, &errstr);
2875 			if (errstr != NULL) {
2876 				fatal("Generator invalid: %s (%s)",
2877 				    opts[i]+10, errstr);
2878 			}
2879 		} else if (strncmp(opts[i], "prime-tests=", 12) == 0) {
2880 			prime_tests = (int)strtonum(opts[i]+12, 1,
2881 			    INT_MAX, &errstr);
2882 			if (errstr) {
2883 				fatal("Invalid number: %s (%s)",
2884 					opts[i]+12, errstr);
2885 			}
2886 		} else {
2887 			fatal("Option \"%s\" is unsupported for moduli "
2888 			    "screening", opts[i]);
2889 		}
2890 	}
2891 
2892 	if (have_identity && strcmp(identity_file, "-") != 0) {
2893 		if ((in = fopen(identity_file, "r")) == NULL) {
2894 			fatal("Couldn't open modulus candidate "
2895 			    "file \"%s\": %s", identity_file,
2896 			    strerror(errno));
2897 		}
2898 	}
2899 
2900 	if ((out = fopen(out_file, "a")) == NULL) {
2901 		fatal("Couldn't open moduli file \"%s\": %s",
2902 		    out_file, strerror(errno));
2903 	}
2904 	setvbuf(out, NULL, _IOLBF, 0);
2905 	if (prime_test(in, out, prime_tests == 0 ? 100 : prime_tests,
2906 	    generator_wanted, checkpoint,
2907 	    start_lineno, lines_to_process) != 0)
2908 		fatal("modulus screening failed");
2909 #else /* WITH_OPENSSL */
2910 	fatal("Moduli screening is not supported");
2911 #endif /* WITH_OPENSSL */
2912 }
2913 
2914 static char *
private_key_passphrase(void)2915