1 /* $OpenBSD: ssh-keygen.c,v 1.189 2010/04/23 22:48:31 djm Exp $ */ 2 /* 3 * Author: Tatu Ylonen <ylo@cs.hut.fi> 4 * Copyright (c) 1994 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 5 * All rights reserved 6 * Identity and host key generation and maintenance. 7 * 8 * As far as I am concerned, the code I have written for this software 9 * can be used freely for any purpose. Any derived versions of this 10 * software must be clearly marked as such, and if the derived work is 11 * incompatible with the protocol description in the RFC file, it must be 12 * called by a name other than "ssh" or "Secure Shell". 13 */ 14 15 #include <sys/types.h> 16 #include <sys/socket.h> 17 #include <sys/stat.h> 18 #include <sys/param.h> 19 20 #include <openssl/evp.h> 21 #include <openssl/pem.h> 22 23 #include <errno.h> 24 #include <fcntl.h> 25 #include <pwd.h> 26 #include <stdio.h> 27 #include <stdlib.h> 28 #include <string.h> 29 #include <unistd.h> 30 31 #include "xmalloc.h" 32 #include "key.h" 33 #include "rsa.h" 34 #include "authfile.h" 35 #include "uuencode.h" 36 #include "buffer.h" 37 #include "pathnames.h" 38 #include "log.h" 39 #include "misc.h" 40 #include "match.h" 41 #include "hostfile.h" 42 #include "dns.h" 43 #include "ssh2.h" 44 45 #ifdef ENABLE_PKCS11 46 #include "ssh-pkcs11.h" 47 #endif 48 49 /* Number of bits in the RSA/DSA key. This value can be set on the command line. */ 50 #define DEFAULT_BITS 2048 51 #define DEFAULT_BITS_DSA 1024 52 u_int32_t bits = 0; 53 54 /* 55 * Flag indicating that we just want to change the passphrase. This can be 56 * set on the command line. 57 */ 58 int change_passphrase = 0; 59 60 /* 61 * Flag indicating that we just want to change the comment. This can be set 62 * on the command line. 63 */ 64 int change_comment = 0; 65 66 int quiet = 0; 67 68 int log_level = SYSLOG_LEVEL_INFO; 69 70 /* Flag indicating that we want to hash a known_hosts file */ 71 int hash_hosts = 0; 72 /* Flag indicating that we want lookup a host in known_hosts file */ 73 int find_host = 0; 74 /* Flag indicating that we want to delete a host from a known_hosts file */ 75 int delete_host = 0; 76 77 /* Flag indicating that we want to show the contents of a certificate */ 78 int show_cert = 0; 79 80 /* Flag indicating that we just want to see the key fingerprint */ 81 int print_fingerprint = 0; 82 int print_bubblebabble = 0; 83 84 /* The identity file name, given on the command line or entered by the user. */ 85 char identity_file[1024]; 86 int have_identity = 0; 87 88 /* This is set to the passphrase if given on the command line. */ 89 char *identity_passphrase = NULL; 90 91 /* This is set to the new passphrase if given on the command line. */ 92 char *identity_new_passphrase = NULL; 93 94 /* This is set to the new comment if given on the command line. */ 95 char *identity_comment = NULL; 96 97 /* Path to CA key when certifying keys. */ 98 char *ca_key_path = NULL; 99 100 /* Certificate serial number */ 101 long long cert_serial = 0; 102 103 /* Key type when certifying */ 104 u_int cert_key_type = SSH2_CERT_TYPE_USER; 105 106 /* "key ID" of signed key */ 107 char *cert_key_id = NULL; 108 109 /* Comma-separated list of principal names for certifying keys */ 110 char *cert_principals = NULL; 111 112 /* Validity period for certificates */ 113 u_int64_t cert_valid_from = 0; 114 u_int64_t cert_valid_to = ~0ULL; 115 116 /* Certificate options */ 117 #define CRITOPT_X_FWD (1) 118 #define CRITOPT_AGENT_FWD (1<<1) 119 #define CRITOPT_PORT_FWD (1<<2) 120 #define CRITOPT_PTY (1<<3) 121 #define CRITOPT_USER_RC (1<<4) 122 #define CRITOPT_DEFAULT (CRITOPT_X_FWD|CRITOPT_AGENT_FWD| \ 123 CRITOPT_PORT_FWD|CRITOPT_PTY| \ 124 CRITOPT_USER_RC) 125 u_int32_t critical_flags = CRITOPT_DEFAULT; 126 char *critical_command = NULL; 127 char *critical_src_addr = NULL; 128 129 /* Dump public key file in format used by real and the original SSH 2 */ 130 int convert_to_ssh2 = 0; 131 int convert_from_ssh2 = 0; 132 int print_public = 0; 133 int print_generic = 0; 134 135 char *key_type_name = NULL; 136 137 /* argv0 */ 138 extern char *__progname; 139 140 char hostname[MAXHOSTNAMELEN]; 141 142 /* moduli.c */ 143 int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *); 144 int prime_test(FILE *, FILE *, u_int32_t, u_int32_t); 145 146 static void 147 ask_filename(struct passwd *pw, const char *prompt) 148 { 149 char buf[1024]; 150 char *name = NULL; 151 152 if (key_type_name == NULL) 153 name = _PATH_SSH_CLIENT_ID_RSA; 154 else { 155 switch (key_type_from_name(key_type_name)) { 156 case KEY_RSA1: 157 name = _PATH_SSH_CLIENT_IDENTITY; 158 break; 159 case KEY_DSA_CERT: 160 case KEY_DSA_CERT_V00: 161 case KEY_DSA: 162 name = _PATH_SSH_CLIENT_ID_DSA; 163 break; 164 case KEY_RSA_CERT: 165 case KEY_RSA_CERT_V00: 166 case KEY_RSA: 167 name = _PATH_SSH_CLIENT_ID_RSA; 168 break; 169 default: 170 fprintf(stderr, "bad key type\n"); 171 exit(1); 172 break; 173 } 174 } 175 snprintf(identity_file, sizeof(identity_file), "%s/%s", pw->pw_dir, name); 176 fprintf(stderr, "%s (%s): ", prompt, identity_file); 177 if (fgets(buf, sizeof(buf), stdin) == NULL) 178 exit(1); 179 buf[strcspn(buf, "\n")] = '\0'; 180 if (strcmp(buf, "") != 0) 181 strlcpy(identity_file, buf, sizeof(identity_file)); 182 have_identity = 1; 183 } 184 185 static Key * 186 load_identity(char *filename) 187 { 188 char *pass; 189 Key *prv; 190 191 prv = key_load_private(filename, "", NULL); 192 if (prv == NULL) { 193 if (identity_passphrase) 194 pass = xstrdup(identity_passphrase); 195 else 196 pass = read_passphrase("Enter passphrase: ", 197 RP_ALLOW_STDIN); 198 prv = key_load_private(filename, pass, NULL); 199 memset(pass, 0, strlen(pass)); 200 xfree(pass); 201 } 202 return prv; 203 } 204 205 #define SSH_COM_PUBLIC_BEGIN "---- BEGIN SSH2 PUBLIC KEY ----" 206 #define SSH_COM_PUBLIC_END "---- END SSH2 PUBLIC KEY ----" 207 #define SSH_COM_PRIVATE_BEGIN "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----" 208 #define SSH_COM_PRIVATE_KEY_MAGIC 0x3f6ff9eb 209 210 static void 211 do_convert_to_ssh2(struct passwd *pw) 212 { 213 Key *k; 214 u_int len; 215 u_char *blob; 216 char comment[61]; 217 struct stat st; 218 219 if (!have_identity) 220 ask_filename(pw, "Enter file in which the key is"); 221 if (stat(identity_file, &st) < 0) { 222 perror(identity_file); 223 exit(1); 224 } 225 if ((k = key_load_public(identity_file, NULL)) == NULL) { 226 if ((k = load_identity(identity_file)) == NULL) { 227 fprintf(stderr, "load failed\n"); 228 exit(1); 229 } 230 } 231 if (k->type == KEY_RSA1) { 232 fprintf(stderr, "version 1 keys are not supported\n"); 233 exit(1); 234 } 235 if (key_to_blob(k, &blob, &len) <= 0) { 236 fprintf(stderr, "key_to_blob failed\n"); 237 exit(1); 238 } 239 /* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */ 240 snprintf(comment, sizeof(comment), 241 "%u-bit %s, converted by %s@%s from OpenSSH", 242 key_size(k), key_type(k), 243 pw->pw_name, hostname); 244 245 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN); 246 fprintf(stdout, "Comment: \"%s\"\n", comment); 247 dump_base64(stdout, blob, len); 248 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END); 249 key_free(k); 250 xfree(blob); 251 exit(0); 252 } 253 254 static void 255 buffer_get_bignum_bits(Buffer *b, BIGNUM *value) 256 { 257 u_int bignum_bits = buffer_get_int(b); 258 u_int bytes = (bignum_bits + 7) / 8; 259 260 if (buffer_len(b) < bytes) 261 fatal("buffer_get_bignum_bits: input buffer too small: " 262 "need %d have %d", bytes, buffer_len(b)); 263 if (BN_bin2bn(buffer_ptr(b), bytes, value) == NULL) 264 fatal("buffer_get_bignum_bits: BN_bin2bn failed"); 265 buffer_consume(b, bytes); 266 } 267 268 static Key * 269 do_convert_private_ssh2_from_blob(u_char *blob, u_int blen) 270 { 271 Buffer b; 272 Key *key = NULL; 273 char *type, *cipher; 274 u_char *sig, data[] = "abcde12345"; 275 int magic, rlen, ktype, i1, i2, i3, i4; 276 u_int slen; 277 u_long e; 278 279 buffer_init(&b); 280 buffer_append(&b, blob, blen); 281 282 magic = buffer_get_int(&b); 283 if (magic != SSH_COM_PRIVATE_KEY_MAGIC) { 284 error("bad magic 0x%x != 0x%x", magic, SSH_COM_PRIVATE_KEY_MAGIC); 285 buffer_free(&b); 286 return NULL; 287 } 288 i1 = buffer_get_int(&b); 289 type = buffer_get_string(&b, NULL); 290 cipher = buffer_get_string(&b, NULL); 291 i2 = buffer_get_int(&b); 292 i3 = buffer_get_int(&b); 293 i4 = buffer_get_int(&b); 294 debug("ignore (%d %d %d %d)", i1, i2, i3, i4); 295 if (strcmp(cipher, "none") != 0) { 296 error("unsupported cipher %s", cipher); 297 xfree(cipher); 298 buffer_free(&b); 299 xfree(type); 300 return NULL; 301 } 302 xfree(cipher); 303 304 if (strstr(type, "dsa")) { 305 ktype = KEY_DSA; 306 } else if (strstr(type, "rsa")) { 307 ktype = KEY_RSA; 308 } else { 309 buffer_free(&b); 310 xfree(type); 311 return NULL; 312 } 313 key = key_new_private(ktype); 314 xfree(type); 315 316 switch (key->type) { 317 case KEY_DSA: 318 buffer_get_bignum_bits(&b, key->dsa->p); 319 buffer_get_bignum_bits(&b, key->dsa->g); 320 buffer_get_bignum_bits(&b, key->dsa->q); 321 buffer_get_bignum_bits(&b, key->dsa->pub_key); 322 buffer_get_bignum_bits(&b, key->dsa->priv_key); 323 break; 324 case KEY_RSA: 325 e = buffer_get_char(&b); 326 debug("e %lx", e); 327 if (e < 30) { 328 e <<= 8; 329 e += buffer_get_char(&b); 330 debug("e %lx", e); 331 e <<= 8; 332 e += buffer_get_char(&b); 333 debug("e %lx", e); 334 } 335 if (!BN_set_word(key->rsa->e, e)) { 336 buffer_free(&b); 337 key_free(key); 338 return NULL; 339 } 340 buffer_get_bignum_bits(&b, key->rsa->d); 341 buffer_get_bignum_bits(&b, key->rsa->n); 342 buffer_get_bignum_bits(&b, key->rsa->iqmp); 343 buffer_get_bignum_bits(&b, key->rsa->q); 344 buffer_get_bignum_bits(&b, key->rsa->p); 345 rsa_generate_additional_parameters(key->rsa); 346 break; 347 } 348 rlen = buffer_len(&b); 349 if (rlen != 0) 350 error("do_convert_private_ssh2_from_blob: " 351 "remaining bytes in key blob %d", rlen); 352 buffer_free(&b); 353 354 /* try the key */ 355 key_sign(key, &sig, &slen, data, sizeof(data)); 356 key_verify(key, sig, slen, data, sizeof(data)); 357 xfree(sig); 358 return key; 359 } 360 361 static int 362 get_line(FILE *fp, char *line, size_t len) 363 { 364 int c; 365 size_t pos = 0; 366 367 line[0] = '\0'; 368 while ((c = fgetc(fp)) != EOF) { 369 if (pos >= len - 1) { 370 fprintf(stderr, "input line too long.\n"); 371 exit(1); 372 } 373 switch (c) { 374 case '\r': 375 c = fgetc(fp); 376 if (c != EOF && c != '\n' && ungetc(c, fp) == EOF) { 377 fprintf(stderr, "unget: %s\n", strerror(errno)); 378 exit(1); 379 } 380 return pos; 381 case '\n': 382 return pos; 383 } 384 line[pos++] = c; 385 line[pos] = '\0'; 386 } 387 /* We reached EOF */ 388 return -1; 389 } 390 391 static void 392 do_convert_from_ssh2(struct passwd *pw) 393 { 394 Key *k; 395 int blen; 396 u_int len; 397 char line[1024]; 398 u_char blob[8096]; 399 char encoded[8096]; 400 struct stat st; 401 int escaped = 0, private = 0, ok; 402 FILE *fp; 403 404 if (!have_identity) 405 ask_filename(pw, "Enter file in which the key is"); 406 if (stat(identity_file, &st) < 0) { 407 perror(identity_file); 408 exit(1); 409 } 410 fp = fopen(identity_file, "r"); 411 if (fp == NULL) { 412 perror(identity_file); 413 exit(1); 414 } 415 encoded[0] = '\0'; 416 while ((blen = get_line(fp, line, sizeof(line))) != -1) { 417 if (line[blen - 1] == '\\') 418 escaped++; 419 if (strncmp(line, "----", 4) == 0 || 420 strstr(line, ": ") != NULL) { 421 if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL) 422 private = 1; 423 if (strstr(line, " END ") != NULL) { 424 break; 425 } 426 /* fprintf(stderr, "ignore: %s", line); */ 427 continue; 428 } 429 if (escaped) { 430 escaped--; 431 /* fprintf(stderr, "escaped: %s", line); */ 432 continue; 433 } 434 strlcat(encoded, line, sizeof(encoded)); 435 } 436 len = strlen(encoded); 437 if (((len % 4) == 3) && 438 (encoded[len-1] == '=') && 439 (encoded[len-2] == '=') && 440 (encoded[len-3] == '=')) 441 encoded[len-3] = '\0'; 442 blen = uudecode(encoded, blob, sizeof(blob)); 443 if (blen < 0) { 444 fprintf(stderr, "uudecode failed.\n"); 445 exit(1); 446 } 447 k = private ? 448 do_convert_private_ssh2_from_blob(blob, blen) : 449 key_from_blob(blob, blen); 450 if (k == NULL) { 451 fprintf(stderr, "decode blob failed.\n"); 452 exit(1); 453 } 454 ok = private ? 455 (k->type == KEY_DSA ? 456 PEM_write_DSAPrivateKey(stdout, k->dsa, NULL, NULL, 0, NULL, NULL) : 457 PEM_write_RSAPrivateKey(stdout, k->rsa, NULL, NULL, 0, NULL, NULL)) : 458 key_write(k, stdout); 459 if (!ok) { 460 fprintf(stderr, "key write failed\n"); 461 exit(1); 462 } 463 key_free(k); 464 if (!private) 465 fprintf(stdout, "\n"); 466 fclose(fp); 467 exit(0); 468 } 469 470 static void 471 do_print_public(struct passwd *pw) 472 { 473 Key *prv; 474 struct stat st; 475 476 if (!have_identity) 477 ask_filename(pw, "Enter file in which the key is"); 478 if (stat(identity_file, &st) < 0) { 479 perror(identity_file); 480 exit(1); 481 } 482 prv = load_identity(identity_file); 483 if (prv == NULL) { 484 fprintf(stderr, "load failed\n"); 485 exit(1); 486 } 487 if (!key_write(prv, stdout)) 488 fprintf(stderr, "key_write failed"); 489 key_free(prv); 490 fprintf(stdout, "\n"); 491 exit(0); 492 } 493 494 static void 495 do_download(struct passwd *pw, char *pkcs11provider) 496 { 497 #ifdef ENABLE_PKCS11 498 Key **keys = NULL; 499 int i, nkeys; 500 501 pkcs11_init(0); 502 nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys); 503 if (nkeys <= 0) 504 fatal("cannot read public key from pkcs11"); 505 for (i = 0; i < nkeys; i++) { 506 key_write(keys[i], stdout); 507 key_free(keys[i]); 508 fprintf(stdout, "\n"); 509 } 510 xfree(keys); 511 pkcs11_terminate(); 512 exit(0); 513 #else 514 fatal("no pkcs11 support"); 515 #endif /* ENABLE_PKCS11 */ 516 } 517 518 static void 519 do_fingerprint(struct passwd *pw) 520 { 521 FILE *f; 522 Key *public; 523 char *comment = NULL, *cp, *ep, line[16*1024], *fp, *ra; 524 int i, skip = 0, num = 0, invalid = 1; 525 enum fp_rep rep; 526 enum fp_type fptype; 527 struct stat st; 528 529 fptype = print_bubblebabble ? SSH_FP_SHA1 : SSH_FP_MD5; 530 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_HEX; 531 532 if (!have_identity) 533 ask_filename(pw, "Enter file in which the key is"); 534 if (stat(identity_file, &st) < 0) { 535 perror(identity_file); 536 exit(1); 537 } 538 public = key_load_public(identity_file, &comment); 539 if (public != NULL) { 540 fp = key_fingerprint(public, fptype, rep); 541 ra = key_fingerprint(public, SSH_FP_MD5, SSH_FP_RANDOMART); 542 printf("%u %s %s (%s)\n", key_size(public), fp, comment, 543 key_type(public)); 544 if (log_level >= SYSLOG_LEVEL_VERBOSE) 545 printf("%s\n", ra); 546 key_free(public); 547 xfree(comment); 548 xfree(ra); 549 xfree(fp); 550 exit(0); 551 } 552 if (comment) { 553 xfree(comment); 554 comment = NULL; 555 } 556 557 f = fopen(identity_file, "r"); 558 if (f != NULL) { 559 while (fgets(line, sizeof(line), f)) { 560 if ((cp = strchr(line, '\n')) == NULL) { 561 error("line %d too long: %.40s...", 562 num + 1, line); 563 skip = 1; 564 continue; 565 } 566 num++; 567 if (skip) { 568 skip = 0; 569 continue; 570 } 571 *cp = '\0'; 572 573 /* Skip leading whitespace, empty and comment lines. */ 574 for (cp = line; *cp == ' ' || *cp == '\t'; cp++) 575 ; 576 if (!*cp || *cp == '\n' || *cp == '#') 577 continue; 578 i = strtol(cp, &ep, 10); 579 if (i == 0 || ep == NULL || (*ep != ' ' && *ep != '\t')) { 580 int quoted = 0; 581 comment = cp; 582 for (; *cp && (quoted || (*cp != ' ' && 583 *cp != '\t')); cp++) { 584 if (*cp == '\\' && cp[1] == '"') 585 cp++; /* Skip both */ 586 else if (*cp == '"') 587 quoted = !quoted; 588 } 589 if (!*cp) 590 continue; 591 *cp++ = '\0'; 592 } 593 ep = cp; 594 public = key_new(KEY_RSA1); 595 if (key_read(public, &cp) != 1) { 596 cp = ep; 597 key_free(public); 598 public = key_new(KEY_UNSPEC); 599 if (key_read(public, &cp) != 1) { 600 key_free(public); 601 continue; 602 } 603 } 604 comment = *cp ? cp : comment; 605 fp = key_fingerprint(public, fptype, rep); 606 ra = key_fingerprint(public, SSH_FP_MD5, SSH_FP_RANDOMART); 607 printf("%u %s %s (%s)\n", key_size(public), fp, 608 comment ? comment : "no comment", key_type(public)); 609 if (log_level >= SYSLOG_LEVEL_VERBOSE) 610 printf("%s\n", ra); 611 xfree(ra); 612 xfree(fp); 613 key_free(public); 614 invalid = 0; 615 } 616 fclose(f); 617 } 618 if (invalid) { 619 printf("%s is not a public key file.\n", identity_file); 620 exit(1); 621 } 622 exit(0); 623 } 624 625 static void 626 printhost(FILE *f, const char *name, Key *public, int ca, int hash) 627 { 628 if (print_fingerprint) { 629 enum fp_rep rep; 630 enum fp_type fptype; 631 char *fp, *ra; 632 633 fptype = print_bubblebabble ? SSH_FP_SHA1 : SSH_FP_MD5; 634 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_HEX; 635 fp = key_fingerprint(public, fptype, rep); 636 ra = key_fingerprint(public, SSH_FP_MD5, SSH_FP_RANDOMART); 637 printf("%u %s %s (%s)\n", key_size(public), fp, name, 638 key_type(public)); 639 if (log_level >= SYSLOG_LEVEL_VERBOSE) 640 printf("%s\n", ra); 641 xfree(ra); 642 xfree(fp); 643 } else { 644 if (hash && (name = host_hash(name, NULL, 0)) == NULL) 645 fatal("hash_host failed"); 646 fprintf(f, "%s%s%s ", ca ? CA_MARKER : "", ca ? " " : "", name); 647 if (!key_write(public, f)) 648 fatal("key_write failed"); 649 fprintf(f, "\n"); 650 } 651 } 652 653 static void 654 do_known_hosts(struct passwd *pw, const char *name) 655 { 656 FILE *in, *out = stdout; 657 Key *pub; 658 char *cp, *cp2, *kp, *kp2; 659 char line[16*1024], tmp[MAXPATHLEN], old[MAXPATHLEN]; 660 int c, skip = 0, inplace = 0, num = 0, invalid = 0, has_unhashed = 0; 661 int ca; 662 663 if (!have_identity) { 664 cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid); 665 if (strlcpy(identity_file, cp, sizeof(identity_file)) >= 666 sizeof(identity_file)) 667 fatal("Specified known hosts path too long"); 668 xfree(cp); 669 have_identity = 1; 670 } 671 if ((in = fopen(identity_file, "r")) == NULL) 672 fatal("fopen: %s", strerror(errno)); 673 674 /* 675 * Find hosts goes to stdout, hash and deletions happen in-place 676 * A corner case is ssh-keygen -HF foo, which should go to stdout 677 */ 678 if (!find_host && (hash_hosts || delete_host)) { 679 if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) || 680 strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) || 681 strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) || 682 strlcat(old, ".old", sizeof(old)) >= sizeof(old)) 683 fatal("known_hosts path too long"); 684 umask(077); 685 if ((c = mkstemp(tmp)) == -1) 686 fatal("mkstemp: %s", strerror(errno)); 687 if ((out = fdopen(c, "w")) == NULL) { 688 c = errno; 689 unlink(tmp); 690 fatal("fdopen: %s", strerror(c)); 691 } 692 inplace = 1; 693 } 694 695 while (fgets(line, sizeof(line), in)) { 696 if ((cp = strchr(line, '\n')) == NULL) { 697 error("line %d too long: %.40s...", num + 1, line); 698 skip = 1; 699 invalid = 1; 700 continue; 701 } 702 num++; 703 if (skip) { 704 skip = 0; 705 continue; 706 } 707 *cp = '\0'; 708 709 /* Skip leading whitespace, empty and comment lines. */ 710 for (cp = line; *cp == ' ' || *cp == '\t'; cp++) 711 ; 712 if (!*cp || *cp == '\n' || *cp == '#') { 713 if (inplace) 714 fprintf(out, "%s\n", cp); 715 continue; 716 } 717 /* Check whether this is a CA key */ 718 if (strncasecmp(cp, CA_MARKER, sizeof(CA_MARKER) - 1) == 0 && 719 (cp[sizeof(CA_MARKER) - 1] == ' ' || 720 cp[sizeof(CA_MARKER) - 1] == '\t')) { 721 ca = 1; 722 cp += sizeof(CA_MARKER); 723 } else 724 ca = 0; 725 726 /* Find the end of the host name portion. */ 727 for (kp = cp; *kp && *kp != ' ' && *kp != '\t'; kp++) 728 ; 729 730 if (*kp == '\0' || *(kp + 1) == '\0') { 731 error("line %d missing key: %.40s...", 732 num, line); 733 invalid = 1; 734 continue; 735 } 736 *kp++ = '\0'; 737 kp2 = kp; 738 739 pub = key_new(KEY_RSA1); 740 if (key_read(pub, &kp) != 1) { 741 kp = kp2; 742 key_free(pub); 743 pub = key_new(KEY_UNSPEC); 744 if (key_read(pub, &kp) != 1) { 745 error("line %d invalid key: %.40s...", 746 num, line); 747 key_free(pub); 748 invalid = 1; 749 continue; 750 } 751 } 752 753 if (*cp == HASH_DELIM) { 754 if (find_host || delete_host) { 755 cp2 = host_hash(name, cp, strlen(cp)); 756 if (cp2 == NULL) { 757 error("line %d: invalid hashed " 758 "name: %.64s...", num, line); 759 invalid = 1; 760 continue; 761 } 762 c = (strcmp(cp2, cp) == 0); 763 if (find_host && c) { 764 printf("# Host %s found: " 765 "line %d type %s%s\n", name, 766 num, key_type(pub), 767 ca ? " (CA key)" : ""); 768 printhost(out, cp, pub, ca, 0); 769 } 770 if (delete_host && !c && !ca) 771 printhost(out, cp, pub, ca, 0); 772 } else if (hash_hosts) 773 printhost(out, cp, pub, ca, 0); 774 } else { 775 if (find_host || delete_host) { 776 c = (match_hostname(name, cp, 777 strlen(cp)) == 1); 778 if (find_host && c) { 779 printf("# Host %s found: " 780 "line %d type %s%s\n", name, 781 num, key_type(pub), 782 ca ? " (CA key)" : ""); 783 printhost(out, name, pub, 784 ca, hash_hosts && !ca); 785 } 786 if (delete_host && !c && !ca) 787 printhost(out, cp, pub, ca, 0); 788 } else if (hash_hosts) { 789 for (cp2 = strsep(&cp, ","); 790 cp2 != NULL && *cp2 != '\0'; 791 cp2 = strsep(&cp, ",")) { 792 if (ca) { 793 fprintf(stderr, "Warning: " 794 "ignoring CA key for host: " 795 "%.64s\n", cp2); 796 printhost(out, cp2, pub, ca, 0); 797 } else if (strcspn(cp2, "*?!") != 798 strlen(cp2)) { 799 fprintf(stderr, "Warning: " 800 "ignoring host name with " 801 "metacharacters: %.64s\n", 802 cp2); 803 printhost(out, cp2, pub, ca, 0); 804 } else 805 printhost(out, cp2, pub, ca, 1); 806 } 807 has_unhashed = 1; 808 } 809 } 810 key_free(pub); 811 } 812 fclose(in); 813 814 if (invalid) { 815 fprintf(stderr, "%s is not a valid known_hosts file.\n", 816 identity_file); 817 if (inplace) { 818 fprintf(stderr, "Not replacing existing known_hosts " 819 "file because of errors\n"); 820 fclose(out); 821 unlink(tmp); 822 } 823 exit(1); 824 } 825 826 if (inplace) { 827 fclose(out); 828 829 /* Backup existing file */ 830 if (unlink(old) == -1 && errno != ENOENT) 831 fatal("unlink %.100s: %s", old, strerror(errno)); 832 if (link(identity_file, old) == -1) 833 fatal("link %.100s to %.100s: %s", identity_file, old, 834 strerror(errno)); 835 /* Move new one into place */ 836 if (rename(tmp, identity_file) == -1) { 837 error("rename\"%s\" to \"%s\": %s", tmp, identity_file, 838 strerror(errno)); 839 unlink(tmp); 840 unlink(old); 841 exit(1); 842 } 843 844 fprintf(stderr, "%s updated.\n", identity_file); 845 fprintf(stderr, "Original contents retained as %s\n", old); 846 if (has_unhashed) { 847 fprintf(stderr, "WARNING: %s contains unhashed " 848 "entries\n", old); 849 fprintf(stderr, "Delete this file to ensure privacy " 850 "of hostnames\n"); 851 } 852 } 853 854 exit(0); 855 } 856 857 /* 858 * Perform changing a passphrase. The argument is the passwd structure 859 * for the current user. 860 */ 861 static void 862 do_change_passphrase(struct passwd *pw) 863 { 864 char *comment; 865 char *old_passphrase, *passphrase1, *passphrase2; 866 struct stat st; 867 Key *private; 868 869 if (!have_identity) 870 ask_filename(pw, "Enter file in which the key is"); 871 if (stat(identity_file, &st) < 0) { 872 perror(identity_file); 873 exit(1); 874 } 875 /* Try to load the file with empty passphrase. */ 876 private = key_load_private(identity_file, "", &comment); 877 if (private == NULL) { 878 if (identity_passphrase) 879 old_passphrase = xstrdup(identity_passphrase); 880 else 881 old_passphrase = 882 read_passphrase("Enter old passphrase: ", 883 RP_ALLOW_STDIN); 884 private = key_load_private(identity_file, old_passphrase, 885 &comment); 886 memset(old_passphrase, 0, strlen(old_passphrase)); 887 xfree(old_passphrase); 888 if (private == NULL) { 889 printf("Bad passphrase.\n"); 890 exit(1); 891 } 892 } 893 printf("Key has comment '%s'\n", comment); 894 895 /* Ask the new passphrase (twice). */ 896 if (identity_new_passphrase) { 897 passphrase1 = xstrdup(identity_new_passphrase); 898 passphrase2 = NULL; 899 } else { 900 passphrase1 = 901 read_passphrase("Enter new passphrase (empty for no " 902 "passphrase): ", RP_ALLOW_STDIN); 903 passphrase2 = read_passphrase("Enter same passphrase again: ", 904 RP_ALLOW_STDIN); 905 906 /* Verify that they are the same. */ 907 if (strcmp(passphrase1, passphrase2) != 0) { 908 memset(passphrase1, 0, strlen(passphrase1)); 909 memset(passphrase2, 0, strlen(passphrase2)); 910 xfree(passphrase1); 911 xfree(passphrase2); 912 printf("Pass phrases do not match. Try again.\n"); 913 exit(1); 914 } 915 /* Destroy the other copy. */ 916 memset(passphrase2, 0, strlen(passphrase2)); 917 xfree(passphrase2); 918 } 919 920 /* Save the file using the new passphrase. */ 921 if (!key_save_private(private, identity_file, passphrase1, comment)) { 922 printf("Saving the key failed: %s.\n", identity_file); 923 memset(passphrase1, 0, strlen(passphrase1)); 924 xfree(passphrase1); 925 key_free(private); 926 xfree(comment); 927 exit(1); 928 } 929 /* Destroy the passphrase and the copy of the key in memory. */ 930 memset(passphrase1, 0, strlen(passphrase1)); 931 xfree(passphrase1); 932 key_free(private); /* Destroys contents */ 933 xfree(comment); 934 935 printf("Your identification has been saved with the new passphrase.\n"); 936 exit(0); 937 } 938 939 /* 940 * Print the SSHFP RR. 941 */ 942 static int 943 do_print_resource_record(struct passwd *pw, char *fname, char *hname) 944 { 945 Key *public; 946 char *comment = NULL; 947 struct stat st; 948 949 if (fname == NULL) 950 ask_filename(pw, "Enter file in which the key is"); 951 if (stat(fname, &st) < 0) { 952 if (errno == ENOENT) 953 return 0; 954 perror(fname); 955 exit(1); 956 } 957 public = key_load_public(fname, &comment); 958 if (public != NULL) { 959 export_dns_rr(hname, public, stdout, print_generic); 960 key_free(public); 961 xfree(comment); 962 return 1; 963 } 964 if (comment) 965 xfree(comment); 966 967 printf("failed to read v2 public key from %s.\n", fname); 968 exit(1); 969 } 970 971 /* 972 * Change the comment of a private key file. 973 */ 974 static void 975 do_change_comment(struct passwd *pw) 976 { 977 char new_comment[1024], *comment, *passphrase; 978 Key *private; 979 Key *public; 980 struct stat st; 981 FILE *f; 982 int fd; 983 984 if (!have_identity) 985 ask_filename(pw, "Enter file in which the key is"); 986 if (stat(identity_file, &st) < 0) { 987 perror(identity_file); 988 exit(1); 989 } 990 private = key_load_private(identity_file, "", &comment); 991 if (private == NULL) { 992 if (identity_passphrase) 993 passphrase = xstrdup(identity_passphrase); 994 else if (identity_new_passphrase) 995 passphrase = xstrdup(identity_new_passphrase); 996 else 997 passphrase = read_passphrase("Enter passphrase: ", 998 RP_ALLOW_STDIN); 999 /* Try to load using the passphrase. */ 1000 private = key_load_private(identity_file, passphrase, &comment); 1001 if (private == NULL) { 1002 memset(passphrase, 0, strlen(passphrase)); 1003 xfree(passphrase); 1004 printf("Bad passphrase.\n"); 1005 exit(1); 1006 } 1007 } else { 1008 passphrase = xstrdup(""); 1009 } 1010 if (private->type != KEY_RSA1) { 1011 fprintf(stderr, "Comments are only supported for RSA1 keys.\n"); 1012 key_free(private); 1013 exit(1); 1014 } 1015 printf("Key now has comment '%s'\n", comment); 1016 1017 if (identity_comment) { 1018 strlcpy(new_comment, identity_comment, sizeof(new_comment)); 1019 } else { 1020 printf("Enter new comment: "); 1021 fflush(stdout); 1022 if (!fgets(new_comment, sizeof(new_comment), stdin)) { 1023 memset(passphrase, 0, strlen(passphrase)); 1024 key_free(private); 1025 exit(1); 1026 } 1027 new_comment[strcspn(new_comment, "\n")] = '\0'; 1028 } 1029 1030 /* Save the file using the new passphrase. */ 1031 if (!key_save_private(private, identity_file, passphrase, new_comment)) { 1032 printf("Saving the key failed: %s.\n", identity_file); 1033 memset(passphrase, 0, strlen(passphrase)); 1034 xfree(passphrase); 1035 key_free(private); 1036 xfree(comment); 1037 exit(1); 1038 } 1039 memset(passphrase, 0, strlen(passphrase)); 1040 xfree(passphrase); 1041 public = key_from_private(private); 1042 key_free(private); 1043 1044 strlcat(identity_file, ".pub", sizeof(identity_file)); 1045 fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644); 1046 if (fd == -1) { 1047 printf("Could not save your public key in %s\n", identity_file); 1048 exit(1); 1049 } 1050 f = fdopen(fd, "w"); 1051 if (f == NULL) { 1052 printf("fdopen %s failed\n", identity_file); 1053 exit(1); 1054 } 1055 if (!key_write(public, f)) 1056 fprintf(stderr, "write key failed\n"); 1057 key_free(public); 1058 fprintf(f, " %s\n", new_comment); 1059 fclose(f); 1060 1061 xfree(comment); 1062 1063 printf("The comment in your key file has been changed.\n"); 1064 exit(0); 1065 } 1066 1067 static const char * 1068 fmt_validity(u_int64_t valid_from, u_int64_t valid_to) 1069 { 1070 char from[32], to[32]; 1071 static char ret[64]; 1072 time_t tt; 1073 struct tm *tm; 1074 1075 *from = *to = '\0'; 1076 if (valid_from == 0 && valid_to == 0xffffffffffffffffULL) 1077 return "forever"; 1078 1079 if (valid_from != 0) { 1080 /* XXX revisit INT_MAX in 2038 :) */ 1081 tt = valid_from > INT_MAX ? INT_MAX : valid_from; 1082 tm = localtime(&tt); 1083 strftime(from, sizeof(from), "%Y-%m-%dT%H:%M:%S", tm); 1084 } 1085 if (valid_to != 0xffffffffffffffffULL) { 1086 /* XXX revisit INT_MAX in 2038 :) */ 1087 tt = valid_to > INT_MAX ? INT_MAX : valid_to; 1088 tm = localtime(&tt); 1089 strftime(to, sizeof(to), "%Y-%m-%dT%H:%M:%S", tm); 1090 } 1091 1092 if (valid_from == 0) { 1093 snprintf(ret, sizeof(ret), "before %s", to); 1094 return ret; 1095 } 1096 if (valid_to == 0xffffffffffffffffULL) { 1097 snprintf(ret, sizeof(ret), "after %s", from); 1098 return ret; 1099 } 1100 1101 snprintf(ret, sizeof(ret), "from %s to %s", from, to); 1102 return ret; 1103 } 1104 1105 static void 1106 add_flag_option(Buffer *c, const char *name) 1107 { 1108 debug3("%s: %s", __func__, name); 1109 buffer_put_cstring(c, name); 1110 buffer_put_string(c, NULL, 0); 1111 } 1112 1113 static void 1114 add_string_option(Buffer *c, const char *name, const char *value) 1115 { 1116 Buffer b; 1117 1118 debug3("%s: %s=%s", __func__, name, value); 1119 buffer_init(&b); 1120 buffer_put_cstring(&b, value); 1121 1122 buffer_put_cstring(c, name); 1123 buffer_put_string(c, buffer_ptr(&b), buffer_len(&b)); 1124 1125 buffer_free(&b); 1126 } 1127 1128 static void 1129 prepare_options_buf(Buffer *c) 1130 { 1131 buffer_clear(c); 1132 if ((critical_flags & CRITOPT_X_FWD) != 0) 1133 add_flag_option(c, "permit-X11-forwarding"); 1134 if ((critical_flags & CRITOPT_AGENT_FWD) != 0) 1135 add_flag_option(c, "permit-agent-forwarding"); 1136 if ((critical_flags & CRITOPT_PORT_FWD) != 0) 1137 add_flag_option(c, "permit-port-forwarding"); 1138 if ((critical_flags & CRITOPT_PTY) != 0) 1139 add_flag_option(c, "permit-pty"); 1140 if ((critical_flags & CRITOPT_USER_RC) != 0) 1141 add_flag_option(c, "permit-user-rc"); 1142 if (critical_command != NULL) 1143 add_string_option(c, "force-command", critical_command); 1144 if (critical_src_addr != NULL) 1145 add_string_option(c, "source-address", critical_src_addr); 1146 } 1147 1148 static void 1149 do_ca_sign(struct passwd *pw, int argc, char **argv) 1150 { 1151 int i, fd; 1152 u_int n; 1153 Key *ca, *public; 1154 char *otmp, *tmp, *cp, *out, *comment, **plist = NULL; 1155 FILE *f; 1156 int v00 = 0; /* legacy keys */ 1157 1158 tmp = tilde_expand_filename(ca_key_path, pw->pw_uid); 1159 if ((ca = load_identity(tmp)) == NULL) 1160 fatal("Couldn't load CA key \"%s\"", tmp); 1161 xfree(tmp); 1162 1163 if (key_type_name != NULL) { 1164 switch (key_type_from_name(key_type_name)) { 1165 case KEY_RSA_CERT_V00: 1166 case KEY_DSA_CERT_V00: 1167 v00 = 1; 1168 break; 1169 case KEY_UNSPEC: 1170 if (strcasecmp(key_type_name, "v00") == 0) { 1171 v00 = 1; 1172 break; 1173 } else if (strcasecmp(key_type_name, "v01") == 0) 1174 break; 1175 /* FALLTHROUGH */ 1176 default: 1177 fprintf(stderr, "unknown key type %s\n", key_type_name); 1178 exit(1); 1179 } 1180 } 1181 1182 for (i = 0; i < argc; i++) { 1183 /* Split list of principals */ 1184 n = 0; 1185 if (cert_principals != NULL) { 1186 otmp = tmp = xstrdup(cert_principals); 1187 plist = NULL; 1188 for (; (cp = strsep(&tmp, ",")) != NULL; n++) { 1189 plist = xrealloc(plist, n + 1, sizeof(*plist)); 1190 if (*(plist[n] = xstrdup(cp)) == '\0') 1191 fatal("Empty principal name"); 1192 } 1193 xfree(otmp); 1194 } 1195 1196 tmp = tilde_expand_filename(argv[i], pw->pw_uid); 1197 if ((public = key_load_public(tmp, &comment)) == NULL) 1198 fatal("%s: unable to open \"%s\"", __func__, tmp); 1199 if (public->type != KEY_RSA && public->type != KEY_DSA) 1200 fatal("%s: key \"%s\" type %s cannot be certified", 1201 __func__, tmp, key_type(public)); 1202 1203 /* Prepare certificate to sign */ 1204 if (key_to_certified(public, v00) != 0) 1205 fatal("Could not upgrade key %s to certificate", tmp); 1206 public->cert->type = cert_key_type; 1207 public->cert->serial = (u_int64_t)cert_serial; 1208 public->cert->key_id = xstrdup(cert_key_id); 1209 public->cert->nprincipals = n; 1210 public->cert->principals = plist; 1211 public->cert->valid_after = cert_valid_from; 1212 public->cert->valid_before = cert_valid_to; 1213 prepare_options_buf(&public->cert->critical); 1214 public->cert->signature_key = key_from_private(ca); 1215 1216 if (key_certify(public, ca) != 0) 1217 fatal("Couldn't not certify key %s", tmp); 1218 1219 if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0) 1220 *cp = '\0'; 1221 xasprintf(&out, "%s-cert.pub", tmp); 1222 xfree(tmp); 1223 1224 if ((fd = open(out, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1) 1225 fatal("Could not open \"%s\" for writing: %s", out, 1226 strerror(errno)); 1227 if ((f = fdopen(fd, "w")) == NULL) 1228 fatal("%s: fdopen: %s", __func__, strerror(errno)); 1229 if (!key_write(public, f)) 1230 fatal("Could not write certified key to %s", out); 1231 fprintf(f, " %s\n", comment); 1232 fclose(f); 1233 1234 if (!quiet) { 1235 logit("Signed %s key %s: id \"%s\" serial %llu%s%s " 1236 "valid %s", key_cert_type(public), 1237 out, public->cert->key_id, public->cert->serial, 1238 cert_principals != NULL ? " for " : "", 1239 cert_principals != NULL ? cert_principals : "", 1240 fmt_validity(cert_valid_from, cert_valid_to)); 1241 } 1242 1243 key_free(public); 1244 xfree(out); 1245 } 1246 exit(0); 1247 } 1248 1249 static u_int64_t 1250 parse_relative_time(const char *s, time_t now) 1251 { 1252 int64_t mul, secs; 1253 1254 mul = *s == '-' ? -1 : 1; 1255 1256 if ((secs = convtime(s + 1)) == -1) 1257 fatal("Invalid relative certificate time %s", s); 1258 if (mul == -1 && secs > now) 1259 fatal("Certificate time %s cannot be represented", s); 1260 return now + (u_int64_t)(secs * mul); 1261 } 1262 1263 static u_int64_t 1264 parse_absolute_time(const char *s) 1265 { 1266 struct tm tm; 1267 time_t tt; 1268 char buf[32], *fmt; 1269 1270 /* 1271 * POSIX strptime says "The application shall ensure that there 1272 * is white-space or other non-alphanumeric characters between 1273 * any two conversion specifications" so arrange things this way. 1274 */ 1275 switch (strlen(s)) { 1276 case 8: 1277 fmt = "%Y-%m-%d"; 1278 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6); 1279 break; 1280 case 14: 1281 fmt = "%Y-%m-%dT%H:%M:%S"; 1282 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s", 1283 s, s + 4, s + 6, s + 8, s + 10, s + 12); 1284 break; 1285 default: 1286 fatal("Invalid certificate time format %s", s); 1287 } 1288 1289 bzero(&tm, sizeof(tm)); 1290 if (strptime(buf, fmt, &tm) == NULL) 1291 fatal("Invalid certificate time %s", s); 1292 if ((tt = mktime(&tm)) < 0) 1293 fatal("Certificate time %s cannot be represented", s); 1294 return (u_int64_t)tt; 1295 } 1296 1297 static void 1298 parse_cert_times(char *timespec) 1299 { 1300 char *from, *to; 1301 time_t now = time(NULL); 1302 int64_t secs; 1303 1304 /* +timespec relative to now */ 1305 if (*timespec == '+' && strchr(timespec, ':') == NULL) { 1306 if ((secs = convtime(timespec + 1)) == -1) 1307 fatal("Invalid relative certificate life %s", timespec); 1308 cert_valid_to = now + secs; 1309 /* 1310 * Backdate certificate one minute to avoid problems on hosts 1311 * with poorly-synchronised clocks. 1312 */ 1313 cert_valid_from = ((now - 59)/ 60) * 60; 1314 return; 1315 } 1316 1317 /* 1318 * from:to, where 1319 * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS 1320 * to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS 1321 */ 1322 from = xstrdup(timespec); 1323 to = strchr(from, ':'); 1324 if (to == NULL || from == to || *(to + 1) == '\0') 1325 fatal("Invalid certificate life specification %s", timespec); 1326 *to++ = '\0'; 1327 1328 if (*from == '-' || *from == '+') 1329 cert_valid_from = parse_relative_time(from, now); 1330 else 1331 cert_valid_from = parse_absolute_time(from); 1332 1333 if (*to == '-' || *to == '+') 1334 cert_valid_to = parse_relative_time(to, cert_valid_from); 1335 else 1336 cert_valid_to = parse_absolute_time(to); 1337 1338 if (cert_valid_to <= cert_valid_from) 1339 fatal("Empty certificate validity interval"); 1340 xfree(from); 1341 } 1342 1343 static void 1344 add_cert_option(char *opt) 1345 { 1346 char *val; 1347 1348 if (strcmp(opt, "clear") == 0) 1349 critical_flags = 0; 1350 else if (strcasecmp(opt, "no-x11-forwarding") == 0) 1351 critical_flags &= ~CRITOPT_X_FWD; 1352 else if (strcasecmp(opt, "permit-x11-forwarding") == 0) 1353 critical_flags |= CRITOPT_X_FWD; 1354 else if (strcasecmp(opt, "no-agent-forwarding") == 0) 1355 critical_flags &= ~CRITOPT_AGENT_FWD; 1356 else if (strcasecmp(opt, "permit-agent-forwarding") == 0) 1357 critical_flags |= CRITOPT_AGENT_FWD; 1358 else if (strcasecmp(opt, "no-port-forwarding") == 0) 1359 critical_flags &= ~CRITOPT_PORT_FWD; 1360 else if (strcasecmp(opt, "permit-port-forwarding") == 0) 1361 critical_flags |= CRITOPT_PORT_FWD; 1362 else if (strcasecmp(opt, "no-pty") == 0) 1363 critical_flags &= ~CRITOPT_PTY; 1364 else if (strcasecmp(opt, "permit-pty") == 0) 1365 critical_flags |= CRITOPT_PTY; 1366 else if (strcasecmp(opt, "no-user-rc") == 0) 1367 critical_flags &= ~CRITOPT_USER_RC; 1368 else if (strcasecmp(opt, "permit-user-rc") == 0) 1369 critical_flags |= CRITOPT_USER_RC; 1370 else if (strncasecmp(opt, "force-command=", 14) == 0) { 1371 val = opt + 14; 1372 if (*val == '\0') 1373 fatal("Empty force-command option"); 1374 if (critical_command != NULL) 1375 fatal("force-command already specified"); 1376 critical_command = xstrdup(val); 1377 } else if (strncasecmp(opt, "source-address=", 15) == 0) { 1378 val = opt + 15; 1379 if (*val == '\0') 1380 fatal("Empty source-address option"); 1381 if (critical_src_addr != NULL) 1382 fatal("source-address already specified"); 1383 if (addr_match_cidr_list(NULL, val) != 0) 1384 fatal("Invalid source-address list"); 1385 critical_src_addr = xstrdup(val); 1386 } else 1387 fatal("Unsupported certificate option \"%s\"", opt); 1388 } 1389 1390 static void 1391 do_show_cert(struct passwd *pw) 1392 { 1393 Key *key; 1394 struct stat st; 1395 char *key_fp, *ca_fp; 1396 Buffer options, option; 1397 u_char *name, *data; 1398 u_int i, dlen, v00; 1399 1400 if (!have_identity) 1401 ask_filename(pw, "Enter file in which the key is"); 1402 if (stat(identity_file, &st) < 0) { 1403 perror(identity_file); 1404 exit(1); 1405 } 1406 if ((key = key_load_public(identity_file, NULL)) == NULL) 1407 fatal("%s is not a public key", identity_file); 1408 if (!key_is_cert(key)) 1409 fatal("%s is not a certificate", identity_file); 1410 v00 = key->type == KEY_RSA_CERT_V00 || key->type == KEY_DSA_CERT_V00; 1411 1412 key_fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX); 1413 ca_fp = key_fingerprint(key->cert->signature_key, 1414 SSH_FP_MD5, SSH_FP_HEX); 1415 1416 printf("%s:\n", identity_file); 1417 printf(" Type: %s %s certificate\n", key_ssh_name(key), 1418 key_cert_type(key)); 1419 printf(" Public key: %s %s\n", key_type(key), key_fp); 1420 printf(" Signing CA: %s %s\n", 1421 key_type(key->cert->signature_key), ca_fp); 1422 printf(" Key ID: \"%s\"\n", key->cert->key_id); 1423 if (!v00) 1424 printf(" Serial: %llu\n", key->cert->serial); 1425 printf(" Valid: %s\n", 1426 fmt_validity(key->cert->valid_after, key->cert->valid_before)); 1427 printf(" Principals: "); 1428 if (key->cert->nprincipals == 0) 1429 printf("(none)\n"); 1430 else { 1431 for (i = 0; i < key->cert->nprincipals; i++) 1432 printf("\n %s", 1433 key->cert->principals[i]); 1434 printf("\n"); 1435 } 1436 printf(" Critical Options: "); 1437 if (buffer_len(&key->cert->critical) == 0) 1438 printf("(none)\n"); 1439 else { 1440 printf("\n"); 1441 buffer_init(&options); 1442 buffer_append(&options, 1443 buffer_ptr(&key->cert->critical), 1444 buffer_len(&key->cert->critical)); 1445 buffer_init(&option); 1446 while (buffer_len(&options) != 0) { 1447 name = buffer_get_string(&options, NULL); 1448 data = buffer_get_string_ptr(&options, &dlen); 1449 buffer_append(&option, data, dlen); 1450 printf(" %s", name); 1451 if (strcmp(name, "permit-X11-forwarding") == 0 || 1452 strcmp(name, "permit-agent-forwarding") == 0 || 1453 strcmp(name, "permit-port-forwarding") == 0 || 1454 strcmp(name, "permit-pty") == 0 || 1455 strcmp(name, "permit-user-rc") == 0) 1456 printf("\n"); 1457 else if (strcmp(name, "force-command") == 0 || 1458 strcmp(name, "source-address") == 0) { 1459 data = buffer_get_string(&option, NULL); 1460 printf(" %s\n", data); 1461 xfree(data); 1462 } else { 1463 printf(" UNKNOWN OPTION (len %u)\n", 1464 buffer_len(&option)); 1465 buffer_clear(&option); 1466 } 1467 xfree(name); 1468 if (buffer_len(&option) != 0) 1469 fatal("Option corrupt: extra data at end"); 1470 } 1471 buffer_free(&option); 1472 buffer_free(&options); 1473 } 1474 if (!v00) { 1475 printf(" Extensions: "); 1476 if (buffer_len(&key->cert->extensions) == 0) 1477 printf("(none)\n"); 1478 else { 1479 printf("\n"); 1480 buffer_init(&options); 1481 buffer_append(&options, 1482 buffer_ptr(&key->cert->extensions), 1483 buffer_len(&key->cert->extensions)); 1484 buffer_init(&option); 1485 while (buffer_len(&options) != 0) { 1486 name = buffer_get_string(&options, NULL); 1487 (void)buffer_get_string_ptr(&options, &dlen); 1488 printf(" %s UNKNOWN OPTION " 1489 "(len %u)\n", name, dlen); 1490 xfree(name); 1491 } 1492 buffer_free(&option); 1493 buffer_free(&options); 1494 } 1495 } 1496 exit(0); 1497 } 1498 1499 static void 1500 usage(void) 1501 { 1502 fprintf(stderr, "usage: %s [options]\n", __progname); 1503 fprintf(stderr, "Options:\n"); 1504 fprintf(stderr, " -a trials Number of trials for screening DH-GEX moduli.\n"); 1505 fprintf(stderr, " -B Show bubblebabble digest of key file.\n"); 1506 fprintf(stderr, " -b bits Number of bits in the key to create.\n"); 1507 fprintf(stderr, " -C comment Provide new comment.\n"); 1508 fprintf(stderr, " -c Change comment in private and public key files.\n"); 1509 #ifdef ENABLE_PKCS11 1510 fprintf(stderr, " -D pkcs11 Download public key from pkcs11 token.\n"); 1511 #endif 1512 fprintf(stderr, " -e Convert OpenSSH to RFC 4716 key file.\n"); 1513 fprintf(stderr, " -F hostname Find hostname in known hosts file.\n"); 1514 fprintf(stderr, " -f filename Filename of the key file.\n"); 1515 fprintf(stderr, " -G file Generate candidates for DH-GEX moduli.\n"); 1516 fprintf(stderr, " -g Use generic DNS resource record format.\n"); 1517 fprintf(stderr, " -H Hash names in known_hosts file.\n"); 1518 fprintf(stderr, " -h Generate host certificate instead of a user certificate.\n"); 1519 fprintf(stderr, " -I key_id Key identifier to include in certificate.\n"); 1520 fprintf(stderr, " -i Convert RFC 4716 to OpenSSH key file.\n"); 1521 fprintf(stderr, " -L Print the contents of a certificate.\n"); 1522 fprintf(stderr, " -l Show fingerprint of key file.\n"); 1523 fprintf(stderr, " -M memory Amount of memory (MB) to use for generating DH-GEX moduli.\n"); 1524 fprintf(stderr, " -n name,... User/host principal names to include in certificate\n"); 1525 fprintf(stderr, " -N phrase Provide new passphrase.\n"); 1526 fprintf(stderr, " -O option Specify a certificate option.\n"); 1527 fprintf(stderr, " -P phrase Provide old passphrase.\n"); 1528 fprintf(stderr, " -p Change passphrase of private key file.\n"); 1529 fprintf(stderr, " -q Quiet.\n"); 1530 fprintf(stderr, " -R hostname Remove host from known_hosts file.\n"); 1531 fprintf(stderr, " -r hostname Print DNS resource record.\n"); 1532 fprintf(stderr, " -s ca_key Certify keys with CA key.\n"); 1533 fprintf(stderr, " -S start Start point (hex) for generating DH-GEX moduli.\n"); 1534 fprintf(stderr, " -T file Screen candidates for DH-GEX moduli.\n"); 1535 fprintf(stderr, " -t type Specify type of key to create.\n"); 1536 fprintf(stderr, " -V from:to Specify certificate validity interval.\n"); 1537 fprintf(stderr, " -v Verbose.\n"); 1538 fprintf(stderr, " -W gen Generator to use for generating DH-GEX moduli.\n"); 1539 fprintf(stderr, " -y Read private key file and print public key.\n"); 1540 fprintf(stderr, " -z serial Specify a serial number.\n"); 1541 1542 exit(1); 1543 } 1544 1545 /* 1546 * Main program for key management. 1547 */ 1548 int 1549 main(int argc, char **argv) 1550 { 1551 char dotsshdir[MAXPATHLEN], comment[1024], *passphrase1, *passphrase2; 1552 char out_file[MAXPATHLEN], *pkcs11provider = NULL; 1553 char *rr_hostname = NULL; 1554 Key *private, *public; 1555 struct passwd *pw; 1556 struct stat st; 1557 int opt, type, fd; 1558 u_int maxbits; 1559 u_int32_t memory = 0, generator_wanted = 0, trials = 100; 1560 int do_gen_candidates = 0, do_screen_candidates = 0; 1561 BIGNUM *start = NULL; 1562 FILE *f; 1563 const char *errstr; 1564 1565 extern int optind; 1566 extern char *optarg; 1567 1568 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ 1569 sanitise_stdfd(); 1570 1571 SSLeay_add_all_algorithms(); 1572 log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1); 1573 1574 /* we need this for the home * directory. */ 1575 pw = getpwuid(getuid()); 1576 if (!pw) { 1577 printf("You don't exist, go away!\n"); 1578 exit(1); 1579 } 1580 if (gethostname(hostname, sizeof(hostname)) < 0) { 1581 perror("gethostname"); 1582 exit(1); 1583 } 1584 1585 while ((opt = getopt(argc, argv, "degiqpclBHLhvxXyF:b:f:t:D:I:P:N:n:" 1586 "O:C:r:g:R:T:G:M:S:s:a:V:W:z:")) != -1) { 1587 switch (opt) { 1588 case 'b': 1589 bits = (u_int32_t)strtonum(optarg, 768, 32768, &errstr); 1590 if (errstr) 1591 fatal("Bits has bad value %s (%s)", 1592 optarg, errstr); 1593 break; 1594 case 'F': 1595 find_host = 1; 1596 rr_hostname = optarg; 1597 break; 1598 case 'H': 1599 hash_hosts = 1; 1600 break; 1601 case 'I': 1602 cert_key_id = optarg; 1603 break; 1604 case 'R': 1605 delete_host = 1; 1606 rr_hostname = optarg; 1607 break; 1608 case 'L': 1609 show_cert = 1; 1610 break; 1611 case 'l': 1612 print_fingerprint = 1; 1613 break; 1614 case 'B': 1615 print_bubblebabble = 1; 1616 break; 1617 case 'n': 1618 cert_principals = optarg; 1619 break; 1620 case 'p': 1621 change_passphrase = 1; 1622 break; 1623 case 'c': 1624 change_comment = 1; 1625 break; 1626 case 'f': 1627 if (strlcpy(identity_file, optarg, sizeof(identity_file)) >= 1628 sizeof(identity_file)) 1629 fatal("Identity filename too long"); 1630 have_identity = 1; 1631 break; 1632 case 'g': 1633 print_generic = 1; 1634 break; 1635 case 'P': 1636 identity_passphrase = optarg; 1637 break; 1638 case 'N': 1639 identity_new_passphrase = optarg; 1640 break; 1641 case 'O': 1642 add_cert_option(optarg); 1643 break; 1644 case 'C': 1645 identity_comment = optarg; 1646 break; 1647 case 'q': 1648 quiet = 1; 1649 break; 1650 case 'e': 1651 case 'x': 1652 /* export key */ 1653 convert_to_ssh2 = 1; 1654 break; 1655 case 'h': 1656 cert_key_type = SSH2_CERT_TYPE_HOST; 1657 critical_flags = 0; 1658 break; 1659 case 'i': 1660 case 'X': 1661 /* import key */ 1662 convert_from_ssh2 = 1; 1663 break; 1664 case 'y': 1665 print_public = 1; 1666 break; 1667 case 'd': 1668 key_type_name = "dsa"; 1669 break; 1670 case 's': 1671 ca_key_path = optarg; 1672 break; 1673 case 't': 1674 key_type_name = optarg; 1675 break; 1676 case 'D': 1677 pkcs11provider = optarg; 1678 break; 1679 case 'v': 1680 if (log_level == SYSLOG_LEVEL_INFO) 1681 log_level = SYSLOG_LEVEL_DEBUG1; 1682 else { 1683 if (log_level >= SYSLOG_LEVEL_DEBUG1 && 1684 log_level < SYSLOG_LEVEL_DEBUG3) 1685 log_level++; 1686 } 1687 break; 1688 case 'r': 1689 rr_hostname = optarg; 1690 break; 1691 case 'W': 1692 generator_wanted = (u_int32_t)strtonum(optarg, 1, 1693 UINT_MAX, &errstr); 1694 if (errstr) 1695 fatal("Desired generator has bad value: %s (%s)", 1696 optarg, errstr); 1697 break; 1698 case 'a': 1699 trials = (u_int32_t)strtonum(optarg, 1, UINT_MAX, &errstr); 1700 if (errstr) 1701 fatal("Invalid number of trials: %s (%s)", 1702 optarg, errstr); 1703 break; 1704 case 'M': 1705 memory = (u_int32_t)strtonum(optarg, 1, UINT_MAX, &errstr); 1706 if (errstr) 1707 fatal("Memory limit is %s: %s", errstr, optarg); 1708 break; 1709 case 'G': 1710 do_gen_candidates = 1; 1711 if (strlcpy(out_file, optarg, sizeof(out_file)) >= 1712 sizeof(out_file)) 1713 fatal("Output filename too long"); 1714 break; 1715 case 'T': 1716 do_screen_candidates = 1; 1717 if (strlcpy(out_file, optarg, sizeof(out_file)) >= 1718 sizeof(out_file)) 1719 fatal("Output filename too long"); 1720 break; 1721 case 'S': 1722 /* XXX - also compare length against bits */ 1723 if (BN_hex2bn(&start, optarg) == 0) 1724 fatal("Invalid start point."); 1725 break; 1726 case 'V': 1727 parse_cert_times(optarg); 1728 break; 1729 case 'z': 1730 cert_serial = strtonum(optarg, 0, LLONG_MAX, &errstr); 1731 if (errstr) 1732 fatal("Invalid serial number: %s", errstr); 1733 break; 1734 case '?': 1735 default: 1736 usage(); 1737 } 1738 } 1739 1740 /* reinit */ 1741 log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1); 1742 1743 argv += optind; 1744 argc -= optind; 1745 1746 if (ca_key_path != NULL) { 1747 if (argc < 1) { 1748 printf("Too few arguments.\n"); 1749 usage(); 1750 } 1751 } else if (argc > 0) { 1752 printf("Too many arguments.\n"); 1753 usage(); 1754 } 1755 if (change_passphrase && change_comment) { 1756 printf("Can only have one of -p and -c.\n"); 1757 usage(); 1758 } 1759 if (print_fingerprint && (delete_host || hash_hosts)) { 1760 printf("Cannot use -l with -D or -R.\n"); 1761 usage(); 1762 } 1763 if (ca_key_path != NULL) { 1764 if (cert_key_id == NULL) 1765 fatal("Must specify key id (-I) when certifying"); 1766 do_ca_sign(pw, argc, argv); 1767 } 1768 if (show_cert) 1769 do_show_cert(pw); 1770 if (delete_host || hash_hosts || find_host) 1771 do_known_hosts(pw, rr_hostname); 1772 if (print_fingerprint || print_bubblebabble) 1773 do_fingerprint(pw); 1774 if (change_passphrase) 1775 do_change_passphrase(pw); 1776 if (change_comment) 1777 do_change_comment(pw); 1778 if (convert_to_ssh2) 1779 do_convert_to_ssh2(pw); 1780 if (convert_from_ssh2) 1781 do_convert_from_ssh2(pw); 1782 if (print_public) 1783 do_print_public(pw); 1784 if (rr_hostname != NULL) { 1785 unsigned int n = 0; 1786 1787 if (have_identity) { 1788 n = do_print_resource_record(pw, 1789 identity_file, rr_hostname); 1790 if (n == 0) { 1791 perror(identity_file); 1792 exit(1); 1793 } 1794 exit(0); 1795 } else { 1796 1797 n += do_print_resource_record(pw, 1798 _PATH_HOST_RSA_KEY_FILE, rr_hostname); 1799 n += do_print_resource_record(pw, 1800 _PATH_HOST_DSA_KEY_FILE, rr_hostname); 1801 1802 if (n == 0) 1803 fatal("no keys found."); 1804 exit(0); 1805 } 1806 } 1807 if (pkcs11provider != NULL) 1808 do_download(pw, pkcs11provider); 1809 1810 if (do_gen_candidates) { 1811 FILE *out = fopen(out_file, "w"); 1812 1813 if (out == NULL) { 1814 error("Couldn't open modulus candidate file \"%s\": %s", 1815 out_file, strerror(errno)); 1816 return (1); 1817 } 1818 if (bits == 0) 1819 bits = DEFAULT_BITS; 1820 if (gen_candidates(out, memory, bits, start) != 0) 1821 fatal("modulus candidate generation failed"); 1822 1823 return (0); 1824 } 1825 1826 if (do_screen_candidates) { 1827 FILE *in; 1828 FILE *out = fopen(out_file, "w"); 1829 1830 if (have_identity && strcmp(identity_file, "-") != 0) { 1831 if ((in = fopen(identity_file, "r")) == NULL) { 1832 fatal("Couldn't open modulus candidate " 1833 "file \"%s\": %s", identity_file, 1834 strerror(errno)); 1835 } 1836 } else 1837 in = stdin; 1838 1839 if (out == NULL) { 1840 fatal("Couldn't open moduli file \"%s\": %s", 1841 out_file, strerror(errno)); 1842 } 1843 if (prime_test(in, out, trials, generator_wanted) != 0) 1844 fatal("modulus screening failed"); 1845 return (0); 1846 } 1847 1848 arc4random_stir(); 1849 1850 if (key_type_name == NULL) 1851 key_type_name = "rsa"; 1852 1853 type = key_type_from_name(key_type_name); 1854 if (type == KEY_UNSPEC) { 1855 fprintf(stderr, "unknown key type %s\n", key_type_name); 1856 exit(1); 1857 } 1858 if (bits == 0) 1859 bits = (type == KEY_DSA) ? DEFAULT_BITS_DSA : DEFAULT_BITS; 1860 maxbits = (type == KEY_DSA) ? 1861 OPENSSL_DSA_MAX_MODULUS_BITS : OPENSSL_RSA_MAX_MODULUS_BITS; 1862 if (bits > maxbits) { 1863 fprintf(stderr, "key bits exceeds maximum %d\n", maxbits); 1864 exit(1); 1865 } 1866 if (type == KEY_DSA && bits != 1024) 1867 fatal("DSA keys must be 1024 bits"); 1868 if (!quiet) 1869 printf("Generating public/private %s key pair.\n", key_type_name); 1870 private = key_generate(type, bits); 1871 if (private == NULL) { 1872 fprintf(stderr, "key_generate failed\n"); 1873 exit(1); 1874 } 1875 public = key_from_private(private); 1876 1877 if (!have_identity) 1878 ask_filename(pw, "Enter file in which to save the key"); 1879 1880 /* Create ~/.ssh directory if it doesn't already exist. */ 1881 snprintf(dotsshdir, sizeof dotsshdir, "%s/%s", 1882 pw->pw_dir, _PATH_SSH_USER_DIR); 1883 if (strstr(identity_file, dotsshdir) != NULL) { 1884 if (stat(dotsshdir, &st) < 0) { 1885 if (errno != ENOENT) { 1886 error("Could not stat %s: %s", dotsshdir, 1887 strerror(errno)); 1888 } else if (mkdir(dotsshdir, 0700) < 0) { 1889 error("Could not create directory '%s': %s", 1890 dotsshdir, strerror(errno)); 1891 } else if (!quiet) 1892 printf("Created directory '%s'.\n", dotsshdir); 1893 } 1894 } 1895 /* If the file already exists, ask the user to confirm. */ 1896 if (stat(identity_file, &st) >= 0) { 1897 char yesno[3]; 1898 printf("%s already exists.\n", identity_file); 1899 printf("Overwrite (y/n)? "); 1900 fflush(stdout); 1901 if (fgets(yesno, sizeof(yesno), stdin) == NULL) 1902 exit(1); 1903 if (yesno[0] != 'y' && yesno[0] != 'Y') 1904 exit(1); 1905 } 1906 /* Ask for a passphrase (twice). */ 1907 if (identity_passphrase) 1908 passphrase1 = xstrdup(identity_passphrase); 1909 else if (identity_new_passphrase) 1910 passphrase1 = xstrdup(identity_new_passphrase); 1911 else { 1912 passphrase_again: 1913 passphrase1 = 1914 read_passphrase("Enter passphrase (empty for no " 1915 "passphrase): ", RP_ALLOW_STDIN); 1916 passphrase2 = read_passphrase("Enter same passphrase again: ", 1917 RP_ALLOW_STDIN); 1918 if (strcmp(passphrase1, passphrase2) != 0) { 1919 /* 1920 * The passphrases do not match. Clear them and 1921 * retry. 1922 */ 1923 memset(passphrase1, 0, strlen(passphrase1)); 1924 memset(passphrase2, 0, strlen(passphrase2)); 1925 xfree(passphrase1); 1926 xfree(passphrase2); 1927 printf("Passphrases do not match. Try again.\n"); 1928 goto passphrase_again; 1929 } 1930 /* Clear the other copy of the passphrase. */ 1931 memset(passphrase2, 0, strlen(passphrase2)); 1932 xfree(passphrase2); 1933 } 1934 1935 if (identity_comment) { 1936 strlcpy(comment, identity_comment, sizeof(comment)); 1937 } else { 1938 /* Create default comment field for the passphrase. */ 1939 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname); 1940 } 1941 1942 /* Save the key with the given passphrase and comment. */ 1943 if (!key_save_private(private, identity_file, passphrase1, comment)) { 1944 printf("Saving the key failed: %s.\n", identity_file); 1945 memset(passphrase1, 0, strlen(passphrase1)); 1946 xfree(passphrase1); 1947 exit(1); 1948 } 1949 /* Clear the passphrase. */ 1950 memset(passphrase1, 0, strlen(passphrase1)); 1951 xfree(passphrase1); 1952 1953 /* Clear the private key and the random number generator. */ 1954 key_free(private); 1955 arc4random_stir(); 1956 1957 if (!quiet) 1958 printf("Your identification has been saved in %s.\n", identity_file); 1959 1960 strlcat(identity_file, ".pub", sizeof(identity_file)); 1961 fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644); 1962 if (fd == -1) { 1963 printf("Could not save your public key in %s\n", identity_file); 1964 exit(1); 1965 } 1966 f = fdopen(fd, "w"); 1967 if (f == NULL) { 1968 printf("fdopen %s failed\n", identity_file); 1969 exit(1); 1970 } 1971 if (!key_write(public, f)) 1972 fprintf(stderr, "write key failed\n"); 1973 fprintf(f, " %s\n", comment); 1974 fclose(f); 1975 1976 if (!quiet) { 1977 char *fp = key_fingerprint(public, SSH_FP_MD5, SSH_FP_HEX); 1978 char *ra = key_fingerprint(public, SSH_FP_MD5, 1979 SSH_FP_RANDOMART); 1980 printf("Your public key has been saved in %s.\n", 1981 identity_file); 1982 printf("The key fingerprint is:\n"); 1983 printf("%s %s\n", fp, comment); 1984 printf("The key's randomart image is:\n"); 1985 printf("%s\n", ra); 1986 xfree(ra); 1987 xfree(fp); 1988 } 1989 1990 key_free(public); 1991 exit(0); 1992 } 1993