1 /* $NetBSD: ks_file.c,v 1.6 2023/06/19 21:41:44 christos 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 heim_error_t error = NULL; 58 hx509_cert cert; 59 int ret; 60 61 cert = hx509_cert_init_data(context, data, len, &error); 62 if (cert == NULL) { 63 ret = heim_error_get_code(error); 64 heim_release(error); 65 return ret; 66 } 67 68 ret = _hx509_collector_certs_add(context, c, cert); 69 hx509_cert_free(cert); 70 return ret; 71 } 72 73 static int 74 try_decrypt(hx509_context context, 75 struct hx509_collector *collector, 76 const AlgorithmIdentifier *alg, 77 const EVP_CIPHER *c, 78 const void *ivdata, 79 const void *password, 80 size_t passwordlen, 81 const void *cipher, 82 size_t len) 83 { 84 heim_octet_string clear; 85 size_t keylen; 86 void *key; 87 int ret; 88 89 keylen = EVP_CIPHER_key_length(c); 90 91 key = malloc(keylen); 92 if (key == NULL) { 93 hx509_clear_error_string(context); 94 return ENOMEM; 95 } 96 97 ret = EVP_BytesToKey(c, EVP_md5(), ivdata, 98 password, passwordlen, 99 1, key, NULL); 100 if (ret <= 0) { 101 ret = HX509_CRYPTO_INTERNAL_ERROR; 102 hx509_set_error_string(context, 0, ret, 103 "Failed to do string2key for private key"); 104 goto out; 105 } 106 107 clear.data = malloc(len); 108 if (clear.data == NULL) { 109 hx509_set_error_string(context, 0, ENOMEM, 110 "Out of memory to decrypt for private key"); 111 ret = ENOMEM; 112 goto out; 113 } 114 clear.length = len; 115 116 { 117 EVP_CIPHER_CTX *ctx; 118 #if OPENSSL_VERSION_NUMBER < 0x10100000UL 119 EVP_CIPHER_CTX ctxst; 120 ctx = &ctxst; 121 EVP_CIPHER_CTX_init(ctx); 122 #else 123 ctx = EVP_CIPHER_CTX_new(); 124 #endif 125 if (!EVP_CipherInit_ex(ctx, c, NULL, key, ivdata, 0)) { 126 hx509_set_error_string(context, 0, EINVAL, 127 "Cannot initialize cipher"); 128 ret = EINVAL; 129 goto out; 130 } 131 EVP_Cipher(ctx, clear.data, cipher, len); 132 #if OPENSSL_VERSION_NUMBER < 0x10100000UL 133 EVP_CIPHER_CTX_cleanup(ctx); 134 #else 135 EVP_CIPHER_CTX_free(ctx); 136 #endif 137 } 138 139 ret = _hx509_collector_private_key_add(context, 140 collector, 141 alg, 142 NULL, 143 &clear, 144 NULL); 145 146 memset_s(clear.data, clear.length, 0, clear.length); 147 free(clear.data); 148 out: 149 memset_s(key, keylen, 0, keylen); 150 free(key); 151 return ret; 152 } 153 154 static int 155 parse_pkcs8_private_key(hx509_context context, const char *fn, 156 struct hx509_collector *c, 157 const hx509_pem_header *headers, 158 const void *data, size_t length, 159 const AlgorithmIdentifier *ai) 160 { 161 PKCS8PrivateKeyInfo ki; 162 heim_octet_string keydata; 163 164 int ret; 165 166 ret = decode_PKCS8PrivateKeyInfo(data, length, &ki, NULL); 167 if (ret) 168 return ret; 169 170 keydata.data = rk_UNCONST(data); 171 keydata.length = length; 172 173 ret = _hx509_collector_private_key_add(context, 174 c, 175 &ki.privateKeyAlgorithm, 176 NULL, 177 &ki.privateKey, 178 &keydata); 179 free_PKCS8PrivateKeyInfo(&ki); 180 return ret; 181 } 182 183 static int 184 parse_pem_private_key(hx509_context context, const char *fn, 185 struct hx509_collector *c, 186 const hx509_pem_header *headers, 187 const void *data, size_t len, 188 const AlgorithmIdentifier *ai) 189 { 190 int ret = 0; 191 const char *enc; 192 193 enc = hx509_pem_find_header(headers, "Proc-Type"); 194 if (enc) { 195 const char *dek; 196 char *type, *iv; 197 ssize_t ssize, size; 198 void *ivdata; 199 const EVP_CIPHER *cipher; 200 const struct _hx509_password *pw; 201 hx509_lock lock; 202 int decrypted = 0; 203 size_t i; 204 205 lock = _hx509_collector_get_lock(c); 206 if (lock == NULL) { 207 hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP, 208 "Failed to get password for " 209 "password protected file %s", fn); 210 return HX509_ALG_NOT_SUPP; 211 } 212 213 if (strcmp(enc, "4,ENCRYPTED") != 0) { 214 hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED, 215 "Private key encrypted in unknown method %s " 216 "in file", 217 enc, fn); 218 hx509_clear_error_string(context); 219 return HX509_PARSING_KEY_FAILED; 220 } 221 222 dek = hx509_pem_find_header(headers, "DEK-Info"); 223 if (dek == NULL) { 224 hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED, 225 "Encrypted private key missing DEK-Info"); 226 return HX509_PARSING_KEY_FAILED; 227 } 228 229 type = strdup(dek); 230 if (type == NULL) { 231 hx509_clear_error_string(context); 232 return ENOMEM; 233 } 234 235 iv = strchr(type, ','); 236 if (iv == NULL) { 237 free(type); 238 hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED, 239 "IV missing"); 240 return HX509_PARSING_KEY_FAILED; 241 } 242 243 *iv++ = '\0'; 244 245 size = strlen(iv); 246 ivdata = malloc(size); 247 if (ivdata == NULL) { 248 hx509_clear_error_string(context); 249 free(type); 250 return ENOMEM; 251 } 252 253 cipher = EVP_get_cipherbyname(type); 254 if (cipher == NULL) { 255 free(ivdata); 256 hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP, 257 "Private key encrypted with " 258 "unsupported cipher: %s", 259 type); 260 free(type); 261 return HX509_ALG_NOT_SUPP; 262 } 263 264 #define PKCS5_SALT_LEN 8 265 266 ssize = hex_decode(iv, ivdata, size); 267 free(type); 268 type = NULL; 269 iv = NULL; 270 271 if (ssize < 0 || ssize < PKCS5_SALT_LEN || ssize < EVP_CIPHER_iv_length(cipher)) { 272 free(ivdata); 273 hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED, 274 "Salt have wrong length in " 275 "private key file"); 276 return HX509_PARSING_KEY_FAILED; 277 } 278 279 pw = _hx509_lock_get_passwords(lock); 280 if (pw != NULL) { 281 const void *password; 282 size_t passwordlen; 283 284 for (i = 0; i < pw->len; i++) { 285 password = pw->val[i]; 286 passwordlen = strlen(password); 287 288 ret = try_decrypt(context, c, ai, cipher, ivdata, 289 password, passwordlen, data, len); 290 if (ret == 0) { 291 decrypted = 1; 292 break; 293 } 294 } 295 } 296 if (!decrypted) { 297 hx509_prompt prompt; 298 char password[128]; 299 300 memset(&prompt, 0, sizeof(prompt)); 301 302 prompt.prompt = "Password for keyfile: "; 303 prompt.type = HX509_PROMPT_TYPE_PASSWORD; 304 prompt.reply.data = password; 305 prompt.reply.length = sizeof(password); 306 307 ret = hx509_lock_prompt(lock, &prompt); 308 if (ret == 0) 309 ret = try_decrypt(context, c, ai, cipher, ivdata, password, 310 strlen(password), data, len); 311 /* XXX add password to lock password collection ? */ 312 memset_s(password, sizeof(password), 0, sizeof(password)); 313 } 314 free(ivdata); 315 316 } else { 317 heim_octet_string keydata; 318 319 keydata.data = rk_UNCONST(data); 320 keydata.length = len; 321 322 ret = _hx509_collector_private_key_add(context, c, ai, NULL, 323 &keydata, NULL); 324 } 325 326 return ret; 327 } 328 329 330 struct pem_formats { 331 const char *name; 332 int (*func)(hx509_context, const char *, struct hx509_collector *, 333 const hx509_pem_header *, const void *, size_t, 334 const AlgorithmIdentifier *); 335 const AlgorithmIdentifier *(*ai)(void); 336 } formats[] = { 337 { "CERTIFICATE", parse_certificate, NULL }, 338 { "PRIVATE KEY", parse_pkcs8_private_key, NULL }, 339 { "RSA PRIVATE KEY", parse_pem_private_key, hx509_signature_rsa }, 340 #ifdef HAVE_HCRYPTO_W_OPENSSL 341 { "EC PRIVATE KEY", parse_pem_private_key, hx509_signature_ecPublicKey } 342 #endif 343 }; 344 345 346 struct pem_ctx { 347 int flags; 348 struct hx509_collector *c; 349 }; 350 351 static int 352 pem_func(hx509_context context, const char *type, 353 const hx509_pem_header *header, 354 const void *data, size_t len, void *ctx) 355 { 356 struct pem_ctx *pem_ctx = (struct pem_ctx*)ctx; 357 int ret = 0; 358 size_t j; 359 360 for (j = 0; j < sizeof(formats)/sizeof(formats[0]); j++) { 361 const char *q = formats[j].name; 362 if (strcasecmp(type, q) == 0) { 363 const AlgorithmIdentifier *ai = NULL; 364 if (formats[j].ai != NULL) 365 ai = (*formats[j].ai)(); 366 367 ret = (*formats[j].func)(context, NULL, pem_ctx->c, 368 header, data, len, ai); 369 if (ret && (pem_ctx->flags & HX509_CERTS_UNPROTECT_ALL)) { 370 hx509_set_error_string(context, HX509_ERROR_APPEND, ret, 371 "Failed parseing PEM format %s", type); 372 return ret; 373 } 374 break; 375 } 376 } 377 if (j == sizeof(formats)/sizeof(formats[0])) { 378 ret = HX509_UNSUPPORTED_OPERATION; 379 hx509_set_error_string(context, 0, ret, 380 "Found no matching PEM format for %s", type); 381 return ret; 382 } 383 return 0; 384 } 385 386 /* 387 * 388 */ 389 390 static int 391 file_init_common(hx509_context context, 392 hx509_certs certs, void **data, int flags, 393 const char *residue, hx509_lock lock, outformat format) 394 { 395 char *p, *pnext; 396 struct ks_file *ksf = NULL; 397 hx509_private_key *keys = NULL; 398 int ret; 399 struct pem_ctx pem_ctx; 400 401 pem_ctx.flags = flags; 402 pem_ctx.c = NULL; 403 404 *data = NULL; 405 406 if (lock == NULL) 407 lock = _hx509_empty_lock; 408 409 ksf = calloc(1, sizeof(*ksf)); 410 if (ksf == NULL) { 411 hx509_clear_error_string(context); 412 return ENOMEM; 413 } 414 ksf->format = format; 415 416 ksf->fn = strdup(residue); 417 if (ksf->fn == NULL) { 418 hx509_clear_error_string(context); 419 ret = ENOMEM; 420 goto out; 421 } 422 423 /* 424 * XXX this is broken, the function should parse the file before 425 * overwriting it 426 */ 427 428 if (flags & HX509_CERTS_CREATE) { 429 ret = hx509_certs_init(context, "MEMORY:ks-file-create", 430 0, lock, &ksf->certs); 431 if (ret) 432 goto out; 433 *data = ksf; 434 return 0; 435 } 436 437 ret = _hx509_collector_alloc(context, lock, &pem_ctx.c); 438 if (ret) 439 goto out; 440 441 for (p = ksf->fn; p != NULL; p = pnext) { 442 FILE *f; 443 444 pnext = strchr(p, ','); 445 if (pnext) 446 *pnext++ = '\0'; 447 448 449 if ((f = fopen(p, "r")) == NULL) { 450 ret = ENOENT; 451 hx509_set_error_string(context, 0, ret, 452 "Failed to open PEM file \"%s\": %s", 453 p, strerror(errno)); 454 goto out; 455 } 456 rk_cloexec_file(f); 457 458 ret = hx509_pem_read(context, f, pem_func, &pem_ctx); 459 fclose(f); 460 if (ret != 0 && ret != HX509_PARSING_KEY_FAILED) 461 goto out; 462 else if (ret == HX509_PARSING_KEY_FAILED) { 463 size_t length; 464 void *ptr; 465 size_t i; 466 467 ret = rk_undumpdata(p, &ptr, &length); 468 if (ret) { 469 hx509_clear_error_string(context); 470 goto out; 471 } 472 473 for (i = 0; i < sizeof(formats)/sizeof(formats[0]); i++) { 474 const AlgorithmIdentifier *ai = NULL; 475 if (formats[i].ai != NULL) 476 ai = (*formats[i].ai)(); 477 478 ret = (*formats[i].func)(context, p, pem_ctx.c, NULL, ptr, length, ai); 479 if (ret == 0) 480 break; 481 } 482 rk_xfree(ptr); 483 if (ret) { 484 hx509_clear_error_string(context); 485 goto out; 486 } 487 } 488 } 489 490 ret = _hx509_collector_collect_certs(context, pem_ctx.c, &ksf->certs); 491 if (ret) 492 goto out; 493 494 ret = _hx509_collector_collect_private_keys(context, pem_ctx.c, &keys); 495 if (ret == 0) { 496 int i; 497 498 for (i = 0; keys[i]; i++) 499 _hx509_certs_keys_add(context, ksf->certs, keys[i]); 500 _hx509_certs_keys_free(context, keys); 501 } 502 503 out: 504 if (ret == 0) 505 *data = ksf; 506 else { 507 if (ksf->fn) 508 free(ksf->fn); 509 free(ksf); 510 } 511 if (pem_ctx.c) 512 _hx509_collector_free(pem_ctx.c); 513 514 return ret; 515 } 516 517 static int 518 file_init_pem(hx509_context context, 519 hx509_certs certs, void **data, int flags, 520 const char *residue, hx509_lock lock) 521 { 522 return file_init_common(context, certs, data, flags, residue, lock, USE_PEM); 523 } 524 525 static int 526 file_init_der(hx509_context context, 527 hx509_certs certs, void **data, int flags, 528 const char *residue, hx509_lock lock) 529 { 530 return file_init_common(context, certs, data, flags, residue, lock, USE_DER); 531 } 532 533 static int 534 file_free(hx509_certs certs, void *data) 535 { 536 struct ks_file *ksf = data; 537 hx509_certs_free(&ksf->certs); 538 free(ksf->fn); 539 free(ksf); 540 return 0; 541 } 542 543 struct store_ctx { 544 FILE *f; 545 outformat format; 546 }; 547 548 static int 549 store_func(hx509_context context, void *ctx, hx509_cert c) 550 { 551 struct store_ctx *sc = ctx; 552 heim_octet_string data; 553 int ret = 0; 554 555 ret = hx509_cert_binary(context, c, &data); 556 if (ret) 557 return ret; 558 559 switch (sc->format) { 560 case USE_DER: 561 fwrite(data.data, data.length, 1, sc->f); 562 free(data.data); 563 break; 564 case USE_PEM: 565 hx509_pem_write(context, "CERTIFICATE", NULL, sc->f, 566 data.data, data.length); 567 free(data.data); 568 if (_hx509_cert_private_key_exportable(c)) { 569 hx509_private_key key = _hx509_cert_private_key(c); 570 ret = _hx509_private_key_export(context, key, 571 HX509_KEY_FORMAT_DER, &data); 572 if (ret) 573 break; 574 ret = hx509_pem_write(context, _hx509_private_pem_name(key), NULL, 575 sc->f, data.data, data.length); 576 free(data.data); 577 } 578 break; 579 } 580 581 return ret; 582 } 583 584 static int 585 file_store(hx509_context context, 586 hx509_certs certs, void *data, int flags, hx509_lock lock) 587 { 588 struct ks_file *ksf = data; 589 struct store_ctx sc; 590 int ret; 591 592 sc.f = fopen(ksf->fn, "w"); 593 if (sc.f == NULL) { 594 hx509_set_error_string(context, 0, ENOENT, 595 "Failed to open file %s for writing"); 596 return ENOENT; 597 } 598 rk_cloexec_file(sc.f); 599 sc.format = ksf->format; 600 601 ret = hx509_certs_iter_f(context, ksf->certs, store_func, &sc); 602 fclose(sc.f); 603 return ret; 604 } 605 606 static int 607 file_add(hx509_context context, hx509_certs certs, void *data, hx509_cert c) 608 { 609 struct ks_file *ksf = data; 610 return hx509_certs_add(context, ksf->certs, c); 611 } 612 613 static int 614 file_iter_start(hx509_context context, 615 hx509_certs certs, void *data, void **cursor) 616 { 617 struct ks_file *ksf = data; 618 return hx509_certs_start_seq(context, ksf->certs, cursor); 619 } 620 621 static int 622 file_iter(hx509_context context, 623 hx509_certs certs, void *data, void *iter, hx509_cert *cert) 624 { 625 struct ks_file *ksf = data; 626 return hx509_certs_next_cert(context, ksf->certs, iter, cert); 627 } 628 629 static int 630 file_iter_end(hx509_context context, 631 hx509_certs certs, 632 void *data, 633 void *cursor) 634 { 635 struct ks_file *ksf = data; 636 return hx509_certs_end_seq(context, ksf->certs, cursor); 637 } 638 639 static int 640 file_getkeys(hx509_context context, 641 hx509_certs certs, 642 void *data, 643 hx509_private_key **keys) 644 { 645 struct ks_file *ksf = data; 646 return _hx509_certs_keys_get(context, ksf->certs, keys); 647 } 648 649 static int 650 file_addkey(hx509_context context, 651 hx509_certs certs, 652 void *data, 653 hx509_private_key key) 654 { 655 struct ks_file *ksf = data; 656 return _hx509_certs_keys_add(context, ksf->certs, key); 657 } 658 659 static struct hx509_keyset_ops keyset_file = { 660 "FILE", 661 0, 662 file_init_pem, 663 file_store, 664 file_free, 665 file_add, 666 NULL, 667 file_iter_start, 668 file_iter, 669 file_iter_end, 670 NULL, 671 file_getkeys, 672 file_addkey 673 }; 674 675 static struct hx509_keyset_ops keyset_pemfile = { 676 "PEM-FILE", 677 0, 678 file_init_pem, 679 file_store, 680 file_free, 681 file_add, 682 NULL, 683 file_iter_start, 684 file_iter, 685 file_iter_end, 686 NULL, 687 file_getkeys, 688 file_addkey 689 }; 690 691 static struct hx509_keyset_ops keyset_derfile = { 692 "DER-FILE", 693 0, 694 file_init_der, 695 file_store, 696 file_free, 697 file_add, 698 NULL, 699 file_iter_start, 700 file_iter, 701 file_iter_end, 702 NULL, 703 file_getkeys, 704 file_addkey 705 }; 706 707 708 void 709 _hx509_ks_file_register(hx509_context context) 710 { 711 _hx509_ks_register(context, &keyset_file); 712 _hx509_ks_register(context, &keyset_pemfile); 713 _hx509_ks_register(context, &keyset_derfile); 714 } 715