xref: /openssh-portable/ssh-keygen.c (revision 224418cf)
1 /* $OpenBSD: ssh-keygen.c,v 1.412 2020/05/29 03:11:54 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 		if ((*k = do_convert_private_ssh2(buf)) == NULL)
674 			fatal("%s: private key conversion failed", __func__);
675 	} else if ((r = sshkey_fromb(buf, k)) != 0)
676 		fatal("decode blob failed: %s", ssh_err(r));
677 	sshbuf_free(buf);
678 	fclose(fp);
679 }
680 
681 static void
do_convert_from_pkcs8(struct sshkey ** k,int * private)682 do_convert_from_pkcs8(struct sshkey **k, int *private)
683 {
684 	EVP_PKEY *pubkey;
685 	FILE *fp;
686 
687 	if ((fp = fopen(identity_file, "r")) == NULL)
688 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
689 	if ((pubkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL)) == NULL) {
690 		fatal("%s: %s is not a recognised public key format", __func__,
691 		    identity_file);
692 	}
693 	fclose(fp);
694 	switch (EVP_PKEY_base_id(pubkey)) {
695 	case EVP_PKEY_RSA:
696 		if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
697 			fatal("sshkey_new failed");
698 		(*k)->type = KEY_RSA;
699 		(*k)->rsa = EVP_PKEY_get1_RSA(pubkey);
700 		break;
701 	case EVP_PKEY_DSA:
702 		if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
703 			fatal("sshkey_new failed");
704 		(*k)->type = KEY_DSA;
705 		(*k)->dsa = EVP_PKEY_get1_DSA(pubkey);
706 		break;
707 #ifdef OPENSSL_HAS_ECC
708 	case EVP_PKEY_EC:
709 		if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
710 			fatal("sshkey_new failed");
711 		(*k)->type = KEY_ECDSA;
712 		(*k)->ecdsa = EVP_PKEY_get1_EC_KEY(pubkey);
713 		(*k)->ecdsa_nid = sshkey_ecdsa_key_to_nid((*k)->ecdsa);
714 		break;
715 #endif
716 	default:
717 		fatal("%s: unsupported pubkey type %d", __func__,
718 		    EVP_PKEY_base_id(pubkey));
719 	}
720 	EVP_PKEY_free(pubkey);
721 	return;
722 }
723 
724 static void
do_convert_from_pem(struct sshkey ** k,int * private)725 do_convert_from_pem(struct sshkey **k, int *private)
726 {
727 	FILE *fp;
728 	RSA *rsa;
729 
730 	if ((fp = fopen(identity_file, "r")) == NULL)
731 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
732 	if ((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
733 		if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
734 			fatal("sshkey_new failed");
735 		(*k)->type = KEY_RSA;
736 		(*k)->rsa = rsa;
737 		fclose(fp);
738 		return;
739 	}
740 	fatal("%s: unrecognised raw private key format", __func__);
741 }
742 
743 static void
do_convert_from(struct passwd * pw)744 do_convert_from(struct passwd *pw)
745 {
746 	struct sshkey *k = NULL;
747 	int r, private = 0, ok = 0;
748 	struct stat st;
749 
750 	if (!have_identity)
751 		ask_filename(pw, "Enter file in which the key is");
752 	if (stat(identity_file, &st) == -1)
753 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
754 
755 	switch (convert_format) {
756 	case FMT_RFC4716:
757 		do_convert_from_ssh2(pw, &k, &private);
758 		break;
759 	case FMT_PKCS8:
760 		do_convert_from_pkcs8(&k, &private);
761 		break;
762 	case FMT_PEM:
763 		do_convert_from_pem(&k, &private);
764 		break;
765 	default:
766 		fatal("%s: unknown key format %d", __func__, convert_format);
767 	}
768 
769 	if (!private) {
770 		if ((r = sshkey_write(k, stdout)) == 0)
771 			ok = 1;
772 		if (ok)
773 			fprintf(stdout, "\n");
774 	} else {
775 		switch (k->type) {
776 		case KEY_DSA:
777 			ok = PEM_write_DSAPrivateKey(stdout, k->dsa, NULL,
778 			    NULL, 0, NULL, NULL);
779 			break;
780 #ifdef OPENSSL_HAS_ECC
781 		case KEY_ECDSA:
782 			ok = PEM_write_ECPrivateKey(stdout, k->ecdsa, NULL,
783 			    NULL, 0, NULL, NULL);
784 			break;
785 #endif
786 		case KEY_RSA:
787 			ok = PEM_write_RSAPrivateKey(stdout, k->rsa, NULL,
788 			    NULL, 0, NULL, NULL);
789 			break;
790 		default:
791 			fatal("%s: unsupported key type %s", __func__,
792 			    sshkey_type(k));
793 		}
794 	}
795 
796 	if (!ok)
797 		fatal("key write failed");
798 	sshkey_free(k);
799 	exit(0);
800 }
801 #endif
802 
803 static void
do_print_public(struct passwd * pw)804 do_print_public(struct passwd *pw)
805 {
806 	struct sshkey *prv;
807 	struct stat st;
808 	int r;
809 	char *comment = NULL;
810 
811 	if (!have_identity)
812 		ask_filename(pw, "Enter file in which the key is");
813 	if (stat(identity_file, &st) == -1)
814 		fatal("%s: %s", identity_file, strerror(errno));
815 	prv = load_identity(identity_file, &comment);
816 	if ((r = sshkey_write(prv, stdout)) != 0)
817 		error("sshkey_write failed: %s", ssh_err(r));
818 	sshkey_free(prv);
819 	if (comment != NULL && *comment != '\0')
820 		fprintf(stdout, " %s", comment);
821 	fprintf(stdout, "\n");
822 	free(comment);
823 	exit(0);
824 }
825 
826 static void
do_download(struct passwd * pw)827 do_download(struct passwd *pw)
828 {
829 #ifdef ENABLE_PKCS11
830 	struct sshkey **keys = NULL;
831 	int i, nkeys;
832 	enum sshkey_fp_rep rep;
833 	int fptype;
834 	char *fp, *ra, **comments = NULL;
835 
836 	fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
837 	rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
838 
839 	pkcs11_init(1);
840 	nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys, &comments);
841 	if (nkeys <= 0)
842 		fatal("cannot read public key from pkcs11");
843 	for (i = 0; i < nkeys; i++) {
844 		if (print_fingerprint) {
845 			fp = sshkey_fingerprint(keys[i], fptype, rep);
846 			ra = sshkey_fingerprint(keys[i], fingerprint_hash,
847 			    SSH_FP_RANDOMART);
848 			if (fp == NULL || ra == NULL)
849 				fatal("%s: sshkey_fingerprint fail", __func__);
850 			printf("%u %s %s (PKCS11 key)\n", sshkey_size(keys[i]),
851 			    fp, sshkey_type(keys[i]));
852 			if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
853 				printf("%s\n", ra);
854 			free(ra);
855 			free(fp);
856 		} else {
857 			(void) sshkey_write(keys[i], stdout); /* XXX check */
858 			fprintf(stdout, "%s%s\n",
859 			    *(comments[i]) == '\0' ? "" : " ", comments[i]);
860 		}
861 		free(comments[i]);
862 		sshkey_free(keys[i]);
863 	}
864 	free(comments);
865 	free(keys);
866 	pkcs11_terminate();
867 	exit(0);
868 #else
869 	fatal("no pkcs11 support");
870 #endif /* ENABLE_PKCS11 */
871 }
872 
873 static struct sshkey *
try_read_key(char ** cpp)874 try_read_key(char **cpp)
875 {
876 	struct sshkey *ret;
877 	int r;
878 
879 	if ((ret = sshkey_new(KEY_UNSPEC)) == NULL)
880 		fatal("sshkey_new failed");
881 	if ((r = sshkey_read(ret, cpp)) == 0)
882 		return ret;
883 	/* Not a key */
884 	sshkey_free(ret);
885 	return NULL;
886 }
887 
888 static void
fingerprint_one_key(const struct sshkey * public,const char * comment)889 fingerprint_one_key(const struct sshkey *public, const char *comment)
890 {
891 	char *fp = NULL, *ra = NULL;
892 	enum sshkey_fp_rep rep;
893 	int fptype;
894 
895 	fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
896 	rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
897 	fp = sshkey_fingerprint(public, fptype, rep);
898 	ra = sshkey_fingerprint(public, fingerprint_hash, SSH_FP_RANDOMART);
899 	if (fp == NULL || ra == NULL)
900 		fatal("%s: sshkey_fingerprint failed", __func__);
901 	mprintf("%u %s %s (%s)\n", sshkey_size(public), fp,
902 	    comment ? comment : "no comment", sshkey_type(public));
903 	if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
904 		printf("%s\n", ra);
905 	free(ra);
906 	free(fp);
907 }
908 
909 static void
fingerprint_private(const char * path)910 fingerprint_private(const char *path)
911 {
912 	struct stat st;
913 	char *comment = NULL;
914 	struct sshkey *privkey = NULL, *pubkey = NULL;
915 	int r;
916 
917 	if (stat(identity_file, &st) == -1)
918 		fatal("%s: %s", path, strerror(errno));
919 	if ((r = sshkey_load_public(path, &pubkey, &comment)) != 0)
920 		debug("load public \"%s\": %s", path, ssh_err(r));
921 	if (pubkey == NULL || comment == NULL || *comment == '\0') {
922 		free(comment);
923 		if ((r = sshkey_load_private(path, NULL,
924 		    &privkey, &comment)) != 0)
925 			debug("load private \"%s\": %s", path, ssh_err(r));
926 	}
927 	if (pubkey == NULL && privkey == NULL)
928 		fatal("%s is not a key file.", path);
929 
930 	fingerprint_one_key(pubkey == NULL ? privkey : pubkey, comment);
931 	sshkey_free(pubkey);
932 	sshkey_free(privkey);
933 	free(comment);
934 }
935 
936 static void
do_fingerprint(struct passwd * pw)937 do_fingerprint(struct passwd *pw)
938 {
939 	FILE *f;
940 	struct sshkey *public = NULL;
941 	char *comment = NULL, *cp, *ep, *line = NULL;
942 	size_t linesize = 0;
943 	int i, invalid = 1;
944 	const char *path;
945 	u_long lnum = 0;
946 
947 	if (!have_identity)
948 		ask_filename(pw, "Enter file in which the key is");
949 	path = identity_file;
950 
951 	if (strcmp(identity_file, "-") == 0) {
952 		f = stdin;
953 		path = "(stdin)";
954 	} else if ((f = fopen(path, "r")) == NULL)
955 		fatal("%s: %s: %s", __progname, path, strerror(errno));
956 
957 	while (getline(&line, &linesize, f) != -1) {
958 		lnum++;
959 		cp = line;
960 		cp[strcspn(cp, "\n")] = '\0';
961 		/* Trim leading space and comments */
962 		cp = line + strspn(line, " \t");
963 		if (*cp == '#' || *cp == '\0')
964 			continue;
965 
966 		/*
967 		 * Input may be plain keys, private keys, authorized_keys
968 		 * or known_hosts.
969 		 */
970 
971 		/*
972 		 * Try private keys first. Assume a key is private if
973 		 * "SSH PRIVATE KEY" appears on the first line and we're
974 		 * not reading from stdin (XXX support private keys on stdin).
975 		 */
976 		if (lnum == 1 && strcmp(identity_file, "-") != 0 &&
977 		    strstr(cp, "PRIVATE KEY") != NULL) {
978 			free(line);
979 			fclose(f);
980 			fingerprint_private(path);
981 			exit(0);
982 		}
983 
984 		/*
985 		 * If it's not a private key, then this must be prepared to
986 		 * accept a public key prefixed with a hostname or options.
987 		 * Try a bare key first, otherwise skip the leading stuff.
988 		 */
989 		if ((public = try_read_key(&cp)) == NULL) {
990 			i = strtol(cp, &ep, 10);
991 			if (i == 0 || ep == NULL ||
992 			    (*ep != ' ' && *ep != '\t')) {
993 				int quoted = 0;
994 
995 				comment = cp;
996 				for (; *cp && (quoted || (*cp != ' ' &&
997 				    *cp != '\t')); cp++) {
998 					if (*cp == '\\' && cp[1] == '"')
999 						cp++;	/* Skip both */
1000 					else if (*cp == '"')
1001 						quoted = !quoted;
1002 				}
1003 				if (!*cp)
1004 					continue;
1005 				*cp++ = '\0';
1006 			}
1007 		}
1008 		/* Retry after parsing leading hostname/key options */
1009 		if (public == NULL && (public = try_read_key(&cp)) == NULL) {
1010 			debug("%s:%lu: not a public key", path, lnum);
1011 			continue;
1012 		}
1013 
1014 		/* Find trailing comment, if any */
1015 		for (; *cp == ' ' || *cp == '\t'; cp++)
1016 			;
1017 		if (*cp != '\0' && *cp != '#')
1018 			comment = cp;
1019 
1020 		fingerprint_one_key(public, comment);
1021 		sshkey_free(public);
1022 		invalid = 0; /* One good key in the file is sufficient */
1023 	}
1024 	fclose(f);
1025 	free(line);
1026 
1027 	if (invalid)
1028 		fatal("%s is not a public key file.", path);
1029 	exit(0);
1030 }
1031 
1032 static void
do_gen_all_hostkeys(struct passwd * pw)1033 do_gen_all_hostkeys(struct passwd *pw)
1034 {
1035 	struct {
1036 		char *key_type;
1037 		char *key_type_display;
1038 		char *path;
1039 	} key_types[] = {
1040 #ifdef WITH_OPENSSL
1041 		{ "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE },
1042 		{ "dsa", "DSA", _PATH_HOST_DSA_KEY_FILE },
1043 #ifdef OPENSSL_HAS_ECC
1044 		{ "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE },
1045 #endif /* OPENSSL_HAS_ECC */
1046 #endif /* WITH_OPENSSL */
1047 		{ "ed25519", "ED25519",_PATH_HOST_ED25519_KEY_FILE },
1048 #ifdef WITH_XMSS
1049 		{ "xmss", "XMSS",_PATH_HOST_XMSS_KEY_FILE },
1050 #endif /* WITH_XMSS */
1051 		{ NULL, NULL, NULL }
1052 	};
1053 
1054 	u_int32_t bits = 0;
1055 	int first = 0;
1056 	struct stat st;
1057 	struct sshkey *private, *public;
1058 	char comment[1024], *prv_tmp, *pub_tmp, *prv_file, *pub_file;
1059 	int i, type, fd, r;
1060 
1061 	for (i = 0; key_types[i].key_type; i++) {
1062 		public = private = NULL;
1063 		prv_tmp = pub_tmp = prv_file = pub_file = NULL;
1064 
1065 		xasprintf(&prv_file, "%s%s",
1066 		    identity_file, key_types[i].path);
1067 
1068 		/* Check whether private key exists and is not zero-length */
1069 		if (stat(prv_file, &st) == 0) {
1070 			if (st.st_size != 0)
1071 				goto next;
1072 		} else if (errno != ENOENT) {
1073 			error("Could not stat %s: %s", key_types[i].path,
1074 			    strerror(errno));
1075 			goto failnext;
1076 		}
1077 
1078 		/*
1079 		 * Private key doesn't exist or is invalid; proceed with
1080 		 * key generation.
1081 		 */
1082 		xasprintf(&prv_tmp, "%s%s.XXXXXXXXXX",
1083 		    identity_file, key_types[i].path);
1084 		xasprintf(&pub_tmp, "%s%s.pub.XXXXXXXXXX",
1085 		    identity_file, key_types[i].path);
1086 		xasprintf(&pub_file, "%s%s.pub",
1087 		    identity_file, key_types[i].path);
1088 
1089 		if (first == 0) {
1090 			first = 1;
1091 			printf("%s: generating new host keys: ", __progname);
1092 		}
1093 		printf("%s ", key_types[i].key_type_display);
1094 		fflush(stdout);
1095 		type = sshkey_type_from_name(key_types[i].key_type);
1096 		if ((fd = mkstemp(prv_tmp)) == -1) {
1097 			error("Could not save your private key in %s: %s",
1098 			    prv_tmp, strerror(errno));
1099 			goto failnext;
1100 		}
1101 		(void)close(fd); /* just using mkstemp() to reserve a name */
1102 		bits = 0;
1103 		type_bits_valid(type, NULL, &bits);
1104 		if ((r = sshkey_generate(type, bits, &private)) != 0) {
1105 			error("sshkey_generate failed: %s", ssh_err(r));
1106 			goto failnext;
1107 		}
1108 		if ((r = sshkey_from_private(private, &public)) != 0)
1109 			fatal("sshkey_from_private failed: %s", ssh_err(r));
1110 		snprintf(comment, sizeof comment, "%s@%s", pw->pw_name,
1111 		    hostname);
1112 		if ((r = sshkey_save_private(private, prv_tmp, "",
1113 		    comment, private_key_format, openssh_format_cipher,
1114 		    rounds)) != 0) {
1115 			error("Saving key \"%s\" failed: %s",
1116 			    prv_tmp, ssh_err(r));
1117 			goto failnext;
1118 		}
1119 		if ((fd = mkstemp(pub_tmp)) == -1) {
1120 			error("Could not save your public key in %s: %s",
1121 			    pub_tmp, strerror(errno));
1122 			goto failnext;
1123 		}
1124 		(void)fchmod(fd, 0644);
1125 		(void)close(fd);
1126 		if ((r = sshkey_save_public(public, pub_tmp, comment)) != 0) {
1127 			fatal("Unable to save public key to %s: %s",
1128 			    identity_file, ssh_err(r));
1129 			goto failnext;
1130 		}
1131 
1132 		/* Rename temporary files to their permanent locations. */
1133 		if (rename(pub_tmp, pub_file) != 0) {
1134 			error("Unable to move %s into position: %s",
1135 			    pub_file, strerror(errno));
1136 			goto failnext;
1137 		}
1138 		if (rename(prv_tmp, prv_file) != 0) {
1139 			error("Unable to move %s into position: %s",
1140 			    key_types[i].path, strerror(errno));
1141  failnext:
1142 			first = 0;
1143 			goto next;
1144 		}
1145  next:
1146 		sshkey_free(private);
1147 		sshkey_free(public);
1148 		free(prv_tmp);
1149 		free(pub_tmp);
1150 		free(prv_file);
1151 		free(pub_file);
1152 	}
1153 	if (first != 0)
1154 		printf("\n");
1155 }
1156 
1157 struct known_hosts_ctx {
1158 	const char *host;	/* Hostname searched for in find/delete case */
1159 	FILE *out;		/* Output file, stdout for find_hosts case */
1160 	int has_unhashed;	/* When hashing, original had unhashed hosts */
1161 	int found_key;		/* For find/delete, host was found */
1162 	int invalid;		/* File contained invalid items; don't delete */
1163 	int hash_hosts;		/* Hash hostnames as we go */
1164 	int find_host;		/* Search for specific hostname */
1165 	int delete_host;	/* Delete host from known_hosts */
1166 };
1167 
1168 static int
known_hosts_hash(struct hostkey_foreach_line * l,void * _ctx)1169 known_hosts_hash(struct hostkey_foreach_line *l, void *_ctx)
1170 {
1171 	struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1172 	char *hashed, *cp, *hosts, *ohosts;
1173 	int has_wild = l->hosts && strcspn(l->hosts, "*?!") != strlen(l->hosts);
1174 	int was_hashed = l->hosts && l->hosts[0] == HASH_DELIM;
1175 
1176 	switch (l->status) {
1177 	case HKF_STATUS_OK:
1178 	case HKF_STATUS_MATCHED:
1179 		/*
1180 		 * Don't hash hosts already already hashed, with wildcard
1181 		 * characters or a CA/revocation marker.
1182 		 */
1183 		if (was_hashed || has_wild || l->marker != MRK_NONE) {
1184 			fprintf(ctx->out, "%s\n", l->line);
1185 			if (has_wild && !ctx->find_host) {
1186 				logit("%s:%lu: ignoring host name "
1187 				    "with wildcard: %.64s", l->path,
1188 				    l->linenum, l->hosts);
1189 			}
1190 			return 0;
1191 		}
1192 		/*
1193 		 * Split any comma-separated hostnames from the host list,
1194 		 * hash and store separately.
1195 		 */
1196 		ohosts = hosts = xstrdup(l->hosts);
1197 		while ((cp = strsep(&hosts, ",")) != NULL && *cp != '\0') {
1198 			lowercase(cp);
1199 			if ((hashed = host_hash(cp, NULL, 0)) == NULL)
1200 				fatal("hash_host failed");
1201 			fprintf(ctx->out, "%s %s\n", hashed, l->rawkey);
1202 			ctx->has_unhashed = 1;
1203 		}
1204 		free(ohosts);
1205 		return 0;
1206 	case HKF_STATUS_INVALID:
1207 		/* Retain invalid lines, but mark file as invalid. */
1208 		ctx->invalid = 1;
1209 		logit("%s:%lu: invalid line", l->path, l->linenum);
1210 		/* FALLTHROUGH */
1211 	default:
1212 		fprintf(ctx->out, "%s\n", l->line);
1213 		return 0;
1214 	}
1215 	/* NOTREACHED */
1216 	return -1;
1217 }
1218 
1219 static int
known_hosts_find_delete(struct hostkey_foreach_line * l,void * _ctx)1220 known_hosts_find_delete(struct hostkey_foreach_line *l, void *_ctx)
1221 {
1222 	struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1223 	enum sshkey_fp_rep rep;
1224 	int fptype;
1225 	char *fp = NULL, *ra = NULL;
1226 
1227 	fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
1228 	rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1229 
1230 	if (l->status == HKF_STATUS_MATCHED) {
1231 		if (ctx->delete_host) {
1232 			if (l->marker != MRK_NONE) {
1233 				/* Don't remove CA and revocation lines */
1234 				fprintf(ctx->out, "%s\n", l->line);
1235 			} else {
1236 				/*
1237 				 * Hostname matches and has no CA/revoke
1238 				 * marker, delete it by *not* writing the
1239 				 * line to ctx->out.
1240 				 */
1241 				ctx->found_key = 1;
1242 				if (!quiet)
1243 					printf("# Host %s found: line %lu\n",
1244 					    ctx->host, l->linenum);
1245 			}
1246 			return 0;
1247 		} else if (ctx->find_host) {
1248 			ctx->found_key = 1;
1249 			if (!quiet) {
1250 				printf("# Host %s found: line %lu %s\n",
1251 				    ctx->host,
1252 				    l->linenum, l->marker == MRK_CA ? "CA" :
1253 				    (l->marker == MRK_REVOKE ? "REVOKED" : ""));
1254 			}
1255 			if (ctx->hash_hosts)
1256 				known_hosts_hash(l, ctx);
1257 			else if (print_fingerprint) {
1258 				fp = sshkey_fingerprint(l->key, fptype, rep);
1259 				ra = sshkey_fingerprint(l->key,
1260 				    fingerprint_hash, SSH_FP_RANDOMART);
1261 				if (fp == NULL || ra == NULL)
1262 					fatal("%s: sshkey_fingerprint failed",
1263 					    __func__);
1264 				mprintf("%s %s %s%s%s\n", ctx->host,
1265 				    sshkey_type(l->key), fp,
1266 				    l->comment[0] ? " " : "",
1267 				    l->comment);
1268 				if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
1269 					printf("%s\n", ra);
1270 				free(ra);
1271 				free(fp);
1272 			} else
1273 				fprintf(ctx->out, "%s\n", l->line);
1274 			return 0;
1275 		}
1276 	} else if (ctx->delete_host) {
1277 		/* Retain non-matching hosts when deleting */
1278 		if (l->status == HKF_STATUS_INVALID) {
1279 			ctx->invalid = 1;
1280 			logit("%s:%lu: invalid line", l->path, l->linenum);
1281 		}
1282 		fprintf(ctx->out, "%s\n", l->line);
1283 	}
1284 	return 0;
1285 }
1286 
1287 static void
do_known_hosts(struct passwd * pw,const char * name,int find_host,int delete_host,int hash_hosts)1288 do_known_hosts(struct passwd *pw, const char *name, int find_host,
1289     int delete_host, int hash_hosts)
1290 {
1291 	char *cp, tmp[PATH_MAX], old[PATH_MAX];
1292 	int r, fd, oerrno, inplace = 0;
1293 	struct known_hosts_ctx ctx;
1294 	u_int foreach_options;
1295 	struct stat sb;
1296 
1297 	if (!have_identity) {
1298 		cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
1299 		if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
1300 		    sizeof(identity_file))
1301 			fatal("Specified known hosts path too long");
1302 		free(cp);
1303 		have_identity = 1;
1304 	}
1305 	if (stat(identity_file, &sb) != 0)
1306 		fatal("Cannot stat %s: %s", identity_file, strerror(errno));
1307 
1308 	memset(&ctx, 0, sizeof(ctx));
1309 	ctx.out = stdout;
1310 	ctx.host = name;
1311 	ctx.hash_hosts = hash_hosts;
1312 	ctx.find_host = find_host;
1313 	ctx.delete_host = delete_host;
1314 
1315 	/*
1316 	 * Find hosts goes to stdout, hash and deletions happen in-place
1317 	 * A corner case is ssh-keygen -HF foo, which should go to stdout
1318 	 */
1319 	if (!find_host && (hash_hosts || delete_host)) {
1320 		if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
1321 		    strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
1322 		    strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
1323 		    strlcat(old, ".old", sizeof(old)) >= sizeof(old))
1324 			fatal("known_hosts path too long");
1325 		umask(077);
1326 		if ((fd = mkstemp(tmp)) == -1)
1327 			fatal("mkstemp: %s", strerror(errno));
1328 		if ((ctx.out = fdopen(fd, "w")) == NULL) {
1329 			oerrno = errno;
1330 			unlink(tmp);
1331 			fatal("fdopen: %s", strerror(oerrno));
1332 		}
1333 		fchmod(fd, sb.st_mode & 0644);
1334 		inplace = 1;
1335 	}
1336 	/* XXX support identity_file == "-" for stdin */
1337 	foreach_options = find_host ? HKF_WANT_MATCH : 0;
1338 	foreach_options |= print_fingerprint ? HKF_WANT_PARSE_KEY : 0;
1339 	if ((r = hostkeys_foreach(identity_file, (find_host || !hash_hosts) ?
1340 	    known_hosts_find_delete : known_hosts_hash, &ctx, name, NULL,
1341 	    foreach_options)) != 0) {
1342 		if (inplace)
1343 			unlink(tmp);
1344 		fatal("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
1345 	}
1346 
1347 	if (inplace)
1348 		fclose(ctx.out);
1349 
1350 	if (ctx.invalid) {
1351 		error("%s is not a valid known_hosts file.", identity_file);
1352 		if (inplace) {
1353 			error("Not replacing existing known_hosts "
1354 			    "file because of errors");
1355 			unlink(tmp);
1356 		}
1357 		exit(1);
1358 	} else if (delete_host && !ctx.found_key) {
1359 		logit("Host %s not found in %s", name, identity_file);
1360 		if (inplace)
1361 			unlink(tmp);
1362 	} else if (inplace) {
1363 		/* Backup existing file */
1364 		if (unlink(old) == -1 && errno != ENOENT)
1365 			fatal("unlink %.100s: %s", old, strerror(errno));
1366 		if (link(identity_file, old) == -1)
1367 			fatal("link %.100s to %.100s: %s", identity_file, old,
1368 			    strerror(errno));
1369 		/* Move new one into place */
1370 		if (rename(tmp, identity_file) == -1) {
1371 			error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
1372 			    strerror(errno));
1373 			unlink(tmp);
1374 			unlink(old);
1375 			exit(1);
1376 		}
1377 
1378 		printf("%s updated.\n", identity_file);
1379 		printf("Original contents retained as %s\n", old);
1380 		if (ctx.has_unhashed) {
1381 			logit("WARNING: %s contains unhashed entries", old);
1382 			logit("Delete this file to ensure privacy "
1383 			    "of hostnames");
1384 		}
1385 	}
1386 
1387 	exit (find_host && !ctx.found_key);
1388 }
1389 
1390 /*
1391  * Perform changing a passphrase.  The argument is the passwd structure
1392  * for the current user.
1393  */
1394 static void
do_change_passphrase(struct passwd * pw)1395 do_change_passphrase(struct passwd *pw)
1396 {
1397 	char *comment;
1398 	char *old_passphrase, *passphrase1, *passphrase2;
1399 	struct stat st;
1400 	struct sshkey *private;
1401 	int r;
1402 
1403 	if (!have_identity)
1404 		ask_filename(pw, "Enter file in which the key is");
1405 	if (stat(identity_file, &st) == -1)
1406 		fatal("%s: %s", identity_file, strerror(errno));
1407 	/* Try to load the file with empty passphrase. */
1408 	r = sshkey_load_private(identity_file, "", &private, &comment);
1409 	if (r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
1410 		if (identity_passphrase)
1411 			old_passphrase = xstrdup(identity_passphrase);
1412 		else
1413 			old_passphrase =
1414 			    read_passphrase("Enter old passphrase: ",
1415 			    RP_ALLOW_STDIN);
1416 		r = sshkey_load_private(identity_file, old_passphrase,
1417 		    &private, &comment);
1418 		freezero(old_passphrase, strlen(old_passphrase));
1419 		if (r != 0)
1420 			goto badkey;
1421 	} else if (r != 0) {
1422  badkey:
1423 		fatal("Failed to load key %s: %s", identity_file, ssh_err(r));
1424 	}
1425 	if (comment)
1426 		mprintf("Key has comment '%s'\n", comment);
1427 
1428 	/* Ask the new passphrase (twice). */
1429 	if (identity_new_passphrase) {
1430 		passphrase1 = xstrdup(identity_new_passphrase);
1431 		passphrase2 = NULL;
1432 	} else {
1433 		passphrase1 =
1434 			read_passphrase("Enter new passphrase (empty for no "
1435 			    "passphrase): ", RP_ALLOW_STDIN);
1436 		passphrase2 = read_passphrase("Enter same passphrase again: ",
1437 		    RP_ALLOW_STDIN);
1438 
1439 		/* Verify that they are the same. */
1440 		if (strcmp(passphrase1, passphrase2) != 0) {
1441 			explicit_bzero(passphrase1, strlen(passphrase1));
1442 			explicit_bzero(passphrase2, strlen(passphrase2));
1443 			free(passphrase1);
1444 			free(passphrase2);
1445 			printf("Pass phrases do not match.  Try again.\n");
1446 			exit(1);
1447 		}
1448 		/* Destroy the other copy. */
1449 		freezero(passphrase2, strlen(passphrase2));
1450 	}
1451 
1452 	/* Save the file using the new passphrase. */
1453 	if ((r = sshkey_save_private(private, identity_file, passphrase1,
1454 	    comment, private_key_format, openssh_format_cipher, rounds)) != 0) {
1455 		error("Saving key \"%s\" failed: %s.",
1456 		    identity_file, ssh_err(r));
1457 		freezero(passphrase1, strlen(passphrase1));
1458 		sshkey_free(private);
1459 		free(comment);
1460 		exit(1);
1461 	}
1462 	/* Destroy the passphrase and the copy of the key in memory. */
1463 	freezero(passphrase1, strlen(passphrase1));
1464 	sshkey_free(private);		 /* Destroys contents */
1465 	free(comment);
1466 
1467 	printf("Your identification has been saved with the new passphrase.\n");
1468 	exit(0);
1469 }
1470 
1471 /*
1472  * Print the SSHFP RR.
1473  */
1474 static int
do_print_resource_record(struct passwd * pw,char * fname,char * hname,int print_generic)1475 do_print_resource_record(struct passwd *pw, char *fname, char *hname,
1476     int print_generic)
1477 {
1478 	struct sshkey *public;
1479 	char *comment = NULL;
1480 	struct stat st;
1481 	int r;
1482 
1483 	if (fname == NULL)
1484 		fatal("%s: no filename", __func__);
1485 	if (stat(fname, &st) == -1) {
1486 		if (errno == ENOENT)
1487 			return 0;
1488 		fatal("%s: %s", fname, strerror(errno));
1489 	}
1490 	if ((r = sshkey_load_public(fname, &public, &comment)) != 0)
1491 		fatal("Failed to read v2 public key from \"%s\": %s.",
1492 		    fname, ssh_err(r));
1493 	export_dns_rr(hname, public, stdout, print_generic);
1494 	sshkey_free(public);
1495 	free(comment);
1496 	return 1;
1497 }
1498 
1499 /*
1500  * Change the comment of a private key file.
1501  */
1502 static void
do_change_comment(struct passwd * pw,const char * identity_comment)1503 do_change_comment(struct passwd *pw, const char *identity_comment)
1504 {
1505 	char new_comment[1024], *comment, *passphrase;
1506 	struct sshkey *private;
1507 	struct sshkey *public;
1508 	struct stat st;
1509 	int r;
1510 
1511 	if (!have_identity)
1512 		ask_filename(pw, "Enter file in which the key is");
1513 	if (stat(identity_file, &st) == -1)
1514 		fatal("%s: %s", identity_file, strerror(errno));
1515 	if ((r = sshkey_load_private(identity_file, "",
1516 	    &private, &comment)) == 0)
1517 		passphrase = xstrdup("");
1518 	else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
1519 		fatal("Cannot load private key \"%s\": %s.",
1520 		    identity_file, ssh_err(r));
1521 	else {
1522 		if (identity_passphrase)
1523 			passphrase = xstrdup(identity_passphrase);
1524 		else if (identity_new_passphrase)
1525 			passphrase = xstrdup(identity_new_passphrase);
1526 		else
1527 			passphrase = read_passphrase("Enter passphrase: ",
1528 			    RP_ALLOW_STDIN);
1529 		/* Try to load using the passphrase. */
1530 		if ((r = sshkey_load_private(identity_file, passphrase,
1531 		    &private, &comment)) != 0) {
1532 			freezero(passphrase, strlen(passphrase));
1533 			fatal("Cannot load private key \"%s\": %s.",
1534 			    identity_file, ssh_err(r));
1535 		}
1536 	}
1537 
1538 	if (private->type != KEY_ED25519 && private->type != KEY_XMSS &&
1539 	    private_key_format != SSHKEY_PRIVATE_OPENSSH) {
1540 		error("Comments are only supported for keys stored in "
1541 		    "the new format (-o).");
1542 		explicit_bzero(passphrase, strlen(passphrase));
1543 		sshkey_free(private);
1544 		exit(1);
1545 	}
1546 	if (comment)
1547 		printf("Old comment: %s\n", comment);
1548 	else
1549 		printf("No existing comment\n");
1550 
1551 	if (identity_comment) {
1552 		strlcpy(new_comment, identity_comment, sizeof(new_comment));
1553 	} else {
1554 		printf("New comment: ");
1555 		fflush(stdout);
1556 		if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1557 			explicit_bzero(passphrase, strlen(passphrase));
1558 			sshkey_free(private);
1559 			exit(1);
1560 		}
1561 		new_comment[strcspn(new_comment, "\n")] = '\0';
1562 	}
1563 	if (comment != NULL && strcmp(comment, new_comment) == 0) {
1564 		printf("No change to comment\n");
1565 		free(passphrase);
1566 		sshkey_free(private);
1567 		free(comment);
1568 		exit(0);
1569 	}
1570 
1571 	/* Save the file using the new passphrase. */
1572 	if ((r = sshkey_save_private(private, identity_file, passphrase,
1573 	    new_comment, private_key_format, openssh_format_cipher,
1574 	    rounds)) != 0) {
1575 		error("Saving key \"%s\" failed: %s",
1576 		    identity_file, ssh_err(r));
1577 		freezero(passphrase, strlen(passphrase));
1578 		sshkey_free(private);
1579 		free(comment);
1580 		exit(1);
1581 	}
1582 	freezero(passphrase, strlen(passphrase));
1583 	if ((r = sshkey_from_private(private, &public)) != 0)
1584 		fatal("sshkey_from_private failed: %s", ssh_err(r));
1585 	sshkey_free(private);
1586 
1587 	strlcat(identity_file, ".pub", sizeof(identity_file));
1588 	if ((r = sshkey_save_public(public, identity_file, new_comment)) != 0) {
1589 		fatal("Unable to save public key to %s: %s",
1590 		    identity_file, ssh_err(r));
1591 	}
1592 	sshkey_free(public);
1593 	free(comment);
1594 
1595 	if (strlen(new_comment) > 0)
1596 		printf("Comment '%s' applied\n", new_comment);
1597 	else
1598 		printf("Comment removed\n");
1599 
1600 	exit(0);
1601 }
1602 
1603 static void
add_flag_option(struct sshbuf * c,const char * name)1604 add_flag_option(struct sshbuf *c, const char *name)
1605 {
1606 	int r;
1607 
1608 	debug3("%s: %s", __func__, name);
1609 	if ((r = sshbuf_put_cstring(c, name)) != 0 ||
1610 	    (r = sshbuf_put_string(c, NULL, 0)) != 0)
1611 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1612 }
1613 
1614 static void
add_string_option(struct sshbuf * c,const char * name,const char * value)1615 add_string_option(struct sshbuf *c, const char *name, const char *value)
1616 {
1617 	struct sshbuf *b;
1618 	int r;
1619 
1620 	debug3("%s: %s=%s", __func__, name, value);
1621 	if ((b = sshbuf_new()) == NULL)
1622 		fatal("%s: sshbuf_new failed", __func__);
1623 	if ((r = sshbuf_put_cstring(b, value)) != 0 ||
1624 	    (r = sshbuf_put_cstring(c, name)) != 0 ||
1625 	    (r = sshbuf_put_stringb(c, b)) != 0)
1626 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1627 
1628 	sshbuf_free(b);
1629 }
1630 
1631 #define OPTIONS_CRITICAL	1
1632 #define OPTIONS_EXTENSIONS	2
1633 static void
prepare_options_buf(struct sshbuf * c,int which)1634 prepare_options_buf(struct sshbuf *c, int which)
1635 {
1636 	size_t i;
1637 
1638 	sshbuf_reset(c);
1639 	if ((which & OPTIONS_CRITICAL) != 0 &&
1640 	    certflags_command != NULL)
1641 		add_string_option(c, "force-command", certflags_command);
1642 	if ((which & OPTIONS_EXTENSIONS) != 0 &&
1643 	    (certflags_flags & CERTOPT_X_FWD) != 0)
1644 		add_flag_option(c, "permit-X11-forwarding");
1645 	if ((which & OPTIONS_EXTENSIONS) != 0 &&
1646 	    (certflags_flags & CERTOPT_AGENT_FWD) != 0)
1647 		add_flag_option(c, "permit-agent-forwarding");
1648 	if ((which & OPTIONS_EXTENSIONS) != 0 &&
1649 	    (certflags_flags & CERTOPT_PORT_FWD) != 0)
1650 		add_flag_option(c, "permit-port-forwarding");
1651 	if ((which & OPTIONS_EXTENSIONS) != 0 &&
1652 	    (certflags_flags & CERTOPT_PTY) != 0)
1653 		add_flag_option(c, "permit-pty");
1654 	if ((which & OPTIONS_EXTENSIONS) != 0 &&
1655 	    (certflags_flags & CERTOPT_USER_RC) != 0)
1656 		add_flag_option(c, "permit-user-rc");
1657 	if ((which & OPTIONS_EXTENSIONS) != 0 &&
1658 	    (certflags_flags & CERTOPT_NO_REQUIRE_USER_PRESENCE) != 0)
1659 		add_flag_option(c, "no-touch-required");
1660 	if ((which & OPTIONS_CRITICAL) != 0 &&
1661 	    certflags_src_addr != NULL)
1662 		add_string_option(c, "source-address", certflags_src_addr);
1663 	for (i = 0; i < ncert_userext; i++) {
1664 		if ((cert_userext[i].crit && (which & OPTIONS_EXTENSIONS)) ||
1665 		    (!cert_userext[i].crit && (which & OPTIONS_CRITICAL)))
1666 			continue;
1667 		if (cert_userext[i].val == NULL)
1668 			add_flag_option(c, cert_userext[i].key);
1669 		else {
1670 			add_string_option(c, cert_userext[i].key,
1671 			    cert_userext[i].val);
1672 		}
1673 	}
1674 }
1675 
1676 static struct sshkey *
load_pkcs11_key(char * path)1677 load_pkcs11_key(char *path)
1678 {
1679 #ifdef ENABLE_PKCS11
1680 	struct sshkey **keys = NULL, *public, *private = NULL;
1681 	int r, i, nkeys;
1682 
1683 	if ((r = sshkey_load_public(path, &public, NULL)) != 0)
1684 		fatal("Couldn't load CA public key \"%s\": %s",
1685 		    path, ssh_err(r));
1686 
1687 	nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase,
1688 	    &keys, NULL);
1689 	debug3("%s: %d keys", __func__, nkeys);
1690 	if (nkeys <= 0)
1691 		fatal("cannot read public key from pkcs11");
1692 	for (i = 0; i < nkeys; i++) {
1693 		if (sshkey_equal_public(public, keys[i])) {
1694 			private = keys[i];
1695 			continue;
1696 		}
1697 		sshkey_free(keys[i]);
1698 	}
1699 	free(keys);
1700 	sshkey_free(public);
1701 	return private;
1702 #else
1703 	fatal("no pkcs11 support");
1704 #endif /* ENABLE_PKCS11 */
1705 }
1706 
1707 /* Signer for sshkey_certify_custom that uses the agent */
1708 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)1709 agent_signer(struct sshkey *key, u_char **sigp, size_t *lenp,
1710     const u_char *data, size_t datalen,
1711     const char *alg, const char *provider, u_int compat, void *ctx)
1712 {
1713 	int *agent_fdp = (int *)ctx;
1714 
1715 	return ssh_agent_sign(*agent_fdp, key, sigp, lenp,
1716 	    data, datalen, alg, compat);
1717 }
1718 
1719 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)1720 do_ca_sign(struct passwd *pw, const char *ca_key_path, int prefer_agent,
1721     unsigned long long cert_serial, int cert_serial_autoinc,
1722     int argc, char **argv)
1723 {
1724 	int r, i, found, agent_fd = -1;
1725 	u_int n;
1726 	struct sshkey *ca, *public;
1727 	char valid[64], *otmp, *tmp, *cp, *out, *comment;
1728 	char *ca_fp = NULL, **plist = NULL;
1729 	struct ssh_identitylist *agent_ids;
1730 	size_t j;
1731 	struct notifier_ctx *notifier = NULL;
1732 
1733 #ifdef ENABLE_PKCS11
1734 	pkcs11_init(1);
1735 #endif
1736 	tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
1737 	if (pkcs11provider != NULL) {
1738 		/* If a PKCS#11 token was specified then try to use it */
1739 		if ((ca = load_pkcs11_key(tmp)) == NULL)
1740 			fatal("No PKCS#11 key matching %s found", ca_key_path);
1741 	} else if (prefer_agent) {
1742 		/*
1743 		 * Agent signature requested. Try to use agent after making
1744 		 * sure the public key specified is actually present in the
1745 		 * agent.
1746 		 */
1747 		if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
1748 			fatal("Cannot load CA public key %s: %s",
1749 			    tmp, ssh_err(r));
1750 		if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
1751 			fatal("Cannot use public key for CA signature: %s",
1752 			    ssh_err(r));
1753 		if ((r = ssh_fetch_identitylist(agent_fd, &agent_ids)) != 0)
1754 			fatal("Retrieve agent key list: %s", ssh_err(r));
1755 		found = 0;
1756 		for (j = 0; j < agent_ids->nkeys; j++) {
1757 			if (sshkey_equal(ca, agent_ids->keys[j])) {
1758 				found = 1;
1759 				break;
1760 			}
1761 		}
1762 		if (!found)
1763 			fatal("CA key %s not found in agent", tmp);
1764 		ssh_free_identitylist(agent_ids);
1765 		ca->flags |= SSHKEY_FLAG_EXT;
1766 	} else {
1767 		/* CA key is assumed to be a private key on the filesystem */
1768 		ca = load_identity(tmp, NULL);
1769 	}
1770 	free(tmp);
1771 
1772 	if (key_type_name != NULL) {
1773 		if (sshkey_type_from_name(key_type_name) != ca->type) {
1774 			fatal("CA key type %s doesn't match specified %s",
1775 			    sshkey_ssh_name(ca), key_type_name);
1776 		}
1777 	} else if (ca->type == KEY_RSA) {
1778 		/* Default to a good signature algorithm */
1779 		key_type_name = "rsa-sha2-512";
1780 	}
1781 	ca_fp = sshkey_fingerprint(ca, fingerprint_hash, SSH_FP_DEFAULT);
1782 
1783 	for (i = 0; i < argc; i++) {
1784 		/* Split list of principals */
1785 		n = 0;
1786 		if (cert_principals != NULL) {
1787 			otmp = tmp = xstrdup(cert_principals);
1788 			plist = NULL;
1789 			for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1790 				plist = xreallocarray(plist, n + 1, sizeof(*plist));
1791 				if (*(plist[n] = xstrdup(cp)) == '\0')
1792 					fatal("Empty principal name");
1793 			}
1794 			free(otmp);
1795 		}
1796 		if (n > SSHKEY_CERT_MAX_PRINCIPALS)
1797 			fatal("Too many certificate principals specified");
1798 
1799 		tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1800 		if ((r = sshkey_load_public(tmp, &public, &comment)) != 0)
1801 			fatal("%s: unable to open \"%s\": %s",
1802 			    __func__, tmp, ssh_err(r));
1803 		if (sshkey_is_cert(public))
1804 			fatal("%s: key \"%s\" type %s cannot be certified",
1805 			    __func__, tmp, sshkey_type(public));
1806 
1807 		/* Prepare certificate to sign */
1808 		if ((r = sshkey_to_certified(public)) != 0)
1809 			fatal("Could not upgrade key %s to certificate: %s",
1810 			    tmp, ssh_err(r));
1811 		public->cert->type = cert_key_type;
1812 		public->cert->serial = (u_int64_t)cert_serial;
1813 		public->cert->key_id = xstrdup(cert_key_id);
1814 		public->cert->nprincipals = n;
1815 		public->cert->principals = plist;
1816 		public->cert->valid_after = cert_valid_from;
1817 		public->cert->valid_before = cert_valid_to;
1818 		prepare_options_buf(public->cert->critical, OPTIONS_CRITICAL);
1819 		prepare_options_buf(public->cert->extensions,
1820 		    OPTIONS_EXTENSIONS);
1821 		if ((r = sshkey_from_private(ca,
1822 		    &public->cert->signature_key)) != 0)
1823 			fatal("sshkey_from_private (ca key): %s", ssh_err(r));
1824 
1825 		if (agent_fd != -1 && (ca->flags & SSHKEY_FLAG_EXT) != 0) {
1826 			if ((r = sshkey_certify_custom(public, ca,
1827 			    key_type_name, sk_provider, agent_signer,
1828 			    &agent_fd)) != 0)
1829 				fatal("Couldn't certify key %s via agent: %s",
1830 				    tmp, ssh_err(r));
1831 		} else {
1832 			if (sshkey_is_sk(ca) &&
1833 			    (ca->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
1834 				notifier = notify_start(0,
1835 				    "Confirm user presence for key %s %s",
1836 				    sshkey_type(ca), ca_fp);
1837 			}
1838 			r = sshkey_certify(public, ca, key_type_name,
1839 			    sk_provider);
1840 			notify_complete(notifier);
1841 			if (r != 0)
1842 				fatal("Couldn't certify key %s: %s",
1843 				    tmp, ssh_err(r));
1844 		}
1845 
1846 		if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
1847 			*cp = '\0';
1848 		xasprintf(&out, "%s-cert.pub", tmp);
1849 		free(tmp);
1850 
1851 		if ((r = sshkey_save_public(public, out, comment)) != 0) {
1852 			fatal("Unable to save public key to %s: %s",
1853 			    identity_file, ssh_err(r));
1854 		}
1855 
1856 		if (!quiet) {
1857 			sshkey_format_cert_validity(public->cert,
1858 			    valid, sizeof(valid));
1859 			logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1860 			    "valid %s", sshkey_cert_type(public),
1861 			    out, public->cert->key_id,
1862 			    (unsigned long long)public->cert->serial,
1863 			    cert_principals != NULL ? " for " : "",
1864 			    cert_principals != NULL ? cert_principals : "",
1865 			    valid);
1866 		}
1867 
1868 		sshkey_free(public);
1869 		free(out);
1870 		if (cert_serial_autoinc)
1871 			cert_serial++;
1872 	}
1873 	free(ca_fp);
1874 #ifdef ENABLE_PKCS11
1875 	pkcs11_terminate();
1876 #endif
1877 	exit(0);
1878 }
1879 
1880 static u_int64_t
parse_relative_time(const char * s,time_t now)1881 parse_relative_time(const char *s, time_t now)
1882 {
1883 	int64_t mul, secs;
1884 
1885 	mul = *s == '-' ? -1 : 1;
1886 
1887 	if ((secs = convtime(s + 1)) == -1)
1888 		fatal("Invalid relative certificate time %s", s);
1889 	if (mul == -1 && secs > now)
1890 		fatal("Certificate time %s cannot be represented", s);
1891 	return now + (u_int64_t)(secs * mul);
1892 }
1893 
1894 static void
parse_cert_times(char * timespec)1895 parse_cert_times(char *timespec)
1896 {
1897 	char *from, *to;
1898 	time_t now = time(NULL);
1899 	int64_t secs;
1900 
1901 	/* +timespec relative to now */
1902 	if (*timespec == '+' && strchr(timespec, ':') == NULL) {
1903 		if ((secs = convtime(timespec + 1)) == -1)
1904 			fatal("Invalid relative certificate life %s", timespec);
1905 		cert_valid_to = now + secs;
1906 		/*
1907 		 * Backdate certificate one minute to avoid problems on hosts
1908 		 * with poorly-synchronised clocks.
1909 		 */
1910 		cert_valid_from = ((now - 59)/ 60) * 60;
1911 		return;
1912 	}
1913 
1914 	/*
1915 	 * from:to, where
1916 	 * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "always"
1917 	 *   to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "forever"
1918 	 */
1919 	from = xstrdup(timespec);
1920 	to = strchr(from, ':');
1921 	if (to == NULL || from == to || *(to + 1) == '\0')
1922 		fatal("Invalid certificate life specification %s", timespec);
1923 	*to++ = '\0';
1924 
1925 	if (*from == '-' || *from == '+')
1926 		cert_valid_from = parse_relative_time(from, now);
1927 	else if (strcmp(from, "always") == 0)
1928 		cert_valid_from = 0;
1929 	else if (parse_absolute_time(from, &cert_valid_from) != 0)
1930 		fatal("Invalid from time \"%s\"", from);
1931 
1932 	if (*to == '-' || *to == '+')
1933 		cert_valid_to = parse_relative_time(to, now);
1934 	else if (strcmp(to, "forever") == 0)
1935 		cert_valid_to = ~(u_int64_t)0;
1936 	else if (parse_absolute_time(to, &cert_valid_to) != 0)
1937 		fatal("Invalid to time \"%s\"", to);
1938 
1939 	if (cert_valid_to <= cert_valid_from)
1940 		fatal("Empty certificate validity interval");
1941 	free(from);
1942 }
1943 
1944 static void
add_cert_option(char * opt)1945 add_cert_option(char *opt)
1946 {
1947 	char *val, *cp;
1948 	int iscrit = 0;
1949 
1950 	if (strcasecmp(opt, "clear") == 0)
1951 		certflags_flags = 0;
1952 	else if (strcasecmp(opt, "no-x11-forwarding") == 0)
1953 		certflags_flags &= ~CERTOPT_X_FWD;
1954 	else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
1955 		certflags_flags |= CERTOPT_X_FWD;
1956 	else if (strcasecmp(opt, "no-agent-forwarding") == 0)
1957 		certflags_flags &= ~CERTOPT_AGENT_FWD;
1958 	else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
1959 		certflags_flags |= CERTOPT_AGENT_FWD;
1960 	else if (strcasecmp(opt, "no-port-forwarding") == 0)
1961 		certflags_flags &= ~CERTOPT_PORT_FWD;
1962 	else if (strcasecmp(opt, "permit-port-forwarding") == 0)
1963 		certflags_flags |= CERTOPT_PORT_FWD;
1964 	else if (strcasecmp(opt, "no-pty") == 0)
1965 		certflags_flags &= ~CERTOPT_PTY;
1966 	else if (strcasecmp(opt, "permit-pty") == 0)
1967 		certflags_flags |= CERTOPT_PTY;
1968 	else if (strcasecmp(opt, "no-user-rc") == 0)
1969 		certflags_flags &= ~CERTOPT_USER_RC;
1970 	else if (strcasecmp(opt, "permit-user-rc") == 0)
1971 		certflags_flags |= CERTOPT_USER_RC;
1972 	else if (strcasecmp(opt, "touch-required") == 0)
1973 		certflags_flags &= ~CERTOPT_NO_REQUIRE_USER_PRESENCE;
1974 	else if (strcasecmp(opt, "no-touch-required") == 0)
1975 		certflags_flags |= CERTOPT_NO_REQUIRE_USER_PRESENCE;
1976 	else if (strncasecmp(opt, "force-command=", 14) == 0) {
1977 		val = opt + 14;
1978 		if (*val == '\0')
1979 			fatal("Empty force-command option");
1980 		if (certflags_command != NULL)
1981 			fatal("force-command already specified");
1982 		certflags_command = xstrdup(val);
1983 	} else if (strncasecmp(opt, "source-address=", 15) == 0) {
1984 		val = opt + 15;
1985 		if (*val == '\0')
1986 			fatal("Empty source-address option");
1987 		if (certflags_src_addr != NULL)
1988 			fatal("source-address already specified");
1989 		if (addr_match_cidr_list(NULL, val) != 0)
1990 			fatal("Invalid source-address list");
1991 		certflags_src_addr = xstrdup(val);
1992 	} else if (strncasecmp(opt, "extension:", 10) == 0 ||
1993 		   (iscrit = (strncasecmp(opt, "critical:", 9) == 0))) {
1994 		val = xstrdup(strchr(opt, ':') + 1);
1995 		if ((cp = strchr(val, '=')) != NULL)
1996 			*cp++ = '\0';
1997 		cert_userext = xreallocarray(cert_userext, ncert_userext + 1,
1998 		    sizeof(*cert_userext));
1999 		cert_userext[ncert_userext].key = val;
2000 		cert_userext[ncert_userext].val = cp == NULL ?
2001 		    NULL : xstrdup(cp);
2002 		cert_userext[ncert_userext].crit = iscrit;
2003 		ncert_userext++;
2004 	} else
2005 		fatal("Unsupported certificate option \"%s\"", opt);
2006 }
2007 
2008 static void
show_options(struct sshbuf * optbuf,int in_critical)2009 show_options(struct sshbuf *optbuf, int in_critical)
2010 {
2011 	char *name, *arg;
2012 	struct sshbuf *options, *option = NULL;
2013 	int r;
2014 
2015 	if ((options = sshbuf_fromb(optbuf)) == NULL)
2016 		fatal("%s: sshbuf_fromb failed", __func__);
2017 	while (sshbuf_len(options) != 0) {
2018 		sshbuf_free(option);
2019 		option = NULL;
2020 		if ((r = sshbuf_get_cstring(options, &name, NULL)) != 0 ||
2021 		    (r = sshbuf_froms(options, &option)) != 0)
2022 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
2023 		printf("                %s", name);
2024 		if (!in_critical &&
2025 		    (strcmp(name, "permit-X11-forwarding") == 0 ||
2026 		    strcmp(name, "permit-agent-forwarding") == 0 ||
2027 		    strcmp(name, "permit-port-forwarding") == 0 ||
2028 		    strcmp(name, "permit-pty") == 0 ||
2029 		    strcmp(name, "permit-user-rc") == 0 ||
2030 		    strcmp(name, "no-touch-required") == 0)) {
2031 			printf("\n");
2032 		} else if (in_critical &&
2033 		    (strcmp(name, "force-command") == 0 ||
2034 		    strcmp(name, "source-address") == 0)) {
2035 			if ((r = sshbuf_get_cstring(option, &arg, NULL)) != 0)
2036 				fatal("%s: buffer error: %s",
2037 				    __func__, ssh_err(r));
2038 			printf(" %s\n", arg);
2039 			free(arg);
2040 		} else {
2041 			printf(" UNKNOWN OPTION (len %zu)\n",
2042 			    sshbuf_len(option));
2043 			sshbuf_reset(option);
2044 		}
2045 		free(name);
2046 		if (sshbuf_len(option) != 0)
2047 			fatal("Option corrupt: extra data at end");
2048 	}
2049 	sshbuf_free(option);
2050 	sshbuf_free(options);
2051 }
2052 
2053 static void
print_cert(struct sshkey * key)2054 print_cert(struct sshkey *key)
2055 {
2056 	char valid[64], *key_fp, *ca_fp;
2057 	u_int i;
2058 
2059 	key_fp = sshkey_fingerprint(key, fingerprint_hash, SSH_FP_DEFAULT);
2060 	ca_fp = sshkey_fingerprint(key->cert->signature_key,
2061 	    fingerprint_hash, SSH_FP_DEFAULT);
2062 	if (key_fp == NULL || ca_fp == NULL)
2063 		fatal("%s: sshkey_fingerprint fail", __func__);
2064 	sshkey_format_cert_validity(key->cert, valid, sizeof(valid));
2065 
2066 	printf("        Type: %s %s certificate\n", sshkey_ssh_name(key),
2067 	    sshkey_cert_type(key));
2068 	printf("        Public key: %s %s\n", sshkey_type(key), key_fp);
2069 	printf("        Signing CA: %s %s (using %s)\n",
2070 	    sshkey_type(key->cert->signature_key), ca_fp,
2071 	    key->cert->signature_type);
2072 	printf("        Key ID: \"%s\"\n", key->cert->key_id);
2073 	printf("        Serial: %llu\n", (unsigned long long)key->cert->serial);
2074 	printf("        Valid: %s\n", valid);
2075 	printf("        Principals: ");
2076 	if (key->cert->nprincipals == 0)
2077 		printf("(none)\n");
2078 	else {
2079 		for (i = 0; i < key->cert->nprincipals; i++)
2080 			printf("\n                %s",
2081 			    key->cert->principals[i]);
2082 		printf("\n");
2083 	}
2084 	printf("        Critical Options: ");
2085 	if (sshbuf_len(key->cert->critical) == 0)
2086 		printf("(none)\n");
2087 	else {
2088 		printf("\n");
2089 		show_options(key->cert->critical, 1);
2090 	}
2091 	printf("        Extensions: ");
2092 	if (sshbuf_len(key->cert->extensions) == 0)
2093 		printf("(none)\n");
2094 	else {
2095 		printf("\n");
2096 		show_options(key->cert->extensions, 0);
2097 	}
2098 }
2099 
2100 static void
do_show_cert(struct passwd * pw)2101 do_show_cert(struct passwd *pw)
2102 {
2103 	struct sshkey *key = NULL;
2104 	struct stat st;
2105 	int r, is_stdin = 0, ok = 0;
2106 	FILE *f;
2107 	char *cp, *line = NULL;
2108 	const char *path;
2109 	size_t linesize = 0;
2110 	u_long lnum = 0;
2111 
2112 	if (!have_identity)
2113 		ask_filename(pw, "Enter file in which the key is");
2114 	if (strcmp(identity_file, "-") != 0 && stat(identity_file, &st) == -1)
2115 		fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
2116 
2117 	path = identity_file;
2118 	if (strcmp(path, "-") == 0) {
2119 		f = stdin;
2120 		path = "(stdin)";
2121 		is_stdin = 1;
2122 	} else if ((f = fopen(identity_file, "r")) == NULL)
2123 		fatal("fopen %s: %s", identity_file, strerror(errno));
2124 
2125 	while (getline(&line, &linesize, f) != -1) {
2126 		lnum++;
2127 		sshkey_free(key);
2128 		key = NULL;
2129 		/* Trim leading space and comments */
2130 		cp = line + strspn(line, " \t");
2131 		if (*cp == '#' || *cp == '\0')
2132 			continue;
2133 		if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2134 			fatal("sshkey_new");
2135 		if ((r = sshkey_read(key, &cp)) != 0) {
2136 			error("%s:%lu: invalid key: %s", path,
2137 			    lnum, ssh_err(r));
2138 			continue;
2139 		}
2140 		if (!sshkey_is_cert(key)) {
2141 			error("%s:%lu is not a certificate", path, lnum);
2142 			continue;
2143 		}
2144 		ok = 1;
2145 		if (!is_stdin && lnum == 1)
2146 			printf("%s:\n", path);
2147 		else
2148 			printf("%s:%lu:\n", path, lnum);
2149 		print_cert(key);
2150 	}
2151 	free(line);
2152 	sshkey_free(key);
2153 	fclose(f);
2154 	exit(ok ? 0 : 1);
2155 }
2156 
2157 static void
load_krl(const char * path,struct ssh_krl ** krlp)2158 load_krl(const char *path, struct ssh_krl **krlp)
2159 {
2160 	struct sshbuf *krlbuf;
2161 	int r;
2162 
2163 	if ((r = sshbuf_load_file(path, &krlbuf)) != 0)
2164 		fatal("Unable to load KRL: %s", ssh_err(r));
2165 	/* XXX check sigs */
2166 	if ((r = ssh_krl_from_blob(krlbuf, krlp, NULL, 0)) != 0 ||
2167 	    *krlp == NULL)
2168 		fatal("Invalid KRL file: %s", ssh_err(r));
2169 	sshbuf_free(krlbuf);
2170 }
2171 
2172 static void
hash_to_blob(const char * cp,u_char ** blobp,size_t * lenp,const char * file,u_long lnum)2173 hash_to_blob(const char *cp, u_char **blobp, size_t *lenp,
2174     const char *file, u_long lnum)
2175 {
2176 	char *tmp;
2177 	size_t tlen;
2178 	struct sshbuf *b;
2179 	int r;
2180 
2181 	if (strncmp(cp, "SHA256:", 7) != 0)
2182 		fatal("%s:%lu: unsupported hash algorithm", file, lnum);
2183 	cp += 7;
2184 
2185 	/*
2186 	 * OpenSSH base64 hashes omit trailing '='
2187 	 * characters; put them back for decode.
2188 	 */
2189 	tlen = strlen(cp);
2190 	tmp = xmalloc(tlen + 4 + 1);
2191 	strlcpy(tmp, cp, tlen + 1);
2192 	while ((tlen % 4) != 0) {
2193 		tmp[tlen++] = '=';
2194 		tmp[tlen] = '\0';
2195 	}
2196 	if ((b = sshbuf_new()) == NULL)
2197 		fatal("%s: sshbuf_new failed", __func__);
2198 	if ((r = sshbuf_b64tod(b, tmp)) != 0)
2199 		fatal("%s:%lu: decode hash failed: %s", file, lnum, ssh_err(r));
2200 	free(tmp);
2201 	*lenp = sshbuf_len(b);
2202 	*blobp = xmalloc(*lenp);
2203 	memcpy(*blobp, sshbuf_ptr(b), *lenp);
2204 	sshbuf_free(b);
2205 }
2206 
2207 static void
update_krl_from_file(struct passwd * pw,const char * file,int wild_ca,const struct sshkey * ca,struct ssh_krl * krl)2208 update_krl_from_file(struct passwd *pw, const char *file, int wild_ca,
2209     const struct sshkey *ca, struct ssh_krl *krl)
2210 {
2211 	struct sshkey *key = NULL;
2212 	u_long lnum = 0;
2213 	char *path, *cp, *ep, *line = NULL;
2214 	u_char *blob = NULL;
2215 	size_t blen = 0, linesize = 0;
2216 	unsigned long long serial, serial2;
2217 	int i, was_explicit_key, was_sha1, was_sha256, was_hash, r;
2218 	FILE *krl_spec;
2219 
2220 	path = tilde_expand_filename(file, pw->pw_uid);
2221 	if (strcmp(path, "-") == 0) {
2222 		krl_spec = stdin;
2223 		free(path);
2224 		path = xstrdup("(standard input)");
2225 	} else if ((krl_spec = fopen(path, "r")) == NULL)
2226 		fatal("fopen %s: %s", path, strerror(errno));
2227 
2228 	if (!quiet)
2229 		printf("Revoking from %s\n", path);
2230 	while (getline(&line, &linesize, krl_spec) != -1) {
2231 		lnum++;
2232 		was_explicit_key = was_sha1 = was_sha256 = was_hash = 0;
2233 		cp = line + strspn(line, " \t");
2234 		/* Trim trailing space, comments and strip \n */
2235 		for (i = 0, r = -1; cp[i] != '\0'; i++) {
2236 			if (cp[i] == '#' || cp[i] == '\n') {
2237 				cp[i] = '\0';
2238 				break;
2239 			}
2240 			if (cp[i] == ' ' || cp[i] == '\t') {
2241 				/* Remember the start of a span of whitespace */
2242 				if (r == -1)
2243 					r = i;
2244 			} else
2245 				r = -1;
2246 		}
2247 		if (r != -1)
2248 			cp[r] = '\0';
2249 		if (*cp == '\0')
2250 			continue;
2251 		if (strncasecmp(cp, "serial:", 7) == 0) {
2252 			if (ca == NULL && !wild_ca) {
2253 				fatal("revoking certificates by serial number "
2254 				    "requires specification of a CA key");
2255 			}
2256 			cp += 7;
2257 			cp = cp + strspn(cp, " \t");
2258 			errno = 0;
2259 			serial = strtoull(cp, &ep, 0);
2260 			if (*cp == '\0' || (*ep != '\0' && *ep != '-'))
2261 				fatal("%s:%lu: invalid serial \"%s\"",
2262 				    path, lnum, cp);
2263 			if (errno == ERANGE && serial == ULLONG_MAX)
2264 				fatal("%s:%lu: serial out of range",
2265 				    path, lnum);
2266 			serial2 = serial;
2267 			if (*ep == '-') {
2268 				cp = ep + 1;
2269 				errno = 0;
2270 				serial2 = strtoull(cp, &ep, 0);
2271 				if (*cp == '\0' || *ep != '\0')
2272 					fatal("%s:%lu: invalid serial \"%s\"",
2273 					    path, lnum, cp);
2274 				if (errno == ERANGE && serial2 == ULLONG_MAX)
2275 					fatal("%s:%lu: serial out of range",
2276 					    path, lnum);
2277 				if (serial2 <= serial)
2278 					fatal("%s:%lu: invalid serial range "
2279 					    "%llu:%llu", path, lnum,
2280 					    (unsigned long long)serial,
2281 					    (unsigned long long)serial2);
2282 			}
2283 			if (ssh_krl_revoke_cert_by_serial_range(krl,
2284 			    ca, serial, serial2) != 0) {
2285 				fatal("%s: revoke serial failed",
2286 				    __func__);
2287 			}
2288 		} else if (strncasecmp(cp, "id:", 3) == 0) {
2289 			if (ca == NULL && !wild_ca) {
2290 				fatal("revoking certificates by key ID "
2291 				    "requires specification of a CA key");
2292 			}
2293 			cp += 3;
2294 			cp = cp + strspn(cp, " \t");
2295 			if (ssh_krl_revoke_cert_by_key_id(krl, ca, cp) != 0)
2296 				fatal("%s: revoke key ID failed", __func__);
2297 		} else if (strncasecmp(cp, "hash:", 5) == 0) {
2298 			cp += 5;
2299 			cp = cp + strspn(cp, " \t");
2300 			hash_to_blob(cp, &blob, &blen, file, lnum);
2301 			r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2302 			if (r != 0)
2303 				fatal("%s: revoke key failed: %s",
2304 				    __func__, ssh_err(r));
2305 		} else {
2306 			if (strncasecmp(cp, "key:", 4) == 0) {
2307 				cp += 4;
2308 				cp = cp + strspn(cp, " \t");
2309 				was_explicit_key = 1;
2310 			} else if (strncasecmp(cp, "sha1:", 5) == 0) {
2311 				cp += 5;
2312 				cp = cp + strspn(cp, " \t");
2313 				was_sha1 = 1;
2314 			} else if (strncasecmp(cp, "sha256:", 7) == 0) {
2315 				cp += 7;
2316 				cp = cp + strspn(cp, " \t");
2317 				was_sha256 = 1;
2318 				/*
2319 				 * Just try to process the line as a key.
2320 				 * Parsing will fail if it isn't.
2321 				 */
2322 			}
2323 			if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2324 				fatal("sshkey_new");
2325 			if ((r = sshkey_read(key, &cp)) != 0)
2326 				fatal("%s:%lu: invalid key: %s",
2327 				    path, lnum, ssh_err(r));
2328 			if (was_explicit_key)
2329 				r = ssh_krl_revoke_key_explicit(krl, key);
2330 			else if (was_sha1) {
2331 				if (sshkey_fingerprint_raw(key,
2332 				    SSH_DIGEST_SHA1, &blob, &blen) != 0) {
2333 					fatal("%s:%lu: fingerprint failed",
2334 					    file, lnum);
2335 				}
2336 				r = ssh_krl_revoke_key_sha1(krl, blob, blen);
2337 			} else if (was_sha256) {
2338 				if (sshkey_fingerprint_raw(key,
2339 				    SSH_DIGEST_SHA256, &blob, &blen) != 0) {
2340 					fatal("%s:%lu: fingerprint failed",
2341 					    file, lnum);
2342 				}
2343 				r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2344 			} else
2345 				r = ssh_krl_revoke_key(krl, key);
2346 			if (r != 0)
2347 				fatal("%s: revoke key failed: %s",
2348 				    __func__, ssh_err(r));
2349 			freezero(blob, blen);
2350 			blob = NULL;
2351 			blen = 0;
2352 			sshkey_free(key);
2353 		}
2354 	}
2355 	if (strcmp(path, "-") != 0)
2356 		fclose(krl_spec);
2357 	free(line);
2358 	free(path);
2359 }
2360 
2361 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)2362 do_gen_krl(struct passwd *pw, int updating, const char *ca_key_path,
2363     unsigned long long krl_version, const char *krl_comment,
2364     int argc, char **argv)
2365 {
2366 	struct ssh_krl *krl;
2367 	struct stat sb;
2368 	struct sshkey *ca = NULL;
2369 	int i, r, wild_ca = 0;
2370 	char *tmp;
2371 	struct sshbuf *kbuf;
2372 
2373 	if (*identity_file == '\0')
2374 		fatal("KRL generation requires an output file");
2375 	if (stat(identity_file, &sb) == -1) {
2376 		if (errno != ENOENT)
2377 			fatal("Cannot access KRL \"%s\": %s",
2378 			    identity_file, strerror(errno));
2379 		if (updating)
2380 			fatal("KRL \"%s\" does not exist", identity_file);
2381 	}
2382 	if (ca_key_path != NULL) {
2383 		if (strcasecmp(ca_key_path, "none") == 0)
2384 			wild_ca = 1;
2385 		else {
2386 			tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
2387 			if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
2388 				fatal("Cannot load CA public key %s: %s",
2389 				    tmp, ssh_err(r));
2390 			free(tmp);
2391 		}
2392 	}
2393 
2394 	if (updating)
2395 		load_krl(identity_file, &krl);
2396 	else if ((krl = ssh_krl_init()) == NULL)
2397 		fatal("couldn't create KRL");
2398 
2399 	if (krl_version != 0)
2400 		ssh_krl_set_version(krl, krl_version);
2401 	if (krl_comment != NULL)
2402 		ssh_krl_set_comment(krl, krl_comment);
2403 
2404 	for (i = 0; i < argc; i++)
2405 		update_krl_from_file(pw, argv[i], wild_ca, ca, krl);
2406 
2407 	if ((kbuf = sshbuf_new()) == NULL)
2408 		fatal("sshbuf_new failed");
2409 	if (ssh_krl_to_blob(krl, kbuf, NULL, 0) != 0)
2410 		fatal("Couldn't generate KRL");
2411 	if ((r = sshbuf_write_file(identity_file, kbuf)) != 0)
2412 		fatal("write %s: %s", identity_file, strerror(errno));
2413 	sshbuf_free(kbuf);
2414 	ssh_krl_free(krl);
2415 	sshkey_free(ca);
2416 }
2417 
2418 static void
do_check_krl(struct passwd * pw,int print_krl,int argc,char ** argv)2419 do_check_krl(struct passwd *pw, int print_krl, int argc, char **argv)
2420 {
2421 	int i, r, ret = 0;
2422 	char *comment;
2423 	struct ssh_krl *krl;
2424 	struct sshkey *k;
2425 
2426 	if (*identity_file == '\0')
2427 		fatal("KRL checking requires an input file");
2428 	load_krl(identity_file, &krl);
2429 	if (print_krl)
2430 		krl_dump(krl, stdout);
2431 	for (i = 0; i < argc; i++) {
2432 		if ((r = sshkey_load_public(argv[i], &k, &comment)) != 0)
2433 			fatal("Cannot load public key %s: %s",
2434 			    argv[i], ssh_err(r));
2435 		r = ssh_krl_check_key(krl, k);
2436 		printf("%s%s%s%s: %s\n", argv[i],
2437 		    *comment ? " (" : "", comment, *comment ? ")" : "",
2438 		    r == 0 ? "ok" : "REVOKED");
2439 		if (r != 0)
2440 			ret = 1;
2441 		sshkey_free(k);
2442 		free(comment);
2443 	}
2444 	ssh_krl_free(krl);
2445 	exit(ret);
2446 }
2447 
2448 static struct sshkey *
load_sign_key(const char * keypath,const struct sshkey * pubkey)2449 load_sign_key(const char *keypath, const struct sshkey *pubkey)
2450 {
2451 	size_t i, slen, plen = strlen(keypath);
2452 	char *privpath = xstrdup(keypath);
2453 	const char *suffixes[] = { "-cert.pub", ".pub", NULL };
2454 	struct sshkey *ret = NULL, *privkey = NULL;
2455 	int r;
2456 
2457 	/*
2458 	 * If passed a public key filename, then try to locate the corresponding
2459 	 * private key. This lets us specify certificates on the command-line
2460 	 * and have ssh-keygen find the appropriate private key.
2461 	 */
2462 	for (i = 0; suffixes[i]; i++) {
2463 		slen = strlen(suffixes[i]);
2464 		if (plen <= slen ||
2465 		    strcmp(privpath + plen - slen, suffixes[i]) != 0)
2466 			continue;
2467 		privpath[plen - slen] = '\0';
2468 		debug("%s: %s looks like a public key, using private key "
2469 		    "path %s instead", __func__, keypath, privpath);
2470 	}
2471 	if ((privkey = load_identity(privpath, NULL)) == NULL) {
2472 		error("Couldn't load identity %s", keypath);
2473 		goto done;
2474 	}
2475 	if (!sshkey_equal_public(pubkey, privkey)) {
2476 		error("Public key %s doesn't match private %s",
2477 		    keypath, privpath);
2478 		goto done;
2479 	}
2480 	if (sshkey_is_cert(pubkey) && !sshkey_is_cert(privkey)) {
2481 		/*
2482 		 * Graft the certificate onto the private key to make
2483 		 * it capable of signing.
2484 		 */
2485 		if ((r = sshkey_to_certified(privkey)) != 0) {
2486 			error("%s: sshkey_to_certified: %s", __func__,
2487 			    ssh_err(r));
2488 			goto done;
2489 		}
2490 		if ((r = sshkey_cert_copy(pubkey, privkey)) != 0) {
2491 			error("%s: sshkey_cert_copy: %s", __func__, ssh_err(r));
2492 			goto done;
2493 		}
2494 	}
2495 	/* success */
2496 	ret = privkey;
2497 	privkey = NULL;
2498  done:
2499 	sshkey_free(privkey);
2500 	free(privpath);
2501 	return ret;
2502 }
2503 
2504 static int
sign_one(struct sshkey * signkey,const char * filename,int fd,const char * sig_namespace,sshsig_signer * signer,void * signer_ctx)2505 sign_one(struct sshkey *signkey, const char *filename, int fd,
2506     const char *sig_namespace, sshsig_signer *signer, void *signer_ctx)
2507 {
2508 	struct sshbuf *sigbuf = NULL, *abuf = NULL;
2509 	int r = SSH_ERR_INTERNAL_ERROR, wfd = -1, oerrno;
2510 	char *wfile = NULL, *asig = NULL, *fp = NULL;
2511 
2512 	if (!quiet) {
2513 		if (fd == STDIN_FILENO)
2514 			fprintf(stderr, "Signing data on standard input\n");
2515 		else
2516 			fprintf(stderr, "Signing file %s\n", filename);
2517 	}
2518 	if (signer == NULL && sshkey_is_sk(signkey) &&
2519 	    (signkey->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
2520 		if ((fp = sshkey_fingerprint(signkey, fingerprint_hash,
2521 		    SSH_FP_DEFAULT)) == NULL)
2522 			fatal("%s: sshkey_fingerprint failed", __func__);
2523 		fprintf(stderr, "Confirm user presence for key %s %s\n",
2524 		    sshkey_type(signkey), fp);
2525 		free(fp);
2526 	}
2527 	if ((r = sshsig_sign_fd(signkey, NULL, sk_provider, fd, sig_namespace,
2528 	    &sigbuf, signer, signer_ctx)) != 0) {
2529 		error("Signing %s failed: %s", filename, ssh_err(r));
2530 		goto out;
2531 	}
2532 	if ((r = sshsig_armor(sigbuf, &abuf)) != 0) {
2533 		error("%s: sshsig_armor: %s", __func__, ssh_err(r));
2534 		goto out;
2535 	}
2536 	if ((asig = sshbuf_dup_string(abuf)) == NULL) {
2537 		error("%s: buffer error", __func__);
2538 		r = SSH_ERR_ALLOC_FAIL;
2539 		goto out;
2540 	}
2541 
2542 	if (fd == STDIN_FILENO) {
2543 		fputs(asig, stdout);
2544 		fflush(stdout);
2545 	} else {
2546 		xasprintf(&wfile, "%s.sig", filename);
2547 		if (confirm_overwrite(wfile)) {
2548 			if ((wfd = open(wfile, O_WRONLY|O_CREAT|O_TRUNC,
2549 			    0666)) == -1) {
2550 				oerrno = errno;
2551 				error("Cannot open %s: %s",
2552 				    wfile, strerror(errno));
2553 				errno = oerrno;
2554 				r = SSH_ERR_SYSTEM_ERROR;
2555 				goto out;
2556 			}
2557 			if (atomicio(vwrite, wfd, asig,
2558 			    strlen(asig)) != strlen(asig)) {
2559 				oerrno = errno;
2560 				error("Cannot write to %s: %s",
2561 				    wfile, strerror(errno));
2562 				errno = oerrno;
2563 				r = SSH_ERR_SYSTEM_ERROR;
2564 				goto out;
2565 			}
2566 			if (!quiet) {
2567 				fprintf(stderr, "Write signature to %s\n",
2568 				    wfile);
2569 			}
2570 		}
2571 	}
2572 	/* success */
2573 	r = 0;
2574  out:
2575 	free(wfile);
2576 	free(asig);
2577 	sshbuf_free(abuf);
2578 	sshbuf_free(sigbuf);
2579 	if (wfd != -1)
2580 		close(wfd);
2581 	return r;
2582 }
2583 
2584 static int
sig_sign(const char * keypath,const char * sig_namespace,int argc,char ** argv)2585 sig_sign(const char *keypath, const char *sig_namespace, int argc, char **argv)
2586 {
2587 	int i, fd = -1, r, ret = -1;
2588 	int agent_fd = -1;
2589 	struct sshkey *pubkey = NULL, *privkey = NULL, *signkey = NULL;
2590 	sshsig_signer *signer = NULL;
2591 
2592 	/* Check file arguments. */
2593 	for (i = 0; i < argc; i++) {
2594 		if (strcmp(argv[i], "-") != 0)
2595 			continue;
2596 		if (i > 0 || argc > 1)
2597 			fatal("Cannot sign mix of paths and standard input");
2598 	}
2599 
2600 	if ((r = sshkey_load_public(keypath, &pubkey, NULL)) != 0) {
2601 		error("Couldn't load public key %s: %s", keypath, ssh_err(r));
2602 		goto done;
2603 	}
2604 
2605 	if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
2606 		debug("Couldn't get agent socket: %s", ssh_err(r));
2607 	else {
2608 		if ((r = ssh_agent_has_key(agent_fd, pubkey)) == 0)
2609 			signer = agent_signer;
2610 		else
2611 			debug("Couldn't find key in agent: %s", ssh_err(r));
2612 	}
2613 
2614 	if (signer == NULL) {
2615 		/* Not using agent - try to load private key */
2616 		if ((privkey = load_sign_key(keypath, pubkey)) == NULL)
2617 			goto done;
2618 		signkey = privkey;
2619 	} else {
2620 		/* Will use key in agent */
2621 		signkey = pubkey;
2622 	}
2623 
2624 	if (argc == 0) {
2625 		if ((r = sign_one(signkey, "(stdin)", STDIN_FILENO,
2626 		    sig_namespace, signer, &agent_fd)) != 0)
2627 			goto done;
2628 	} else {
2629 		for (i = 0; i < argc; i++) {
2630 			if (strcmp(argv[i], "-") == 0)
2631 				fd = STDIN_FILENO;
2632 			else if ((fd = open(argv[i], O_RDONLY)) == -1) {
2633 				error("Cannot open %s for signing: %s",
2634 				    argv[i], strerror(errno));
2635 				goto done;
2636 			}
2637 			if ((r = sign_one(signkey, argv[i], fd, sig_namespace,
2638 			    signer, &agent_fd)) != 0)
2639 				goto done;
2640 			if (fd != STDIN_FILENO)
2641 				close(fd);
2642 			fd = -1;
2643 		}
2644 	}
2645 
2646 	ret = 0;
2647 done:
2648 	if (fd != -1 && fd != STDIN_FILENO)
2649 		close(fd);
2650 	sshkey_free(pubkey);
2651 	sshkey_free(privkey);
2652 	return ret;
2653 }
2654 
2655 static int
sig_verify(const char * signature,const char * sig_namespace,const char * principal,const char * allowed_keys,const char * revoked_keys)2656 sig_verify(const char *signature, const char *sig_namespace,
2657     const char *principal, const char *allowed_keys, const char *revoked_keys)
2658 {
2659 	int r, ret = -1;
2660 	struct sshbuf *sigbuf = NULL, *abuf = NULL;
2661 	struct sshkey *sign_key = NULL;
2662 	char *fp = NULL;
2663 	struct sshkey_sig_details *sig_details = NULL;
2664 
2665 	memset(&sig_details, 0, sizeof(sig_details));
2666 	if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
2667 		error("Couldn't read signature file: %s", ssh_err(r));
2668 		goto done;
2669 	}
2670 
2671 	if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
2672 		error("%s: sshsig_armor: %s", __func__, ssh_err(r));
2673 		goto done;
2674 	}
2675 	if ((r = sshsig_verify_fd(sigbuf, STDIN_FILENO, sig_namespace,
2676 	    &sign_key, &sig_details)) != 0)
2677 		goto done; /* sshsig_verify() prints error */
2678 
2679 	if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
2680 	    SSH_FP_DEFAULT)) == NULL)
2681 		fatal("%s: sshkey_fingerprint failed", __func__);
2682 	debug("Valid (unverified) signature from key %s", fp);
2683 	if (sig_details != NULL) {
2684 		debug2("%s: signature details: counter = %u, flags = 0x%02x",
2685 		    __func__, sig_details->sk_counter, sig_details->sk_flags);
2686 	}
2687 	free(fp);
2688 	fp = NULL;
2689 
2690 	if (revoked_keys != NULL) {
2691 		if ((r = sshkey_check_revoked(sign_key, revoked_keys)) != 0) {
2692 			debug3("sshkey_check_revoked failed: %s", ssh_err(r));
2693 			goto done;
2694 		}
2695 	}
2696 
2697 	if (allowed_keys != NULL &&
2698 	    (r = sshsig_check_allowed_keys(allowed_keys, sign_key,
2699 					   principal, sig_namespace)) != 0) {
2700 		debug3("sshsig_check_allowed_keys failed: %s", ssh_err(r));
2701 		goto done;
2702 	}
2703 	/* success */
2704 	ret = 0;
2705 done:
2706 	if (!quiet) {
2707 		if (ret == 0) {
2708 			if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
2709 			    SSH_FP_DEFAULT)) == NULL) {
2710 				fatal("%s: sshkey_fingerprint failed",
2711 				    __func__);
2712 			}
2713 			if (principal == NULL) {
2714 				printf("Good \"%s\" signature with %s key %s\n",
2715 				       sig_namespace, sshkey_type(sign_key), fp);
2716 
2717 			} else {
2718 				printf("Good \"%s\" signature for %s with %s key %s\n",
2719 				       sig_namespace, principal,
2720 				       sshkey_type(sign_key), fp);
2721 			}
2722 		} else {
2723 			printf("Could not verify signature.\n");
2724 		}
2725 	}
2726 	sshbuf_free(sigbuf);
2727 	sshbuf_free(abuf);
2728 	sshkey_free(sign_key);
2729 	sshkey_sig_details_free(sig_details);
2730 	free(fp);
2731 	return ret;
2732 }
2733 
2734 static int
sig_find_principals(const char * signature,const char * allowed_keys)2735 sig_find_principals(const char *signature, const char *allowed_keys) {
2736 	int r, ret = -1;
2737 	struct sshbuf *sigbuf = NULL, *abuf = NULL;
2738 	struct sshkey *sign_key = NULL;
2739 	char *principals = NULL, *cp, *tmp;
2740 
2741 	if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
2742 		error("Couldn't read signature file: %s", ssh_err(r));
2743 		goto done;
2744 	}
2745 	if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
2746 		error("%s: sshsig_armor: %s", __func__, ssh_err(r));
2747 		goto done;
2748 	}
2749 	if ((r = sshsig_get_pubkey(sigbuf, &sign_key)) != 0) {
2750 		error("%s: sshsig_get_pubkey: %s",
2751 		    __func__, ssh_err(r));
2752 		goto done;
2753 	}
2754 	if ((r = sshsig_find_principals(allowed_keys, sign_key,
2755 	    &principals)) != 0) {
2756 		error("%s: sshsig_get_principal: %s",
2757 		      __func__, ssh_err(r));
2758 		goto done;
2759 	}
2760 	ret = 0;
2761 done:
2762 	if (ret == 0 ) {
2763 		/* Emit matching principals one per line */
2764 		tmp = principals;
2765 		while ((cp = strsep(&tmp, ",")) != NULL && *cp != '\0')
2766 			puts(cp);
2767 	} else {
2768 		fprintf(stderr, "No principal matched.\n");
2769 	}
2770 	sshbuf_free(sigbuf);
2771 	sshbuf_free(abuf);
2772 	sshkey_free(sign_key);
2773 	free(principals);
2774 	return ret;
2775 }
2776 
2777 static void
do_moduli_gen(const char * out_file,char ** opts,size_t nopts)2778 do_moduli_gen(const char *out_file, char **opts, size_t nopts)
2779 {
2780 #ifdef WITH_OPENSSL
2781 	/* Moduli generation/screening */
2782 	u_int32_t memory = 0;
2783 	BIGNUM *start = NULL;
2784 	int moduli_bits = 0;
2785 	FILE *out;
2786 	size_t i;
2787 	const char *errstr;
2788 
2789 	/* Parse options */
2790 	for (i = 0; i < nopts; i++) {
2791 		if (strncmp(opts[i], "memory=", 7) == 0) {
2792 			memory = (u_int32_t)strtonum(opts[i]+7, 1,
2793 			    UINT_MAX, &errstr);
2794 			if (errstr) {
2795 				fatal("Memory limit is %s: %s",
2796 				    errstr, opts[i]+7);
2797 			}
2798 		} else if (strncmp(opts[i], "start=", 6) == 0) {
2799 			/* XXX - also compare length against bits */
2800 			if (BN_hex2bn(&start, opts[i]+6) == 0)
2801 				fatal("Invalid start point.");
2802 		} else if (strncmp(opts[i], "bits=", 5) == 0) {
2803 			moduli_bits = (int)strtonum(opts[i]+5, 1,
2804 			    INT_MAX, &errstr);
2805 			if (errstr) {
2806 				fatal("Invalid number: %s (%s)",
2807 					opts[i]+12, errstr);
2808 			}
2809 		} else {
2810 			fatal("Option \"%s\" is unsupported for moduli "
2811 			    "generation", opts[i]);
2812 		}
2813 	}
2814 
2815 	if ((out = fopen(out_file, "w")) == NULL) {
2816 		fatal("Couldn't open modulus candidate file \"%s\": %s",
2817 		    out_file, strerror(errno));
2818 	}
2819 	setvbuf(out, NULL, _IOLBF, 0);
2820 
2821 	if (moduli_bits == 0)
2822 		moduli_bits = DEFAULT_BITS;
2823 	if (gen_candidates(out, memory, moduli_bits, start) != 0)
2824 		fatal("modulus candidate generation failed");
2825 #else /* WITH_OPENSSL */
2826 	fatal("Moduli generation is not supported");
2827 #endif /* WITH_OPENSSL */
2828 }
2829 
2830 static void
do_moduli_screen(const char * out_file,char ** opts,size_t nopts)2831 do_moduli_screen(const char *out_file, char **opts, size_t nopts)
2832 {
2833 #ifdef WITH_OPENSSL
2834 	/* Moduli generation/screening */
2835 	char *checkpoint = NULL;
2836 	u_int32_t generator_wanted = 0;
2837 	unsigned long start_lineno = 0, lines_to_process = 0;
2838 	int prime_tests = 0;
2839 	FILE *out, *in = stdin;
2840 	size_t i;
2841 	const char *errstr;
2842 
2843 	/* Parse options */
2844 	for (i = 0; i < nopts; i++) {
2845 		if (strncmp(opts[i], "lines=", 6) == 0) {
2846 			lines_to_process = strtoul(opts[i]+6, NULL, 10);
2847 		} else if (strncmp(opts[i], "start-line=", 11) == 0) {
2848 			start_lineno = strtoul(opts[i]+11, NULL, 10);
2849 		} else if (strncmp(opts[i], "checkpoint=", 11) == 0) {
2850 			checkpoint = xstrdup(opts[i]+11);
2851 		} else if (strncmp(opts[i], "generator=", 10) == 0) {
2852 			generator_wanted = (u_int32_t)strtonum(
2853 			    opts[i]+10, 1, UINT_MAX, &errstr);
2854 			if (errstr != NULL) {
2855 				fatal("Generator invalid: %s (%s)",
2856 				    opts[i]+10, errstr);
2857 			}
2858 		} else if (strncmp(opts[i], "prime-tests=", 12) == 0) {
2859 			prime_tests = (int)strtonum(opts[i]+12, 1,
2860 			    INT_MAX, &errstr);
2861 			if (errstr) {
2862 				fatal("Invalid number: %s (%s)",
2863 					opts[i]+12, errstr);
2864 			}
2865 		} else {
2866 			fatal("Option \"%s\" is unsupported for moduli "
2867 			    "screening", opts[i]);
2868 		}
2869 	}
2870 
2871 	if (have_identity && strcmp(identity_file, "-") != 0) {
2872 		if ((in = fopen(identity_file, "r")) == NULL) {
2873 			fatal("Couldn't open modulus candidate "
2874 			    "file \"%s\": %s", identity_file,
2875 			    strerror(errno));
2876 		}
2877 	}
2878 
2879 	if ((out = fopen(out_file, "a")) == NULL) {
2880 		fatal("Couldn't open moduli file \"%s\": %s",
2881 		    out_file, strerror(errno));
2882 	}
2883 	setvbuf(out, NULL, _IOLBF, 0);
2884 	if (prime_test(in, out, prime_tests == 0 ? 100 : prime_tests,
2885 	    generator_wanted, checkpoint,
2886 	    start_lineno, lines_to_process) != 0)
2887 		fatal("modulus screening failed");
2888 #else /* WITH_OPENSSL */
2889 	fatal("Moduli screening is not supported");
2890 #endif /* WITH_OPENSSL */
2891 }
2892 
2893 static char *
private_key_passphrase(void)2894 private_key_passphrase(void)
2895 {
2896 	char *passphrase1, *passphrase2;
2897 
2898 	/* Ask for a passphrase (twice). */
2899 	if (identity_passphrase)
2900 		passphrase1 = xstrdup(identity_passphrase);
2901 	else if (identity_new_passphrase)
2902 		passphrase1 = xstrdup(identity_new_passphrase);
2903 	else {
2904 passphrase_again:
2905 		passphrase1 =
2906 			read_passphrase("Enter passphrase (empty for no "
2907 			    "passphrase): ", RP_ALLOW_STDIN);
2908 		passphrase2 = read_passphrase("Enter same passphrase again: ",
2909 		    RP_ALLOW_STDIN);
2910 		if (strcmp(passphrase1, passphrase2) != 0) {
2911 			/*
2912 			 * The passphrases do not match.  Clear them and
2913 			 * retry.
2914 			 */
2915 			freezero(passphrase1, strlen(passphrase1));
2916 			freezero(passphrase2, strlen(passphrase2));
2917 			printf("Passphrases do not match.  Try again.\n");
2918 			goto passphrase_again;
2919 		}
2920 		/* Clear the other copy of the passphrase. */
2921 		freezero(passphrase2, strlen(passphrase2));
2922 	}
2923 	return passphrase1;
2924 }
2925