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