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