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 if (strstr(keydir, "object="))
139 snprintf(key_id, sizeof(key_id),
140 "pkcs11:%s;type=public",
143 snprintf(key_id, sizeof(key_id),
144 "pkcs11:%s;object=%s;type=public",
147 snprintf(key_id, sizeof(key_id),
148 "pkcs11:object=%s;type=public",
150 } else if (engine_id) {
152 snprintf(key_id, sizeof(key_id),
156 snprintf(key_id, sizeof(key_id),
160 fprintf(stderr, "Engine not supported\n");
164 key = ENGINE_load_public_key(engine, key_id, NULL, NULL);
166 return rsa_err("Failure loading public key from engine");
168 /* Convert to a RSA_style key. */
169 rsa = EVP_PKEY_get1_RSA(key);
171 rsa_err("Couldn't convert to a RSA style key");
187 * rsa_get_pub_key() - read a public key
189 * @keydir: Directory containing the key (PEM file) or key prefix (engine)
190 * @name Name of key file (will have a .crt extension)
191 * @engine Engine to use
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)
195 static int rsa_get_pub_key(const char *keydir, const char *name,
196 ENGINE *engine, RSA **rsap)
199 return rsa_engine_get_pub_key(keydir, name, engine, rsap);
200 return rsa_pem_get_pub_key(keydir, name, rsap);
204 * rsa_pem_get_priv_key() - read a private key from a .key file
206 * @keydir: Directory containing the key
207 * @name Name of key file (will have a .key extension)
208 * @rsap Returns RSA object, or NULL on failure
209 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
211 static int rsa_pem_get_priv_key(const char *keydir, const char *name,
219 snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
220 f = fopen(path, "r");
222 fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
223 path, strerror(errno));
227 rsa = PEM_read_RSAPrivateKey(f, 0, NULL, path);
229 rsa_err("Failure reading private key");
240 * rsa_engine_get_priv_key() - read a private key from given engine
242 * @keydir: Key prefix
244 * @engine Engine to use
245 * @rsap Returns RSA object, or NULL on failure
246 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
248 static int rsa_engine_get_priv_key(const char *keydir, const char *name,
249 ENGINE *engine, RSA **rsap)
251 const char *engine_id;
259 engine_id = ENGINE_get_id(engine);
261 if (engine_id && !strcmp(engine_id, "pkcs11")) {
263 if (strstr(keydir, "object="))
264 snprintf(key_id, sizeof(key_id),
265 "pkcs11:%s;type=private",
268 snprintf(key_id, sizeof(key_id),
269 "pkcs11:%s;object=%s;type=private",
272 snprintf(key_id, sizeof(key_id),
273 "pkcs11:object=%s;type=private",
275 } else if (engine_id) {
277 snprintf(key_id, sizeof(key_id),
281 snprintf(key_id, sizeof(key_id),
285 fprintf(stderr, "Engine not supported\n");
289 key = ENGINE_load_private_key(engine, key_id, NULL, NULL);
291 return rsa_err("Failure loading private key from engine");
293 /* Convert to a RSA_style key. */
294 rsa = EVP_PKEY_get1_RSA(key);
296 rsa_err("Couldn't convert to a RSA style key");
312 * rsa_get_priv_key() - read a private key
314 * @keydir: Directory containing the key (PEM file) or key prefix (engine)
316 * @engine Engine to use for signing
317 * @rsap Returns RSA object, or NULL on failure
318 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
320 static int rsa_get_priv_key(const char *keydir, const char *name,
321 ENGINE *engine, RSA **rsap)
324 return rsa_engine_get_priv_key(keydir, name, engine, rsap);
325 return rsa_pem_get_priv_key(keydir, name, rsap);
328 static int rsa_init(void)
332 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
333 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
334 ret = SSL_library_init();
336 ret = OPENSSL_init_ssl(0, NULL);
339 fprintf(stderr, "Failure to init SSL library\n");
342 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
343 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
344 SSL_load_error_strings();
346 OpenSSL_add_all_algorithms();
347 OpenSSL_add_all_digests();
348 OpenSSL_add_all_ciphers();
354 static int rsa_engine_init(const char *engine_id, ENGINE **pe)
359 ENGINE_load_builtin_engines();
361 e = ENGINE_by_id(engine_id);
363 fprintf(stderr, "Engine isn't available\n");
365 goto err_engine_by_id;
368 if (!ENGINE_init(e)) {
369 fprintf(stderr, "Couldn't initialize engine\n");
371 goto err_engine_init;
374 if (!ENGINE_set_default_RSA(e)) {
375 fprintf(stderr, "Couldn't set engine as default for RSA\n");
389 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
390 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
396 static void rsa_remove(void)
398 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
399 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
400 CRYPTO_cleanup_all_ex_data();
402 #ifdef HAVE_ERR_REMOVE_THREAD_STATE
403 ERR_remove_thread_state(NULL);
411 static void rsa_engine_remove(ENGINE *e)
419 static int rsa_sign_with_key(RSA *rsa, struct padding_algo *padding_algo,
420 struct checksum_algo *checksum_algo,
421 const struct image_region region[], int region_count,
422 uint8_t **sigp, uint *sig_size)
432 key = EVP_PKEY_new();
434 return rsa_err("EVP_PKEY object creation failed");
436 if (!EVP_PKEY_set1_RSA(key, rsa)) {
437 ret = rsa_err("EVP key setup failed");
441 size = EVP_PKEY_size(key);
444 fprintf(stderr, "Out of memory for signature (%zu bytes)\n",
450 context = EVP_MD_CTX_create();
452 ret = rsa_err("EVP context creation failed");
455 EVP_MD_CTX_init(context);
457 ckey = EVP_PKEY_CTX_new(key, NULL);
459 ret = rsa_err("EVP key context creation failed");
463 if (EVP_DigestSignInit(context, &ckey,
464 checksum_algo->calculate_sign(),
466 ret = rsa_err("Signer setup failed");
470 #ifdef CONFIG_FIT_ENABLE_RSASSA_PSS_SUPPORT
471 if (padding_algo && !strcmp(padding_algo->name, "pss")) {
472 if (EVP_PKEY_CTX_set_rsa_padding(ckey,
473 RSA_PKCS1_PSS_PADDING) <= 0) {
474 ret = rsa_err("Signer padding setup failed");
478 #endif /* CONFIG_FIT_ENABLE_RSASSA_PSS_SUPPORT */
480 for (i = 0; i < region_count; i++) {
481 if (!EVP_DigestSignUpdate(context, region[i].data,
483 ret = rsa_err("Signing data failed");
488 if (!EVP_DigestSignFinal(context, sig, &size)) {
489 ret = rsa_err("Could not obtain signature");
493 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
494 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
495 EVP_MD_CTX_cleanup(context);
497 EVP_MD_CTX_reset(context);
499 EVP_MD_CTX_destroy(context);
502 debug("Got signature: %d bytes, expected %zu\n", *sig_size, size);
509 EVP_MD_CTX_destroy(context);
518 int rsa_sign(struct image_sign_info *info,
519 const struct image_region region[], int region_count,
520 uint8_t **sigp, uint *sig_len)
530 if (info->engine_id) {
531 ret = rsa_engine_init(info->engine_id, &e);
536 ret = rsa_get_priv_key(info->keydir, info->keyname, e, &rsa);
539 ret = rsa_sign_with_key(rsa, info->padding, info->checksum, region,
540 region_count, sigp, sig_len);
546 rsa_engine_remove(e);
555 rsa_engine_remove(e);
562 * rsa_get_exponent(): - Get the public exponent from an RSA key
564 static int rsa_get_exponent(RSA *key, uint64_t *e)
577 RSA_get0_key(key, NULL, &key_e, NULL);
578 if (BN_num_bits(key_e) > 64)
581 *e = BN_get_word(key_e);
583 if (BN_num_bits(key_e) < 33) {
588 bn_te = BN_dup(key_e);
592 if (!BN_rshift(bn_te, bn_te, 32))
595 if (!BN_mask_bits(bn_te, 32))
598 te = BN_get_word(bn_te);
611 * rsa_get_params(): - Get the important parameters of an RSA public key
613 int rsa_get_params(RSA *key, uint64_t *exponent, uint32_t *n0_invp,
614 BIGNUM **modulusp, BIGNUM **r_squaredp)
616 BIGNUM *big1, *big2, *big32, *big2_32;
617 BIGNUM *n, *r, *r_squared, *tmp;
619 BN_CTX *bn_ctx = BN_CTX_new();
622 /* Initialize BIGNUMs */
627 r_squared = BN_new();
631 if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 ||
633 fprintf(stderr, "Out of memory (bignum)\n");
637 if (0 != rsa_get_exponent(key, exponent))
640 RSA_get0_key(key, &key_n, NULL, NULL);
641 if (!BN_copy(n, key_n) || !BN_set_word(big1, 1L) ||
642 !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L))
646 if (!BN_exp(big2_32, big2, big32, bn_ctx))
649 /* Calculate n0_inv = -1 / n[0] mod 2^32 */
650 if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) ||
651 !BN_sub(tmp, big2_32, tmp))
653 *n0_invp = BN_get_word(tmp);
655 /* Calculate R = 2^(# of key bits) */
656 if (!BN_set_word(tmp, BN_num_bits(n)) ||
657 !BN_exp(r, big2, tmp, bn_ctx))
660 /* Calculate r_squared = R^2 mod n */
661 if (!BN_copy(r_squared, r) ||
662 !BN_mul(tmp, r_squared, r, bn_ctx) ||
663 !BN_mod(r_squared, tmp, n, bn_ctx))
667 *r_squaredp = r_squared;
676 fprintf(stderr, "Bignum operations failed\n");
683 static int fdt_add_bignum(void *blob, int noffset, const char *prop_name,
684 BIGNUM *num, int num_bits)
686 int nwords = num_bits / 32;
689 BIGNUM *tmp, *big2, *big32, *big2_32;
699 * Note: This code assumes that all of the above succeed, or all fail.
700 * In practice memory allocations generally do not fail (unless the
701 * process is killed), so it does not seem worth handling each of these
702 * as a separate case. Technicaly this could leak memory on failure,
703 * but a) it won't happen in practice, and b) it doesn't matter as we
704 * will immediately exit with a failure code.
706 if (!tmp || !big2 || !big32 || !big2_32) {
707 fprintf(stderr, "Out of memory (bignum)\n");
712 fprintf(stderr, "Out of memory (bignum context)\n");
715 BN_set_word(big2, 2L);
716 BN_set_word(big32, 32L);
717 BN_exp(big2_32, big2, big32, ctx); /* B = 2^32 */
719 size = nwords * sizeof(uint32_t);
722 fprintf(stderr, "Out of memory (%d bytes)\n", size);
726 /* Write out modulus as big endian array of integers */
727 for (ptr = buf + nwords - 1; ptr >= buf; ptr--) {
728 BN_mod(tmp, num, big2_32, ctx); /* n = N mod B */
729 *ptr = cpu_to_fdt32(BN_get_word(tmp));
730 BN_rshift(num, num, 32); /* N = N/B */
734 * We try signing with successively increasing size values, so this
735 * might fail several times
737 ret = fdt_setprop(blob, noffset, prop_name, buf, size);
744 return ret ? -FDT_ERR_NOSPACE : 0;
747 int rsa_add_verify_data(struct image_sign_info *info, void *keydest)
749 BIGNUM *modulus, *r_squared;
759 debug("%s: Getting verification data\n", __func__);
760 if (info->engine_id) {
761 ret = rsa_engine_init(info->engine_id, &e);
765 ret = rsa_get_pub_key(info->keydir, info->keyname, e, &rsa);
767 goto err_get_pub_key;
768 ret = rsa_get_params(rsa, &exponent, &n0_inv, &modulus, &r_squared);
771 bits = BN_num_bits(modulus);
772 parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME);
773 if (parent == -FDT_ERR_NOTFOUND) {
774 parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME);
777 if (ret != -FDT_ERR_NOSPACE) {
778 fprintf(stderr, "Couldn't create signature node: %s\n",
779 fdt_strerror(parent));
786 /* Either create or overwrite the named key node */
787 snprintf(name, sizeof(name), "key-%s", info->keyname);
788 node = fdt_subnode_offset(keydest, parent, name);
789 if (node == -FDT_ERR_NOTFOUND) {
790 node = fdt_add_subnode(keydest, parent, name);
793 if (ret != -FDT_ERR_NOSPACE) {
794 fprintf(stderr, "Could not create key subnode: %s\n",
798 } else if (node < 0) {
799 fprintf(stderr, "Cannot select keys parent: %s\n",
805 ret = fdt_setprop_string(keydest, node, FIT_KEY_HINT,
809 ret = fdt_setprop_u32(keydest, node, "rsa,num-bits", bits);
811 ret = fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv);
813 ret = fdt_setprop_u64(keydest, node, "rsa,exponent", exponent);
816 ret = fdt_add_bignum(keydest, node, "rsa,modulus", modulus,
820 ret = fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared,
824 ret = fdt_setprop_string(keydest, node, FIT_ALGO_PROP,
827 if (!ret && info->require_keys) {
828 ret = fdt_setprop_string(keydest, node, FIT_KEY_REQUIRED,
835 ret = ret == -FDT_ERR_NOSPACE ? -ENOSPC : -EIO;
840 rsa_engine_remove(e);