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