1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright (c) 2013, Google Inc.
12 #include <u-boot/fdt-libcrypto.h>
13 #include <openssl/bn.h>
14 #include <openssl/rsa.h>
15 #include <openssl/pem.h>
16 #include <openssl/err.h>
17 #include <openssl/ssl.h>
18 #include <openssl/evp.h>
19 #include <openssl/engine.h>
21 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
22 #define HAVE_ERR_REMOVE_THREAD_STATE
25 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
26 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
27 static void RSA_get0_key(const RSA *r,
28 const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
39 static int rsa_err(const char *msg)
41 unsigned long sslErr = ERR_get_error();
43 fprintf(stderr, "%s", msg);
44 fprintf(stderr, ": %s\n",
45 ERR_error_string(sslErr, 0));
51 * rsa_pem_get_pub_key() - read a public key from a .crt file
53 * @keydir: Directory containins the key
54 * @name Name of key file (will have a .crt extension)
55 * @rsap Returns RSA object, or NULL on failure
56 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
58 static int rsa_pem_get_pub_key(const char *keydir, const char *name, RSA **rsap)
68 snprintf(path, sizeof(path), "%s/%s.crt", keydir, name);
71 fprintf(stderr, "Couldn't open RSA certificate: '%s': %s\n",
72 path, strerror(errno));
76 /* Read the certificate */
78 if (!PEM_read_X509(f, &cert, NULL, NULL)) {
79 rsa_err("Couldn't read certificate");
84 /* Get the public key from the certificate. */
85 key = X509_get_pubkey(cert);
87 rsa_err("Couldn't read public key\n");
92 /* Convert to a RSA_style key. */
93 rsa = EVP_PKEY_get1_RSA(key);
95 rsa_err("Couldn't convert to a RSA style key");
116 * rsa_engine_get_pub_key() - read a public key from given engine
118 * @keydir: Key prefix
120 * @engine Engine to use
121 * @rsap Returns RSA object, or NULL on failure
122 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
124 static int rsa_engine_get_pub_key(const char *keydir, const char *name,
125 ENGINE *engine, RSA **rsap)
127 const char *engine_id;
135 engine_id = ENGINE_get_id(engine);
137 if (engine_id && !strcmp(engine_id, "pkcs11")) {
139 if (strstr(keydir, "object="))
140 snprintf(key_id, sizeof(key_id),
141 "pkcs11:%s;type=public",
144 snprintf(key_id, sizeof(key_id),
145 "pkcs11:%s;object=%s;type=public",
148 snprintf(key_id, sizeof(key_id),
149 "pkcs11:object=%s;type=public",
151 } else if (engine_id) {
153 snprintf(key_id, sizeof(key_id),
157 snprintf(key_id, sizeof(key_id),
161 fprintf(stderr, "Engine not supported\n");
165 key = ENGINE_load_public_key(engine, key_id, NULL, NULL);
167 return rsa_err("Failure loading public key from engine");
169 /* Convert to a RSA_style key. */
170 rsa = EVP_PKEY_get1_RSA(key);
172 rsa_err("Couldn't convert to a RSA style key");
188 * rsa_get_pub_key() - read a public key
190 * @keydir: Directory containing the key (PEM file) or key prefix (engine)
191 * @name Name of key file (will have a .crt extension)
192 * @engine Engine to use
193 * @rsap Returns RSA object, or NULL on failure
194 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
196 static int rsa_get_pub_key(const char *keydir, const char *name,
197 ENGINE *engine, RSA **rsap)
200 return rsa_engine_get_pub_key(keydir, name, engine, rsap);
201 return rsa_pem_get_pub_key(keydir, name, rsap);
205 * rsa_pem_get_priv_key() - read a private key from a .key file
207 * @keydir: Directory containing the key
208 * @name Name of key file (will have a .key extension)
209 * @rsap Returns RSA object, or NULL on failure
210 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
212 static int rsa_pem_get_priv_key(const char *keydir, const char *name,
213 const char *keyfile, RSA **rsap)
221 snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
223 snprintf(path, sizeof(path), "%s", keyfile);
227 f = fopen(path, "r");
229 fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
230 path, strerror(errno));
234 rsa = PEM_read_RSAPrivateKey(f, 0, NULL, path);
236 rsa_err("Failure reading private key");
247 * rsa_engine_get_priv_key() - read a private key from given engine
249 * @keydir: Key prefix
251 * @engine Engine to use
252 * @rsap Returns RSA object, or NULL on failure
253 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
255 static int rsa_engine_get_priv_key(const char *keydir, const char *name,
257 ENGINE *engine, RSA **rsap)
259 const char *engine_id;
267 engine_id = ENGINE_get_id(engine);
269 if (engine_id && !strcmp(engine_id, "pkcs11")) {
270 if (!keydir && !name) {
271 fprintf(stderr, "Please use 'keydir' with PKCS11\n");
275 if (strstr(keydir, "object="))
276 snprintf(key_id, sizeof(key_id),
277 "pkcs11:%s;type=private",
280 snprintf(key_id, sizeof(key_id),
281 "pkcs11:%s;object=%s;type=private",
284 snprintf(key_id, sizeof(key_id),
285 "pkcs11:object=%s;type=private",
287 } else if (engine_id) {
289 snprintf(key_id, sizeof(key_id),
293 snprintf(key_id, sizeof(key_id),
297 snprintf(key_id, sizeof(key_id), "%s", keyfile);
302 fprintf(stderr, "Engine not supported\n");
306 key = ENGINE_load_private_key(engine, key_id, NULL, NULL);
308 return rsa_err("Failure loading private key from engine");
310 /* Convert to a RSA_style key. */
311 rsa = EVP_PKEY_get1_RSA(key);
313 rsa_err("Couldn't convert to a RSA style key");
329 * rsa_get_priv_key() - read a private key
331 * @keydir: Directory containing the key (PEM file) or key prefix (engine)
333 * @engine Engine to use for signing
334 * @rsap Returns RSA object, or NULL on failure
335 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
337 static int rsa_get_priv_key(const char *keydir, const char *name,
338 const char *keyfile, ENGINE *engine, RSA **rsap)
341 return rsa_engine_get_priv_key(keydir, name, keyfile, engine,
343 return rsa_pem_get_priv_key(keydir, name, keyfile, rsap);
346 static int rsa_init(void)
350 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
351 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
352 ret = SSL_library_init();
354 ret = OPENSSL_init_ssl(0, NULL);
357 fprintf(stderr, "Failure to init SSL library\n");
360 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
361 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
362 SSL_load_error_strings();
364 OpenSSL_add_all_algorithms();
365 OpenSSL_add_all_digests();
366 OpenSSL_add_all_ciphers();
372 static int rsa_engine_init(const char *engine_id, ENGINE **pe)
377 ENGINE_load_builtin_engines();
379 e = ENGINE_by_id(engine_id);
381 fprintf(stderr, "Engine isn't available\n");
383 goto err_engine_by_id;
386 if (!ENGINE_init(e)) {
387 fprintf(stderr, "Couldn't initialize engine\n");
389 goto err_engine_init;
392 if (!ENGINE_set_default_RSA(e)) {
393 fprintf(stderr, "Couldn't set engine as default for RSA\n");
407 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
408 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
414 static void rsa_remove(void)
416 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
417 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
418 CRYPTO_cleanup_all_ex_data();
420 #ifdef HAVE_ERR_REMOVE_THREAD_STATE
421 ERR_remove_thread_state(NULL);
429 static void rsa_engine_remove(ENGINE *e)
437 static int rsa_sign_with_key(RSA *rsa, struct padding_algo *padding_algo,
438 struct checksum_algo *checksum_algo,
439 const struct image_region region[], int region_count,
440 uint8_t **sigp, uint *sig_size)
450 key = EVP_PKEY_new();
452 return rsa_err("EVP_PKEY object creation failed");
454 if (!EVP_PKEY_set1_RSA(key, rsa)) {
455 ret = rsa_err("EVP key setup failed");
459 size = EVP_PKEY_size(key);
462 fprintf(stderr, "Out of memory for signature (%zu bytes)\n",
468 context = EVP_MD_CTX_create();
470 ret = rsa_err("EVP context creation failed");
473 EVP_MD_CTX_init(context);
475 ckey = EVP_PKEY_CTX_new(key, NULL);
477 ret = rsa_err("EVP key context creation failed");
481 if (EVP_DigestSignInit(context, &ckey,
482 checksum_algo->calculate_sign(),
484 ret = rsa_err("Signer setup failed");
488 #ifdef CONFIG_FIT_ENABLE_RSASSA_PSS_SUPPORT
489 if (padding_algo && !strcmp(padding_algo->name, "pss")) {
490 if (EVP_PKEY_CTX_set_rsa_padding(ckey,
491 RSA_PKCS1_PSS_PADDING) <= 0) {
492 ret = rsa_err("Signer padding setup failed");
496 #endif /* CONFIG_FIT_ENABLE_RSASSA_PSS_SUPPORT */
498 for (i = 0; i < region_count; i++) {
499 if (!EVP_DigestSignUpdate(context, region[i].data,
501 ret = rsa_err("Signing data failed");
506 if (!EVP_DigestSignFinal(context, sig, &size)) {
507 ret = rsa_err("Could not obtain signature");
511 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
512 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
513 EVP_MD_CTX_cleanup(context);
515 EVP_MD_CTX_reset(context);
517 EVP_MD_CTX_destroy(context);
520 debug("Got signature: %d bytes, expected %zu\n", *sig_size, size);
527 EVP_MD_CTX_destroy(context);
536 int rsa_sign(struct image_sign_info *info,
537 const struct image_region region[], int region_count,
538 uint8_t **sigp, uint *sig_len)
548 if (info->engine_id) {
549 ret = rsa_engine_init(info->engine_id, &e);
554 ret = rsa_get_priv_key(info->keydir, info->keyname, info->keyfile,
558 ret = rsa_sign_with_key(rsa, info->padding, info->checksum, region,
559 region_count, sigp, sig_len);
565 rsa_engine_remove(e);
574 rsa_engine_remove(e);
581 * rsa_get_exponent(): - Get the public exponent from an RSA key
583 static int rsa_get_exponent(RSA *key, uint64_t *e)
596 RSA_get0_key(key, NULL, &key_e, NULL);
597 if (BN_num_bits(key_e) > 64)
600 *e = BN_get_word(key_e);
602 if (BN_num_bits(key_e) < 33) {
607 bn_te = BN_dup(key_e);
611 if (!BN_rshift(bn_te, bn_te, 32))
614 if (!BN_mask_bits(bn_te, 32))
617 te = BN_get_word(bn_te);
630 * rsa_get_params(): - Get the important parameters of an RSA public key
632 int rsa_get_params(RSA *key, uint64_t *exponent, uint32_t *n0_invp,
633 BIGNUM **modulusp, BIGNUM **r_squaredp)
635 BIGNUM *big1, *big2, *big32, *big2_32;
636 BIGNUM *n, *r, *r_squared, *tmp;
638 BN_CTX *bn_ctx = BN_CTX_new();
641 /* Initialize BIGNUMs */
646 r_squared = BN_new();
650 if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 ||
652 fprintf(stderr, "Out of memory (bignum)\n");
656 if (0 != rsa_get_exponent(key, exponent))
659 RSA_get0_key(key, &key_n, NULL, NULL);
660 if (!BN_copy(n, key_n) || !BN_set_word(big1, 1L) ||
661 !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L))
665 if (!BN_exp(big2_32, big2, big32, bn_ctx))
668 /* Calculate n0_inv = -1 / n[0] mod 2^32 */
669 if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) ||
670 !BN_sub(tmp, big2_32, tmp))
672 *n0_invp = BN_get_word(tmp);
674 /* Calculate R = 2^(# of key bits) */
675 if (!BN_set_word(tmp, BN_num_bits(n)) ||
676 !BN_exp(r, big2, tmp, bn_ctx))
679 /* Calculate r_squared = R^2 mod n */
680 if (!BN_copy(r_squared, r) ||
681 !BN_mul(tmp, r_squared, r, bn_ctx) ||
682 !BN_mod(r_squared, tmp, n, bn_ctx))
686 *r_squaredp = r_squared;
695 fprintf(stderr, "Bignum operations failed\n");
702 int rsa_add_verify_data(struct image_sign_info *info, void *keydest)
704 BIGNUM *modulus, *r_squared;
714 debug("%s: Getting verification data\n", __func__);
715 if (info->engine_id) {
716 ret = rsa_engine_init(info->engine_id, &e);
720 ret = rsa_get_pub_key(info->keydir, info->keyname, e, &rsa);
722 goto err_get_pub_key;
723 ret = rsa_get_params(rsa, &exponent, &n0_inv, &modulus, &r_squared);
726 bits = BN_num_bits(modulus);
727 parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME);
728 if (parent == -FDT_ERR_NOTFOUND) {
729 parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME);
732 if (ret != -FDT_ERR_NOSPACE) {
733 fprintf(stderr, "Couldn't create signature node: %s\n",
734 fdt_strerror(parent));
741 /* Either create or overwrite the named key node */
742 snprintf(name, sizeof(name), "key-%s", info->keyname);
743 node = fdt_subnode_offset(keydest, parent, name);
744 if (node == -FDT_ERR_NOTFOUND) {
745 node = fdt_add_subnode(keydest, parent, name);
748 if (ret != -FDT_ERR_NOSPACE) {
749 fprintf(stderr, "Could not create key subnode: %s\n",
753 } else if (node < 0) {
754 fprintf(stderr, "Cannot select keys parent: %s\n",
760 ret = fdt_setprop_string(keydest, node, FIT_KEY_HINT,
764 ret = fdt_setprop_u32(keydest, node, "rsa,num-bits", bits);
766 ret = fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv);
768 ret = fdt_setprop_u64(keydest, node, "rsa,exponent", exponent);
771 ret = fdt_add_bignum(keydest, node, "rsa,modulus", modulus,
775 ret = fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared,
779 ret = fdt_setprop_string(keydest, node, FIT_ALGO_PROP,
782 if (!ret && info->require_keys) {
783 ret = fdt_setprop_string(keydest, node, FIT_KEY_REQUIRED,
790 ret = ret == -FDT_ERR_NOSPACE ? -ENOSPC : -EIO;
795 rsa_engine_remove(e);