1 /* $NetBSD: ks_file.c,v 1.1.1.2 2014/04/24 12:45:41 pettai Exp $ */ 2 3 /* 4 * Copyright (c) 2005 - 2007 Kungliga Tekniska Högskolan 5 * (Royal Institute of Technology, Stockholm, Sweden). 6 * All rights reserved. 7 * 8 * Redistribution and use in source and binary forms, with or without 9 * modification, are permitted provided that the following conditions 10 * are met: 11 * 12 * 1. Redistributions of source code must retain the above copyright 13 * notice, this list of conditions and the following disclaimer. 14 * 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 19 * 3. Neither the name of the Institute nor the names of its contributors 20 * may be used to endorse or promote products derived from this software 21 * without specific prior written permission. 22 * 23 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND 24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 26 * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE 27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 33 * SUCH DAMAGE. 34 */ 35 36 #include "hx_locl.h" 37 38 typedef enum { USE_PEM, USE_DER } outformat; 39 40 struct ks_file { 41 hx509_certs certs; 42 char *fn; 43 outformat format; 44 }; 45 46 /* 47 * 48 */ 49 50 static int 51 parse_certificate(hx509_context context, const char *fn, 52 struct hx509_collector *c, 53 const hx509_pem_header *headers, 54 const void *data, size_t len, 55 const AlgorithmIdentifier *ai) 56 { 57 hx509_cert cert; 58 int ret; 59 60 ret = hx509_cert_init_data(context, data, len, &cert); 61 if (ret) 62 return ret; 63 64 ret = _hx509_collector_certs_add(context, c, cert); 65 hx509_cert_free(cert); 66 return ret; 67 } 68 69 static int 70 try_decrypt(hx509_context context, 71 struct hx509_collector *collector, 72 const AlgorithmIdentifier *alg, 73 const EVP_CIPHER *c, 74 const void *ivdata, 75 const void *password, 76 size_t passwordlen, 77 const void *cipher, 78 size_t len) 79 { 80 heim_octet_string clear; 81 size_t keylen; 82 void *key; 83 int ret; 84 85 keylen = EVP_CIPHER_key_length(c); 86 87 key = malloc(keylen); 88 if (key == NULL) { 89 hx509_clear_error_string(context); 90 return ENOMEM; 91 } 92 93 ret = EVP_BytesToKey(c, EVP_md5(), ivdata, 94 password, passwordlen, 95 1, key, NULL); 96 if (ret <= 0) { 97 hx509_set_error_string(context, 0, HX509_CRYPTO_INTERNAL_ERROR, 98 "Failed to do string2key for private key"); 99 return HX509_CRYPTO_INTERNAL_ERROR; 100 } 101 102 clear.data = malloc(len); 103 if (clear.data == NULL) { 104 hx509_set_error_string(context, 0, ENOMEM, 105 "Out of memory to decrypt for private key"); 106 ret = ENOMEM; 107 goto out; 108 } 109 clear.length = len; 110 111 { 112 EVP_CIPHER_CTX ctx; 113 EVP_CIPHER_CTX_init(&ctx); 114 EVP_CipherInit_ex(&ctx, c, NULL, key, ivdata, 0); 115 EVP_Cipher(&ctx, clear.data, cipher, len); 116 EVP_CIPHER_CTX_cleanup(&ctx); 117 } 118 119 ret = _hx509_collector_private_key_add(context, 120 collector, 121 alg, 122 NULL, 123 &clear, 124 NULL); 125 126 memset(clear.data, 0, clear.length); 127 free(clear.data); 128 out: 129 memset(key, 0, keylen); 130 free(key); 131 return ret; 132 } 133 134 static int 135 parse_pkcs8_private_key(hx509_context context, const char *fn, 136 struct hx509_collector *c, 137 const hx509_pem_header *headers, 138 const void *data, size_t length, 139 const AlgorithmIdentifier *ai) 140 { 141 PKCS8PrivateKeyInfo ki; 142 heim_octet_string keydata; 143 144 int ret; 145 146 ret = decode_PKCS8PrivateKeyInfo(data, length, &ki, NULL); 147 if (ret) 148 return ret; 149 150 keydata.data = rk_UNCONST(data); 151 keydata.length = length; 152 153 ret = _hx509_collector_private_key_add(context, 154 c, 155 &ki.privateKeyAlgorithm, 156 NULL, 157 &ki.privateKey, 158 &keydata); 159 free_PKCS8PrivateKeyInfo(&ki); 160 return ret; 161 } 162 163 static int 164 parse_pem_private_key(hx509_context context, const char *fn, 165 struct hx509_collector *c, 166 const hx509_pem_header *headers, 167 const void *data, size_t len, 168 const AlgorithmIdentifier *ai) 169 { 170 int ret = 0; 171 const char *enc; 172 173 enc = hx509_pem_find_header(headers, "Proc-Type"); 174 if (enc) { 175 const char *dek; 176 char *type, *iv; 177 ssize_t ssize, size; 178 void *ivdata; 179 const EVP_CIPHER *cipher; 180 const struct _hx509_password *pw; 181 hx509_lock lock; 182 int decrypted = 0; 183 size_t i; 184 185 lock = _hx509_collector_get_lock(c); 186 if (lock == NULL) { 187 hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP, 188 "Failed to get password for " 189 "password protected file %s", fn); 190 return HX509_ALG_NOT_SUPP; 191 } 192 193 if (strcmp(enc, "4,ENCRYPTED") != 0) { 194 hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED, 195 "Private key encrypted in unknown method %s " 196 "in file", 197 enc, fn); 198 hx509_clear_error_string(context); 199 return HX509_PARSING_KEY_FAILED; 200 } 201 202 dek = hx509_pem_find_header(headers, "DEK-Info"); 203 if (dek == NULL) { 204 hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED, 205 "Encrypted private key missing DEK-Info"); 206 return HX509_PARSING_KEY_FAILED; 207 } 208 209 type = strdup(dek); 210 if (type == NULL) { 211 hx509_clear_error_string(context); 212 return ENOMEM; 213 } 214 215 iv = strchr(type, ','); 216 if (iv == NULL) { 217 free(type); 218 hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED, 219 "IV missing"); 220 return HX509_PARSING_KEY_FAILED; 221 } 222 223 *iv++ = '\0'; 224 225 size = strlen(iv); 226 ivdata = malloc(size); 227 if (ivdata == NULL) { 228 hx509_clear_error_string(context); 229 free(type); 230 return ENOMEM; 231 } 232 233 cipher = EVP_get_cipherbyname(type); 234 if (cipher == NULL) { 235 free(ivdata); 236 hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP, 237 "Private key encrypted with " 238 "unsupported cipher: %s", 239 type); 240 free(type); 241 return HX509_ALG_NOT_SUPP; 242 } 243 244 #define PKCS5_SALT_LEN 8 245 246 ssize = hex_decode(iv, ivdata, size); 247 free(type); 248 type = NULL; 249 iv = NULL; 250 251 if (ssize < 0 || ssize < PKCS5_SALT_LEN || ssize < EVP_CIPHER_iv_length(cipher)) { 252 free(ivdata); 253 hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED, 254 "Salt have wrong length in " 255 "private key file"); 256 return HX509_PARSING_KEY_FAILED; 257 } 258 259 pw = _hx509_lock_get_passwords(lock); 260 if (pw != NULL) { 261 const void *password; 262 size_t passwordlen; 263 264 for (i = 0; i < pw->len; i++) { 265 password = pw->val[i]; 266 passwordlen = strlen(password); 267 268 ret = try_decrypt(context, c, ai, cipher, ivdata, 269 password, passwordlen, data, len); 270 if (ret == 0) { 271 decrypted = 1; 272 break; 273 } 274 } 275 } 276 if (!decrypted) { 277 hx509_prompt prompt; 278 char password[128]; 279 280 memset(&prompt, 0, sizeof(prompt)); 281 282 prompt.prompt = "Password for keyfile: "; 283 prompt.type = HX509_PROMPT_TYPE_PASSWORD; 284 prompt.reply.data = password; 285 prompt.reply.length = sizeof(password); 286 287 ret = hx509_lock_prompt(lock, &prompt); 288 if (ret == 0) 289 ret = try_decrypt(context, c, ai, cipher, ivdata, password, 290 strlen(password), data, len); 291 /* XXX add password to lock password collection ? */ 292 memset(password, 0, sizeof(password)); 293 } 294 free(ivdata); 295 296 } else { 297 heim_octet_string keydata; 298 299 keydata.data = rk_UNCONST(data); 300 keydata.length = len; 301 302 ret = _hx509_collector_private_key_add(context, c, ai, NULL, 303 &keydata, NULL); 304 } 305 306 return ret; 307 } 308 309 310 struct pem_formats { 311 const char *name; 312 int (*func)(hx509_context, const char *, struct hx509_collector *, 313 const hx509_pem_header *, const void *, size_t, 314 const AlgorithmIdentifier *); 315 const AlgorithmIdentifier *(*ai)(void); 316 } formats[] = { 317 { "CERTIFICATE", parse_certificate, NULL }, 318 { "PRIVATE KEY", parse_pkcs8_private_key, NULL }, 319 { "RSA PRIVATE KEY", parse_pem_private_key, hx509_signature_rsa }, 320 { "EC PRIVATE KEY", parse_pem_private_key, hx509_signature_ecPublicKey } 321 }; 322 323 324 struct pem_ctx { 325 int flags; 326 struct hx509_collector *c; 327 }; 328 329 static int 330 pem_func(hx509_context context, const char *type, 331 const hx509_pem_header *header, 332 const void *data, size_t len, void *ctx) 333 { 334 struct pem_ctx *pem_ctx = (struct pem_ctx*)ctx; 335 int ret = 0; 336 size_t j; 337 338 for (j = 0; j < sizeof(formats)/sizeof(formats[0]); j++) { 339 const char *q = formats[j].name; 340 if (strcasecmp(type, q) == 0) { 341 const AlgorithmIdentifier *ai = NULL; 342 if (formats[j].ai != NULL) 343 ai = (*formats[j].ai)(); 344 345 ret = (*formats[j].func)(context, NULL, pem_ctx->c, 346 header, data, len, ai); 347 if (ret && (pem_ctx->flags & HX509_CERTS_UNPROTECT_ALL)) { 348 hx509_set_error_string(context, HX509_ERROR_APPEND, ret, 349 "Failed parseing PEM format %s", type); 350 return ret; 351 } 352 break; 353 } 354 } 355 if (j == sizeof(formats)/sizeof(formats[0])) { 356 ret = HX509_UNSUPPORTED_OPERATION; 357 hx509_set_error_string(context, 0, ret, 358 "Found no matching PEM format for %s", type); 359 return ret; 360 } 361 return 0; 362 } 363 364 /* 365 * 366 */ 367 368 static int 369 file_init_common(hx509_context context, 370 hx509_certs certs, void **data, int flags, 371 const char *residue, hx509_lock lock, outformat format) 372 { 373 char *p, *pnext; 374 struct ks_file *ksf = NULL; 375 hx509_private_key *keys = NULL; 376 int ret; 377 struct pem_ctx pem_ctx; 378 379 pem_ctx.flags = flags; 380 pem_ctx.c = NULL; 381 382 *data = NULL; 383 384 if (lock == NULL) 385 lock = _hx509_empty_lock; 386 387 ksf = calloc(1, sizeof(*ksf)); 388 if (ksf == NULL) { 389 hx509_clear_error_string(context); 390 return ENOMEM; 391 } 392 ksf->format = format; 393 394 ksf->fn = strdup(residue); 395 if (ksf->fn == NULL) { 396 hx509_clear_error_string(context); 397 ret = ENOMEM; 398 goto out; 399 } 400 401 /* 402 * XXX this is broken, the function should parse the file before 403 * overwriting it 404 */ 405 406 if (flags & HX509_CERTS_CREATE) { 407 ret = hx509_certs_init(context, "MEMORY:ks-file-create", 408 0, lock, &ksf->certs); 409 if (ret) 410 goto out; 411 *data = ksf; 412 return 0; 413 } 414 415 ret = _hx509_collector_alloc(context, lock, &pem_ctx.c); 416 if (ret) 417 goto out; 418 419 for (p = ksf->fn; p != NULL; p = pnext) { 420 FILE *f; 421 422 pnext = strchr(p, ','); 423 if (pnext) 424 *pnext++ = '\0'; 425 426 427 if ((f = fopen(p, "r")) == NULL) { 428 ret = ENOENT; 429 hx509_set_error_string(context, 0, ret, 430 "Failed to open PEM file \"%s\": %s", 431 p, strerror(errno)); 432 goto out; 433 } 434 rk_cloexec_file(f); 435 436 ret = hx509_pem_read(context, f, pem_func, &pem_ctx); 437 fclose(f); 438 if (ret != 0 && ret != HX509_PARSING_KEY_FAILED) 439 goto out; 440 else if (ret == HX509_PARSING_KEY_FAILED) { 441 size_t length; 442 void *ptr; 443 size_t i; 444 445 ret = rk_undumpdata(p, &ptr, &length); 446 if (ret) { 447 hx509_clear_error_string(context); 448 goto out; 449 } 450 451 for (i = 0; i < sizeof(formats)/sizeof(formats[0]); i++) { 452 const AlgorithmIdentifier *ai = NULL; 453 if (formats[i].ai != NULL) 454 ai = (*formats[i].ai)(); 455 456 ret = (*formats[i].func)(context, p, pem_ctx.c, NULL, ptr, length, ai); 457 if (ret == 0) 458 break; 459 } 460 rk_xfree(ptr); 461 if (ret) { 462 hx509_clear_error_string(context); 463 goto out; 464 } 465 } 466 } 467 468 ret = _hx509_collector_collect_certs(context, pem_ctx.c, &ksf->certs); 469 if (ret) 470 goto out; 471 472 ret = _hx509_collector_collect_private_keys(context, pem_ctx.c, &keys); 473 if (ret == 0) { 474 int i; 475 476 for (i = 0; keys[i]; i++) 477 _hx509_certs_keys_add(context, ksf->certs, keys[i]); 478 _hx509_certs_keys_free(context, keys); 479 } 480 481 out: 482 if (ret == 0) 483 *data = ksf; 484 else { 485 if (ksf->fn) 486 free(ksf->fn); 487 free(ksf); 488 } 489 if (pem_ctx.c) 490 _hx509_collector_free(pem_ctx.c); 491 492 return ret; 493 } 494 495 static int 496 file_init_pem(hx509_context context, 497 hx509_certs certs, void **data, int flags, 498 const char *residue, hx509_lock lock) 499 { 500 return file_init_common(context, certs, data, flags, residue, lock, USE_PEM); 501 } 502 503 static int 504 file_init_der(hx509_context context, 505 hx509_certs certs, void **data, int flags, 506 const char *residue, hx509_lock lock) 507 { 508 return file_init_common(context, certs, data, flags, residue, lock, USE_DER); 509 } 510 511 static int 512 file_free(hx509_certs certs, void *data) 513 { 514 struct ks_file *ksf = data; 515 hx509_certs_free(&ksf->certs); 516 free(ksf->fn); 517 free(ksf); 518 return 0; 519 } 520 521 struct store_ctx { 522 FILE *f; 523 outformat format; 524 }; 525 526 static int 527 store_func(hx509_context context, void *ctx, hx509_cert c) 528 { 529 struct store_ctx *sc = ctx; 530 heim_octet_string data; 531 int ret; 532 533 ret = hx509_cert_binary(context, c, &data); 534 if (ret) 535 return ret; 536 537 switch (sc->format) { 538 case USE_DER: 539 fwrite(data.data, data.length, 1, sc->f); 540 free(data.data); 541 break; 542 case USE_PEM: 543 hx509_pem_write(context, "CERTIFICATE", NULL, sc->f, 544 data.data, data.length); 545 free(data.data); 546 if (_hx509_cert_private_key_exportable(c)) { 547 hx509_private_key key = _hx509_cert_private_key(c); 548 ret = _hx509_private_key_export(context, key, 549 HX509_KEY_FORMAT_DER, &data); 550 if (ret) 551 break; 552 hx509_pem_write(context, _hx509_private_pem_name(key), NULL, sc->f, 553 data.data, data.length); 554 free(data.data); 555 } 556 break; 557 } 558 559 return 0; 560 } 561 562 static int 563 file_store(hx509_context context, 564 hx509_certs certs, void *data, int flags, hx509_lock lock) 565 { 566 struct ks_file *ksf = data; 567 struct store_ctx sc; 568 int ret; 569 570 sc.f = fopen(ksf->fn, "w"); 571 if (sc.f == NULL) { 572 hx509_set_error_string(context, 0, ENOENT, 573 "Failed to open file %s for writing"); 574 return ENOENT; 575 } 576 rk_cloexec_file(sc.f); 577 sc.format = ksf->format; 578 579 ret = hx509_certs_iter_f(context, ksf->certs, store_func, &sc); 580 fclose(sc.f); 581 return ret; 582 } 583 584 static int 585 file_add(hx509_context context, hx509_certs certs, void *data, hx509_cert c) 586 { 587 struct ks_file *ksf = data; 588 return hx509_certs_add(context, ksf->certs, c); 589 } 590 591 static int 592 file_iter_start(hx509_context context, 593 hx509_certs certs, void *data, void **cursor) 594 { 595 struct ks_file *ksf = data; 596 return hx509_certs_start_seq(context, ksf->certs, cursor); 597 } 598 599 static int 600 file_iter(hx509_context context, 601 hx509_certs certs, void *data, void *iter, hx509_cert *cert) 602 { 603 struct ks_file *ksf = data; 604 return hx509_certs_next_cert(context, ksf->certs, iter, cert); 605 } 606 607 static int 608 file_iter_end(hx509_context context, 609 hx509_certs certs, 610 void *data, 611 void *cursor) 612 { 613 struct ks_file *ksf = data; 614 return hx509_certs_end_seq(context, ksf->certs, cursor); 615 } 616 617 static int 618 file_getkeys(hx509_context context, 619 hx509_certs certs, 620 void *data, 621 hx509_private_key **keys) 622 { 623 struct ks_file *ksf = data; 624 return _hx509_certs_keys_get(context, ksf->certs, keys); 625 } 626 627 static int 628 file_addkey(hx509_context context, 629 hx509_certs certs, 630 void *data, 631 hx509_private_key key) 632 { 633 struct ks_file *ksf = data; 634 return _hx509_certs_keys_add(context, ksf->certs, key); 635 } 636 637 static struct hx509_keyset_ops keyset_file = { 638 "FILE", 639 0, 640 file_init_pem, 641 file_store, 642 file_free, 643 file_add, 644 NULL, 645 file_iter_start, 646 file_iter, 647 file_iter_end, 648 NULL, 649 file_getkeys, 650 file_addkey 651 }; 652 653 static struct hx509_keyset_ops keyset_pemfile = { 654 "PEM-FILE", 655 0, 656 file_init_pem, 657 file_store, 658 file_free, 659 file_add, 660 NULL, 661 file_iter_start, 662 file_iter, 663 file_iter_end, 664 NULL, 665 file_getkeys, 666 file_addkey 667 }; 668 669 static struct hx509_keyset_ops keyset_derfile = { 670 "DER-FILE", 671 0, 672 file_init_der, 673 file_store, 674 file_free, 675 file_add, 676 NULL, 677 file_iter_start, 678 file_iter, 679 file_iter_end, 680 NULL, 681 file_getkeys, 682 file_addkey 683 }; 684 685 686 void 687 _hx509_ks_file_register(hx509_context context) 688 { 689 _hx509_ks_register(context, &keyset_file); 690 _hx509_ks_register(context, &keyset_pemfile); 691 _hx509_ks_register(context, &keyset_derfile); 692 } 693