1 // SPDX-License-Identifier: GPL-2.0+ 2 /* 3 * Copyright (c) 2013, Google Inc. 4 */ 5 6 #include "mkimage.h" 7 #include <stdio.h> 8 #include <string.h> 9 #include <image.h> 10 #include <time.h> 11 #include <openssl/bn.h> 12 #include <openssl/rsa.h> 13 #include <openssl/pem.h> 14 #include <openssl/err.h> 15 #include <openssl/ssl.h> 16 #include <openssl/evp.h> 17 #include <openssl/engine.h> 18 19 #if OPENSSL_VERSION_NUMBER >= 0x10000000L 20 #define HAVE_ERR_REMOVE_THREAD_STATE 21 #endif 22 23 #if OPENSSL_VERSION_NUMBER < 0x10100000L 24 static void RSA_get0_key(const RSA *r, 25 const BIGNUM **n, const BIGNUM **e, const BIGNUM **d) 26 { 27 if (n != NULL) 28 *n = r->n; 29 if (e != NULL) 30 *e = r->e; 31 if (d != NULL) 32 *d = r->d; 33 } 34 #endif 35 36 static int rsa_err(const char *msg) 37 { 38 unsigned long sslErr = ERR_get_error(); 39 40 fprintf(stderr, "%s", msg); 41 fprintf(stderr, ": %s\n", 42 ERR_error_string(sslErr, 0)); 43 44 return -1; 45 } 46 47 /** 48 * rsa_pem_get_pub_key() - read a public key from a .crt file 49 * 50 * @keydir: Directory containins the key 51 * @name Name of key file (will have a .crt extension) 52 * @rsap Returns RSA object, or NULL on failure 53 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL) 54 */ 55 static int rsa_pem_get_pub_key(const char *keydir, const char *name, RSA **rsap) 56 { 57 char path[1024]; 58 EVP_PKEY *key; 59 X509 *cert; 60 RSA *rsa; 61 FILE *f; 62 int ret; 63 64 *rsap = NULL; 65 snprintf(path, sizeof(path), "%s/%s.crt", keydir, name); 66 f = fopen(path, "r"); 67 if (!f) { 68 fprintf(stderr, "Couldn't open RSA certificate: '%s': %s\n", 69 path, strerror(errno)); 70 return -EACCES; 71 } 72 73 /* Read the certificate */ 74 cert = NULL; 75 if (!PEM_read_X509(f, &cert, NULL, NULL)) { 76 rsa_err("Couldn't read certificate"); 77 ret = -EINVAL; 78 goto err_cert; 79 } 80 81 /* Get the public key from the certificate. */ 82 key = X509_get_pubkey(cert); 83 if (!key) { 84 rsa_err("Couldn't read public key\n"); 85 ret = -EINVAL; 86 goto err_pubkey; 87 } 88 89 /* Convert to a RSA_style key. */ 90 rsa = EVP_PKEY_get1_RSA(key); 91 if (!rsa) { 92 rsa_err("Couldn't convert to a RSA style key"); 93 ret = -EINVAL; 94 goto err_rsa; 95 } 96 fclose(f); 97 EVP_PKEY_free(key); 98 X509_free(cert); 99 *rsap = rsa; 100 101 return 0; 102 103 err_rsa: 104 EVP_PKEY_free(key); 105 err_pubkey: 106 X509_free(cert); 107 err_cert: 108 fclose(f); 109 return ret; 110 } 111 112 /** 113 * rsa_engine_get_pub_key() - read a public key from given engine 114 * 115 * @keydir: Key prefix 116 * @name Name of key 117 * @engine Engine to use 118 * @rsap Returns RSA object, or NULL on failure 119 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL) 120 */ 121 static int rsa_engine_get_pub_key(const char *keydir, const char *name, 122 ENGINE *engine, RSA **rsap) 123 { 124 const char *engine_id; 125 char key_id[1024]; 126 EVP_PKEY *key; 127 RSA *rsa; 128 int ret; 129 130 *rsap = NULL; 131 132 engine_id = ENGINE_get_id(engine); 133 134 if (engine_id && !strcmp(engine_id, "pkcs11")) { 135 if (keydir) 136 snprintf(key_id, sizeof(key_id), 137 "pkcs11:%s;object=%s;type=public", 138 keydir, name); 139 else 140 snprintf(key_id, sizeof(key_id), 141 "pkcs11:object=%s;type=public", 142 name); 143 } else { 144 fprintf(stderr, "Engine not supported\n"); 145 return -ENOTSUP; 146 } 147 148 key = ENGINE_load_public_key(engine, key_id, NULL, NULL); 149 if (!key) 150 return rsa_err("Failure loading public key from engine"); 151 152 /* Convert to a RSA_style key. */ 153 rsa = EVP_PKEY_get1_RSA(key); 154 if (!rsa) { 155 rsa_err("Couldn't convert to a RSA style key"); 156 ret = -EINVAL; 157 goto err_rsa; 158 } 159 160 EVP_PKEY_free(key); 161 *rsap = rsa; 162 163 return 0; 164 165 err_rsa: 166 EVP_PKEY_free(key); 167 return ret; 168 } 169 170 /** 171 * rsa_get_pub_key() - read a public key 172 * 173 * @keydir: Directory containing the key (PEM file) or key prefix (engine) 174 * @name Name of key file (will have a .crt extension) 175 * @engine Engine to use 176 * @rsap Returns RSA object, or NULL on failure 177 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL) 178 */ 179 static int rsa_get_pub_key(const char *keydir, const char *name, 180 ENGINE *engine, RSA **rsap) 181 { 182 if (engine) 183 return rsa_engine_get_pub_key(keydir, name, engine, rsap); 184 return rsa_pem_get_pub_key(keydir, name, rsap); 185 } 186 187 /** 188 * rsa_pem_get_priv_key() - read a private key from a .key file 189 * 190 * @keydir: Directory containing the key 191 * @name Name of key file (will have a .key extension) 192 * @rsap Returns RSA object, or NULL on failure 193 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL) 194 */ 195 static int rsa_pem_get_priv_key(const char *keydir, const char *name, 196 RSA **rsap) 197 { 198 char path[1024]; 199 RSA *rsa; 200 FILE *f; 201 202 *rsap = NULL; 203 snprintf(path, sizeof(path), "%s/%s.key", keydir, name); 204 f = fopen(path, "r"); 205 if (!f) { 206 fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n", 207 path, strerror(errno)); 208 return -ENOENT; 209 } 210 211 rsa = PEM_read_RSAPrivateKey(f, 0, NULL, path); 212 if (!rsa) { 213 rsa_err("Failure reading private key"); 214 fclose(f); 215 return -EPROTO; 216 } 217 fclose(f); 218 *rsap = rsa; 219 220 return 0; 221 } 222 223 /** 224 * rsa_engine_get_priv_key() - read a private key from given engine 225 * 226 * @keydir: Key prefix 227 * @name Name of key 228 * @engine Engine to use 229 * @rsap Returns RSA object, or NULL on failure 230 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL) 231 */ 232 static int rsa_engine_get_priv_key(const char *keydir, const char *name, 233 ENGINE *engine, RSA **rsap) 234 { 235 const char *engine_id; 236 char key_id[1024]; 237 EVP_PKEY *key; 238 RSA *rsa; 239 int ret; 240 241 *rsap = NULL; 242 243 engine_id = ENGINE_get_id(engine); 244 245 if (engine_id && !strcmp(engine_id, "pkcs11")) { 246 if (keydir) 247 snprintf(key_id, sizeof(key_id), 248 "pkcs11:%s;object=%s;type=private", 249 keydir, name); 250 else 251 snprintf(key_id, sizeof(key_id), 252 "pkcs11:object=%s;type=private", 253 name); 254 } else { 255 fprintf(stderr, "Engine not supported\n"); 256 return -ENOTSUP; 257 } 258 259 key = ENGINE_load_private_key(engine, key_id, NULL, NULL); 260 if (!key) 261 return rsa_err("Failure loading private key from engine"); 262 263 /* Convert to a RSA_style key. */ 264 rsa = EVP_PKEY_get1_RSA(key); 265 if (!rsa) { 266 rsa_err("Couldn't convert to a RSA style key"); 267 ret = -EINVAL; 268 goto err_rsa; 269 } 270 271 EVP_PKEY_free(key); 272 *rsap = rsa; 273 274 return 0; 275 276 err_rsa: 277 EVP_PKEY_free(key); 278 return ret; 279 } 280 281 /** 282 * rsa_get_priv_key() - read a private key 283 * 284 * @keydir: Directory containing the key (PEM file) or key prefix (engine) 285 * @name Name of key 286 * @engine Engine to use for signing 287 * @rsap Returns RSA object, or NULL on failure 288 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL) 289 */ 290 static int rsa_get_priv_key(const char *keydir, const char *name, 291 ENGINE *engine, RSA **rsap) 292 { 293 if (engine) 294 return rsa_engine_get_priv_key(keydir, name, engine, rsap); 295 return rsa_pem_get_priv_key(keydir, name, rsap); 296 } 297 298 static int rsa_init(void) 299 { 300 int ret; 301 302 #if OPENSSL_VERSION_NUMBER < 0x10100000L 303 ret = SSL_library_init(); 304 #else 305 ret = OPENSSL_init_ssl(0, NULL); 306 #endif 307 if (!ret) { 308 fprintf(stderr, "Failure to init SSL library\n"); 309 return -1; 310 } 311 #if OPENSSL_VERSION_NUMBER < 0x10100000L 312 SSL_load_error_strings(); 313 314 OpenSSL_add_all_algorithms(); 315 OpenSSL_add_all_digests(); 316 OpenSSL_add_all_ciphers(); 317 #endif 318 319 return 0; 320 } 321 322 static int rsa_engine_init(const char *engine_id, ENGINE **pe) 323 { 324 ENGINE *e; 325 int ret; 326 327 ENGINE_load_builtin_engines(); 328 329 e = ENGINE_by_id(engine_id); 330 if (!e) { 331 fprintf(stderr, "Engine isn't available\n"); 332 ret = -1; 333 goto err_engine_by_id; 334 } 335 336 if (!ENGINE_init(e)) { 337 fprintf(stderr, "Couldn't initialize engine\n"); 338 ret = -1; 339 goto err_engine_init; 340 } 341 342 if (!ENGINE_set_default_RSA(e)) { 343 fprintf(stderr, "Couldn't set engine as default for RSA\n"); 344 ret = -1; 345 goto err_set_rsa; 346 } 347 348 *pe = e; 349 350 return 0; 351 352 err_set_rsa: 353 ENGINE_finish(e); 354 err_engine_init: 355 ENGINE_free(e); 356 err_engine_by_id: 357 #if OPENSSL_VERSION_NUMBER < 0x10100000L 358 ENGINE_cleanup(); 359 #endif 360 return ret; 361 } 362 363 static void rsa_remove(void) 364 { 365 #if OPENSSL_VERSION_NUMBER < 0x10100000L 366 CRYPTO_cleanup_all_ex_data(); 367 ERR_free_strings(); 368 #ifdef HAVE_ERR_REMOVE_THREAD_STATE 369 ERR_remove_thread_state(NULL); 370 #else 371 ERR_remove_state(0); 372 #endif 373 EVP_cleanup(); 374 #endif 375 } 376 377 static void rsa_engine_remove(ENGINE *e) 378 { 379 if (e) { 380 ENGINE_finish(e); 381 ENGINE_free(e); 382 } 383 } 384 385 static int rsa_sign_with_key(RSA *rsa, struct checksum_algo *checksum_algo, 386 const struct image_region region[], int region_count, 387 uint8_t **sigp, uint *sig_size) 388 { 389 EVP_PKEY *key; 390 EVP_MD_CTX *context; 391 int size, ret = 0; 392 uint8_t *sig; 393 int i; 394 395 key = EVP_PKEY_new(); 396 if (!key) 397 return rsa_err("EVP_PKEY object creation failed"); 398 399 if (!EVP_PKEY_set1_RSA(key, rsa)) { 400 ret = rsa_err("EVP key setup failed"); 401 goto err_set; 402 } 403 404 size = EVP_PKEY_size(key); 405 sig = malloc(size); 406 if (!sig) { 407 fprintf(stderr, "Out of memory for signature (%d bytes)\n", 408 size); 409 ret = -ENOMEM; 410 goto err_alloc; 411 } 412 413 context = EVP_MD_CTX_create(); 414 if (!context) { 415 ret = rsa_err("EVP context creation failed"); 416 goto err_create; 417 } 418 EVP_MD_CTX_init(context); 419 if (!EVP_SignInit(context, checksum_algo->calculate_sign())) { 420 ret = rsa_err("Signer setup failed"); 421 goto err_sign; 422 } 423 424 for (i = 0; i < region_count; i++) { 425 if (!EVP_SignUpdate(context, region[i].data, region[i].size)) { 426 ret = rsa_err("Signing data failed"); 427 goto err_sign; 428 } 429 } 430 431 if (!EVP_SignFinal(context, sig, sig_size, key)) { 432 ret = rsa_err("Could not obtain signature"); 433 goto err_sign; 434 } 435 #if OPENSSL_VERSION_NUMBER < 0x10100000L 436 EVP_MD_CTX_cleanup(context); 437 #else 438 EVP_MD_CTX_reset(context); 439 #endif 440 EVP_MD_CTX_destroy(context); 441 EVP_PKEY_free(key); 442 443 debug("Got signature: %d bytes, expected %d\n", *sig_size, size); 444 *sigp = sig; 445 *sig_size = size; 446 447 return 0; 448 449 err_sign: 450 EVP_MD_CTX_destroy(context); 451 err_create: 452 free(sig); 453 err_alloc: 454 err_set: 455 EVP_PKEY_free(key); 456 return ret; 457 } 458 459 int rsa_sign(struct image_sign_info *info, 460 const struct image_region region[], int region_count, 461 uint8_t **sigp, uint *sig_len) 462 { 463 RSA *rsa; 464 ENGINE *e = NULL; 465 int ret; 466 467 ret = rsa_init(); 468 if (ret) 469 return ret; 470 471 if (info->engine_id) { 472 ret = rsa_engine_init(info->engine_id, &e); 473 if (ret) 474 goto err_engine; 475 } 476 477 ret = rsa_get_priv_key(info->keydir, info->keyname, e, &rsa); 478 if (ret) 479 goto err_priv; 480 ret = rsa_sign_with_key(rsa, info->checksum, region, 481 region_count, sigp, sig_len); 482 if (ret) 483 goto err_sign; 484 485 RSA_free(rsa); 486 if (info->engine_id) 487 rsa_engine_remove(e); 488 rsa_remove(); 489 490 return ret; 491 492 err_sign: 493 RSA_free(rsa); 494 err_priv: 495 if (info->engine_id) 496 rsa_engine_remove(e); 497 err_engine: 498 rsa_remove(); 499 return ret; 500 } 501 502 /* 503 * rsa_get_exponent(): - Get the public exponent from an RSA key 504 */ 505 static int rsa_get_exponent(RSA *key, uint64_t *e) 506 { 507 int ret; 508 BIGNUM *bn_te; 509 const BIGNUM *key_e; 510 uint64_t te; 511 512 ret = -EINVAL; 513 bn_te = NULL; 514 515 if (!e) 516 goto cleanup; 517 518 RSA_get0_key(key, NULL, &key_e, NULL); 519 if (BN_num_bits(key_e) > 64) 520 goto cleanup; 521 522 *e = BN_get_word(key_e); 523 524 if (BN_num_bits(key_e) < 33) { 525 ret = 0; 526 goto cleanup; 527 } 528 529 bn_te = BN_dup(key_e); 530 if (!bn_te) 531 goto cleanup; 532 533 if (!BN_rshift(bn_te, bn_te, 32)) 534 goto cleanup; 535 536 if (!BN_mask_bits(bn_te, 32)) 537 goto cleanup; 538 539 te = BN_get_word(bn_te); 540 te <<= 32; 541 *e |= te; 542 ret = 0; 543 544 cleanup: 545 if (bn_te) 546 BN_free(bn_te); 547 548 return ret; 549 } 550 551 /* 552 * rsa_get_params(): - Get the important parameters of an RSA public key 553 */ 554 int rsa_get_params(RSA *key, uint64_t *exponent, uint32_t *n0_invp, 555 BIGNUM **modulusp, BIGNUM **r_squaredp) 556 { 557 BIGNUM *big1, *big2, *big32, *big2_32; 558 BIGNUM *n, *r, *r_squared, *tmp; 559 const BIGNUM *key_n; 560 BN_CTX *bn_ctx = BN_CTX_new(); 561 int ret = 0; 562 563 /* Initialize BIGNUMs */ 564 big1 = BN_new(); 565 big2 = BN_new(); 566 big32 = BN_new(); 567 r = BN_new(); 568 r_squared = BN_new(); 569 tmp = BN_new(); 570 big2_32 = BN_new(); 571 n = BN_new(); 572 if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 || 573 !n) { 574 fprintf(stderr, "Out of memory (bignum)\n"); 575 return -ENOMEM; 576 } 577 578 if (0 != rsa_get_exponent(key, exponent)) 579 ret = -1; 580 581 RSA_get0_key(key, &key_n, NULL, NULL); 582 if (!BN_copy(n, key_n) || !BN_set_word(big1, 1L) || 583 !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L)) 584 ret = -1; 585 586 /* big2_32 = 2^32 */ 587 if (!BN_exp(big2_32, big2, big32, bn_ctx)) 588 ret = -1; 589 590 /* Calculate n0_inv = -1 / n[0] mod 2^32 */ 591 if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) || 592 !BN_sub(tmp, big2_32, tmp)) 593 ret = -1; 594 *n0_invp = BN_get_word(tmp); 595 596 /* Calculate R = 2^(# of key bits) */ 597 if (!BN_set_word(tmp, BN_num_bits(n)) || 598 !BN_exp(r, big2, tmp, bn_ctx)) 599 ret = -1; 600 601 /* Calculate r_squared = R^2 mod n */ 602 if (!BN_copy(r_squared, r) || 603 !BN_mul(tmp, r_squared, r, bn_ctx) || 604 !BN_mod(r_squared, tmp, n, bn_ctx)) 605 ret = -1; 606 607 *modulusp = n; 608 *r_squaredp = r_squared; 609 610 BN_free(big1); 611 BN_free(big2); 612 BN_free(big32); 613 BN_free(r); 614 BN_free(tmp); 615 BN_free(big2_32); 616 if (ret) { 617 fprintf(stderr, "Bignum operations failed\n"); 618 return -ENOMEM; 619 } 620 621 return ret; 622 } 623 624 static int fdt_add_bignum(void *blob, int noffset, const char *prop_name, 625 BIGNUM *num, int num_bits) 626 { 627 int nwords = num_bits / 32; 628 int size; 629 uint32_t *buf, *ptr; 630 BIGNUM *tmp, *big2, *big32, *big2_32; 631 BN_CTX *ctx; 632 int ret; 633 634 tmp = BN_new(); 635 big2 = BN_new(); 636 big32 = BN_new(); 637 big2_32 = BN_new(); 638 if (!tmp || !big2 || !big32 || !big2_32) { 639 fprintf(stderr, "Out of memory (bignum)\n"); 640 return -ENOMEM; 641 } 642 ctx = BN_CTX_new(); 643 if (!tmp) { 644 fprintf(stderr, "Out of memory (bignum context)\n"); 645 return -ENOMEM; 646 } 647 BN_set_word(big2, 2L); 648 BN_set_word(big32, 32L); 649 BN_exp(big2_32, big2, big32, ctx); /* B = 2^32 */ 650 651 size = nwords * sizeof(uint32_t); 652 buf = malloc(size); 653 if (!buf) { 654 fprintf(stderr, "Out of memory (%d bytes)\n", size); 655 return -ENOMEM; 656 } 657 658 /* Write out modulus as big endian array of integers */ 659 for (ptr = buf + nwords - 1; ptr >= buf; ptr--) { 660 BN_mod(tmp, num, big2_32, ctx); /* n = N mod B */ 661 *ptr = cpu_to_fdt32(BN_get_word(tmp)); 662 BN_rshift(num, num, 32); /* N = N/B */ 663 } 664 665 /* 666 * We try signing with successively increasing size values, so this 667 * might fail several times 668 */ 669 ret = fdt_setprop(blob, noffset, prop_name, buf, size); 670 if (ret) 671 return -FDT_ERR_NOSPACE; 672 free(buf); 673 BN_free(tmp); 674 BN_free(big2); 675 BN_free(big32); 676 BN_free(big2_32); 677 678 return ret; 679 } 680 681 int rsa_add_verify_data(struct image_sign_info *info, void *keydest) 682 { 683 BIGNUM *modulus, *r_squared; 684 uint64_t exponent; 685 uint32_t n0_inv; 686 int parent, node; 687 char name[100]; 688 int ret; 689 int bits; 690 RSA *rsa; 691 ENGINE *e = NULL; 692 693 debug("%s: Getting verification data\n", __func__); 694 if (info->engine_id) { 695 ret = rsa_engine_init(info->engine_id, &e); 696 if (ret) 697 return ret; 698 } 699 ret = rsa_get_pub_key(info->keydir, info->keyname, e, &rsa); 700 if (ret) 701 goto err_get_pub_key; 702 ret = rsa_get_params(rsa, &exponent, &n0_inv, &modulus, &r_squared); 703 if (ret) 704 goto err_get_params; 705 bits = BN_num_bits(modulus); 706 parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME); 707 if (parent == -FDT_ERR_NOTFOUND) { 708 parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME); 709 if (parent < 0) { 710 ret = parent; 711 if (ret != -FDT_ERR_NOSPACE) { 712 fprintf(stderr, "Couldn't create signature node: %s\n", 713 fdt_strerror(parent)); 714 } 715 } 716 } 717 if (ret) 718 goto done; 719 720 /* Either create or overwrite the named key node */ 721 snprintf(name, sizeof(name), "key-%s", info->keyname); 722 node = fdt_subnode_offset(keydest, parent, name); 723 if (node == -FDT_ERR_NOTFOUND) { 724 node = fdt_add_subnode(keydest, parent, name); 725 if (node < 0) { 726 ret = node; 727 if (ret != -FDT_ERR_NOSPACE) { 728 fprintf(stderr, "Could not create key subnode: %s\n", 729 fdt_strerror(node)); 730 } 731 } 732 } else if (node < 0) { 733 fprintf(stderr, "Cannot select keys parent: %s\n", 734 fdt_strerror(node)); 735 ret = node; 736 } 737 738 if (!ret) { 739 ret = fdt_setprop_string(keydest, node, "key-name-hint", 740 info->keyname); 741 } 742 if (!ret) 743 ret = fdt_setprop_u32(keydest, node, "rsa,num-bits", bits); 744 if (!ret) 745 ret = fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv); 746 if (!ret) { 747 ret = fdt_setprop_u64(keydest, node, "rsa,exponent", exponent); 748 } 749 if (!ret) { 750 ret = fdt_add_bignum(keydest, node, "rsa,modulus", modulus, 751 bits); 752 } 753 if (!ret) { 754 ret = fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared, 755 bits); 756 } 757 if (!ret) { 758 ret = fdt_setprop_string(keydest, node, FIT_ALGO_PROP, 759 info->name); 760 } 761 if (!ret && info->require_keys) { 762 ret = fdt_setprop_string(keydest, node, "required", 763 info->require_keys); 764 } 765 done: 766 BN_free(modulus); 767 BN_free(r_squared); 768 if (ret) 769 ret = ret == -FDT_ERR_NOSPACE ? -ENOSPC : -EIO; 770 err_get_params: 771 RSA_free(rsa); 772 err_get_pub_key: 773 if (info->engine_id) 774 rsa_engine_remove(e); 775 776 return ret; 777 } 778