1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright (c) 2013, Google Inc.
12 #include <openssl/bn.h>
13 #include <openssl/rsa.h>
14 #include <openssl/pem.h>
15 #include <openssl/err.h>
16 #include <openssl/ssl.h>
17 #include <openssl/evp.h>
18 #include <openssl/engine.h>
20 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
21 #define HAVE_ERR_REMOVE_THREAD_STATE
24 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
25 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
26 static void RSA_get0_key(const RSA *r,
27 const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
38 static int rsa_err(const char *msg)
40 unsigned long sslErr = ERR_get_error();
42 fprintf(stderr, "%s", msg);
43 fprintf(stderr, ": %s\n",
44 ERR_error_string(sslErr, 0));
50 * rsa_pem_get_pub_key() - read a public key from a .crt file
52 * @keydir: Directory containins the key
53 * @name Name of key file (will have a .crt extension)
54 * @rsap Returns RSA object, or NULL on failure
55 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
57 static int rsa_pem_get_pub_key(const char *keydir, const char *name, RSA **rsap)
67 snprintf(path, sizeof(path), "%s/%s.crt", keydir, name);
70 fprintf(stderr, "Couldn't open RSA certificate: '%s': %s\n",
71 path, strerror(errno));
75 /* Read the certificate */
77 if (!PEM_read_X509(f, &cert, NULL, NULL)) {
78 rsa_err("Couldn't read certificate");
83 /* Get the public key from the certificate. */
84 key = X509_get_pubkey(cert);
86 rsa_err("Couldn't read public key\n");
91 /* Convert to a RSA_style key. */
92 rsa = EVP_PKEY_get1_RSA(key);
94 rsa_err("Couldn't convert to a RSA style key");
115 * rsa_engine_get_pub_key() - read a public key from given engine
117 * @keydir: Key prefix
119 * @engine Engine to use
120 * @rsap Returns RSA object, or NULL on failure
121 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
123 static int rsa_engine_get_pub_key(const char *keydir, const char *name,
124 ENGINE *engine, RSA **rsap)
126 const char *engine_id;
134 engine_id = ENGINE_get_id(engine);
136 if (engine_id && !strcmp(engine_id, "pkcs11")) {
138 snprintf(key_id, sizeof(key_id),
139 "pkcs11:%s;object=%s;type=public",
142 snprintf(key_id, sizeof(key_id),
143 "pkcs11:object=%s;type=public",
145 } else if (engine_id) {
147 snprintf(key_id, sizeof(key_id),
151 snprintf(key_id, sizeof(key_id),
155 fprintf(stderr, "Engine not supported\n");
159 key = ENGINE_load_public_key(engine, key_id, NULL, NULL);
161 return rsa_err("Failure loading public key from engine");
163 /* Convert to a RSA_style key. */
164 rsa = EVP_PKEY_get1_RSA(key);
166 rsa_err("Couldn't convert to a RSA style key");
182 * rsa_get_pub_key() - read a public key
184 * @keydir: Directory containing the key (PEM file) or key prefix (engine)
185 * @name Name of key file (will have a .crt extension)
186 * @engine Engine to use
187 * @rsap Returns RSA object, or NULL on failure
188 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
190 static int rsa_get_pub_key(const char *keydir, const char *name,
191 ENGINE *engine, RSA **rsap)
194 return rsa_engine_get_pub_key(keydir, name, engine, rsap);
195 return rsa_pem_get_pub_key(keydir, name, rsap);
199 * rsa_pem_get_priv_key() - read a private key from a .key file
201 * @keydir: Directory containing the key
202 * @name Name of key file (will have a .key extension)
203 * @rsap Returns RSA object, or NULL on failure
204 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
206 static int rsa_pem_get_priv_key(const char *keydir, const char *name,
214 snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
215 f = fopen(path, "r");
217 fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
218 path, strerror(errno));
222 rsa = PEM_read_RSAPrivateKey(f, 0, NULL, path);
224 rsa_err("Failure reading private key");
235 * rsa_engine_get_priv_key() - read a private key from given engine
237 * @keydir: Key prefix
239 * @engine Engine to use
240 * @rsap Returns RSA object, or NULL on failure
241 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
243 static int rsa_engine_get_priv_key(const char *keydir, const char *name,
244 ENGINE *engine, RSA **rsap)
246 const char *engine_id;
254 engine_id = ENGINE_get_id(engine);
256 if (engine_id && !strcmp(engine_id, "pkcs11")) {
258 snprintf(key_id, sizeof(key_id),
259 "pkcs11:%s;object=%s;type=private",
262 snprintf(key_id, sizeof(key_id),
263 "pkcs11:object=%s;type=private",
265 } else if (engine_id) {
267 snprintf(key_id, sizeof(key_id),
271 snprintf(key_id, sizeof(key_id),
275 fprintf(stderr, "Engine not supported\n");
279 key = ENGINE_load_private_key(engine, key_id, NULL, NULL);
281 return rsa_err("Failure loading private key from engine");
283 /* Convert to a RSA_style key. */
284 rsa = EVP_PKEY_get1_RSA(key);
286 rsa_err("Couldn't convert to a RSA style key");
302 * rsa_get_priv_key() - read a private key
304 * @keydir: Directory containing the key (PEM file) or key prefix (engine)
306 * @engine Engine to use for signing
307 * @rsap Returns RSA object, or NULL on failure
308 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
310 static int rsa_get_priv_key(const char *keydir, const char *name,
311 ENGINE *engine, RSA **rsap)
314 return rsa_engine_get_priv_key(keydir, name, engine, rsap);
315 return rsa_pem_get_priv_key(keydir, name, rsap);
318 static int rsa_init(void)
322 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
323 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
324 ret = SSL_library_init();
326 ret = OPENSSL_init_ssl(0, NULL);
329 fprintf(stderr, "Failure to init SSL library\n");
332 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
333 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
334 SSL_load_error_strings();
336 OpenSSL_add_all_algorithms();
337 OpenSSL_add_all_digests();
338 OpenSSL_add_all_ciphers();
344 static int rsa_engine_init(const char *engine_id, ENGINE **pe)
349 ENGINE_load_builtin_engines();
351 e = ENGINE_by_id(engine_id);
353 fprintf(stderr, "Engine isn't available\n");
355 goto err_engine_by_id;
358 if (!ENGINE_init(e)) {
359 fprintf(stderr, "Couldn't initialize engine\n");
361 goto err_engine_init;
364 if (!ENGINE_set_default_RSA(e)) {
365 fprintf(stderr, "Couldn't set engine as default for RSA\n");
379 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
380 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
386 static void rsa_remove(void)
388 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
389 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
390 CRYPTO_cleanup_all_ex_data();
392 #ifdef HAVE_ERR_REMOVE_THREAD_STATE
393 ERR_remove_thread_state(NULL);
401 static void rsa_engine_remove(ENGINE *e)
409 static int rsa_sign_with_key(RSA *rsa, struct padding_algo *padding_algo,
410 struct checksum_algo *checksum_algo,
411 const struct image_region region[], int region_count,
412 uint8_t **sigp, uint *sig_size)
422 key = EVP_PKEY_new();
424 return rsa_err("EVP_PKEY object creation failed");
426 if (!EVP_PKEY_set1_RSA(key, rsa)) {
427 ret = rsa_err("EVP key setup failed");
431 size = EVP_PKEY_size(key);
434 fprintf(stderr, "Out of memory for signature (%zu bytes)\n",
440 context = EVP_MD_CTX_create();
442 ret = rsa_err("EVP context creation failed");
445 EVP_MD_CTX_init(context);
447 ckey = EVP_PKEY_CTX_new(key, NULL);
449 ret = rsa_err("EVP key context creation failed");
453 if (EVP_DigestSignInit(context, &ckey,
454 checksum_algo->calculate_sign(),
456 ret = rsa_err("Signer setup failed");
460 #ifdef CONFIG_FIT_ENABLE_RSASSA_PSS_SUPPORT
461 if (padding_algo && !strcmp(padding_algo->name, "pss")) {
462 if (EVP_PKEY_CTX_set_rsa_padding(ckey,
463 RSA_PKCS1_PSS_PADDING) <= 0) {
464 ret = rsa_err("Signer padding setup failed");
468 #endif /* CONFIG_FIT_ENABLE_RSASSA_PSS_SUPPORT */
470 for (i = 0; i < region_count; i++) {
471 if (!EVP_DigestSignUpdate(context, region[i].data,
473 ret = rsa_err("Signing data failed");
478 if (!EVP_DigestSignFinal(context, sig, &size)) {
479 ret = rsa_err("Could not obtain signature");
483 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
484 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
485 EVP_MD_CTX_cleanup(context);
487 EVP_MD_CTX_reset(context);
489 EVP_MD_CTX_destroy(context);
492 debug("Got signature: %d bytes, expected %zu\n", *sig_size, size);
499 EVP_MD_CTX_destroy(context);
508 int rsa_sign(struct image_sign_info *info,
509 const struct image_region region[], int region_count,
510 uint8_t **sigp, uint *sig_len)
520 if (info->engine_id) {
521 ret = rsa_engine_init(info->engine_id, &e);
526 ret = rsa_get_priv_key(info->keydir, info->keyname, e, &rsa);
529 ret = rsa_sign_with_key(rsa, info->padding, info->checksum, region,
530 region_count, sigp, sig_len);
536 rsa_engine_remove(e);
545 rsa_engine_remove(e);
552 * rsa_get_exponent(): - Get the public exponent from an RSA key
554 static int rsa_get_exponent(RSA *key, uint64_t *e)
567 RSA_get0_key(key, NULL, &key_e, NULL);
568 if (BN_num_bits(key_e) > 64)
571 *e = BN_get_word(key_e);
573 if (BN_num_bits(key_e) < 33) {
578 bn_te = BN_dup(key_e);
582 if (!BN_rshift(bn_te, bn_te, 32))
585 if (!BN_mask_bits(bn_te, 32))
588 te = BN_get_word(bn_te);
601 * rsa_get_params(): - Get the important parameters of an RSA public key
603 int rsa_get_params(RSA *key, uint64_t *exponent, uint32_t *n0_invp,
604 BIGNUM **modulusp, BIGNUM **r_squaredp)
606 BIGNUM *big1, *big2, *big32, *big2_32;
607 BIGNUM *n, *r, *r_squared, *tmp;
609 BN_CTX *bn_ctx = BN_CTX_new();
612 /* Initialize BIGNUMs */
617 r_squared = BN_new();
621 if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 ||
623 fprintf(stderr, "Out of memory (bignum)\n");
627 if (0 != rsa_get_exponent(key, exponent))
630 RSA_get0_key(key, &key_n, NULL, NULL);
631 if (!BN_copy(n, key_n) || !BN_set_word(big1, 1L) ||
632 !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L))
636 if (!BN_exp(big2_32, big2, big32, bn_ctx))
639 /* Calculate n0_inv = -1 / n[0] mod 2^32 */
640 if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) ||
641 !BN_sub(tmp, big2_32, tmp))
643 *n0_invp = BN_get_word(tmp);
645 /* Calculate R = 2^(# of key bits) */
646 if (!BN_set_word(tmp, BN_num_bits(n)) ||
647 !BN_exp(r, big2, tmp, bn_ctx))
650 /* Calculate r_squared = R^2 mod n */
651 if (!BN_copy(r_squared, r) ||
652 !BN_mul(tmp, r_squared, r, bn_ctx) ||
653 !BN_mod(r_squared, tmp, n, bn_ctx))
657 *r_squaredp = r_squared;
666 fprintf(stderr, "Bignum operations failed\n");
673 static int fdt_add_bignum(void *blob, int noffset, const char *prop_name,
674 BIGNUM *num, int num_bits)
676 int nwords = num_bits / 32;
679 BIGNUM *tmp, *big2, *big32, *big2_32;
689 * Note: This code assumes that all of the above succeed, or all fail.
690 * In practice memory allocations generally do not fail (unless the
691 * process is killed), so it does not seem worth handling each of these
692 * as a separate case. Technicaly this could leak memory on failure,
693 * but a) it won't happen in practice, and b) it doesn't matter as we
694 * will immediately exit with a failure code.
696 if (!tmp || !big2 || !big32 || !big2_32) {
697 fprintf(stderr, "Out of memory (bignum)\n");
702 fprintf(stderr, "Out of memory (bignum context)\n");
705 BN_set_word(big2, 2L);
706 BN_set_word(big32, 32L);
707 BN_exp(big2_32, big2, big32, ctx); /* B = 2^32 */
709 size = nwords * sizeof(uint32_t);
712 fprintf(stderr, "Out of memory (%d bytes)\n", size);
716 /* Write out modulus as big endian array of integers */
717 for (ptr = buf + nwords - 1; ptr >= buf; ptr--) {
718 BN_mod(tmp, num, big2_32, ctx); /* n = N mod B */
719 *ptr = cpu_to_fdt32(BN_get_word(tmp));
720 BN_rshift(num, num, 32); /* N = N/B */
724 * We try signing with successively increasing size values, so this
725 * might fail several times
727 ret = fdt_setprop(blob, noffset, prop_name, buf, size);
734 return ret ? -FDT_ERR_NOSPACE : 0;
737 int rsa_add_verify_data(struct image_sign_info *info, void *keydest)
739 BIGNUM *modulus, *r_squared;
749 debug("%s: Getting verification data\n", __func__);
750 if (info->engine_id) {
751 ret = rsa_engine_init(info->engine_id, &e);
755 ret = rsa_get_pub_key(info->keydir, info->keyname, e, &rsa);
757 goto err_get_pub_key;
758 ret = rsa_get_params(rsa, &exponent, &n0_inv, &modulus, &r_squared);
761 bits = BN_num_bits(modulus);
762 parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME);
763 if (parent == -FDT_ERR_NOTFOUND) {
764 parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME);
767 if (ret != -FDT_ERR_NOSPACE) {
768 fprintf(stderr, "Couldn't create signature node: %s\n",
769 fdt_strerror(parent));
776 /* Either create or overwrite the named key node */
777 snprintf(name, sizeof(name), "key-%s", info->keyname);
778 node = fdt_subnode_offset(keydest, parent, name);
779 if (node == -FDT_ERR_NOTFOUND) {
780 node = fdt_add_subnode(keydest, parent, name);
783 if (ret != -FDT_ERR_NOSPACE) {
784 fprintf(stderr, "Could not create key subnode: %s\n",
788 } else if (node < 0) {
789 fprintf(stderr, "Cannot select keys parent: %s\n",
795 ret = fdt_setprop_string(keydest, node, "key-name-hint",
799 ret = fdt_setprop_u32(keydest, node, "rsa,num-bits", bits);
801 ret = fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv);
803 ret = fdt_setprop_u64(keydest, node, "rsa,exponent", exponent);
806 ret = fdt_add_bignum(keydest, node, "rsa,modulus", modulus,
810 ret = fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared,
814 ret = fdt_setprop_string(keydest, node, FIT_ALGO_PROP,
817 if (!ret && info->require_keys) {
818 ret = fdt_setprop_string(keydest, node, "required",
825 ret = ret == -FDT_ERR_NOSPACE ? -ENOSPC : -EIO;
830 rsa_engine_remove(e);