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