1 /* $NetBSD: ssh-keygen.c,v 1.41 2021/09/27 17:03:13 christos Exp $ */ 2 /* $OpenBSD: ssh-keygen.c,v 1.437 2021/09/08 03:23:44 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.41 2021/09/27 17:03:13 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 <stdarg.h> 34 #include <stdio.h> 35 #include <stdlib.h> 36 #include <string.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_process_opts(char * const *opts, size_t nopts, uint64_t *verify_timep, 2658 int *print_pubkey) 2659 { 2660 size_t i; 2661 time_t now; 2662 2663 *verify_timep = 0; 2664 if (print_pubkey != NULL) 2665 *print_pubkey = 0; 2666 for (i = 0; i < nopts; i++) { 2667 if (strncasecmp(opts[i], "verify-time=", 12) == 0) { 2668 if (parse_absolute_time(opts[i] + 12, 2669 verify_timep) != 0 || *verify_timep == 0) { 2670 error("Invalid \"verify-time\" option"); 2671 return SSH_ERR_INVALID_ARGUMENT; 2672 } 2673 } else if (print_pubkey && 2674 strcasecmp(opts[i], "print-pubkey") == 0) { 2675 *print_pubkey = 1; 2676 } else { 2677 error("Invalid option \"%s\"", opts[i]); 2678 return SSH_ERR_INVALID_ARGUMENT; 2679 } 2680 } 2681 if (*verify_timep == 0) { 2682 if ((now = time(NULL)) < 0) { 2683 error("Time is before epoch"); 2684 return SSH_ERR_INVALID_ARGUMENT; 2685 } 2686 *verify_timep = (uint64_t)now; 2687 } 2688 return 0; 2689 } 2690 2691 static int 2692 sig_verify(const char *signature, const char *sig_namespace, 2693 const char *principal, const char *allowed_keys, const char *revoked_keys, 2694 char * const *opts, size_t nopts) 2695 { 2696 int r, ret = -1; 2697 int print_pubkey = 0; 2698 struct sshbuf *sigbuf = NULL, *abuf = NULL; 2699 struct sshkey *sign_key = NULL; 2700 char *fp = NULL; 2701 struct sshkey_sig_details *sig_details = NULL; 2702 uint64_t verify_time = 0; 2703 2704 if (sig_process_opts(opts, nopts, &verify_time, &print_pubkey) != 0) 2705 goto done; /* error already logged */ 2706 2707 memset(&sig_details, 0, sizeof(sig_details)); 2708 if ((r = sshbuf_load_file(signature, &abuf)) != 0) { 2709 error_r(r, "Couldn't read signature file"); 2710 goto done; 2711 } 2712 2713 if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) { 2714 error_fr(r, "sshsig_armor"); 2715 goto done; 2716 } 2717 if ((r = sshsig_verify_fd(sigbuf, STDIN_FILENO, sig_namespace, 2718 &sign_key, &sig_details)) != 0) 2719 goto done; /* sshsig_verify() prints error */ 2720 2721 if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash, 2722 SSH_FP_DEFAULT)) == NULL) 2723 fatal_f("sshkey_fingerprint failed"); 2724 debug("Valid (unverified) signature from key %s", fp); 2725 if (sig_details != NULL) { 2726 debug2_f("signature details: counter = %u, flags = 0x%02x", 2727 sig_details->sk_counter, sig_details->sk_flags); 2728 } 2729 free(fp); 2730 fp = NULL; 2731 2732 if (revoked_keys != NULL) { 2733 if ((r = sshkey_check_revoked(sign_key, revoked_keys)) != 0) { 2734 debug3_fr(r, "sshkey_check_revoked"); 2735 goto done; 2736 } 2737 } 2738 2739 if (allowed_keys != NULL && (r = sshsig_check_allowed_keys(allowed_keys, 2740 sign_key, principal, sig_namespace, verify_time)) != 0) { 2741 debug3_fr(r, "sshsig_check_allowed_keys"); 2742 goto done; 2743 } 2744 /* success */ 2745 ret = 0; 2746 done: 2747 if (!quiet) { 2748 if (ret == 0) { 2749 if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash, 2750 SSH_FP_DEFAULT)) == NULL) 2751 fatal_f("sshkey_fingerprint failed"); 2752 if (principal == NULL) { 2753 printf("Good \"%s\" signature with %s key %s\n", 2754 sig_namespace, sshkey_type(sign_key), fp); 2755 2756 } else { 2757 printf("Good \"%s\" signature for %s with %s key %s\n", 2758 sig_namespace, principal, 2759 sshkey_type(sign_key), fp); 2760 } 2761 } else { 2762 printf("Could not verify signature.\n"); 2763 } 2764 } 2765 /* Print the signature key if requested */ 2766 if (ret == 0 && print_pubkey && sign_key != NULL) { 2767 if ((r = sshkey_write(sign_key, stdout)) == 0) 2768 fputc('\n', stdout); 2769 else { 2770 error_r(r, "Could not print public key.\n"); 2771 ret = -1; 2772 } 2773 } 2774 sshbuf_free(sigbuf); 2775 sshbuf_free(abuf); 2776 sshkey_free(sign_key); 2777 sshkey_sig_details_free(sig_details); 2778 free(fp); 2779 return ret; 2780 } 2781 2782 static int 2783 sig_find_principals(const char *signature, const char *allowed_keys, 2784 char * const *opts, size_t nopts) 2785 { 2786 int r, ret = -1; 2787 struct sshbuf *sigbuf = NULL, *abuf = NULL; 2788 struct sshkey *sign_key = NULL; 2789 char *principals = NULL, *cp, *tmp; 2790 uint64_t verify_time = 0; 2791 2792 if (sig_process_opts(opts, nopts, &verify_time, NULL) != 0) 2793 goto done; /* error already logged */ 2794 2795 if ((r = sshbuf_load_file(signature, &abuf)) != 0) { 2796 error_r(r, "Couldn't read signature file"); 2797 goto done; 2798 } 2799 if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) { 2800 error_fr(r, "sshsig_armor"); 2801 goto done; 2802 } 2803 if ((r = sshsig_get_pubkey(sigbuf, &sign_key)) != 0) { 2804 error_fr(r, "sshsig_get_pubkey"); 2805 goto done; 2806 } 2807 if ((r = sshsig_find_principals(allowed_keys, sign_key, 2808 verify_time, &principals)) != 0) { 2809 if (r != SSH_ERR_KEY_NOT_FOUND) 2810 error_fr(r, "sshsig_find_principal"); 2811 goto done; 2812 } 2813 ret = 0; 2814 done: 2815 if (ret == 0 ) { 2816 /* Emit matching principals one per line */ 2817 tmp = principals; 2818 while ((cp = strsep(&tmp, ",")) != NULL && *cp != '\0') 2819 puts(cp); 2820 } else { 2821 fprintf(stderr, "No principal matched.\n"); 2822 } 2823 sshbuf_free(sigbuf); 2824 sshbuf_free(abuf); 2825 sshkey_free(sign_key); 2826 free(principals); 2827 return ret; 2828 } 2829 2830 static void 2831 do_moduli_gen(const char *out_file, char **opts, size_t nopts) 2832 { 2833 #ifdef WITH_OPENSSL 2834 /* Moduli generation/screening */ 2835 u_int32_t memory = 0; 2836 BIGNUM *start = NULL; 2837 int moduli_bits = 0; 2838 FILE *out; 2839 size_t i; 2840 const char *errstr; 2841 2842 /* Parse options */ 2843 for (i = 0; i < nopts; i++) { 2844 if (strncmp(opts[i], "memory=", 7) == 0) { 2845 memory = (u_int32_t)strtonum(opts[i]+7, 1, 2846 UINT_MAX, &errstr); 2847 if (errstr) { 2848 fatal("Memory limit is %s: %s", 2849 errstr, opts[i]+7); 2850 } 2851 } else if (strncmp(opts[i], "start=", 6) == 0) { 2852 /* XXX - also compare length against bits */ 2853 if (BN_hex2bn(&start, opts[i]+6) == 0) 2854 fatal("Invalid start point."); 2855 } else if (strncmp(opts[i], "bits=", 5) == 0) { 2856 moduli_bits = (int)strtonum(opts[i]+5, 1, 2857 INT_MAX, &errstr); 2858 if (errstr) { 2859 fatal("Invalid number: %s (%s)", 2860 opts[i]+12, errstr); 2861 } 2862 } else { 2863 fatal("Option \"%s\" is unsupported for moduli " 2864 "generation", opts[i]); 2865 } 2866 } 2867 2868 if ((out = fopen(out_file, "w")) == NULL) { 2869 fatal("Couldn't open modulus candidate file \"%s\": %s", 2870 out_file, strerror(errno)); 2871 } 2872 setvbuf(out, NULL, _IOLBF, 0); 2873 2874 if (moduli_bits == 0) 2875 moduli_bits = DEFAULT_BITS; 2876 if (gen_candidates(out, memory, moduli_bits, start) != 0) 2877 fatal("modulus candidate generation failed"); 2878 #else /* WITH_OPENSSL */ 2879 fatal("Moduli generation is not supported"); 2880 #endif /* WITH_OPENSSL */ 2881 } 2882 2883 static void 2884 do_moduli_screen(const char *out_file, char **opts, size_t nopts) 2885 { 2886 #ifdef WITH_OPENSSL 2887 /* Moduli generation/screening */ 2888 char *checkpoint = NULL; 2889 u_int32_t generator_wanted = 0; 2890 unsigned long start_lineno = 0, lines_to_process = 0; 2891 int prime_tests = 0; 2892 FILE *out, *in = stdin; 2893 size_t i; 2894 const char *errstr; 2895 2896 /* Parse options */ 2897 for (i = 0; i < nopts; i++) { 2898 if (strncmp(opts[i], "lines=", 6) == 0) { 2899 lines_to_process = strtoul(opts[i]+6, NULL, 10); 2900 } else if (strncmp(opts[i], "start-line=", 11) == 0) { 2901 start_lineno = strtoul(opts[i]+11, NULL, 10); 2902 } else if (strncmp(opts[i], "checkpoint=", 11) == 0) { 2903 checkpoint = xstrdup(opts[i]+11); 2904 } else if (strncmp(opts[i], "generator=", 10) == 0) { 2905 generator_wanted = (u_int32_t)strtonum( 2906 opts[i]+10, 1, UINT_MAX, &errstr); 2907 if (errstr != NULL) { 2908 fatal("Generator invalid: %s (%s)", 2909 opts[i]+10, errstr); 2910 } 2911 } else if (strncmp(opts[i], "prime-tests=", 12) == 0) { 2912 prime_tests = (int)strtonum(opts[i]+12, 1, 2913 INT_MAX, &errstr); 2914 if (errstr) { 2915 fatal("Invalid number: %s (%s)", 2916 opts[i]+12, errstr); 2917 } 2918 } else { 2919 fatal("Option \"%s\" is unsupported for moduli " 2920 "screening", opts[i]); 2921 } 2922 } 2923 2924 if (have_identity && strcmp(identity_file, "-") != 0) { 2925 if ((in = fopen(identity_file, "r")) == NULL) { 2926 fatal("Couldn't open modulus candidate " 2927 "file \"%s\": %s", identity_file, 2928 strerror(errno)); 2929 } 2930 } 2931 2932 if ((out = fopen(out_file, "a")) == NULL) { 2933 fatal("Couldn't open moduli file \"%s\": %s", 2934 out_file, strerror(errno)); 2935 } 2936 setvbuf(out, NULL, _IOLBF, 0); 2937 if (prime_test(in, out, prime_tests == 0 ? 100 : prime_tests, 2938 generator_wanted, checkpoint, 2939 start_lineno, lines_to_process) != 0) 2940 fatal("modulus screening failed"); 2941 #else /* WITH_OPENSSL */ 2942 fatal("Moduli screening is not supported"); 2943 #endif /* WITH_OPENSSL */ 2944 } 2945 2946 static char * 2947 private_key_passphrase(void) 2948 { 2949 char *passphrase1, *passphrase2; 2950 2951 /* Ask for a passphrase (twice). */ 2952 if (identity_passphrase) 2953 passphrase1 = xstrdup(identity_passphrase); 2954 else if (identity_new_passphrase) 2955 passphrase1 = xstrdup(identity_new_passphrase); 2956 else { 2957 passphrase_again: 2958 passphrase1 = 2959 read_passphrase("Enter passphrase (empty for no " 2960 "passphrase): ", RP_ALLOW_STDIN); 2961 passphrase2 = read_passphrase("Enter same passphrase again: ", 2962 RP_ALLOW_STDIN); 2963 if (strcmp(passphrase1, passphrase2) != 0) { 2964 /* 2965 * The passphrases do not match. Clear them and 2966 * retry. 2967 */ 2968 freezero(passphrase1, strlen(passphrase1)); 2969 freezero(passphrase2, strlen(passphrase2)); 2970 printf("Passphrases do not match. Try again.\n"); 2971 goto passphrase_again; 2972 } 2973 /* Clear the other copy of the passphrase. */ 2974 freezero(passphrase2, strlen(passphrase2)); 2975 } 2976 return passphrase1; 2977 } 2978 2979 static const char * 2980 skip_ssh_url_preamble(const char *s) 2981 { 2982 if (strncmp(s, "ssh://", 6) == 0) 2983 return s + 6; 2984 else if (strncmp(s, "ssh:", 4) == 0) 2985 return s + 4; 2986 return s; 2987 } 2988 2989 static int 2990 do_download_sk(const char *skprovider, const char *device) 2991 { 2992 struct sshkey **keys; 2993 size_t nkeys, i; 2994 int r, ret = -1; 2995 char *fp, *pin = NULL, *pass = NULL, *path, *pubpath; 2996 const char *ext; 2997 2998 if (skprovider == NULL) 2999 fatal("Cannot download keys without provider"); 3000 3001 pin = read_passphrase("Enter PIN for authenticator: ", RP_ALLOW_STDIN); 3002 if (!quiet) { 3003 printf("You may need to touch your authenticator " 3004 "to authorize key download.\n"); 3005 } 3006 if ((r = sshsk_load_resident(skprovider, device, pin, 3007 &keys, &nkeys)) != 0) { 3008 if (pin != NULL) 3009 freezero(pin, strlen(pin)); 3010 error_r(r, "Unable to load resident keys"); 3011 return -1; 3012 } 3013 if (nkeys == 0) 3014 logit("No keys to download"); 3015 if (pin != NULL) 3016 freezero(pin, strlen(pin)); 3017 3018 for (i = 0; i < nkeys; i++) { 3019 if (keys[i]->type != KEY_ECDSA_SK && 3020 keys[i]->type != KEY_ED25519_SK) { 3021 error("Unsupported key type %s (%d)", 3022 sshkey_type(keys[i]), keys[i]->type); 3023 continue; 3024 } 3025 if ((fp = sshkey_fingerprint(keys[i], 3026 fingerprint_hash, SSH_FP_DEFAULT)) == NULL) 3027 fatal_f("sshkey_fingerprint failed"); 3028 debug_f("key %zu: %s %s %s (flags 0x%02x)", i, 3029 sshkey_type(keys[i]), fp, keys[i]->sk_application, 3030 keys[i]->sk_flags); 3031 ext = skip_ssh_url_preamble(keys[i]->sk_application); 3032 xasprintf(&path, "id_%s_rk%s%s", 3033 keys[i]->type == KEY_ECDSA_SK ? "ecdsa_sk" : "ed25519_sk", 3034 *ext == '\0' ? "" : "_", ext); 3035 3036 /* If the file already exists, ask the user to confirm. */ 3037 if (!confirm_overwrite(path)) { 3038 free(path); 3039 break; 3040 } 3041 3042 /* Save the key with the application string as the comment */ 3043 if (pass == NULL) 3044 pass = private_key_passphrase(); 3045 if ((r = sshkey_save_private(keys[i], path, pass, 3046 keys[i]->sk_application, private_key_format, 3047 openssh_format_cipher, rounds)) != 0) { 3048 error_r(r, "Saving key \"%s\" failed", path); 3049 free(path); 3050 break; 3051 } 3052 if (!quiet) { 3053 printf("Saved %s key%s%s to %s\n", 3054 sshkey_type(keys[i]), 3055 *ext != '\0' ? " " : "", 3056 *ext != '\0' ? keys[i]->sk_application : "", 3057 path); 3058 } 3059 3060 /* Save public key too */ 3061 xasprintf(&pubpath, "%s.pub", path); 3062 free(path); 3063 if ((r = sshkey_save_public(keys[i], pubpath, 3064 keys[i]->sk_application)) != 0) { 3065 error_r(r, "Saving public key \"%s\" failed", pubpath); 3066 free(pubpath); 3067 break; 3068 } 3069 free(pubpath); 3070 } 3071 3072 if (i >= nkeys) 3073 ret = 0; /* success */ 3074 if (pass != NULL) 3075 freezero(pass, strlen(pass)); 3076 for (i = 0; i < nkeys; i++) 3077 sshkey_free(keys[i]); 3078 free(keys); 3079 return ret; 3080 } 3081 3082 static void 3083 save_attestation(struct sshbuf *attest, const char *path) 3084 { 3085 mode_t omask; 3086 int r; 3087 3088 if (path == NULL) 3089 return; /* nothing to do */ 3090 if (attest == NULL || sshbuf_len(attest) == 0) 3091 fatal("Enrollment did not return attestation data"); 3092 omask = umask(077); 3093 r = sshbuf_write_file(path, attest); 3094 umask(omask); 3095 if (r != 0) 3096 fatal_r(r, "Unable to write attestation data \"%s\"", path); 3097 if (!quiet) 3098 printf("Your FIDO attestation certificate has been saved in " 3099 "%s\n", path); 3100 } 3101 3102 __dead static void 3103 usage(void) 3104 { 3105 fprintf(stderr, 3106 "usage: ssh-keygen [-q] [-a rounds] [-b bits] [-C comment] [-f output_keyfile]\n" 3107 " [-m format] [-N new_passphrase] [-O option]\n" 3108 " [-t dsa | ecdsa | ecdsa-sk | ed25519 | ed25519-sk | rsa]\n" 3109 " [-w provider] [-Z cipher]\n" 3110 " ssh-keygen -p [-a rounds] [-f keyfile] [-m format] [-N new_passphrase]\n" 3111 " [-P old_passphrase] [-Z cipher]\n" 3112 #ifdef WITH_OPENSSL 3113 " ssh-keygen -i [-f input_keyfile] [-m key_format]\n" 3114 " ssh-keygen -e [-f input_keyfile] [-m key_format]\n" 3115 #endif 3116 " ssh-keygen -y [-f input_keyfile]\n" 3117 " ssh-keygen -c [-a rounds] [-C comment] [-f keyfile] [-P passphrase]\n" 3118 " ssh-keygen -l [-v] [-E fingerprint_hash] [-f input_keyfile]\n" 3119 " ssh-keygen -B [-f input_keyfile]\n"); 3120 #ifdef ENABLE_PKCS11 3121 fprintf(stderr, 3122 " ssh-keygen -D pkcs11\n"); 3123 #endif 3124 fprintf(stderr, 3125 " ssh-keygen -F hostname [-lv] [-f known_hosts_file]\n" 3126 " ssh-keygen -H [-f known_hosts_file]\n" 3127 " ssh-keygen -K [-a rounds] [-w provider]\n" 3128 " ssh-keygen -R hostname [-f known_hosts_file]\n" 3129 " ssh-keygen -r hostname [-g] [-f input_keyfile]\n" 3130 #ifdef WITH_OPENSSL 3131 " ssh-keygen -M generate [-O option] output_file\n" 3132 " ssh-keygen -M screen [-f input_file] [-O option] output_file\n" 3133 #endif 3134 " ssh-keygen -I certificate_identity -s ca_key [-hU] [-D pkcs11_provider]\n" 3135 " [-n principals] [-O option] [-V validity_interval]\n" 3136 " [-z serial_number] file ...\n" 3137 " ssh-keygen -L [-f input_keyfile]\n" 3138 " ssh-keygen -A [-a rounds] [-f prefix_path]\n" 3139 " ssh-keygen -k -f krl_file [-u] [-s ca_public] [-z version_number]\n" 3140 " file ...\n" 3141 " ssh-keygen -Q [-l] -f krl_file [file ...]\n" 3142 " ssh-keygen -Y find-principals -s signature_file -f allowed_signers_file\n" 3143 " ssh-keygen -Y check-novalidate -n namespace -s signature_file\n" 3144 " ssh-keygen -Y sign -f key_file -n namespace file ...\n" 3145 " ssh-keygen -Y verify -f allowed_signers_file -I signer_identity\n" 3146 " -n namespace -s signature_file [-r revocation_file]\n"); 3147 exit(1); 3148 } 3149 3150 /* 3151 * Main program for key management. 3152 */ 3153 int 3154 main(int argc, char **argv) 3155 { 3156 char comment[1024], *passphrase; 3157 char *rr_hostname = NULL, *ep, *fp, *ra; 3158 struct sshkey *private, *public; 3159 struct passwd *pw; 3160 int r, opt, type; 3161 int change_passphrase = 0, change_comment = 0, show_cert = 0; 3162 int find_host = 0, delete_host = 0, hash_hosts = 0; 3163 int gen_all_hostkeys = 0, gen_krl = 0, update_krl = 0, check_krl = 0; 3164 int prefer_agent = 0, convert_to = 0, convert_from = 0; 3165 int print_public = 0, print_generic = 0, cert_serial_autoinc = 0; 3166 int do_gen_candidates = 0, do_screen_candidates = 0, download_sk = 0; 3167 unsigned long long cert_serial = 0; 3168 char *identity_comment = NULL, *ca_key_path = NULL, **opts = NULL; 3169 char *sk_application = NULL, *sk_device = NULL, *sk_user = NULL; 3170 char *sk_attestation_path = NULL; 3171 struct sshbuf *challenge = NULL, *attest = NULL; 3172 size_t i, nopts = 0; 3173 u_int32_t bits = 0; 3174 uint8_t sk_flags = SSH_SK_USER_PRESENCE_REQD; 3175 const char *errstr; 3176 int log_level = SYSLOG_LEVEL_INFO; 3177 char *sign_op = NULL; 3178 3179 extern int optind; 3180 extern char *optarg; 3181 3182 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ 3183 sanitise_stdfd(); 3184 3185 #ifdef WITH_OPENSSL 3186 OpenSSL_add_all_algorithms(); 3187 #endif 3188 log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1); 3189 3190 setlocale(LC_CTYPE, ""); 3191 3192 /* we need this for the home * directory. */ 3193 pw = getpwuid(getuid()); 3194 if (!pw) 3195 fatal("No user exists for uid %lu", (u_long)getuid()); 3196 pw = pwcopy(pw); 3197 if (gethostname(hostname, sizeof(hostname)) == -1) 3198 fatal("gethostname: %s", strerror(errno)); 3199 3200 sk_provider = getenv("SSH_SK_PROVIDER"); 3201 3202 /* Remaining characters: dGjJSTWx */ 3203 while ((opt = getopt(argc, argv, "ABHKLQUXceghiklopquvy" 3204 "C:D:E:F:I:M:N:O:P:R:V:Y:Z:" 3205 "a:b:f:g:m:n:r:s:t:w:z:")) != -1) { 3206 switch (opt) { 3207 case 'A': 3208 gen_all_hostkeys = 1; 3209 break; 3210 case 'b': 3211 bits = (u_int32_t)strtonum(optarg, 1, UINT32_MAX, 3212 &errstr); 3213 if (errstr) 3214 fatal("Bits has bad value %s (%s)", 3215 optarg, errstr); 3216 break; 3217 case 'E': 3218 fingerprint_hash = ssh_digest_alg_by_name(optarg); 3219 if (fingerprint_hash == -1) 3220 fatal("Invalid hash algorithm \"%s\"", optarg); 3221 break; 3222 case 'F': 3223 find_host = 1; 3224 rr_hostname = optarg; 3225 break; 3226 case 'H': 3227 hash_hosts = 1; 3228 break; 3229 case 'I': 3230 cert_key_id = optarg; 3231 break; 3232 case 'R': 3233 delete_host = 1; 3234 rr_hostname = optarg; 3235 break; 3236 case 'L': 3237 show_cert = 1; 3238 break; 3239 case 'l': 3240 print_fingerprint = 1; 3241 break; 3242 case 'B': 3243 print_bubblebabble = 1; 3244 break; 3245 case 'm': 3246 if (strcasecmp(optarg, "RFC4716") == 0 || 3247 strcasecmp(optarg, "ssh2") == 0) { 3248 convert_format = FMT_RFC4716; 3249 break; 3250 } 3251 if (strcasecmp(optarg, "PKCS8") == 0) { 3252 convert_format = FMT_PKCS8; 3253 private_key_format = SSHKEY_PRIVATE_PKCS8; 3254 break; 3255 } 3256 if (strcasecmp(optarg, "PEM") == 0) { 3257 convert_format = FMT_PEM; 3258 private_key_format = SSHKEY_PRIVATE_PEM; 3259 break; 3260 } 3261 fatal("Unsupported conversion format \"%s\"", optarg); 3262 case 'n': 3263 cert_principals = optarg; 3264 break; 3265 case 'o': 3266 /* no-op; new format is already the default */ 3267 break; 3268 case 'p': 3269 change_passphrase = 1; 3270 break; 3271 case 'c': 3272 change_comment = 1; 3273 break; 3274 case 'f': 3275 if (strlcpy(identity_file, optarg, 3276 sizeof(identity_file)) >= sizeof(identity_file)) 3277 fatal("Identity filename too long"); 3278 have_identity = 1; 3279 break; 3280 case 'g': 3281 print_generic = 1; 3282 break; 3283 case 'K': 3284 download_sk = 1; 3285 break; 3286 case 'P': 3287 identity_passphrase = optarg; 3288 break; 3289 case 'N': 3290 identity_new_passphrase = optarg; 3291 break; 3292 case 'Q': 3293 check_krl = 1; 3294 break; 3295 case 'O': 3296 opts = xrecallocarray(opts, nopts, nopts + 1, 3297 sizeof(*opts)); 3298 opts[nopts++] = xstrdup(optarg); 3299 break; 3300 case 'Z': 3301 openssh_format_cipher = optarg; 3302 if (cipher_by_name(openssh_format_cipher) == NULL) 3303 fatal("Invalid OpenSSH-format cipher '%s'", 3304 openssh_format_cipher); 3305 break; 3306 case 'C': 3307 identity_comment = optarg; 3308 break; 3309 case 'q': 3310 quiet = 1; 3311 break; 3312 case 'e': 3313 /* export key */ 3314 convert_to = 1; 3315 break; 3316 case 'h': 3317 cert_key_type = SSH2_CERT_TYPE_HOST; 3318 certflags_flags = 0; 3319 break; 3320 case 'k': 3321 gen_krl = 1; 3322 break; 3323 case 'i': 3324 case 'X': 3325 /* import key */ 3326 convert_from = 1; 3327 break; 3328 case 'y': 3329 print_public = 1; 3330 break; 3331 case 's': 3332 ca_key_path = optarg; 3333 break; 3334 case 't': 3335 key_type_name = optarg; 3336 break; 3337 case 'D': 3338 pkcs11provider = optarg; 3339 break; 3340 case 'U': 3341 prefer_agent = 1; 3342 break; 3343 case 'u': 3344 update_krl = 1; 3345 break; 3346 case 'v': 3347 if (log_level == SYSLOG_LEVEL_INFO) 3348 log_level = SYSLOG_LEVEL_DEBUG1; 3349 else { 3350 if (log_level >= SYSLOG_LEVEL_DEBUG1 && 3351 log_level < SYSLOG_LEVEL_DEBUG3) 3352 log_level++; 3353 } 3354 break; 3355 case 'r': 3356 rr_hostname = optarg; 3357 break; 3358 case 'a': 3359 rounds = (int)strtonum(optarg, 1, INT_MAX, &errstr); 3360 if (errstr) 3361 fatal("Invalid number: %s (%s)", 3362 optarg, errstr); 3363 break; 3364 case 'V': 3365 parse_cert_times(optarg); 3366 break; 3367 case 'Y': 3368 sign_op = optarg; 3369 break; 3370 case 'w': 3371 sk_provider = optarg; 3372 break; 3373 case 'z': 3374 errno = 0; 3375 if (*optarg == '+') { 3376 cert_serial_autoinc = 1; 3377 optarg++; 3378 } 3379 cert_serial = strtoull(optarg, &ep, 10); 3380 if (*optarg < '0' || *optarg > '9' || *ep != '\0' || 3381 (errno == ERANGE && cert_serial == ULLONG_MAX)) 3382 fatal("Invalid serial number \"%s\"", optarg); 3383 break; 3384 case 'M': 3385 if (strcmp(optarg, "generate") == 0) 3386 do_gen_candidates = 1; 3387 else if (strcmp(optarg, "screen") == 0) 3388 do_screen_candidates = 1; 3389 else 3390 fatal("Unsupported moduli option %s", optarg); 3391 break; 3392 case '?': 3393 default: 3394 usage(); 3395 } 3396 } 3397 3398 if (sk_provider == NULL) 3399 sk_provider = "internal"; 3400 3401 /* reinit */ 3402 log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1); 3403 3404 argv += optind; 3405 argc -= optind; 3406 3407 if (sign_op != NULL) { 3408 if (strncmp(sign_op, "find-principals", 15) == 0) { 3409 if (ca_key_path == NULL) { 3410 error("Too few arguments for find-principals:" 3411 "missing signature file"); 3412 exit(1); 3413 } 3414 if (!have_identity) { 3415 error("Too few arguments for find-principals:" 3416 "missing allowed keys file"); 3417 exit(1); 3418 } 3419 return sig_find_principals(ca_key_path, identity_file, 3420 opts, nopts); 3421 } else if (strncmp(sign_op, "sign", 4) == 0) { 3422 if (cert_principals == NULL || 3423 *cert_principals == '\0') { 3424 error("Too few arguments for sign: " 3425 "missing namespace"); 3426 exit(1); 3427 } 3428 if (!have_identity) { 3429 error("Too few arguments for sign: " 3430 "missing key"); 3431 exit(1); 3432 } 3433 return sig_sign(identity_file, cert_principals, 3434 argc, argv); 3435 } else if (strncmp(sign_op, "check-novalidate", 16) == 0) { 3436 if (ca_key_path == NULL) { 3437 error("Too few arguments for check-novalidate: " 3438 "missing signature file"); 3439 exit(1); 3440 } 3441 return sig_verify(ca_key_path, cert_principals, 3442 NULL, NULL, NULL, opts, nopts); 3443 } else if (strncmp(sign_op, "verify", 6) == 0) { 3444 if (cert_principals == NULL || 3445 *cert_principals == '\0') { 3446 error("Too few arguments for verify: " 3447 "missing namespace"); 3448 exit(1); 3449 } 3450 if (ca_key_path == NULL) { 3451 error("Too few arguments for verify: " 3452 "missing signature file"); 3453 exit(1); 3454 } 3455 if (!have_identity) { 3456 error("Too few arguments for sign: " 3457 "missing allowed keys file"); 3458 exit(1); 3459 } 3460 if (cert_key_id == NULL) { 3461 error("Too few arguments for verify: " 3462 "missing principal ID"); 3463 exit(1); 3464 } 3465 return sig_verify(ca_key_path, cert_principals, 3466 cert_key_id, identity_file, rr_hostname, 3467 opts, nopts); 3468 } 3469 error("Unsupported operation for -Y: \"%s\"", sign_op); 3470 usage(); 3471 /* NOTREACHED */ 3472 } 3473 3474 if (ca_key_path != NULL) { 3475 if (argc < 1 && !gen_krl) { 3476 error("Too few arguments."); 3477 usage(); 3478 } 3479 } else if (argc > 0 && !gen_krl && !check_krl && 3480 !do_gen_candidates && !do_screen_candidates) { 3481 error("Too many arguments."); 3482 usage(); 3483 } 3484 if (change_passphrase && change_comment) { 3485 error("Can only have one of -p and -c."); 3486 usage(); 3487 } 3488 if (print_fingerprint && (delete_host || hash_hosts)) { 3489 error("Cannot use -l with -H or -R."); 3490 usage(); 3491 } 3492 if (gen_krl) { 3493 do_gen_krl(pw, update_krl, ca_key_path, 3494 cert_serial, identity_comment, argc, argv); 3495 return (0); 3496 } 3497 if (check_krl) { 3498 do_check_krl(pw, print_fingerprint, argc, argv); 3499 return (0); 3500 } 3501 if (ca_key_path != NULL) { 3502 if (cert_key_id == NULL) 3503 fatal("Must specify key id (-I) when certifying"); 3504 for (i = 0; i < nopts; i++) 3505 add_cert_option(opts[i]); 3506 do_ca_sign(pw, ca_key_path, prefer_agent, 3507 cert_serial, cert_serial_autoinc, argc, argv); 3508 } 3509 if (show_cert) 3510 do_show_cert(pw); 3511 if (delete_host || hash_hosts || find_host) { 3512 do_known_hosts(pw, rr_hostname, find_host, 3513 delete_host, hash_hosts); 3514 } 3515 if (pkcs11provider != NULL) 3516 do_download(pw); 3517 if (download_sk) { 3518 for (i = 0; i < nopts; i++) { 3519 if (strncasecmp(opts[i], "device=", 7) == 0) { 3520 sk_device = xstrdup(opts[i] + 7); 3521 } else { 3522 fatal("Option \"%s\" is unsupported for " 3523 "FIDO authenticator download", opts[i]); 3524 } 3525 } 3526 return do_download_sk(sk_provider, sk_device); 3527 } 3528 if (print_fingerprint || print_bubblebabble) 3529 do_fingerprint(pw); 3530 if (change_passphrase) 3531 do_change_passphrase(pw); 3532 if (change_comment) 3533 do_change_comment(pw, identity_comment); 3534 #ifdef WITH_OPENSSL 3535 if (convert_to) 3536 do_convert_to(pw); 3537 if (convert_from) 3538 do_convert_from(pw); 3539 #else /* WITH_OPENSSL */ 3540 if (convert_to || convert_from) 3541 fatal("key conversion disabled at compile time"); 3542 #endif /* WITH_OPENSSL */ 3543 if (print_public) 3544 do_print_public(pw); 3545 if (rr_hostname != NULL) { 3546 unsigned int n = 0; 3547 3548 if (have_identity) { 3549 n = do_print_resource_record(pw, identity_file, 3550 rr_hostname, print_generic); 3551 if (n == 0) 3552 fatal("%s: %s", identity_file, strerror(errno)); 3553 exit(0); 3554 } else { 3555 3556 n += do_print_resource_record(pw, 3557 _PATH_HOST_RSA_KEY_FILE, rr_hostname, 3558 print_generic); 3559 n += do_print_resource_record(pw, 3560 _PATH_HOST_DSA_KEY_FILE, rr_hostname, 3561 print_generic); 3562 n += do_print_resource_record(pw, 3563 _PATH_HOST_ECDSA_KEY_FILE, rr_hostname, 3564 print_generic); 3565 n += do_print_resource_record(pw, 3566 _PATH_HOST_ED25519_KEY_FILE, rr_hostname, 3567 print_generic); 3568 n += do_print_resource_record(pw, 3569 _PATH_HOST_XMSS_KEY_FILE, rr_hostname, 3570 print_generic); 3571 if (n == 0) 3572 fatal("no keys found."); 3573 exit(0); 3574 } 3575 } 3576 3577 if (do_gen_candidates || do_screen_candidates) { 3578 if (argc <= 0) 3579 fatal("No output file specified"); 3580 else if (argc > 1) 3581 fatal("Too many output files specified"); 3582 } 3583 if (do_gen_candidates) { 3584 do_moduli_gen(argv[0], opts, nopts); 3585 return 0; 3586 } 3587 if (do_screen_candidates) { 3588 do_moduli_screen(argv[0], opts, nopts); 3589 return 0; 3590 } 3591 3592 if (gen_all_hostkeys) { 3593 do_gen_all_hostkeys(pw); 3594 return (0); 3595 } 3596 3597 if (key_type_name == NULL) 3598 key_type_name = DEFAULT_KEY_TYPE_NAME; 3599 3600 type = sshkey_type_from_name(key_type_name); 3601 type_bits_valid(type, key_type_name, &bits); 3602 3603 if (!quiet) 3604 printf("Generating public/private %s key pair.\n", 3605 key_type_name); 3606 switch (type) { 3607 case KEY_ECDSA_SK: 3608 case KEY_ED25519_SK: 3609 for (i = 0; i < nopts; i++) { 3610 if (strcasecmp(opts[i], "no-touch-required") == 0) { 3611 sk_flags &= ~SSH_SK_USER_PRESENCE_REQD; 3612 } else if (strcasecmp(opts[i], "verify-required") == 0) { 3613 sk_flags |= SSH_SK_USER_VERIFICATION_REQD; 3614 } else if (strcasecmp(opts[i], "resident") == 0) { 3615 sk_flags |= SSH_SK_RESIDENT_KEY; 3616 } else if (strncasecmp(opts[i], "device=", 7) == 0) { 3617 sk_device = xstrdup(opts[i] + 7); 3618 } else if (strncasecmp(opts[i], "user=", 5) == 0) { 3619 sk_user = xstrdup(opts[i] + 5); 3620 } else if (strncasecmp(opts[i], "challenge=", 10) == 0) { 3621 if ((r = sshbuf_load_file(opts[i] + 10, 3622 &challenge)) != 0) { 3623 fatal_r(r, "Unable to load FIDO " 3624 "enrollment challenge \"%s\"", 3625 opts[i] + 10); 3626 } 3627 } else if (strncasecmp(opts[i], 3628 "write-attestation=", 18) == 0) { 3629 sk_attestation_path = opts[i] + 18; 3630 } else if (strncasecmp(opts[i], 3631 "application=", 12) == 0) { 3632 sk_application = xstrdup(opts[i] + 12); 3633 if (strncmp(sk_application, "ssh:", 4) != 0) { 3634 fatal("FIDO application string must " 3635 "begin with \"ssh:\""); 3636 } 3637 } else { 3638 fatal("Option \"%s\" is unsupported for " 3639 "FIDO authenticator enrollment", opts[i]); 3640 } 3641 } 3642 if (!quiet) { 3643 printf("You may need to touch your authenticator " 3644 "to authorize key generation.\n"); 3645 } 3646 if ((attest = sshbuf_new()) == NULL) 3647 fatal("sshbuf_new failed"); 3648 if ((sk_flags & 3649 (SSH_SK_USER_VERIFICATION_REQD|SSH_SK_RESIDENT_KEY))) { 3650 passphrase = read_passphrase("Enter PIN for " 3651 "authenticator: ", RP_ALLOW_STDIN); 3652 } else { 3653 passphrase = NULL; 3654 } 3655 for (i = 0 ; ; i++) { 3656 fflush(stdout); 3657 r = sshsk_enroll(type, sk_provider, sk_device, 3658 sk_application == NULL ? "ssh:" : sk_application, 3659 sk_user, sk_flags, passphrase, challenge, 3660 &private, attest); 3661 if (r == 0) 3662 break; 3663 if (r != SSH_ERR_KEY_WRONG_PASSPHRASE) 3664 fatal_r(r, "Key enrollment failed"); 3665 else if (passphrase != NULL) { 3666 error("PIN incorrect"); 3667 freezero(passphrase, strlen(passphrase)); 3668 passphrase = NULL; 3669 } 3670 if (i >= 3) 3671 fatal("Too many incorrect PINs"); 3672 passphrase = read_passphrase("Enter PIN for " 3673 "authenticator: ", RP_ALLOW_STDIN); 3674 if (!quiet) { 3675 printf("You may need to touch your " 3676 "authenticator (again) to authorize " 3677 "key generation.\n"); 3678 } 3679 } 3680 if (passphrase != NULL) { 3681 freezero(passphrase, strlen(passphrase)); 3682 passphrase = NULL; 3683 } 3684 break; 3685 default: 3686 if ((r = sshkey_generate(type, bits, &private)) != 0) 3687 fatal("sshkey_generate failed"); 3688 break; 3689 } 3690 if ((r = sshkey_from_private(private, &public)) != 0) 3691 fatal_r(r, "sshkey_from_private"); 3692 3693 if (!have_identity) 3694 ask_filename(pw, "Enter file in which to save the key"); 3695 3696 /* Create ~/.ssh directory if it doesn't already exist. */ 3697 hostfile_create_user_ssh_dir(identity_file, !quiet); 3698 3699 /* If the file already exists, ask the user to confirm. */ 3700 if (!confirm_overwrite(identity_file)) 3701 exit(1); 3702 3703 /* Determine the passphrase for the private key */ 3704 passphrase = private_key_passphrase(); 3705 if (identity_comment) { 3706 strlcpy(comment, identity_comment, sizeof(comment)); 3707 } else { 3708 /* Create default comment field for the passphrase. */ 3709 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname); 3710 } 3711 3712 /* Save the key with the given passphrase and comment. */ 3713 if ((r = sshkey_save_private(private, identity_file, passphrase, 3714 comment, private_key_format, openssh_format_cipher, rounds)) != 0) { 3715 error_r(r, "Saving key \"%s\" failed", identity_file); 3716 freezero(passphrase, strlen(passphrase)); 3717 exit(1); 3718 } 3719 freezero(passphrase, strlen(passphrase)); 3720 sshkey_free(private); 3721 3722 if (!quiet) { 3723 printf("Your identification has been saved in %s\n", 3724 identity_file); 3725 } 3726 3727 strlcat(identity_file, ".pub", sizeof(identity_file)); 3728 if ((r = sshkey_save_public(public, identity_file, comment)) != 0) 3729 fatal_r(r, "Unable to save public key to %s", identity_file); 3730 3731 if (!quiet) { 3732 fp = sshkey_fingerprint(public, fingerprint_hash, 3733 SSH_FP_DEFAULT); 3734 ra = sshkey_fingerprint(public, fingerprint_hash, 3735 SSH_FP_RANDOMART); 3736 if (fp == NULL || ra == NULL) 3737 fatal("sshkey_fingerprint failed"); 3738 printf("Your public key has been saved in %s\n", 3739 identity_file); 3740 printf("The key fingerprint is:\n"); 3741 printf("%s %s\n", fp, comment); 3742 printf("The key's randomart image is:\n"); 3743 printf("%s\n", ra); 3744 free(ra); 3745 free(fp); 3746 } 3747 3748 if (sk_attestation_path != NULL) 3749 save_attestation(attest, sk_attestation_path); 3750 3751 sshbuf_free(attest); 3752 sshkey_free(public); 3753 3754 exit(0); 3755 } 3756