1 /* $OpenBSD: authfile.c,v 1.76 2006/08/03 03:34:41 deraadt 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 /* Version identification string for SSH v1 identity files. */ 68 static const char authfile_id_string[] = 69 "SSH PRIVATE KEY FILE FORMAT 1.1\n"; 70 71 /* 72 * Saves the authentication (private) key in a file, encrypting it with 73 * passphrase. The identification of the file (lowest 64 bits of n) will 74 * precede the key to provide identification of the key without needing a 75 * passphrase. 76 */ 77 78 static int 79 key_save_private_rsa1(Key *key, const char *filename, const char *passphrase, 80 const char *comment) 81 { 82 Buffer buffer, encrypted; 83 u_char buf[100], *cp; 84 int fd, i, cipher_num; 85 CipherContext ciphercontext; 86 Cipher *cipher; 87 u_int32_t rnd; 88 89 /* 90 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting 91 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER. 92 */ 93 cipher_num = (strcmp(passphrase, "") == 0) ? 94 SSH_CIPHER_NONE : SSH_AUTHFILE_CIPHER; 95 if ((cipher = cipher_by_number(cipher_num)) == NULL) 96 fatal("save_private_key_rsa: bad cipher"); 97 98 /* This buffer is used to built the secret part of the private key. */ 99 buffer_init(&buffer); 100 101 /* Put checkbytes for checking passphrase validity. */ 102 rnd = arc4random(); 103 buf[0] = rnd & 0xff; 104 buf[1] = (rnd >> 8) & 0xff; 105 buf[2] = buf[0]; 106 buf[3] = buf[1]; 107 buffer_append(&buffer, buf, 4); 108 109 /* 110 * Store the private key (n and e will not be stored because they 111 * will be stored in plain text, and storing them also in encrypted 112 * format would just give known plaintext). 113 */ 114 buffer_put_bignum(&buffer, key->rsa->d); 115 buffer_put_bignum(&buffer, key->rsa->iqmp); 116 buffer_put_bignum(&buffer, key->rsa->q); /* reverse from SSL p */ 117 buffer_put_bignum(&buffer, key->rsa->p); /* reverse from SSL q */ 118 119 /* Pad the part to be encrypted until its size is a multiple of 8. */ 120 while (buffer_len(&buffer) % 8 != 0) 121 buffer_put_char(&buffer, 0); 122 123 /* This buffer will be used to contain the data in the file. */ 124 buffer_init(&encrypted); 125 126 /* First store keyfile id string. */ 127 for (i = 0; authfile_id_string[i]; i++) 128 buffer_put_char(&encrypted, authfile_id_string[i]); 129 buffer_put_char(&encrypted, 0); 130 131 /* Store cipher type. */ 132 buffer_put_char(&encrypted, cipher_num); 133 buffer_put_int(&encrypted, 0); /* For future extension */ 134 135 /* Store public key. This will be in plain text. */ 136 buffer_put_int(&encrypted, BN_num_bits(key->rsa->n)); 137 buffer_put_bignum(&encrypted, key->rsa->n); 138 buffer_put_bignum(&encrypted, key->rsa->e); 139 buffer_put_cstring(&encrypted, comment); 140 141 /* Allocate space for the private part of the key in the buffer. */ 142 cp = buffer_append_space(&encrypted, buffer_len(&buffer)); 143 144 cipher_set_key_string(&ciphercontext, cipher, passphrase, 145 CIPHER_ENCRYPT); 146 cipher_crypt(&ciphercontext, cp, 147 buffer_ptr(&buffer), buffer_len(&buffer)); 148 cipher_cleanup(&ciphercontext); 149 memset(&ciphercontext, 0, sizeof(ciphercontext)); 150 151 /* Destroy temporary data. */ 152 memset(buf, 0, sizeof(buf)); 153 buffer_free(&buffer); 154 155 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600); 156 if (fd < 0) { 157 error("open %s failed: %s.", filename, strerror(errno)); 158 buffer_free(&encrypted); 159 return 0; 160 } 161 if (atomicio(vwrite, fd, buffer_ptr(&encrypted), 162 buffer_len(&encrypted)) != buffer_len(&encrypted)) { 163 error("write to key file %s failed: %s", filename, 164 strerror(errno)); 165 buffer_free(&encrypted); 166 close(fd); 167 unlink(filename); 168 return 0; 169 } 170 close(fd); 171 buffer_free(&encrypted); 172 return 1; 173 } 174 175 /* save SSH v2 key in OpenSSL PEM format */ 176 static int 177 key_save_private_pem(Key *key, const char *filename, const char *_passphrase, 178 const char *comment) 179 { 180 FILE *fp; 181 int fd; 182 int success = 0; 183 int len = strlen(_passphrase); 184 u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL; 185 const EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL; 186 187 if (len > 0 && len <= 4) { 188 error("passphrase too short: have %d bytes, need > 4", len); 189 return 0; 190 } 191 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600); 192 if (fd < 0) { 193 error("open %s failed: %s.", filename, strerror(errno)); 194 return 0; 195 } 196 fp = fdopen(fd, "w"); 197 if (fp == NULL) { 198 error("fdopen %s failed: %s.", filename, strerror(errno)); 199 close(fd); 200 return 0; 201 } 202 switch (key->type) { 203 case KEY_DSA: 204 success = PEM_write_DSAPrivateKey(fp, key->dsa, 205 cipher, passphrase, len, NULL, NULL); 206 break; 207 case KEY_RSA: 208 success = PEM_write_RSAPrivateKey(fp, key->rsa, 209 cipher, passphrase, len, NULL, NULL); 210 break; 211 } 212 fclose(fp); 213 return success; 214 } 215 216 int 217 key_save_private(Key *key, const char *filename, const char *passphrase, 218 const char *comment) 219 { 220 switch (key->type) { 221 case KEY_RSA1: 222 return key_save_private_rsa1(key, filename, passphrase, 223 comment); 224 case KEY_DSA: 225 case KEY_RSA: 226 return key_save_private_pem(key, filename, passphrase, 227 comment); 228 default: 229 break; 230 } 231 error("key_save_private: cannot save key type %d", key->type); 232 return 0; 233 } 234 235 /* 236 * Loads the public part of the ssh v1 key file. Returns NULL if an error was 237 * encountered (the file does not exist or is not readable), and the key 238 * otherwise. 239 */ 240 241 static Key * 242 key_load_public_rsa1(int fd, const char *filename, char **commentp) 243 { 244 Buffer buffer; 245 Key *pub; 246 struct stat st; 247 char *cp; 248 u_int i; 249 size_t len; 250 251 if (fstat(fd, &st) < 0) { 252 error("fstat for key file %.200s failed: %.100s", 253 filename, strerror(errno)); 254 return NULL; 255 } 256 if (st.st_size > 1*1024*1024) { 257 error("key file %.200s too large", filename); 258 return NULL; 259 } 260 len = (size_t)st.st_size; /* truncated */ 261 262 buffer_init(&buffer); 263 cp = buffer_append_space(&buffer, len); 264 265 if (atomicio(read, fd, cp, len) != len) { 266 debug("Read from key file %.200s failed: %.100s", filename, 267 strerror(errno)); 268 buffer_free(&buffer); 269 return NULL; 270 } 271 272 /* Check that it is at least big enough to contain the ID string. */ 273 if (len < sizeof(authfile_id_string)) { 274 debug3("Not a RSA1 key file %.200s.", filename); 275 buffer_free(&buffer); 276 return NULL; 277 } 278 /* 279 * Make sure it begins with the id string. Consume the id string 280 * from the buffer. 281 */ 282 for (i = 0; i < sizeof(authfile_id_string); i++) 283 if (buffer_get_char(&buffer) != authfile_id_string[i]) { 284 debug3("Not a RSA1 key file %.200s.", filename); 285 buffer_free(&buffer); 286 return NULL; 287 } 288 /* Skip cipher type and reserved data. */ 289 (void) buffer_get_char(&buffer); /* cipher type */ 290 (void) buffer_get_int(&buffer); /* reserved */ 291 292 /* Read the public key from the buffer. */ 293 (void) buffer_get_int(&buffer); 294 pub = key_new(KEY_RSA1); 295 buffer_get_bignum(&buffer, pub->rsa->n); 296 buffer_get_bignum(&buffer, pub->rsa->e); 297 if (commentp) 298 *commentp = buffer_get_string(&buffer, NULL); 299 /* The encrypted private part is not parsed by this function. */ 300 301 buffer_free(&buffer); 302 return pub; 303 } 304 305 /* load public key from private-key file, works only for SSH v1 */ 306 Key * 307 key_load_public_type(int type, const char *filename, char **commentp) 308 { 309 Key *pub; 310 int fd; 311 312 if (type == KEY_RSA1) { 313 fd = open(filename, O_RDONLY); 314 if (fd < 0) 315 return NULL; 316 pub = key_load_public_rsa1(fd, filename, commentp); 317 close(fd); 318 return pub; 319 } 320 return NULL; 321 } 322 323 /* 324 * Loads the private key from the file. Returns 0 if an error is encountered 325 * (file does not exist or is not readable, or passphrase is bad). This 326 * initializes the private key. 327 * Assumes we are called under uid of the owner of the file. 328 */ 329 330 static Key * 331 key_load_private_rsa1(int fd, const char *filename, const char *passphrase, 332 char **commentp) 333 { 334 u_int i; 335 int check1, check2, cipher_type; 336 size_t len; 337 Buffer buffer, decrypted; 338 u_char *cp; 339 CipherContext ciphercontext; 340 Cipher *cipher; 341 Key *prv = NULL; 342 struct stat st; 343 344 if (fstat(fd, &st) < 0) { 345 error("fstat for key file %.200s failed: %.100s", 346 filename, strerror(errno)); 347 close(fd); 348 return NULL; 349 } 350 if (st.st_size > 1*1024*1024) { 351 error("key file %.200s too large", filename); 352 close(fd); 353 return (NULL); 354 } 355 len = (size_t)st.st_size; /* truncated */ 356 357 buffer_init(&buffer); 358 cp = buffer_append_space(&buffer, len); 359 360 if (atomicio(read, fd, cp, len) != len) { 361 debug("Read from key file %.200s failed: %.100s", filename, 362 strerror(errno)); 363 buffer_free(&buffer); 364 close(fd); 365 return NULL; 366 } 367 368 /* Check that it is at least big enough to contain the ID string. */ 369 if (len < sizeof(authfile_id_string)) { 370 debug3("Not a RSA1 key file %.200s.", filename); 371 buffer_free(&buffer); 372 close(fd); 373 return NULL; 374 } 375 /* 376 * Make sure it begins with the id string. Consume the id string 377 * from the buffer. 378 */ 379 for (i = 0; i < sizeof(authfile_id_string); i++) 380 if (buffer_get_char(&buffer) != authfile_id_string[i]) { 381 debug3("Not a RSA1 key file %.200s.", filename); 382 buffer_free(&buffer); 383 close(fd); 384 return NULL; 385 } 386 387 /* Read cipher type. */ 388 cipher_type = buffer_get_char(&buffer); 389 (void) buffer_get_int(&buffer); /* Reserved data. */ 390 391 /* Read the public key from the buffer. */ 392 (void) buffer_get_int(&buffer); 393 prv = key_new_private(KEY_RSA1); 394 395 buffer_get_bignum(&buffer, prv->rsa->n); 396 buffer_get_bignum(&buffer, prv->rsa->e); 397 if (commentp) 398 *commentp = buffer_get_string(&buffer, NULL); 399 else 400 xfree(buffer_get_string(&buffer, NULL)); 401 402 /* Check that it is a supported cipher. */ 403 cipher = cipher_by_number(cipher_type); 404 if (cipher == NULL) { 405 debug("Unsupported cipher %d used in key file %.200s.", 406 cipher_type, filename); 407 buffer_free(&buffer); 408 goto fail; 409 } 410 /* Initialize space for decrypted data. */ 411 buffer_init(&decrypted); 412 cp = buffer_append_space(&decrypted, buffer_len(&buffer)); 413 414 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */ 415 cipher_set_key_string(&ciphercontext, cipher, passphrase, 416 CIPHER_DECRYPT); 417 cipher_crypt(&ciphercontext, cp, 418 buffer_ptr(&buffer), buffer_len(&buffer)); 419 cipher_cleanup(&ciphercontext); 420 memset(&ciphercontext, 0, sizeof(ciphercontext)); 421 buffer_free(&buffer); 422 423 check1 = buffer_get_char(&decrypted); 424 check2 = buffer_get_char(&decrypted); 425 if (check1 != buffer_get_char(&decrypted) || 426 check2 != buffer_get_char(&decrypted)) { 427 if (strcmp(passphrase, "") != 0) 428 debug("Bad passphrase supplied for key file %.200s.", 429 filename); 430 /* Bad passphrase. */ 431 buffer_free(&decrypted); 432 goto fail; 433 } 434 /* Read the rest of the private key. */ 435 buffer_get_bignum(&decrypted, prv->rsa->d); 436 buffer_get_bignum(&decrypted, prv->rsa->iqmp); /* u */ 437 /* in SSL and SSH v1 p and q are exchanged */ 438 buffer_get_bignum(&decrypted, prv->rsa->q); /* p */ 439 buffer_get_bignum(&decrypted, prv->rsa->p); /* q */ 440 441 /* calculate p-1 and q-1 */ 442 rsa_generate_additional_parameters(prv->rsa); 443 444 buffer_free(&decrypted); 445 446 /* enable blinding */ 447 if (RSA_blinding_on(prv->rsa, NULL) != 1) { 448 error("key_load_private_rsa1: RSA_blinding_on failed"); 449 goto fail; 450 } 451 close(fd); 452 return prv; 453 454 fail: 455 if (commentp) 456 xfree(*commentp); 457 close(fd); 458 key_free(prv); 459 return NULL; 460 } 461 462 Key * 463 key_load_private_pem(int fd, int type, const char *passphrase, 464 char **commentp) 465 { 466 FILE *fp; 467 EVP_PKEY *pk = NULL; 468 Key *prv = NULL; 469 char *name = "<no key>"; 470 471 fp = fdopen(fd, "r"); 472 if (fp == NULL) { 473 error("fdopen failed: %s", strerror(errno)); 474 close(fd); 475 return NULL; 476 } 477 pk = PEM_read_PrivateKey(fp, NULL, NULL, (char *)passphrase); 478 if (pk == NULL) { 479 debug("PEM_read_PrivateKey failed"); 480 (void)ERR_get_error(); 481 } else if (pk->type == EVP_PKEY_RSA && 482 (type == KEY_UNSPEC||type==KEY_RSA)) { 483 prv = key_new(KEY_UNSPEC); 484 prv->rsa = EVP_PKEY_get1_RSA(pk); 485 prv->type = KEY_RSA; 486 name = "rsa w/o comment"; 487 #ifdef DEBUG_PK 488 RSA_print_fp(stderr, prv->rsa, 8); 489 #endif 490 if (RSA_blinding_on(prv->rsa, NULL) != 1) { 491 error("key_load_private_pem: RSA_blinding_on failed"); 492 key_free(prv); 493 prv = NULL; 494 } 495 } else if (pk->type == EVP_PKEY_DSA && 496 (type == KEY_UNSPEC||type==KEY_DSA)) { 497 prv = key_new(KEY_UNSPEC); 498 prv->dsa = EVP_PKEY_get1_DSA(pk); 499 prv->type = KEY_DSA; 500 name = "dsa w/o comment"; 501 #ifdef DEBUG_PK 502 DSA_print_fp(stderr, prv->dsa, 8); 503 #endif 504 } else { 505 error("PEM_read_PrivateKey: mismatch or " 506 "unknown EVP_PKEY save_type %d", pk->save_type); 507 } 508 fclose(fp); 509 if (pk != NULL) 510 EVP_PKEY_free(pk); 511 if (prv != NULL && commentp) 512 *commentp = xstrdup(name); 513 debug("read PEM private key done: type %s", 514 prv ? key_type(prv) : "<unknown>"); 515 return prv; 516 } 517 518 int 519 key_perm_ok(int fd, const char *filename) 520 { 521 struct stat st; 522 523 if (fstat(fd, &st) < 0) 524 return 0; 525 /* 526 * if a key owned by the user is accessed, then we check the 527 * permissions of the file. if the key owned by a different user, 528 * then we don't care. 529 */ 530 if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) { 531 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); 532 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @"); 533 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); 534 error("Permissions 0%3.3o for '%s' are too open.", 535 (u_int)st.st_mode & 0777, filename); 536 error("It is recommended that your private key files are NOT accessible by others."); 537 error("This private key will be ignored."); 538 return 0; 539 } 540 return 1; 541 } 542 543 Key * 544 key_load_private_type(int type, const char *filename, const char *passphrase, 545 char **commentp, int *perm_ok) 546 { 547 int fd; 548 549 fd = open(filename, O_RDONLY); 550 if (fd < 0) 551 return NULL; 552 if (!key_perm_ok(fd, filename)) { 553 if (perm_ok != NULL) 554 *perm_ok = 0; 555 error("bad permissions: ignore key: %s", filename); 556 close(fd); 557 return NULL; 558 } 559 if (perm_ok != NULL) 560 *perm_ok = 1; 561 switch (type) { 562 case KEY_RSA1: 563 return key_load_private_rsa1(fd, filename, passphrase, 564 commentp); 565 /* closes fd */ 566 case KEY_DSA: 567 case KEY_RSA: 568 case KEY_UNSPEC: 569 return key_load_private_pem(fd, type, passphrase, commentp); 570 /* closes fd */ 571 default: 572 close(fd); 573 break; 574 } 575 return NULL; 576 } 577 578 Key * 579 key_load_private(const char *filename, const char *passphrase, 580 char **commentp) 581 { 582 Key *pub, *prv; 583 int fd; 584 585 fd = open(filename, O_RDONLY); 586 if (fd < 0) 587 return NULL; 588 if (!key_perm_ok(fd, filename)) { 589 error("bad permissions: ignore key: %s", filename); 590 close(fd); 591 return NULL; 592 } 593 pub = key_load_public_rsa1(fd, filename, commentp); 594 lseek(fd, (off_t) 0, SEEK_SET); /* rewind */ 595 if (pub == NULL) { 596 /* closes fd */ 597 prv = key_load_private_pem(fd, KEY_UNSPEC, passphrase, NULL); 598 /* use the filename as a comment for PEM */ 599 if (commentp && prv) 600 *commentp = xstrdup(filename); 601 } else { 602 /* it's a SSH v1 key if the public key part is readable */ 603 key_free(pub); 604 /* closes fd */ 605 prv = key_load_private_rsa1(fd, filename, passphrase, NULL); 606 } 607 return prv; 608 } 609 610 static int 611 key_try_load_public(Key *k, const char *filename, char **commentp) 612 { 613 FILE *f; 614 char line[SSH_MAX_PUBKEY_BYTES]; 615 char *cp; 616 u_long linenum = 0; 617 618 f = fopen(filename, "r"); 619 if (f != NULL) { 620 while (read_keyfile_line(f, filename, line, sizeof(line), 621 &linenum) != -1) { 622 cp = line; 623 switch (*cp) { 624 case '#': 625 case '\n': 626 case '\0': 627 continue; 628 } 629 /* Skip leading whitespace. */ 630 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++) 631 ; 632 if (*cp) { 633 if (key_read(k, &cp) == 1) { 634 if (commentp) 635 *commentp=xstrdup(filename); 636 fclose(f); 637 return 1; 638 } 639 } 640 } 641 fclose(f); 642 } 643 return 0; 644 } 645 646 /* load public key from ssh v1 private or any pubkey file */ 647 Key * 648 key_load_public(const char *filename, char **commentp) 649 { 650 Key *pub; 651 char file[MAXPATHLEN]; 652 653 /* try rsa1 private key */ 654 pub = key_load_public_type(KEY_RSA1, filename, commentp); 655 if (pub != NULL) 656 return pub; 657 658 /* try rsa1 public key */ 659 pub = key_new(KEY_RSA1); 660 if (key_try_load_public(pub, filename, commentp) == 1) 661 return pub; 662 key_free(pub); 663 664 /* try ssh2 public key */ 665 pub = key_new(KEY_UNSPEC); 666 if (key_try_load_public(pub, filename, commentp) == 1) 667 return pub; 668 if ((strlcpy(file, filename, sizeof file) < sizeof(file)) && 669 (strlcat(file, ".pub", sizeof file) < sizeof(file)) && 670 (key_try_load_public(pub, file, commentp) == 1)) 671 return pub; 672 key_free(pub); 673 return NULL; 674 } 675