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