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