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