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