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