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