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