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