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