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