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