1 /* $OpenBSD: authfile.c,v 1.98 2013/11/21 00:45:43 djm Exp $ */ 2 /* 3 * Author: Tatu Ylonen <ylo@cs.hut.fi> 4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 5 * All rights reserved 6 * This file contains functions for reading and writing identity files, and 7 * for reading the passphrase from the user. 8 * 9 * As far as I am concerned, the code I have written for this software 10 * can be used freely for any purpose. Any derived versions of this 11 * software must be clearly marked as such, and if the derived work is 12 * incompatible with the protocol description in the RFC file, it must be 13 * called by a name other than "ssh" or "Secure Shell". 14 * 15 * 16 * Copyright (c) 2000 Markus Friedl. All rights reserved. 17 * 18 * Redistribution and use in source and binary forms, with or without 19 * modification, are permitted provided that the following conditions 20 * are met: 21 * 1. Redistributions of source code must retain the above copyright 22 * notice, this list of conditions and the following disclaimer. 23 * 2. Redistributions in binary form must reproduce the above copyright 24 * notice, this list of conditions and the following disclaimer in the 25 * documentation and/or other materials provided with the distribution. 26 * 27 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 28 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 29 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 30 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 31 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 32 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 33 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 34 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 35 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 36 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 37 */ 38 39 40 #include <sys/types.h> 41 #include <sys/stat.h> 42 #include <sys/param.h> 43 #include <sys/uio.h> 44 45 #include <openssl/err.h> 46 #include <openssl/evp.h> 47 #include <openssl/pem.h> 48 49 #include <errno.h> 50 #include <fcntl.h> 51 #include <stdio.h> 52 #include <stdlib.h> 53 #include <string.h> 54 #include <unistd.h> 55 56 #include "xmalloc.h" 57 #include "cipher.h" 58 #include "buffer.h" 59 #include "key.h" 60 #include "ssh.h" 61 #include "log.h" 62 #include "authfile.h" 63 #include "rsa.h" 64 #include "misc.h" 65 #include "atomicio.h" 66 67 #define MAX_KEY_FILE_SIZE (1024 * 1024) 68 69 /* Version identification string for SSH v1 identity files. */ 70 static const char authfile_id_string[] = 71 "SSH PRIVATE KEY FILE FORMAT 1.1\n"; 72 73 /* 74 * Serialises the authentication (private) key to a blob, encrypting it with 75 * passphrase. The identification of the blob (lowest 64 bits of n) will 76 * precede the key to provide identification of the key without needing a 77 * passphrase. 78 */ 79 static int 80 key_private_rsa1_to_blob(Key *key, Buffer *blob, const char *passphrase, 81 const char *comment) 82 { 83 Buffer buffer, encrypted; 84 u_char buf[100], *cp; 85 int i, cipher_num; 86 CipherContext ciphercontext; 87 const Cipher *cipher; 88 u_int32_t rnd; 89 90 /* 91 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting 92 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER. 93 */ 94 cipher_num = (strcmp(passphrase, "") == 0) ? 95 SSH_CIPHER_NONE : SSH_AUTHFILE_CIPHER; 96 if ((cipher = cipher_by_number(cipher_num)) == NULL) 97 fatal("save_private_key_rsa: bad cipher"); 98 99 /* This buffer is used to built the secret part of the private key. */ 100 buffer_init(&buffer); 101 102 /* Put checkbytes for checking passphrase validity. */ 103 rnd = arc4random(); 104 buf[0] = rnd & 0xff; 105 buf[1] = (rnd >> 8) & 0xff; 106 buf[2] = buf[0]; 107 buf[3] = buf[1]; 108 buffer_append(&buffer, buf, 4); 109 110 /* 111 * Store the private key (n and e will not be stored because they 112 * will be stored in plain text, and storing them also in encrypted 113 * format would just give known plaintext). 114 */ 115 buffer_put_bignum(&buffer, key->rsa->d); 116 buffer_put_bignum(&buffer, key->rsa->iqmp); 117 buffer_put_bignum(&buffer, key->rsa->q); /* reverse from SSL p */ 118 buffer_put_bignum(&buffer, key->rsa->p); /* reverse from SSL q */ 119 120 /* Pad the part to be encrypted until its size is a multiple of 8. */ 121 while (buffer_len(&buffer) % 8 != 0) 122 buffer_put_char(&buffer, 0); 123 124 /* This buffer will be used to contain the data in the file. */ 125 buffer_init(&encrypted); 126 127 /* First store keyfile id string. */ 128 for (i = 0; authfile_id_string[i]; i++) 129 buffer_put_char(&encrypted, authfile_id_string[i]); 130 buffer_put_char(&encrypted, 0); 131 132 /* Store cipher type. */ 133 buffer_put_char(&encrypted, cipher_num); 134 buffer_put_int(&encrypted, 0); /* For future extension */ 135 136 /* Store public key. This will be in plain text. */ 137 buffer_put_int(&encrypted, BN_num_bits(key->rsa->n)); 138 buffer_put_bignum(&encrypted, key->rsa->n); 139 buffer_put_bignum(&encrypted, key->rsa->e); 140 buffer_put_cstring(&encrypted, comment); 141 142 /* Allocate space for the private part of the key in the buffer. */ 143 cp = buffer_append_space(&encrypted, buffer_len(&buffer)); 144 145 cipher_set_key_string(&ciphercontext, cipher, passphrase, 146 CIPHER_ENCRYPT); 147 cipher_crypt(&ciphercontext, 0, cp, 148 buffer_ptr(&buffer), buffer_len(&buffer), 0, 0); 149 cipher_cleanup(&ciphercontext); 150 memset(&ciphercontext, 0, sizeof(ciphercontext)); 151 152 /* Destroy temporary data. */ 153 memset(buf, 0, sizeof(buf)); 154 buffer_free(&buffer); 155 156 buffer_append(blob, buffer_ptr(&encrypted), buffer_len(&encrypted)); 157 buffer_free(&encrypted); 158 159 return 1; 160 } 161 162 /* convert SSH v2 key in OpenSSL PEM format */ 163 static int 164 key_private_pem_to_blob(Key *key, Buffer *blob, const char *_passphrase, 165 const char *comment) 166 { 167 int success = 0; 168 int blen, len = strlen(_passphrase); 169 u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL; 170 const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL; 171 const u_char *bptr; 172 BIO *bio; 173 174 if (len > 0 && len <= 4) { 175 error("passphrase too short: have %d bytes, need > 4", len); 176 return 0; 177 } 178 if ((bio = BIO_new(BIO_s_mem())) == NULL) { 179 error("%s: BIO_new failed", __func__); 180 return 0; 181 } 182 switch (key->type) { 183 case KEY_DSA: 184 success = PEM_write_bio_DSAPrivateKey(bio, key->dsa, 185 cipher, passphrase, len, NULL, NULL); 186 break; 187 case KEY_ECDSA: 188 success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa, 189 cipher, passphrase, len, NULL, NULL); 190 break; 191 case KEY_RSA: 192 success = PEM_write_bio_RSAPrivateKey(bio, key->rsa, 193 cipher, passphrase, len, NULL, NULL); 194 break; 195 } 196 if (success) { 197 if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0) 198 success = 0; 199 else 200 buffer_append(blob, bptr, blen); 201 } 202 BIO_free(bio); 203 return success; 204 } 205 206 /* Save a key blob to a file */ 207 static int 208 key_save_private_blob(Buffer *keybuf, const char *filename) 209 { 210 int fd; 211 212 if ((fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600)) < 0) { 213 error("open %s failed: %s.", filename, strerror(errno)); 214 return 0; 215 } 216 if (atomicio(vwrite, fd, buffer_ptr(keybuf), 217 buffer_len(keybuf)) != buffer_len(keybuf)) { 218 error("write to key file %s failed: %s", filename, 219 strerror(errno)); 220 close(fd); 221 unlink(filename); 222 return 0; 223 } 224 close(fd); 225 return 1; 226 } 227 228 /* Serialise "key" to buffer "blob" */ 229 static int 230 key_private_to_blob(Key *key, Buffer *blob, const char *passphrase, 231 const char *comment) 232 { 233 switch (key->type) { 234 case KEY_RSA1: 235 return key_private_rsa1_to_blob(key, blob, passphrase, comment); 236 case KEY_DSA: 237 case KEY_ECDSA: 238 case KEY_RSA: 239 return key_private_pem_to_blob(key, blob, passphrase, comment); 240 default: 241 error("%s: cannot save key type %d", __func__, key->type); 242 return 0; 243 } 244 } 245 246 int 247 key_save_private(Key *key, const char *filename, const char *passphrase, 248 const char *comment) 249 { 250 Buffer keyblob; 251 int success = 0; 252 253 buffer_init(&keyblob); 254 if (!key_private_to_blob(key, &keyblob, passphrase, comment)) 255 goto out; 256 if (!key_save_private_blob(&keyblob, filename)) 257 goto out; 258 success = 1; 259 out: 260 buffer_free(&keyblob); 261 return success; 262 } 263 264 /* 265 * Parse the public, unencrypted portion of a RSA1 key. 266 */ 267 static Key * 268 key_parse_public_rsa1(Buffer *blob, char **commentp) 269 { 270 Key *pub; 271 Buffer copy; 272 273 /* Check that it is at least big enough to contain the ID string. */ 274 if (buffer_len(blob) < sizeof(authfile_id_string)) { 275 debug3("Truncated RSA1 identifier"); 276 return NULL; 277 } 278 279 /* 280 * Make sure it begins with the id string. Consume the id string 281 * from the buffer. 282 */ 283 if (memcmp(buffer_ptr(blob), authfile_id_string, 284 sizeof(authfile_id_string)) != 0) { 285 debug3("Incorrect RSA1 identifier"); 286 return NULL; 287 } 288 buffer_init(©); 289 buffer_append(©, buffer_ptr(blob), buffer_len(blob)); 290 buffer_consume(©, sizeof(authfile_id_string)); 291 292 /* Skip cipher type and reserved data. */ 293 (void) buffer_get_char(©); /* cipher type */ 294 (void) buffer_get_int(©); /* reserved */ 295 296 /* Read the public key from the buffer. */ 297 (void) buffer_get_int(©); 298 pub = key_new(KEY_RSA1); 299 buffer_get_bignum(©, pub->rsa->n); 300 buffer_get_bignum(©, pub->rsa->e); 301 if (commentp) 302 *commentp = buffer_get_string(©, NULL); 303 /* The encrypted private part is not parsed by this function. */ 304 buffer_free(©); 305 306 return pub; 307 } 308 309 /* Load a key from a fd into a buffer */ 310 int 311 key_load_file(int fd, const char *filename, Buffer *blob) 312 { 313 u_char buf[1024]; 314 size_t len; 315 struct stat st; 316 317 if (fstat(fd, &st) < 0) { 318 error("%s: fstat of key file %.200s%sfailed: %.100s", __func__, 319 filename == NULL ? "" : filename, 320 filename == NULL ? "" : " ", 321 strerror(errno)); 322 return 0; 323 } 324 if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 && 325 st.st_size > MAX_KEY_FILE_SIZE) { 326 toobig: 327 error("%s: key file %.200s%stoo large", __func__, 328 filename == NULL ? "" : filename, 329 filename == NULL ? "" : " "); 330 return 0; 331 } 332 buffer_clear(blob); 333 for (;;) { 334 if ((len = atomicio(read, fd, buf, sizeof(buf))) == 0) { 335 if (errno == EPIPE) 336 break; 337 debug("%s: read from key file %.200s%sfailed: %.100s", 338 __func__, filename == NULL ? "" : filename, 339 filename == NULL ? "" : " ", strerror(errno)); 340 buffer_clear(blob); 341 bzero(buf, sizeof(buf)); 342 return 0; 343 } 344 buffer_append(blob, buf, len); 345 if (buffer_len(blob) > MAX_KEY_FILE_SIZE) { 346 buffer_clear(blob); 347 bzero(buf, sizeof(buf)); 348 goto toobig; 349 } 350 } 351 bzero(buf, sizeof(buf)); 352 if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 && 353 st.st_size != buffer_len(blob)) { 354 debug("%s: key file %.200s%schanged size while reading", 355 __func__, filename == NULL ? "" : filename, 356 filename == NULL ? "" : " "); 357 buffer_clear(blob); 358 return 0; 359 } 360 361 return 1; 362 } 363 364 /* 365 * Loads the public part of the ssh v1 key file. Returns NULL if an error was 366 * encountered (the file does not exist or is not readable), and the key 367 * otherwise. 368 */ 369 static Key * 370 key_load_public_rsa1(int fd, const char *filename, char **commentp) 371 { 372 Buffer buffer; 373 Key *pub; 374 375 buffer_init(&buffer); 376 if (!key_load_file(fd, filename, &buffer)) { 377 buffer_free(&buffer); 378 return NULL; 379 } 380 381 pub = key_parse_public_rsa1(&buffer, commentp); 382 if (pub == NULL) 383 debug3("Could not load \"%s\" as a RSA1 public key", filename); 384 buffer_free(&buffer); 385 return pub; 386 } 387 388 /* load public key from private-key file, works only for SSH v1 */ 389 Key * 390 key_load_public_type(int type, const char *filename, char **commentp) 391 { 392 Key *pub; 393 int fd; 394 395 if (type == KEY_RSA1) { 396 fd = open(filename, O_RDONLY); 397 if (fd < 0) 398 return NULL; 399 pub = key_load_public_rsa1(fd, filename, commentp); 400 close(fd); 401 return pub; 402 } 403 return NULL; 404 } 405 406 static Key * 407 key_parse_private_rsa1(Buffer *blob, const char *passphrase, char **commentp) 408 { 409 int check1, check2, cipher_type; 410 Buffer decrypted; 411 u_char *cp; 412 CipherContext ciphercontext; 413 const Cipher *cipher; 414 Key *prv = NULL; 415 Buffer copy; 416 417 /* Check that it is at least big enough to contain the ID string. */ 418 if (buffer_len(blob) < sizeof(authfile_id_string)) { 419 debug3("Truncated RSA1 identifier"); 420 return NULL; 421 } 422 423 /* 424 * Make sure it begins with the id string. Consume the id string 425 * from the buffer. 426 */ 427 if (memcmp(buffer_ptr(blob), authfile_id_string, 428 sizeof(authfile_id_string)) != 0) { 429 debug3("Incorrect RSA1 identifier"); 430 return NULL; 431 } 432 buffer_init(©); 433 buffer_append(©, buffer_ptr(blob), buffer_len(blob)); 434 buffer_consume(©, sizeof(authfile_id_string)); 435 436 /* Read cipher type. */ 437 cipher_type = buffer_get_char(©); 438 (void) buffer_get_int(©); /* Reserved data. */ 439 440 /* Read the public key from the buffer. */ 441 (void) buffer_get_int(©); 442 prv = key_new_private(KEY_RSA1); 443 444 buffer_get_bignum(©, prv->rsa->n); 445 buffer_get_bignum(©, prv->rsa->e); 446 if (commentp) 447 *commentp = buffer_get_string(©, NULL); 448 else 449 (void)buffer_get_string_ptr(©, NULL); 450 451 /* Check that it is a supported cipher. */ 452 cipher = cipher_by_number(cipher_type); 453 if (cipher == NULL) { 454 debug("Unsupported RSA1 cipher %d", cipher_type); 455 buffer_free(©); 456 goto fail; 457 } 458 /* Initialize space for decrypted data. */ 459 buffer_init(&decrypted); 460 cp = buffer_append_space(&decrypted, buffer_len(©)); 461 462 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */ 463 cipher_set_key_string(&ciphercontext, cipher, passphrase, 464 CIPHER_DECRYPT); 465 cipher_crypt(&ciphercontext, 0, cp, 466 buffer_ptr(©), buffer_len(©), 0, 0); 467 cipher_cleanup(&ciphercontext); 468 memset(&ciphercontext, 0, sizeof(ciphercontext)); 469 buffer_free(©); 470 471 check1 = buffer_get_char(&decrypted); 472 check2 = buffer_get_char(&decrypted); 473 if (check1 != buffer_get_char(&decrypted) || 474 check2 != buffer_get_char(&decrypted)) { 475 if (strcmp(passphrase, "") != 0) 476 debug("Bad passphrase supplied for RSA1 key"); 477 /* Bad passphrase. */ 478 buffer_free(&decrypted); 479 goto fail; 480 } 481 /* Read the rest of the private key. */ 482 buffer_get_bignum(&decrypted, prv->rsa->d); 483 buffer_get_bignum(&decrypted, prv->rsa->iqmp); /* u */ 484 /* in SSL and SSH v1 p and q are exchanged */ 485 buffer_get_bignum(&decrypted, prv->rsa->q); /* p */ 486 buffer_get_bignum(&decrypted, prv->rsa->p); /* q */ 487 488 /* calculate p-1 and q-1 */ 489 rsa_generate_additional_parameters(prv->rsa); 490 491 buffer_free(&decrypted); 492 493 /* enable blinding */ 494 if (RSA_blinding_on(prv->rsa, NULL) != 1) { 495 error("%s: RSA_blinding_on failed", __func__); 496 goto fail; 497 } 498 return prv; 499 500 fail: 501 if (commentp != NULL) 502 free(*commentp); 503 key_free(prv); 504 return NULL; 505 } 506 507 static Key * 508 key_parse_private_pem(Buffer *blob, int type, const char *passphrase, 509 char **commentp) 510 { 511 EVP_PKEY *pk = NULL; 512 Key *prv = NULL; 513 char *name = "<no key>"; 514 BIO *bio; 515 516 if ((bio = BIO_new_mem_buf(buffer_ptr(blob), 517 buffer_len(blob))) == NULL) { 518 error("%s: BIO_new_mem_buf failed", __func__); 519 return NULL; 520 } 521 522 pk = PEM_read_bio_PrivateKey(bio, NULL, NULL, (char *)passphrase); 523 BIO_free(bio); 524 if (pk == NULL) { 525 debug("%s: PEM_read_PrivateKey failed", __func__); 526 (void)ERR_get_error(); 527 } else if (pk->type == EVP_PKEY_RSA && 528 (type == KEY_UNSPEC||type==KEY_RSA)) { 529 prv = key_new(KEY_UNSPEC); 530 prv->rsa = EVP_PKEY_get1_RSA(pk); 531 prv->type = KEY_RSA; 532 name = "rsa w/o comment"; 533 #ifdef DEBUG_PK 534 RSA_print_fp(stderr, prv->rsa, 8); 535 #endif 536 if (RSA_blinding_on(prv->rsa, NULL) != 1) { 537 error("%s: RSA_blinding_on failed", __func__); 538 key_free(prv); 539 prv = NULL; 540 } 541 } else if (pk->type == EVP_PKEY_DSA && 542 (type == KEY_UNSPEC||type==KEY_DSA)) { 543 prv = key_new(KEY_UNSPEC); 544 prv->dsa = EVP_PKEY_get1_DSA(pk); 545 prv->type = KEY_DSA; 546 name = "dsa w/o comment"; 547 #ifdef DEBUG_PK 548 DSA_print_fp(stderr, prv->dsa, 8); 549 #endif 550 } else if (pk->type == EVP_PKEY_EC && 551 (type == KEY_UNSPEC||type==KEY_ECDSA)) { 552 prv = key_new(KEY_UNSPEC); 553 prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk); 554 prv->type = KEY_ECDSA; 555 if ((prv->ecdsa_nid = key_ecdsa_key_to_nid(prv->ecdsa)) == -1 || 556 key_curve_nid_to_name(prv->ecdsa_nid) == NULL || 557 key_ec_validate_public(EC_KEY_get0_group(prv->ecdsa), 558 EC_KEY_get0_public_key(prv->ecdsa)) != 0 || 559 key_ec_validate_private(prv->ecdsa) != 0) { 560 error("%s: bad ECDSA key", __func__); 561 key_free(prv); 562 prv = NULL; 563 } 564 name = "ecdsa w/o comment"; 565 #ifdef DEBUG_PK 566 if (prv != NULL && prv->ecdsa != NULL) 567 key_dump_ec_key(prv->ecdsa); 568 #endif 569 } else { 570 error("%s: PEM_read_PrivateKey: mismatch or " 571 "unknown EVP_PKEY save_type %d", __func__, pk->save_type); 572 } 573 if (pk != NULL) 574 EVP_PKEY_free(pk); 575 if (prv != NULL && commentp) 576 *commentp = xstrdup(name); 577 debug("read PEM private key done: type %s", 578 prv ? key_type(prv) : "<unknown>"); 579 return prv; 580 } 581 582 Key * 583 key_load_private_pem(int fd, int type, const char *passphrase, 584 char **commentp) 585 { 586 Buffer buffer; 587 Key *prv; 588 589 buffer_init(&buffer); 590 if (!key_load_file(fd, NULL, &buffer)) { 591 buffer_free(&buffer); 592 return NULL; 593 } 594 prv = key_parse_private_pem(&buffer, type, passphrase, commentp); 595 buffer_free(&buffer); 596 return prv; 597 } 598 599 int 600 key_perm_ok(int fd, const char *filename) 601 { 602 struct stat st; 603 604 if (fstat(fd, &st) < 0) 605 return 0; 606 /* 607 * if a key owned by the user is accessed, then we check the 608 * permissions of the file. if the key owned by a different user, 609 * then we don't care. 610 */ 611 if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) { 612 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); 613 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @"); 614 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); 615 error("Permissions 0%3.3o for '%s' are too open.", 616 (u_int)st.st_mode & 0777, filename); 617 error("It is recommended that your private key files are NOT accessible by others."); 618 error("This private key will be ignored."); 619 return 0; 620 } 621 return 1; 622 } 623 624 static Key * 625 key_parse_private_type(Buffer *blob, int type, const char *passphrase, 626 char **commentp) 627 { 628 switch (type) { 629 case KEY_RSA1: 630 return key_parse_private_rsa1(blob, passphrase, commentp); 631 case KEY_DSA: 632 case KEY_ECDSA: 633 case KEY_RSA: 634 case KEY_UNSPEC: 635 return key_parse_private_pem(blob, type, passphrase, commentp); 636 default: 637 error("%s: cannot parse key type %d", __func__, type); 638 break; 639 } 640 return NULL; 641 } 642 643 Key * 644 key_load_private_type(int type, const char *filename, const char *passphrase, 645 char **commentp, int *perm_ok) 646 { 647 int fd; 648 Key *ret; 649 Buffer buffer; 650 651 fd = open(filename, O_RDONLY); 652 if (fd < 0) { 653 debug("could not open key file '%s': %s", filename, 654 strerror(errno)); 655 if (perm_ok != NULL) 656 *perm_ok = 0; 657 return NULL; 658 } 659 if (!key_perm_ok(fd, filename)) { 660 if (perm_ok != NULL) 661 *perm_ok = 0; 662 error("bad permissions: ignore key: %s", filename); 663 close(fd); 664 return NULL; 665 } 666 if (perm_ok != NULL) 667 *perm_ok = 1; 668 669 buffer_init(&buffer); 670 if (!key_load_file(fd, filename, &buffer)) { 671 buffer_free(&buffer); 672 close(fd); 673 return NULL; 674 } 675 close(fd); 676 ret = key_parse_private_type(&buffer, type, passphrase, commentp); 677 buffer_free(&buffer); 678 return ret; 679 } 680 681 Key * 682 key_parse_private(Buffer *buffer, const char *filename, 683 const char *passphrase, char **commentp) 684 { 685 Key *pub, *prv; 686 687 /* it's a SSH v1 key if the public key part is readable */ 688 pub = key_parse_public_rsa1(buffer, commentp); 689 if (pub == NULL) { 690 prv = key_parse_private_type(buffer, KEY_UNSPEC, 691 passphrase, NULL); 692 /* use the filename as a comment for PEM */ 693 if (commentp && prv) 694 *commentp = xstrdup(filename); 695 } else { 696 key_free(pub); 697 /* key_parse_public_rsa1() has already loaded the comment */ 698 prv = key_parse_private_type(buffer, KEY_RSA1, passphrase, 699 NULL); 700 } 701 return prv; 702 } 703 704 Key * 705 key_load_private(const char *filename, const char *passphrase, 706 char **commentp) 707 { 708 Key *prv; 709 Buffer buffer; 710 int fd; 711 712 fd = open(filename, O_RDONLY); 713 if (fd < 0) { 714 debug("could not open key file '%s': %s", filename, 715 strerror(errno)); 716 return NULL; 717 } 718 if (!key_perm_ok(fd, filename)) { 719 error("bad permissions: ignore key: %s", filename); 720 close(fd); 721 return NULL; 722 } 723 724 buffer_init(&buffer); 725 if (!key_load_file(fd, filename, &buffer)) { 726 buffer_free(&buffer); 727 close(fd); 728 return NULL; 729 } 730 close(fd); 731 732 prv = key_parse_private(&buffer, filename, passphrase, commentp); 733 buffer_free(&buffer); 734 return prv; 735 } 736 737 static int 738 key_try_load_public(Key *k, const char *filename, char **commentp) 739 { 740 FILE *f; 741 char line[SSH_MAX_PUBKEY_BYTES]; 742 char *cp; 743 u_long linenum = 0; 744 745 f = fopen(filename, "r"); 746 if (f != NULL) { 747 while (read_keyfile_line(f, filename, line, sizeof(line), 748 &linenum) != -1) { 749 cp = line; 750 switch (*cp) { 751 case '#': 752 case '\n': 753 case '\0': 754 continue; 755 } 756 /* Abort loading if this looks like a private key */ 757 if (strncmp(cp, "-----BEGIN", 10) == 0) 758 break; 759 /* Skip leading whitespace. */ 760 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++) 761 ; 762 if (*cp) { 763 if (key_read(k, &cp) == 1) { 764 cp[strcspn(cp, "\r\n")] = '\0'; 765 if (commentp) { 766 *commentp = xstrdup(*cp ? 767 cp : filename); 768 } 769 fclose(f); 770 return 1; 771 } 772 } 773 } 774 fclose(f); 775 } 776 return 0; 777 } 778 779 /* load public key from ssh v1 private or any pubkey file */ 780 Key * 781 key_load_public(const char *filename, char **commentp) 782 { 783 Key *pub; 784 char file[MAXPATHLEN]; 785 786 /* try rsa1 private key */ 787 pub = key_load_public_type(KEY_RSA1, filename, commentp); 788 if (pub != NULL) 789 return pub; 790 791 /* try rsa1 public key */ 792 pub = key_new(KEY_RSA1); 793 if (key_try_load_public(pub, filename, commentp) == 1) 794 return pub; 795 key_free(pub); 796 797 /* try ssh2 public key */ 798 pub = key_new(KEY_UNSPEC); 799 if (key_try_load_public(pub, filename, commentp) == 1) 800 return pub; 801 if ((strlcpy(file, filename, sizeof file) < sizeof(file)) && 802 (strlcat(file, ".pub", sizeof file) < sizeof(file)) && 803 (key_try_load_public(pub, file, commentp) == 1)) 804 return pub; 805 key_free(pub); 806 return NULL; 807 } 808 809 /* Load the certificate associated with the named private key */ 810 Key * 811 key_load_cert(const char *filename) 812 { 813 Key *pub; 814 char *file; 815 816 pub = key_new(KEY_UNSPEC); 817 xasprintf(&file, "%s-cert.pub", filename); 818 if (key_try_load_public(pub, file, NULL) == 1) { 819 free(file); 820 return pub; 821 } 822 free(file); 823 key_free(pub); 824 return NULL; 825 } 826 827 /* Load private key and certificate */ 828 Key * 829 key_load_private_cert(int type, const char *filename, const char *passphrase, 830 int *perm_ok) 831 { 832 Key *key, *pub; 833 834 switch (type) { 835 case KEY_RSA: 836 case KEY_DSA: 837 case KEY_ECDSA: 838 break; 839 default: 840 error("%s: unsupported key type", __func__); 841 return NULL; 842 } 843 844 if ((key = key_load_private_type(type, filename, 845 passphrase, NULL, perm_ok)) == NULL) 846 return NULL; 847 848 if ((pub = key_load_cert(filename)) == NULL) { 849 key_free(key); 850 return NULL; 851 } 852 853 /* Make sure the private key matches the certificate */ 854 if (key_equal_public(key, pub) == 0) { 855 error("%s: certificate does not match private key %s", 856 __func__, filename); 857 } else if (key_to_certified(key, key_cert_is_legacy(pub)) != 0) { 858 error("%s: key_to_certified failed", __func__); 859 } else { 860 key_cert_copy(pub, key); 861 key_free(pub); 862 return key; 863 } 864 865 key_free(key); 866 key_free(pub); 867 return NULL; 868 } 869 870 /* 871 * Returns 1 if the specified "key" is listed in the file "filename", 872 * 0 if the key is not listed or -1 on error. 873 * If strict_type is set then the key type must match exactly, 874 * otherwise a comparison that ignores certficiate data is performed. 875 */ 876 int 877 key_in_file(Key *key, const char *filename, int strict_type) 878 { 879 FILE *f; 880 char line[SSH_MAX_PUBKEY_BYTES]; 881 char *cp; 882 u_long linenum = 0; 883 int ret = 0; 884 Key *pub; 885 int (*key_compare)(const Key *, const Key *) = strict_type ? 886 key_equal : key_equal_public; 887 888 if ((f = fopen(filename, "r")) == NULL) { 889 if (errno == ENOENT) { 890 debug("%s: keyfile \"%s\" missing", __func__, filename); 891 return 0; 892 } else { 893 error("%s: could not open keyfile \"%s\": %s", __func__, 894 filename, strerror(errno)); 895 return -1; 896 } 897 } 898 899 while (read_keyfile_line(f, filename, line, sizeof(line), 900 &linenum) != -1) { 901 cp = line; 902 903 /* Skip leading whitespace. */ 904 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++) 905 ; 906 907 /* Skip comments and empty lines */ 908 switch (*cp) { 909 case '#': 910 case '\n': 911 case '\0': 912 continue; 913 } 914 915 pub = key_new(KEY_UNSPEC); 916 if (key_read(pub, &cp) != 1) { 917 key_free(pub); 918 continue; 919 } 920 if (key_compare(key, pub)) { 921 ret = 1; 922 key_free(pub); 923 break; 924 } 925 key_free(pub); 926 } 927 fclose(f); 928 return ret; 929 } 930 931