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