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,
220 snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
221 f = fopen(path, "r");
223 fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
224 path, strerror(errno));
228 rsa = PEM_read_RSAPrivateKey(f, 0, NULL, path);
230 rsa_err("Failure reading private key");
241 * rsa_engine_get_priv_key() - read a private key from given engine
243 * @keydir: Key prefix
245 * @engine Engine to use
246 * @rsap Returns RSA object, or NULL on failure
247 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
249 static int rsa_engine_get_priv_key(const char *keydir, const char *name,
250 ENGINE *engine, RSA **rsap)
252 const char *engine_id;
260 engine_id = ENGINE_get_id(engine);
262 if (engine_id && !strcmp(engine_id, "pkcs11")) {
264 if (strstr(keydir, "object="))
265 snprintf(key_id, sizeof(key_id),
266 "pkcs11:%s;type=private",
269 snprintf(key_id, sizeof(key_id),
270 "pkcs11:%s;object=%s;type=private",
273 snprintf(key_id, sizeof(key_id),
274 "pkcs11:object=%s;type=private",
276 } else if (engine_id) {
278 snprintf(key_id, sizeof(key_id),
282 snprintf(key_id, sizeof(key_id),
286 fprintf(stderr, "Engine not supported\n");
290 key = ENGINE_load_private_key(engine, key_id, NULL, NULL);
292 return rsa_err("Failure loading private key from engine");
294 /* Convert to a RSA_style key. */
295 rsa = EVP_PKEY_get1_RSA(key);
297 rsa_err("Couldn't convert to a RSA style key");
313 * rsa_get_priv_key() - read a private key
315 * @keydir: Directory containing the key (PEM file) or key prefix (engine)
317 * @engine Engine to use for signing
318 * @rsap Returns RSA object, or NULL on failure
319 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
321 static int rsa_get_priv_key(const char *keydir, const char *name,
322 ENGINE *engine, RSA **rsap)
325 return rsa_engine_get_priv_key(keydir, name, engine, rsap);
326 return rsa_pem_get_priv_key(keydir, name, rsap);
329 static int rsa_init(void)
333 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
334 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
335 ret = SSL_library_init();
337 ret = OPENSSL_init_ssl(0, NULL);
340 fprintf(stderr, "Failure to init SSL library\n");
343 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
344 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
345 SSL_load_error_strings();
347 OpenSSL_add_all_algorithms();
348 OpenSSL_add_all_digests();
349 OpenSSL_add_all_ciphers();
355 static int rsa_engine_init(const char *engine_id, ENGINE **pe)
360 ENGINE_load_builtin_engines();
362 e = ENGINE_by_id(engine_id);
364 fprintf(stderr, "Engine isn't available\n");
366 goto err_engine_by_id;
369 if (!ENGINE_init(e)) {
370 fprintf(stderr, "Couldn't initialize engine\n");
372 goto err_engine_init;
375 if (!ENGINE_set_default_RSA(e)) {
376 fprintf(stderr, "Couldn't set engine as default for RSA\n");
390 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
391 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
397 static void rsa_remove(void)
399 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
400 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
401 CRYPTO_cleanup_all_ex_data();
403 #ifdef HAVE_ERR_REMOVE_THREAD_STATE
404 ERR_remove_thread_state(NULL);
412 static void rsa_engine_remove(ENGINE *e)
420 static int rsa_sign_with_key(RSA *rsa, struct padding_algo *padding_algo,
421 struct checksum_algo *checksum_algo,
422 const struct image_region region[], int region_count,
423 uint8_t **sigp, uint *sig_size)
433 key = EVP_PKEY_new();
435 return rsa_err("EVP_PKEY object creation failed");
437 if (!EVP_PKEY_set1_RSA(key, rsa)) {
438 ret = rsa_err("EVP key setup failed");
442 size = EVP_PKEY_size(key);
445 fprintf(stderr, "Out of memory for signature (%zu bytes)\n",
451 context = EVP_MD_CTX_create();
453 ret = rsa_err("EVP context creation failed");
456 EVP_MD_CTX_init(context);
458 ckey = EVP_PKEY_CTX_new(key, NULL);
460 ret = rsa_err("EVP key context creation failed");
464 if (EVP_DigestSignInit(context, &ckey,
465 checksum_algo->calculate_sign(),
467 ret = rsa_err("Signer setup failed");
471 #ifdef CONFIG_FIT_ENABLE_RSASSA_PSS_SUPPORT
472 if (padding_algo && !strcmp(padding_algo->name, "pss")) {
473 if (EVP_PKEY_CTX_set_rsa_padding(ckey,
474 RSA_PKCS1_PSS_PADDING) <= 0) {
475 ret = rsa_err("Signer padding setup failed");
479 #endif /* CONFIG_FIT_ENABLE_RSASSA_PSS_SUPPORT */
481 for (i = 0; i < region_count; i++) {
482 if (!EVP_DigestSignUpdate(context, region[i].data,
484 ret = rsa_err("Signing data failed");
489 if (!EVP_DigestSignFinal(context, sig, &size)) {
490 ret = rsa_err("Could not obtain signature");
494 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
495 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
496 EVP_MD_CTX_cleanup(context);
498 EVP_MD_CTX_reset(context);
500 EVP_MD_CTX_destroy(context);
503 debug("Got signature: %d bytes, expected %zu\n", *sig_size, size);
510 EVP_MD_CTX_destroy(context);
519 int rsa_sign(struct image_sign_info *info,
520 const struct image_region region[], int region_count,
521 uint8_t **sigp, uint *sig_len)
531 if (info->engine_id) {
532 ret = rsa_engine_init(info->engine_id, &e);
537 ret = rsa_get_priv_key(info->keydir, info->keyname, e, &rsa);
540 ret = rsa_sign_with_key(rsa, info->padding, info->checksum, region,
541 region_count, sigp, sig_len);
547 rsa_engine_remove(e);
556 rsa_engine_remove(e);
563 * rsa_get_exponent(): - Get the public exponent from an RSA key
565 static int rsa_get_exponent(RSA *key, uint64_t *e)
578 RSA_get0_key(key, NULL, &key_e, NULL);
579 if (BN_num_bits(key_e) > 64)
582 *e = BN_get_word(key_e);
584 if (BN_num_bits(key_e) < 33) {
589 bn_te = BN_dup(key_e);
593 if (!BN_rshift(bn_te, bn_te, 32))
596 if (!BN_mask_bits(bn_te, 32))
599 te = BN_get_word(bn_te);
612 * rsa_get_params(): - Get the important parameters of an RSA public key
614 int rsa_get_params(RSA *key, uint64_t *exponent, uint32_t *n0_invp,
615 BIGNUM **modulusp, BIGNUM **r_squaredp)
617 BIGNUM *big1, *big2, *big32, *big2_32;
618 BIGNUM *n, *r, *r_squared, *tmp;
620 BN_CTX *bn_ctx = BN_CTX_new();
623 /* Initialize BIGNUMs */
628 r_squared = BN_new();
632 if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 ||
634 fprintf(stderr, "Out of memory (bignum)\n");
638 if (0 != rsa_get_exponent(key, exponent))
641 RSA_get0_key(key, &key_n, NULL, NULL);
642 if (!BN_copy(n, key_n) || !BN_set_word(big1, 1L) ||
643 !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L))
647 if (!BN_exp(big2_32, big2, big32, bn_ctx))
650 /* Calculate n0_inv = -1 / n[0] mod 2^32 */
651 if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) ||
652 !BN_sub(tmp, big2_32, tmp))
654 *n0_invp = BN_get_word(tmp);
656 /* Calculate R = 2^(# of key bits) */
657 if (!BN_set_word(tmp, BN_num_bits(n)) ||
658 !BN_exp(r, big2, tmp, bn_ctx))
661 /* Calculate r_squared = R^2 mod n */
662 if (!BN_copy(r_squared, r) ||
663 !BN_mul(tmp, r_squared, r, bn_ctx) ||
664 !BN_mod(r_squared, tmp, n, bn_ctx))
668 *r_squaredp = r_squared;
677 fprintf(stderr, "Bignum operations failed\n");
684 int rsa_add_verify_data(struct image_sign_info *info, void *keydest)
686 BIGNUM *modulus, *r_squared;
696 debug("%s: Getting verification data\n", __func__);
697 if (info->engine_id) {
698 ret = rsa_engine_init(info->engine_id, &e);
702 ret = rsa_get_pub_key(info->keydir, info->keyname, e, &rsa);
704 goto err_get_pub_key;
705 ret = rsa_get_params(rsa, &exponent, &n0_inv, &modulus, &r_squared);
708 bits = BN_num_bits(modulus);
709 parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME);
710 if (parent == -FDT_ERR_NOTFOUND) {
711 parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME);
714 if (ret != -FDT_ERR_NOSPACE) {
715 fprintf(stderr, "Couldn't create signature node: %s\n",
716 fdt_strerror(parent));
723 /* Either create or overwrite the named key node */
724 snprintf(name, sizeof(name), "key-%s", info->keyname);
725 node = fdt_subnode_offset(keydest, parent, name);
726 if (node == -FDT_ERR_NOTFOUND) {
727 node = fdt_add_subnode(keydest, parent, name);
730 if (ret != -FDT_ERR_NOSPACE) {
731 fprintf(stderr, "Could not create key subnode: %s\n",
735 } else if (node < 0) {
736 fprintf(stderr, "Cannot select keys parent: %s\n",
742 ret = fdt_setprop_string(keydest, node, FIT_KEY_HINT,
746 ret = fdt_setprop_u32(keydest, node, "rsa,num-bits", bits);
748 ret = fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv);
750 ret = fdt_setprop_u64(keydest, node, "rsa,exponent", exponent);
753 ret = fdt_add_bignum(keydest, node, "rsa,modulus", modulus,
757 ret = fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared,
761 ret = fdt_setprop_string(keydest, node, FIT_ALGO_PROP,
764 if (!ret && info->require_keys) {
765 ret = fdt_setprop_string(keydest, node, FIT_KEY_REQUIRED,
772 ret = ret == -FDT_ERR_NOSPACE ? -ENOSPC : -EIO;
777 rsa_engine_remove(e);