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