1 /* $OpenBSD: authfile.c,v 1.99 2013/12/06 13:34:54 markus 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, 2013 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 <util.h> 57 58 #include "xmalloc.h" 59 #include "cipher.h" 60 #include "buffer.h" 61 #include "key.h" 62 #include "ssh.h" 63 #include "log.h" 64 #include "authfile.h" 65 #include "rsa.h" 66 #include "misc.h" 67 #include "atomicio.h" 68 #include "uuencode.h" 69 70 /* openssh private key file format */ 71 #define MARK_BEGIN "-----BEGIN OPENSSH PRIVATE KEY-----\n" 72 #define MARK_END "-----END OPENSSH PRIVATE KEY-----\n" 73 #define KDFNAME "bcrypt" 74 #define AUTH_MAGIC "openssh-key-v1" 75 #define SALT_LEN 16 76 #define DEFAULT_CIPHERNAME "aes256-cbc" 77 #define DEFAULT_ROUNDS 16 78 79 #define MAX_KEY_FILE_SIZE (1024 * 1024) 80 81 /* Version identification string for SSH v1 identity files. */ 82 static const char authfile_id_string[] = 83 "SSH PRIVATE KEY FILE FORMAT 1.1\n"; 84 85 static int 86 key_private_to_blob2(Key *prv, Buffer *blob, const char *passphrase, 87 const char *comment, const char *ciphername, int rounds) 88 { 89 u_char *key, *cp, salt[SALT_LEN]; 90 size_t keylen, ivlen, blocksize, authlen; 91 u_int len, check; 92 int i, n; 93 const Cipher *c; 94 Buffer encoded, b, kdf; 95 CipherContext ctx; 96 const char *kdfname = KDFNAME; 97 98 if (rounds <= 0) 99 rounds = DEFAULT_ROUNDS; 100 if (passphrase == NULL || !strlen(passphrase)) { 101 ciphername = "none"; 102 kdfname = "none"; 103 } else if (ciphername == NULL) 104 ciphername = DEFAULT_CIPHERNAME; 105 else if (cipher_number(ciphername) != SSH_CIPHER_SSH2) 106 fatal("invalid cipher"); 107 108 if ((c = cipher_by_name(ciphername)) == NULL) 109 fatal("unknown cipher name"); 110 buffer_init(&kdf); 111 blocksize = cipher_blocksize(c); 112 keylen = cipher_keylen(c); 113 ivlen = cipher_ivlen(c); 114 authlen = cipher_authlen(c); 115 key = xcalloc(1, keylen + ivlen); 116 if (strcmp(kdfname, "none") != 0) { 117 arc4random_buf(salt, SALT_LEN); 118 if (bcrypt_pbkdf(passphrase, strlen(passphrase), 119 salt, SALT_LEN, key, keylen + ivlen, rounds) < 0) 120 fatal("bcrypt_pbkdf failed"); 121 buffer_put_string(&kdf, salt, SALT_LEN); 122 buffer_put_int(&kdf, rounds); 123 } 124 cipher_init(&ctx, c, key, keylen, key + keylen , ivlen, 1); 125 memset(key, 0, keylen + ivlen); 126 free(key); 127 128 buffer_init(&encoded); 129 buffer_append(&encoded, AUTH_MAGIC, sizeof(AUTH_MAGIC)); 130 buffer_put_cstring(&encoded, ciphername); 131 buffer_put_cstring(&encoded, kdfname); 132 buffer_put_string(&encoded, buffer_ptr(&kdf), buffer_len(&kdf)); 133 buffer_put_int(&encoded, 1); /* number of keys */ 134 key_to_blob(prv, &cp, &len); /* public key */ 135 buffer_put_string(&encoded, cp, len); 136 137 memset(cp, 0, len); 138 free(cp); 139 140 buffer_free(&kdf); 141 142 /* set up the buffer that will be encrypted */ 143 buffer_init(&b); 144 145 /* Random check bytes */ 146 check = arc4random(); 147 buffer_put_int(&b, check); 148 buffer_put_int(&b, check); 149 150 /* append private key and comment*/ 151 key_private_serialize(prv, &b); 152 buffer_put_cstring(&b, comment); 153 154 /* padding */ 155 i = 0; 156 while (buffer_len(&b) % blocksize) 157 buffer_put_char(&b, ++i & 0xff); 158 159 /* length */ 160 buffer_put_int(&encoded, buffer_len(&b)); 161 162 /* encrypt */ 163 cp = buffer_append_space(&encoded, buffer_len(&b) + authlen); 164 if (cipher_crypt(&ctx, 0, cp, buffer_ptr(&b), buffer_len(&b), 0, 165 authlen) != 0) 166 fatal("%s: cipher_crypt failed", __func__); 167 buffer_free(&b); 168 cipher_cleanup(&ctx); 169 170 /* uuencode */ 171 len = 2 * buffer_len(&encoded); 172 cp = xmalloc(len); 173 n = uuencode(buffer_ptr(&encoded), buffer_len(&encoded), 174 (char *)cp, len); 175 if (n < 0) 176 fatal("%s: uuencode", __func__); 177 178 buffer_clear(blob); 179 buffer_append(blob, MARK_BEGIN, sizeof(MARK_BEGIN) - 1); 180 for (i = 0; i < n; i++) { 181 buffer_put_char(blob, cp[i]); 182 if (i % 70 == 69) 183 buffer_put_char(blob, '\n'); 184 } 185 if (i % 70 != 69) 186 buffer_put_char(blob, '\n'); 187 buffer_append(blob, MARK_END, sizeof(MARK_END) - 1); 188 free(cp); 189 190 return buffer_len(blob); 191 } 192 193 static Key * 194 key_parse_private2(Buffer *blob, int type, const char *passphrase, 195 char **commentp) 196 { 197 u_char *key = NULL, *cp, *salt = NULL, pad, last; 198 char *comment = NULL, *ciphername = NULL, *kdfname = NULL, *kdfp; 199 u_int keylen = 0, ivlen, blocksize, slen, klen, len, rounds, nkeys; 200 u_int check1, check2, m1len, m2len; 201 size_t authlen; 202 const Cipher *c; 203 Buffer b, encoded, copy, kdf; 204 CipherContext ctx; 205 Key *k = NULL; 206 int dlen, ret, i; 207 208 buffer_init(&b); 209 buffer_init(&kdf); 210 buffer_init(&encoded); 211 buffer_init(©); 212 213 /* uudecode */ 214 m1len = sizeof(MARK_BEGIN) - 1; 215 m2len = sizeof(MARK_END) - 1; 216 cp = buffer_ptr(blob); 217 len = buffer_len(blob); 218 if (len < m1len || memcmp(cp, MARK_BEGIN, m1len)) { 219 debug("%s: missing begin marker", __func__); 220 goto out; 221 } 222 cp += m1len; 223 len -= m1len; 224 while (len) { 225 if (*cp != '\n' && *cp != '\r') 226 buffer_put_char(&encoded, *cp); 227 last = *cp; 228 len--; 229 cp++; 230 if (last == '\n') { 231 if (len >= m2len && !memcmp(cp, MARK_END, m2len)) { 232 buffer_put_char(&encoded, '\0'); 233 break; 234 } 235 } 236 } 237 if (!len) { 238 debug("%s: no end marker", __func__); 239 goto out; 240 } 241 len = buffer_len(&encoded); 242 if ((cp = buffer_append_space(©, len)) == NULL) { 243 error("%s: buffer_append_space", __func__); 244 goto out; 245 } 246 if ((dlen = uudecode(buffer_ptr(&encoded), cp, len)) < 0) { 247 error("%s: uudecode failed", __func__); 248 goto out; 249 } 250 if ((u_int)dlen > len) { 251 error("%s: crazy uudecode length %d > %u", __func__, dlen, len); 252 goto out; 253 } 254 buffer_consume_end(©, len - dlen); 255 if (buffer_len(©) < sizeof(AUTH_MAGIC) || 256 memcmp(buffer_ptr(©), AUTH_MAGIC, sizeof(AUTH_MAGIC))) { 257 error("%s: bad magic", __func__); 258 goto out; 259 } 260 buffer_consume(©, sizeof(AUTH_MAGIC)); 261 262 ciphername = buffer_get_cstring_ret(©, NULL); 263 if (ciphername == NULL || 264 (c = cipher_by_name(ciphername)) == NULL) { 265 error("%s: unknown cipher name", __func__); 266 goto out; 267 } 268 if ((passphrase == NULL || !strlen(passphrase)) && 269 strcmp(ciphername, "none") != 0) { 270 /* passphrase required */ 271 goto out; 272 } 273 kdfname = buffer_get_cstring_ret(©, NULL); 274 if (kdfname == NULL || 275 (!strcmp(kdfname, "none") && !strcmp(kdfname, "bcrypt"))) { 276 error("%s: unknown kdf name", __func__); 277 goto out; 278 } 279 if (!strcmp(kdfname, "none") && strcmp(ciphername, "none") != 0) { 280 error("%s: cipher %s requires kdf", __func__, ciphername); 281 goto out; 282 } 283 /* kdf options */ 284 kdfp = buffer_get_string_ptr_ret(©, &klen); 285 if (kdfp == NULL) { 286 error("%s: kdf options not set", __func__); 287 goto out; 288 } 289 if (klen > 0) { 290 if ((cp = buffer_append_space(&kdf, klen)) == NULL) { 291 error("%s: kdf alloc failed", __func__); 292 goto out; 293 } 294 memcpy(cp, kdfp, klen); 295 } 296 /* number of keys */ 297 if (buffer_get_int_ret(&nkeys, ©) < 0) { 298 error("%s: key counter missing", __func__); 299 goto out; 300 } 301 if (nkeys != 1) { 302 error("%s: only one key supported", __func__); 303 goto out; 304 } 305 /* pubkey */ 306 if ((cp = buffer_get_string_ret(©, &len)) == NULL) { 307 error("%s: pubkey not found", __func__); 308 goto out; 309 } 310 free(cp); /* XXX check pubkey against decrypted private key */ 311 312 /* size of encrypted key blob */ 313 len = buffer_get_int(©); 314 blocksize = cipher_blocksize(c); 315 authlen = cipher_authlen(c); 316 if (len < blocksize) { 317 error("%s: encrypted data too small", __func__); 318 goto out; 319 } 320 if (len % blocksize) { 321 error("%s: length not multiple of blocksize", __func__); 322 goto out; 323 } 324 325 /* setup key */ 326 keylen = cipher_keylen(c); 327 ivlen = cipher_ivlen(c); 328 key = xcalloc(1, keylen + ivlen); 329 if (!strcmp(kdfname, "bcrypt")) { 330 if ((salt = buffer_get_string_ret(&kdf, &slen)) == NULL) { 331 error("%s: salt not set", __func__); 332 goto out; 333 } 334 if (buffer_get_int_ret(&rounds, &kdf) < 0) { 335 error("%s: rounds not set", __func__); 336 goto out; 337 } 338 if (bcrypt_pbkdf(passphrase, strlen(passphrase), salt, slen, 339 key, keylen + ivlen, rounds) < 0) { 340 error("%s: bcrypt_pbkdf failed", __func__); 341 goto out; 342 } 343 } 344 345 cp = buffer_append_space(&b, len); 346 cipher_init(&ctx, c, key, keylen, key + keylen, ivlen, 0); 347 ret = cipher_crypt(&ctx, 0, cp, buffer_ptr(©), len, 0, authlen); 348 cipher_cleanup(&ctx); 349 buffer_consume(©, len); 350 351 /* fail silently on decryption errors */ 352 if (ret != 0) { 353 debug("%s: decrypt failed", __func__); 354 goto out; 355 } 356 357 if (buffer_len(©) != 0) { 358 error("%s: key blob has trailing data (len = %u)", __func__, 359 buffer_len(©)); 360 goto out; 361 } 362 363 /* check bytes */ 364 if (buffer_get_int_ret(&check1, &b) < 0 || 365 buffer_get_int_ret(&check2, &b) < 0) { 366 error("check bytes missing"); 367 goto out; 368 } 369 if (check1 != check2) { 370 debug("%s: decrypt failed: 0x%08x != 0x%08x", __func__, 371 check1, check2); 372 goto out; 373 } 374 375 k = key_private_deserialize(&b); 376 377 /* comment */ 378 comment = buffer_get_cstring_ret(&b, NULL); 379 380 i = 0; 381 while (buffer_len(&b)) { 382 if (buffer_get_char_ret(&pad, &b) == -1 || 383 pad != (++i & 0xff)) { 384 error("%s: bad padding", __func__); 385 key_free(k); 386 k = NULL; 387 goto out; 388 } 389 } 390 391 if (k && commentp) { 392 *commentp = comment; 393 comment = NULL; 394 } 395 396 /* XXX decode pubkey and check against private */ 397 out: 398 free(ciphername); 399 free(kdfname); 400 free(salt); 401 free(comment); 402 if (key) 403 memset(key, 0, keylen + ivlen); 404 free(key); 405 buffer_free(&encoded); 406 buffer_free(©); 407 buffer_free(&kdf); 408 buffer_free(&b); 409 return k; 410 } 411 412 /* 413 * Serialises the authentication (private) key to a blob, encrypting it with 414 * passphrase. The identification of the blob (lowest 64 bits of n) will 415 * precede the key to provide identification of the key without needing a 416 * passphrase. 417 */ 418 static int 419 key_private_rsa1_to_blob(Key *key, Buffer *blob, const char *passphrase, 420 const char *comment) 421 { 422 Buffer buffer, encrypted; 423 u_char buf[100], *cp; 424 int i, cipher_num; 425 CipherContext ciphercontext; 426 const Cipher *cipher; 427 u_int32_t rnd; 428 429 /* 430 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting 431 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER. 432 */ 433 cipher_num = (strcmp(passphrase, "") == 0) ? 434 SSH_CIPHER_NONE : SSH_AUTHFILE_CIPHER; 435 if ((cipher = cipher_by_number(cipher_num)) == NULL) 436 fatal("save_private_key_rsa: bad cipher"); 437 438 /* This buffer is used to built the secret part of the private key. */ 439 buffer_init(&buffer); 440 441 /* Put checkbytes for checking passphrase validity. */ 442 rnd = arc4random(); 443 buf[0] = rnd & 0xff; 444 buf[1] = (rnd >> 8) & 0xff; 445 buf[2] = buf[0]; 446 buf[3] = buf[1]; 447 buffer_append(&buffer, buf, 4); 448 449 /* 450 * Store the private key (n and e will not be stored because they 451 * will be stored in plain text, and storing them also in encrypted 452 * format would just give known plaintext). 453 */ 454 buffer_put_bignum(&buffer, key->rsa->d); 455 buffer_put_bignum(&buffer, key->rsa->iqmp); 456 buffer_put_bignum(&buffer, key->rsa->q); /* reverse from SSL p */ 457 buffer_put_bignum(&buffer, key->rsa->p); /* reverse from SSL q */ 458 459 /* Pad the part to be encrypted until its size is a multiple of 8. */ 460 while (buffer_len(&buffer) % 8 != 0) 461 buffer_put_char(&buffer, 0); 462 463 /* This buffer will be used to contain the data in the file. */ 464 buffer_init(&encrypted); 465 466 /* First store keyfile id string. */ 467 for (i = 0; authfile_id_string[i]; i++) 468 buffer_put_char(&encrypted, authfile_id_string[i]); 469 buffer_put_char(&encrypted, 0); 470 471 /* Store cipher type. */ 472 buffer_put_char(&encrypted, cipher_num); 473 buffer_put_int(&encrypted, 0); /* For future extension */ 474 475 /* Store public key. This will be in plain text. */ 476 buffer_put_int(&encrypted, BN_num_bits(key->rsa->n)); 477 buffer_put_bignum(&encrypted, key->rsa->n); 478 buffer_put_bignum(&encrypted, key->rsa->e); 479 buffer_put_cstring(&encrypted, comment); 480 481 /* Allocate space for the private part of the key in the buffer. */ 482 cp = buffer_append_space(&encrypted, buffer_len(&buffer)); 483 484 cipher_set_key_string(&ciphercontext, cipher, passphrase, 485 CIPHER_ENCRYPT); 486 if (cipher_crypt(&ciphercontext, 0, cp, 487 buffer_ptr(&buffer), buffer_len(&buffer), 0, 0) != 0) 488 fatal("%s: cipher_crypt failed", __func__); 489 cipher_cleanup(&ciphercontext); 490 memset(&ciphercontext, 0, sizeof(ciphercontext)); 491 492 /* Destroy temporary data. */ 493 memset(buf, 0, sizeof(buf)); 494 buffer_free(&buffer); 495 496 buffer_append(blob, buffer_ptr(&encrypted), buffer_len(&encrypted)); 497 buffer_free(&encrypted); 498 499 return 1; 500 } 501 502 /* convert SSH v2 key in OpenSSL PEM format */ 503 static int 504 key_private_pem_to_blob(Key *key, Buffer *blob, const char *_passphrase, 505 const char *comment) 506 { 507 int success = 0; 508 int blen, len = strlen(_passphrase); 509 u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL; 510 const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL; 511 const u_char *bptr; 512 BIO *bio; 513 514 if (len > 0 && len <= 4) { 515 error("passphrase too short: have %d bytes, need > 4", len); 516 return 0; 517 } 518 if ((bio = BIO_new(BIO_s_mem())) == NULL) { 519 error("%s: BIO_new failed", __func__); 520 return 0; 521 } 522 switch (key->type) { 523 case KEY_DSA: 524 success = PEM_write_bio_DSAPrivateKey(bio, key->dsa, 525 cipher, passphrase, len, NULL, NULL); 526 break; 527 case KEY_ECDSA: 528 success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa, 529 cipher, passphrase, len, NULL, NULL); 530 break; 531 case KEY_RSA: 532 success = PEM_write_bio_RSAPrivateKey(bio, key->rsa, 533 cipher, passphrase, len, NULL, NULL); 534 break; 535 } 536 if (success) { 537 if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0) 538 success = 0; 539 else 540 buffer_append(blob, bptr, blen); 541 } 542 BIO_free(bio); 543 return success; 544 } 545 546 /* Save a key blob to a file */ 547 static int 548 key_save_private_blob(Buffer *keybuf, const char *filename) 549 { 550 int fd; 551 552 if ((fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600)) < 0) { 553 error("open %s failed: %s.", filename, strerror(errno)); 554 return 0; 555 } 556 if (atomicio(vwrite, fd, buffer_ptr(keybuf), 557 buffer_len(keybuf)) != buffer_len(keybuf)) { 558 error("write to key file %s failed: %s", filename, 559 strerror(errno)); 560 close(fd); 561 unlink(filename); 562 return 0; 563 } 564 close(fd); 565 return 1; 566 } 567 568 /* Serialise "key" to buffer "blob" */ 569 static int 570 key_private_to_blob(Key *key, Buffer *blob, const char *passphrase, 571 const char *comment, int force_new_format, const char *new_format_cipher, 572 int new_format_rounds) 573 { 574 switch (key->type) { 575 case KEY_RSA1: 576 return key_private_rsa1_to_blob(key, blob, passphrase, comment); 577 case KEY_DSA: 578 case KEY_ECDSA: 579 case KEY_RSA: 580 if (force_new_format) { 581 return key_private_to_blob2(key, blob, passphrase, 582 comment, new_format_cipher, new_format_rounds); 583 } 584 return key_private_pem_to_blob(key, blob, passphrase, comment); 585 default: 586 error("%s: cannot save key type %d", __func__, key->type); 587 return 0; 588 } 589 } 590 591 int 592 key_save_private(Key *key, const char *filename, const char *passphrase, 593 const char *comment, int force_new_format, const char *new_format_cipher, 594 int new_format_rounds) 595 { 596 Buffer keyblob; 597 int success = 0; 598 599 buffer_init(&keyblob); 600 if (!key_private_to_blob(key, &keyblob, passphrase, comment, 601 force_new_format, new_format_cipher, new_format_rounds)) 602 goto out; 603 if (!key_save_private_blob(&keyblob, filename)) 604 goto out; 605 success = 1; 606 out: 607 buffer_free(&keyblob); 608 return success; 609 } 610 611 /* 612 * Parse the public, unencrypted portion of a RSA1 key. 613 */ 614 static Key * 615 key_parse_public_rsa1(Buffer *blob, char **commentp) 616 { 617 Key *pub; 618 Buffer copy; 619 620 /* Check that it is at least big enough to contain the ID string. */ 621 if (buffer_len(blob) < sizeof(authfile_id_string)) { 622 debug3("Truncated RSA1 identifier"); 623 return NULL; 624 } 625 626 /* 627 * Make sure it begins with the id string. Consume the id string 628 * from the buffer. 629 */ 630 if (memcmp(buffer_ptr(blob), authfile_id_string, 631 sizeof(authfile_id_string)) != 0) { 632 debug3("Incorrect RSA1 identifier"); 633 return NULL; 634 } 635 buffer_init(©); 636 buffer_append(©, buffer_ptr(blob), buffer_len(blob)); 637 buffer_consume(©, sizeof(authfile_id_string)); 638 639 /* Skip cipher type and reserved data. */ 640 (void) buffer_get_char(©); /* cipher type */ 641 (void) buffer_get_int(©); /* reserved */ 642 643 /* Read the public key from the buffer. */ 644 (void) buffer_get_int(©); 645 pub = key_new(KEY_RSA1); 646 buffer_get_bignum(©, pub->rsa->n); 647 buffer_get_bignum(©, pub->rsa->e); 648 if (commentp) 649 *commentp = buffer_get_string(©, NULL); 650 /* The encrypted private part is not parsed by this function. */ 651 buffer_free(©); 652 653 return pub; 654 } 655 656 /* Load a key from a fd into a buffer */ 657 int 658 key_load_file(int fd, const char *filename, Buffer *blob) 659 { 660 u_char buf[1024]; 661 size_t len; 662 struct stat st; 663 664 if (fstat(fd, &st) < 0) { 665 error("%s: fstat of key file %.200s%sfailed: %.100s", __func__, 666 filename == NULL ? "" : filename, 667 filename == NULL ? "" : " ", 668 strerror(errno)); 669 return 0; 670 } 671 if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 && 672 st.st_size > MAX_KEY_FILE_SIZE) { 673 toobig: 674 error("%s: key file %.200s%stoo large", __func__, 675 filename == NULL ? "" : filename, 676 filename == NULL ? "" : " "); 677 return 0; 678 } 679 buffer_clear(blob); 680 for (;;) { 681 if ((len = atomicio(read, fd, buf, sizeof(buf))) == 0) { 682 if (errno == EPIPE) 683 break; 684 debug("%s: read from key file %.200s%sfailed: %.100s", 685 __func__, filename == NULL ? "" : filename, 686 filename == NULL ? "" : " ", strerror(errno)); 687 buffer_clear(blob); 688 bzero(buf, sizeof(buf)); 689 return 0; 690 } 691 buffer_append(blob, buf, len); 692 if (buffer_len(blob) > MAX_KEY_FILE_SIZE) { 693 buffer_clear(blob); 694 bzero(buf, sizeof(buf)); 695 goto toobig; 696 } 697 } 698 bzero(buf, sizeof(buf)); 699 if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 && 700 st.st_size != buffer_len(blob)) { 701 debug("%s: key file %.200s%schanged size while reading", 702 __func__, filename == NULL ? "" : filename, 703 filename == NULL ? "" : " "); 704 buffer_clear(blob); 705 return 0; 706 } 707 708 return 1; 709 } 710 711 /* 712 * Loads the public part of the ssh v1 key file. Returns NULL if an error was 713 * encountered (the file does not exist or is not readable), and the key 714 * otherwise. 715 */ 716 static Key * 717 key_load_public_rsa1(int fd, const char *filename, char **commentp) 718 { 719 Buffer buffer; 720 Key *pub; 721 722 buffer_init(&buffer); 723 if (!key_load_file(fd, filename, &buffer)) { 724 buffer_free(&buffer); 725 return NULL; 726 } 727 728 pub = key_parse_public_rsa1(&buffer, commentp); 729 if (pub == NULL) 730 debug3("Could not load \"%s\" as a RSA1 public key", filename); 731 buffer_free(&buffer); 732 return pub; 733 } 734 735 /* load public key from private-key file, works only for SSH v1 */ 736 Key * 737 key_load_public_type(int type, const char *filename, char **commentp) 738 { 739 Key *pub; 740 int fd; 741 742 if (type == KEY_RSA1) { 743 fd = open(filename, O_RDONLY); 744 if (fd < 0) 745 return NULL; 746 pub = key_load_public_rsa1(fd, filename, commentp); 747 close(fd); 748 return pub; 749 } 750 return NULL; 751 } 752 753 static Key * 754 key_parse_private_rsa1(Buffer *blob, const char *passphrase, char **commentp) 755 { 756 int check1, check2, cipher_type; 757 Buffer decrypted; 758 u_char *cp; 759 CipherContext ciphercontext; 760 const Cipher *cipher; 761 Key *prv = NULL; 762 Buffer copy; 763 764 /* Check that it is at least big enough to contain the ID string. */ 765 if (buffer_len(blob) < sizeof(authfile_id_string)) { 766 debug3("Truncated RSA1 identifier"); 767 return NULL; 768 } 769 770 /* 771 * Make sure it begins with the id string. Consume the id string 772 * from the buffer. 773 */ 774 if (memcmp(buffer_ptr(blob), authfile_id_string, 775 sizeof(authfile_id_string)) != 0) { 776 debug3("Incorrect RSA1 identifier"); 777 return NULL; 778 } 779 buffer_init(©); 780 buffer_append(©, buffer_ptr(blob), buffer_len(blob)); 781 buffer_consume(©, sizeof(authfile_id_string)); 782 783 /* Read cipher type. */ 784 cipher_type = buffer_get_char(©); 785 (void) buffer_get_int(©); /* Reserved data. */ 786 787 /* Read the public key from the buffer. */ 788 (void) buffer_get_int(©); 789 prv = key_new_private(KEY_RSA1); 790 791 buffer_get_bignum(©, prv->rsa->n); 792 buffer_get_bignum(©, prv->rsa->e); 793 if (commentp) 794 *commentp = buffer_get_string(©, NULL); 795 else 796 (void)buffer_get_string_ptr(©, NULL); 797 798 /* Check that it is a supported cipher. */ 799 cipher = cipher_by_number(cipher_type); 800 if (cipher == NULL) { 801 debug("Unsupported RSA1 cipher %d", cipher_type); 802 buffer_free(©); 803 goto fail; 804 } 805 /* Initialize space for decrypted data. */ 806 buffer_init(&decrypted); 807 cp = buffer_append_space(&decrypted, buffer_len(©)); 808 809 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */ 810 cipher_set_key_string(&ciphercontext, cipher, passphrase, 811 CIPHER_DECRYPT); 812 if (cipher_crypt(&ciphercontext, 0, cp, 813 buffer_ptr(©), buffer_len(©), 0, 0) != 0) 814 fatal("%s: cipher_crypt failed", __func__); 815 cipher_cleanup(&ciphercontext); 816 memset(&ciphercontext, 0, sizeof(ciphercontext)); 817 buffer_free(©); 818 819 check1 = buffer_get_char(&decrypted); 820 check2 = buffer_get_char(&decrypted); 821 if (check1 != buffer_get_char(&decrypted) || 822 check2 != buffer_get_char(&decrypted)) { 823 if (strcmp(passphrase, "") != 0) 824 debug("Bad passphrase supplied for RSA1 key"); 825 /* Bad passphrase. */ 826 buffer_free(&decrypted); 827 goto fail; 828 } 829 /* Read the rest of the private key. */ 830 buffer_get_bignum(&decrypted, prv->rsa->d); 831 buffer_get_bignum(&decrypted, prv->rsa->iqmp); /* u */ 832 /* in SSL and SSH v1 p and q are exchanged */ 833 buffer_get_bignum(&decrypted, prv->rsa->q); /* p */ 834 buffer_get_bignum(&decrypted, prv->rsa->p); /* q */ 835 836 /* calculate p-1 and q-1 */ 837 rsa_generate_additional_parameters(prv->rsa); 838 839 buffer_free(&decrypted); 840 841 /* enable blinding */ 842 if (RSA_blinding_on(prv->rsa, NULL) != 1) { 843 error("%s: RSA_blinding_on failed", __func__); 844 goto fail; 845 } 846 return prv; 847 848 fail: 849 if (commentp != NULL) 850 free(*commentp); 851 key_free(prv); 852 return NULL; 853 } 854 855 static Key * 856 key_parse_private_pem(Buffer *blob, int type, const char *passphrase, 857 char **commentp) 858 { 859 EVP_PKEY *pk = NULL; 860 Key *prv = NULL; 861 char *name = "<no key>"; 862 BIO *bio; 863 864 if ((bio = BIO_new_mem_buf(buffer_ptr(blob), 865 buffer_len(blob))) == NULL) { 866 error("%s: BIO_new_mem_buf failed", __func__); 867 return NULL; 868 } 869 870 pk = PEM_read_bio_PrivateKey(bio, NULL, NULL, (char *)passphrase); 871 BIO_free(bio); 872 if (pk == NULL) { 873 debug("%s: PEM_read_PrivateKey failed", __func__); 874 (void)ERR_get_error(); 875 } else if (pk->type == EVP_PKEY_RSA && 876 (type == KEY_UNSPEC||type==KEY_RSA)) { 877 prv = key_new(KEY_UNSPEC); 878 prv->rsa = EVP_PKEY_get1_RSA(pk); 879 prv->type = KEY_RSA; 880 name = "rsa w/o comment"; 881 #ifdef DEBUG_PK 882 RSA_print_fp(stderr, prv->rsa, 8); 883 #endif 884 if (RSA_blinding_on(prv->rsa, NULL) != 1) { 885 error("%s: RSA_blinding_on failed", __func__); 886 key_free(prv); 887 prv = NULL; 888 } 889 } else if (pk->type == EVP_PKEY_DSA && 890 (type == KEY_UNSPEC||type==KEY_DSA)) { 891 prv = key_new(KEY_UNSPEC); 892 prv->dsa = EVP_PKEY_get1_DSA(pk); 893 prv->type = KEY_DSA; 894 name = "dsa w/o comment"; 895 #ifdef DEBUG_PK 896 DSA_print_fp(stderr, prv->dsa, 8); 897 #endif 898 } else if (pk->type == EVP_PKEY_EC && 899 (type == KEY_UNSPEC||type==KEY_ECDSA)) { 900 prv = key_new(KEY_UNSPEC); 901 prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk); 902 prv->type = KEY_ECDSA; 903 if ((prv->ecdsa_nid = key_ecdsa_key_to_nid(prv->ecdsa)) == -1 || 904 key_curve_nid_to_name(prv->ecdsa_nid) == NULL || 905 key_ec_validate_public(EC_KEY_get0_group(prv->ecdsa), 906 EC_KEY_get0_public_key(prv->ecdsa)) != 0 || 907 key_ec_validate_private(prv->ecdsa) != 0) { 908 error("%s: bad ECDSA key", __func__); 909 key_free(prv); 910 prv = NULL; 911 } 912 name = "ecdsa w/o comment"; 913 #ifdef DEBUG_PK 914 if (prv != NULL && prv->ecdsa != NULL) 915 key_dump_ec_key(prv->ecdsa); 916 #endif 917 } else { 918 error("%s: PEM_read_PrivateKey: mismatch or " 919 "unknown EVP_PKEY save_type %d", __func__, pk->save_type); 920 } 921 if (pk != NULL) 922 EVP_PKEY_free(pk); 923 if (prv != NULL && commentp) 924 *commentp = xstrdup(name); 925 debug("read PEM private key done: type %s", 926 prv ? key_type(prv) : "<unknown>"); 927 return prv; 928 } 929 930 Key * 931 key_load_private_pem(int fd, int type, const char *passphrase, 932 char **commentp) 933 { 934 Buffer buffer; 935 Key *prv; 936 937 buffer_init(&buffer); 938 if (!key_load_file(fd, NULL, &buffer)) { 939 buffer_free(&buffer); 940 return NULL; 941 } 942 prv = key_parse_private_pem(&buffer, type, passphrase, commentp); 943 buffer_free(&buffer); 944 return prv; 945 } 946 947 int 948 key_perm_ok(int fd, const char *filename) 949 { 950 struct stat st; 951 952 if (fstat(fd, &st) < 0) 953 return 0; 954 /* 955 * if a key owned by the user is accessed, then we check the 956 * permissions of the file. if the key owned by a different user, 957 * then we don't care. 958 */ 959 if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) { 960 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); 961 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @"); 962 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); 963 error("Permissions 0%3.3o for '%s' are too open.", 964 (u_int)st.st_mode & 0777, filename); 965 error("It is recommended that your private key files are NOT accessible by others."); 966 error("This private key will be ignored."); 967 return 0; 968 } 969 return 1; 970 } 971 972 static Key * 973 key_parse_private_type(Buffer *blob, int type, const char *passphrase, 974 char **commentp) 975 { 976 Key *k; 977 978 switch (type) { 979 case KEY_RSA1: 980 return key_parse_private_rsa1(blob, passphrase, commentp); 981 case KEY_DSA: 982 case KEY_ECDSA: 983 case KEY_RSA: 984 case KEY_UNSPEC: 985 if ((k = key_parse_private2(blob, type, passphrase, commentp))) 986 return k; 987 return key_parse_private_pem(blob, type, passphrase, commentp); 988 default: 989 error("%s: cannot parse key type %d", __func__, type); 990 break; 991 } 992 return NULL; 993 } 994 995 Key * 996 key_load_private_type(int type, const char *filename, const char *passphrase, 997 char **commentp, int *perm_ok) 998 { 999 int fd; 1000 Key *ret; 1001 Buffer buffer; 1002 1003 fd = open(filename, O_RDONLY); 1004 if (fd < 0) { 1005 debug("could not open key file '%s': %s", filename, 1006 strerror(errno)); 1007 if (perm_ok != NULL) 1008 *perm_ok = 0; 1009 return NULL; 1010 } 1011 if (!key_perm_ok(fd, filename)) { 1012 if (perm_ok != NULL) 1013 *perm_ok = 0; 1014 error("bad permissions: ignore key: %s", filename); 1015 close(fd); 1016 return NULL; 1017 } 1018 if (perm_ok != NULL) 1019 *perm_ok = 1; 1020 1021 buffer_init(&buffer); 1022 if (!key_load_file(fd, filename, &buffer)) { 1023 buffer_free(&buffer); 1024 close(fd); 1025 return NULL; 1026 } 1027 close(fd); 1028 ret = key_parse_private_type(&buffer, type, passphrase, commentp); 1029 buffer_free(&buffer); 1030 return ret; 1031 } 1032 1033 Key * 1034 key_parse_private(Buffer *buffer, const char *filename, 1035 const char *passphrase, char **commentp) 1036 { 1037 Key *pub, *prv; 1038 1039 /* it's a SSH v1 key if the public key part is readable */ 1040 pub = key_parse_public_rsa1(buffer, commentp); 1041 if (pub == NULL) { 1042 prv = key_parse_private_type(buffer, KEY_UNSPEC, 1043 passphrase, NULL); 1044 /* use the filename as a comment for PEM */ 1045 if (commentp && prv) 1046 *commentp = xstrdup(filename); 1047 } else { 1048 key_free(pub); 1049 /* key_parse_public_rsa1() has already loaded the comment */ 1050 prv = key_parse_private_type(buffer, KEY_RSA1, passphrase, 1051 NULL); 1052 } 1053 return prv; 1054 } 1055 1056 Key * 1057 key_load_private(const char *filename, const char *passphrase, 1058 char **commentp) 1059 { 1060 Key *prv; 1061 Buffer buffer; 1062 int fd; 1063 1064 fd = open(filename, O_RDONLY); 1065 if (fd < 0) { 1066 debug("could not open key file '%s': %s", filename, 1067 strerror(errno)); 1068 return NULL; 1069 } 1070 if (!key_perm_ok(fd, filename)) { 1071 error("bad permissions: ignore key: %s", filename); 1072 close(fd); 1073 return NULL; 1074 } 1075 1076 buffer_init(&buffer); 1077 if (!key_load_file(fd, filename, &buffer)) { 1078 buffer_free(&buffer); 1079 close(fd); 1080 return NULL; 1081 } 1082 close(fd); 1083 1084 prv = key_parse_private(&buffer, filename, passphrase, commentp); 1085 buffer_free(&buffer); 1086 return prv; 1087 } 1088 1089 static int 1090 key_try_load_public(Key *k, const char *filename, char **commentp) 1091 { 1092 FILE *f; 1093 char line[SSH_MAX_PUBKEY_BYTES]; 1094 char *cp; 1095 u_long linenum = 0; 1096 1097 f = fopen(filename, "r"); 1098 if (f != NULL) { 1099 while (read_keyfile_line(f, filename, line, sizeof(line), 1100 &linenum) != -1) { 1101 cp = line; 1102 switch (*cp) { 1103 case '#': 1104 case '\n': 1105 case '\0': 1106 continue; 1107 } 1108 /* Abort loading if this looks like a private key */ 1109 if (strncmp(cp, "-----BEGIN", 10) == 0) 1110 break; 1111 /* Skip leading whitespace. */ 1112 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++) 1113 ; 1114 if (*cp) { 1115 if (key_read(k, &cp) == 1) { 1116 cp[strcspn(cp, "\r\n")] = '\0'; 1117 if (commentp) { 1118 *commentp = xstrdup(*cp ? 1119 cp : filename); 1120 } 1121 fclose(f); 1122 return 1; 1123 } 1124 } 1125 } 1126 fclose(f); 1127 } 1128 return 0; 1129 } 1130 1131 /* load public key from ssh v1 private or any pubkey file */ 1132 Key * 1133 key_load_public(const char *filename, char **commentp) 1134 { 1135 Key *pub; 1136 char file[MAXPATHLEN]; 1137 1138 /* try rsa1 private key */ 1139 pub = key_load_public_type(KEY_RSA1, filename, commentp); 1140 if (pub != NULL) 1141 return pub; 1142 1143 /* try rsa1 public key */ 1144 pub = key_new(KEY_RSA1); 1145 if (key_try_load_public(pub, filename, commentp) == 1) 1146 return pub; 1147 key_free(pub); 1148 1149 /* try ssh2 public key */ 1150 pub = key_new(KEY_UNSPEC); 1151 if (key_try_load_public(pub, filename, commentp) == 1) 1152 return pub; 1153 if ((strlcpy(file, filename, sizeof file) < sizeof(file)) && 1154 (strlcat(file, ".pub", sizeof file) < sizeof(file)) && 1155 (key_try_load_public(pub, file, commentp) == 1)) 1156 return pub; 1157 key_free(pub); 1158 return NULL; 1159 } 1160 1161 /* Load the certificate associated with the named private key */ 1162 Key * 1163 key_load_cert(const char *filename) 1164 { 1165 Key *pub; 1166 char *file; 1167 1168 pub = key_new(KEY_UNSPEC); 1169 xasprintf(&file, "%s-cert.pub", filename); 1170 if (key_try_load_public(pub, file, NULL) == 1) { 1171 free(file); 1172 return pub; 1173 } 1174 free(file); 1175 key_free(pub); 1176 return NULL; 1177 } 1178 1179 /* Load private key and certificate */ 1180 Key * 1181 key_load_private_cert(int type, const char *filename, const char *passphrase, 1182 int *perm_ok) 1183 { 1184 Key *key, *pub; 1185 1186 switch (type) { 1187 case KEY_RSA: 1188 case KEY_DSA: 1189 case KEY_ECDSA: 1190 break; 1191 default: 1192 error("%s: unsupported key type", __func__); 1193 return NULL; 1194 } 1195 1196 if ((key = key_load_private_type(type, filename, 1197 passphrase, NULL, perm_ok)) == NULL) 1198 return NULL; 1199 1200 if ((pub = key_load_cert(filename)) == NULL) { 1201 key_free(key); 1202 return NULL; 1203 } 1204 1205 /* Make sure the private key matches the certificate */ 1206 if (key_equal_public(key, pub) == 0) { 1207 error("%s: certificate does not match private key %s", 1208 __func__, filename); 1209 } else if (key_to_certified(key, key_cert_is_legacy(pub)) != 0) { 1210 error("%s: key_to_certified failed", __func__); 1211 } else { 1212 key_cert_copy(pub, key); 1213 key_free(pub); 1214 return key; 1215 } 1216 1217 key_free(key); 1218 key_free(pub); 1219 return NULL; 1220 } 1221 1222 /* 1223 * Returns 1 if the specified "key" is listed in the file "filename", 1224 * 0 if the key is not listed or -1 on error. 1225 * If strict_type is set then the key type must match exactly, 1226 * otherwise a comparison that ignores certficiate data is performed. 1227 */ 1228 int 1229 key_in_file(Key *key, const char *filename, int strict_type) 1230 { 1231 FILE *f; 1232 char line[SSH_MAX_PUBKEY_BYTES]; 1233 char *cp; 1234 u_long linenum = 0; 1235 int ret = 0; 1236 Key *pub; 1237 int (*key_compare)(const Key *, const Key *) = strict_type ? 1238 key_equal : key_equal_public; 1239 1240 if ((f = fopen(filename, "r")) == NULL) { 1241 if (errno == ENOENT) { 1242 debug("%s: keyfile \"%s\" missing", __func__, filename); 1243 return 0; 1244 } else { 1245 error("%s: could not open keyfile \"%s\": %s", __func__, 1246 filename, strerror(errno)); 1247 return -1; 1248 } 1249 } 1250 1251 while (read_keyfile_line(f, filename, line, sizeof(line), 1252 &linenum) != -1) { 1253 cp = line; 1254 1255 /* Skip leading whitespace. */ 1256 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++) 1257 ; 1258 1259 /* Skip comments and empty lines */ 1260 switch (*cp) { 1261 case '#': 1262 case '\n': 1263 case '\0': 1264 continue; 1265 } 1266 1267 pub = key_new(KEY_UNSPEC); 1268 if (key_read(pub, &cp) != 1) { 1269 key_free(pub); 1270 continue; 1271 } 1272 if (key_compare(key, pub)) { 1273 ret = 1; 1274 key_free(pub); 1275 break; 1276 } 1277 key_free(pub); 1278 } 1279 fclose(f); 1280 return ret; 1281 } 1282