1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright (c) 2013, Google Inc.
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>
19 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
20 #define HAVE_ERR_REMOVE_THREAD_STATE
23 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
24 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
25 static void RSA_get0_key(const RSA *r,
26 const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
37 static int rsa_err(const char *msg)
39 unsigned long sslErr = ERR_get_error();
41 fprintf(stderr, "%s", msg);
42 fprintf(stderr, ": %s\n",
43 ERR_error_string(sslErr, 0));
49 * rsa_pem_get_pub_key() - read a public key from a .crt file
51 * @keydir: Directory containins the key
52 * @name Name of key file (will have a .crt extension)
53 * @rsap Returns RSA object, or NULL on failure
54 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
56 static int rsa_pem_get_pub_key(const char *keydir, const char *name, RSA **rsap)
66 snprintf(path, sizeof(path), "%s/%s.crt", keydir, name);
69 fprintf(stderr, "Couldn't open RSA certificate: '%s': %s\n",
70 path, strerror(errno));
74 /* Read the certificate */
76 if (!PEM_read_X509(f, &cert, NULL, NULL)) {
77 rsa_err("Couldn't read certificate");
82 /* Get the public key from the certificate. */
83 key = X509_get_pubkey(cert);
85 rsa_err("Couldn't read public key\n");
90 /* Convert to a RSA_style key. */
91 rsa = EVP_PKEY_get1_RSA(key);
93 rsa_err("Couldn't convert to a RSA style key");
114 * rsa_engine_get_pub_key() - read a public key from given engine
116 * @keydir: Key prefix
118 * @engine Engine to use
119 * @rsap Returns RSA object, or NULL on failure
120 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
122 static int rsa_engine_get_pub_key(const char *keydir, const char *name,
123 ENGINE *engine, RSA **rsap)
125 const char *engine_id;
133 engine_id = ENGINE_get_id(engine);
135 if (engine_id && !strcmp(engine_id, "pkcs11")) {
137 snprintf(key_id, sizeof(key_id),
138 "pkcs11:%s;object=%s;type=public",
141 snprintf(key_id, sizeof(key_id),
142 "pkcs11:object=%s;type=public",
144 } else if (engine_id) {
146 snprintf(key_id, sizeof(key_id),
150 snprintf(key_id, sizeof(key_id),
154 fprintf(stderr, "Engine not supported\n");
158 key = ENGINE_load_public_key(engine, key_id, NULL, NULL);
160 return rsa_err("Failure loading public key from engine");
162 /* Convert to a RSA_style key. */
163 rsa = EVP_PKEY_get1_RSA(key);
165 rsa_err("Couldn't convert to a RSA style key");
181 * rsa_get_pub_key() - read a public key
183 * @keydir: Directory containing the key (PEM file) or key prefix (engine)
184 * @name Name of key file (will have a .crt extension)
185 * @engine Engine to use
186 * @rsap Returns RSA object, or NULL on failure
187 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
189 static int rsa_get_pub_key(const char *keydir, const char *name,
190 ENGINE *engine, RSA **rsap)
193 return rsa_engine_get_pub_key(keydir, name, engine, rsap);
194 return rsa_pem_get_pub_key(keydir, name, rsap);
198 * rsa_pem_get_priv_key() - read a private key from a .key file
200 * @keydir: Directory containing the key
201 * @name Name of key file (will have a .key extension)
202 * @rsap Returns RSA object, or NULL on failure
203 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
205 static int rsa_pem_get_priv_key(const char *keydir, const char *name,
213 snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
214 f = fopen(path, "r");
216 fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
217 path, strerror(errno));
221 rsa = PEM_read_RSAPrivateKey(f, 0, NULL, path);
223 rsa_err("Failure reading private key");
234 * rsa_engine_get_priv_key() - read a private key from given engine
236 * @keydir: Key prefix
238 * @engine Engine to use
239 * @rsap Returns RSA object, or NULL on failure
240 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
242 static int rsa_engine_get_priv_key(const char *keydir, const char *name,
243 ENGINE *engine, RSA **rsap)
245 const char *engine_id;
253 engine_id = ENGINE_get_id(engine);
255 if (engine_id && !strcmp(engine_id, "pkcs11")) {
257 snprintf(key_id, sizeof(key_id),
258 "pkcs11:%s;object=%s;type=private",
261 snprintf(key_id, sizeof(key_id),
262 "pkcs11:object=%s;type=private",
264 } else if (engine_id) {
266 snprintf(key_id, sizeof(key_id),
270 snprintf(key_id, sizeof(key_id),
274 fprintf(stderr, "Engine not supported\n");
278 key = ENGINE_load_private_key(engine, key_id, NULL, NULL);
280 return rsa_err("Failure loading private key from engine");
282 /* Convert to a RSA_style key. */
283 rsa = EVP_PKEY_get1_RSA(key);
285 rsa_err("Couldn't convert to a RSA style key");
301 * rsa_get_priv_key() - read a private key
303 * @keydir: Directory containing the key (PEM file) or key prefix (engine)
305 * @engine Engine to use for signing
306 * @rsap Returns RSA object, or NULL on failure
307 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
309 static int rsa_get_priv_key(const char *keydir, const char *name,
310 ENGINE *engine, RSA **rsap)
313 return rsa_engine_get_priv_key(keydir, name, engine, rsap);
314 return rsa_pem_get_priv_key(keydir, name, rsap);
317 static int rsa_init(void)
321 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
322 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
323 ret = SSL_library_init();
325 ret = OPENSSL_init_ssl(0, NULL);
328 fprintf(stderr, "Failure to init SSL library\n");
331 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
332 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
333 SSL_load_error_strings();
335 OpenSSL_add_all_algorithms();
336 OpenSSL_add_all_digests();
337 OpenSSL_add_all_ciphers();
343 static int rsa_engine_init(const char *engine_id, ENGINE **pe)
348 ENGINE_load_builtin_engines();
350 e = ENGINE_by_id(engine_id);
352 fprintf(stderr, "Engine isn't available\n");
354 goto err_engine_by_id;
357 if (!ENGINE_init(e)) {
358 fprintf(stderr, "Couldn't initialize engine\n");
360 goto err_engine_init;
363 if (!ENGINE_set_default_RSA(e)) {
364 fprintf(stderr, "Couldn't set engine as default for RSA\n");
378 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
379 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
385 static void rsa_remove(void)
387 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
388 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
389 CRYPTO_cleanup_all_ex_data();
391 #ifdef HAVE_ERR_REMOVE_THREAD_STATE
392 ERR_remove_thread_state(NULL);
400 static void rsa_engine_remove(ENGINE *e)
408 static int rsa_sign_with_key(RSA *rsa, struct padding_algo *padding_algo,
409 struct checksum_algo *checksum_algo,
410 const struct image_region region[], int region_count,
411 uint8_t **sigp, uint *sig_size)
421 key = EVP_PKEY_new();
423 return rsa_err("EVP_PKEY object creation failed");
425 if (!EVP_PKEY_set1_RSA(key, rsa)) {
426 ret = rsa_err("EVP key setup failed");
430 size = EVP_PKEY_size(key);
433 fprintf(stderr, "Out of memory for signature (%zu bytes)\n",
439 context = EVP_MD_CTX_create();
441 ret = rsa_err("EVP context creation failed");
444 EVP_MD_CTX_init(context);
446 ckey = EVP_PKEY_CTX_new(key, NULL);
448 ret = rsa_err("EVP key context creation failed");
452 if (EVP_DigestSignInit(context, &ckey,
453 checksum_algo->calculate_sign(),
455 ret = rsa_err("Signer setup failed");
459 #ifdef CONFIG_FIT_ENABLE_RSASSA_PSS_SUPPORT
460 if (padding_algo && !strcmp(padding_algo->name, "pss")) {
461 if (EVP_PKEY_CTX_set_rsa_padding(ckey,
462 RSA_PKCS1_PSS_PADDING) <= 0) {
463 ret = rsa_err("Signer padding setup failed");
467 #endif /* CONFIG_FIT_ENABLE_RSASSA_PSS_SUPPORT */
469 for (i = 0; i < region_count; i++) {
470 if (!EVP_DigestSignUpdate(context, region[i].data,
472 ret = rsa_err("Signing data failed");
477 if (!EVP_DigestSignFinal(context, sig, &size)) {
478 ret = rsa_err("Could not obtain signature");
482 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
483 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
484 EVP_MD_CTX_cleanup(context);
486 EVP_MD_CTX_reset(context);
488 EVP_MD_CTX_destroy(context);
491 debug("Got signature: %d bytes, expected %zu\n", *sig_size, size);
498 EVP_MD_CTX_destroy(context);
507 int rsa_sign(struct image_sign_info *info,
508 const struct image_region region[], int region_count,
509 uint8_t **sigp, uint *sig_len)
519 if (info->engine_id) {
520 ret = rsa_engine_init(info->engine_id, &e);
525 ret = rsa_get_priv_key(info->keydir, info->keyname, e, &rsa);
528 ret = rsa_sign_with_key(rsa, info->padding, info->checksum, region,
529 region_count, sigp, sig_len);
535 rsa_engine_remove(e);
544 rsa_engine_remove(e);
551 * rsa_get_exponent(): - Get the public exponent from an RSA key
553 static int rsa_get_exponent(RSA *key, uint64_t *e)
566 RSA_get0_key(key, NULL, &key_e, NULL);
567 if (BN_num_bits(key_e) > 64)
570 *e = BN_get_word(key_e);
572 if (BN_num_bits(key_e) < 33) {
577 bn_te = BN_dup(key_e);
581 if (!BN_rshift(bn_te, bn_te, 32))
584 if (!BN_mask_bits(bn_te, 32))
587 te = BN_get_word(bn_te);
600 * rsa_get_params(): - Get the important parameters of an RSA public key
602 int rsa_get_params(RSA *key, uint64_t *exponent, uint32_t *n0_invp,
603 BIGNUM **modulusp, BIGNUM **r_squaredp)
605 BIGNUM *big1, *big2, *big32, *big2_32;
606 BIGNUM *n, *r, *r_squared, *tmp;
608 BN_CTX *bn_ctx = BN_CTX_new();
611 /* Initialize BIGNUMs */
616 r_squared = BN_new();
620 if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 ||
622 fprintf(stderr, "Out of memory (bignum)\n");
626 if (0 != rsa_get_exponent(key, exponent))
629 RSA_get0_key(key, &key_n, NULL, NULL);
630 if (!BN_copy(n, key_n) || !BN_set_word(big1, 1L) ||
631 !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L))
635 if (!BN_exp(big2_32, big2, big32, bn_ctx))
638 /* Calculate n0_inv = -1 / n[0] mod 2^32 */
639 if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) ||
640 !BN_sub(tmp, big2_32, tmp))
642 *n0_invp = BN_get_word(tmp);
644 /* Calculate R = 2^(# of key bits) */
645 if (!BN_set_word(tmp, BN_num_bits(n)) ||
646 !BN_exp(r, big2, tmp, bn_ctx))
649 /* Calculate r_squared = R^2 mod n */
650 if (!BN_copy(r_squared, r) ||
651 !BN_mul(tmp, r_squared, r, bn_ctx) ||
652 !BN_mod(r_squared, tmp, n, bn_ctx))
656 *r_squaredp = r_squared;
665 fprintf(stderr, "Bignum operations failed\n");
672 static int fdt_add_bignum(void *blob, int noffset, const char *prop_name,
673 BIGNUM *num, int num_bits)
675 int nwords = num_bits / 32;
678 BIGNUM *tmp, *big2, *big32, *big2_32;
688 * Note: This code assumes that all of the above succeed, or all fail.
689 * In practice memory allocations generally do not fail (unless the
690 * process is killed), so it does not seem worth handling each of these
691 * as a separate case. Technicaly this could leak memory on failure,
692 * but a) it won't happen in practice, and b) it doesn't matter as we
693 * will immediately exit with a failure code.
695 if (!tmp || !big2 || !big32 || !big2_32) {
696 fprintf(stderr, "Out of memory (bignum)\n");
701 fprintf(stderr, "Out of memory (bignum context)\n");
704 BN_set_word(big2, 2L);
705 BN_set_word(big32, 32L);
706 BN_exp(big2_32, big2, big32, ctx); /* B = 2^32 */
708 size = nwords * sizeof(uint32_t);
711 fprintf(stderr, "Out of memory (%d bytes)\n", size);
715 /* Write out modulus as big endian array of integers */
716 for (ptr = buf + nwords - 1; ptr >= buf; ptr--) {
717 BN_mod(tmp, num, big2_32, ctx); /* n = N mod B */
718 *ptr = cpu_to_fdt32(BN_get_word(tmp));
719 BN_rshift(num, num, 32); /* N = N/B */
723 * We try signing with successively increasing size values, so this
724 * might fail several times
726 ret = fdt_setprop(blob, noffset, prop_name, buf, size);
733 return ret ? -FDT_ERR_NOSPACE : 0;
736 int rsa_add_verify_data(struct image_sign_info *info, void *keydest)
738 BIGNUM *modulus, *r_squared;
748 debug("%s: Getting verification data\n", __func__);
749 if (info->engine_id) {
750 ret = rsa_engine_init(info->engine_id, &e);
754 ret = rsa_get_pub_key(info->keydir, info->keyname, e, &rsa);
756 goto err_get_pub_key;
757 ret = rsa_get_params(rsa, &exponent, &n0_inv, &modulus, &r_squared);
760 bits = BN_num_bits(modulus);
761 parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME);
762 if (parent == -FDT_ERR_NOTFOUND) {
763 parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME);
766 if (ret != -FDT_ERR_NOSPACE) {
767 fprintf(stderr, "Couldn't create signature node: %s\n",
768 fdt_strerror(parent));
775 /* Either create or overwrite the named key node */
776 snprintf(name, sizeof(name), "key-%s", info->keyname);
777 node = fdt_subnode_offset(keydest, parent, name);
778 if (node == -FDT_ERR_NOTFOUND) {
779 node = fdt_add_subnode(keydest, parent, name);
782 if (ret != -FDT_ERR_NOSPACE) {
783 fprintf(stderr, "Could not create key subnode: %s\n",
787 } else if (node < 0) {
788 fprintf(stderr, "Cannot select keys parent: %s\n",
794 ret = fdt_setprop_string(keydest, node, "key-name-hint",
798 ret = fdt_setprop_u32(keydest, node, "rsa,num-bits", bits);
800 ret = fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv);
802 ret = fdt_setprop_u64(keydest, node, "rsa,exponent", exponent);
805 ret = fdt_add_bignum(keydest, node, "rsa,modulus", modulus,
809 ret = fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared,
813 ret = fdt_setprop_string(keydest, node, FIT_ALGO_PROP,
816 if (!ret && info->require_keys) {
817 ret = fdt_setprop_string(keydest, node, "required",
824 ret = ret == -FDT_ERR_NOSPACE ? -ENOSPC : -EIO;
829 rsa_engine_remove(e);