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/ec.h>
15 #include <openssl/rsa.h>
16 #include <openssl/pem.h>
17 #include <openssl/err.h>
18 #include <openssl/ssl.h>
19 #include <openssl/evp.h>
20 #include <openssl/engine.h>
22 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
23 #define HAVE_ERR_REMOVE_THREAD_STATE
26 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
27 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
28 static void RSA_get0_key(const RSA *r,
29 const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
40 static int rsa_err(const char *msg)
42 unsigned long sslErr = ERR_get_error();
44 fprintf(stderr, "%s", msg);
45 fprintf(stderr, ": %s\n",
46 ERR_error_string(sslErr, 0));
52 * rsa_pem_get_pub_key() - read a public key from a .crt file
54 * @keydir: Directory containins the key
55 * @name Name of key file (will have a .crt extension)
56 * @evpp Returns EVP_PKEY object, or NULL on failure
57 * @return 0 if ok, -ve on error (in which case *evpp will be set to NULL)
59 static int rsa_pem_get_pub_key(const char *keydir, const char *name, EVP_PKEY **evpp)
71 snprintf(path, sizeof(path), "%s/%s.crt", keydir, name);
74 fprintf(stderr, "Couldn't open RSA certificate: '%s': %s\n",
75 path, strerror(errno));
79 /* Read the certificate */
81 if (!PEM_read_X509(f, &cert, NULL, NULL)) {
82 rsa_err("Couldn't read certificate");
87 /* Get the public key from the certificate. */
88 key = X509_get_pubkey(cert);
90 rsa_err("Couldn't read public key\n");
109 * rsa_engine_get_pub_key() - read a public key from given engine
111 * @keydir: Key prefix
113 * @engine Engine to use
114 * @evpp Returns EVP_PKEY object, or NULL on failure
115 * @return 0 if ok, -ve on error (in which case *evpp will be set to NULL)
117 static int rsa_engine_get_pub_key(const char *keydir, const char *name,
118 ENGINE *engine, EVP_PKEY **evpp)
120 const char *engine_id;
122 EVP_PKEY *key = NULL;
129 engine_id = ENGINE_get_id(engine);
131 if (engine_id && !strcmp(engine_id, "pkcs11")) {
133 if (strstr(keydir, "object="))
134 snprintf(key_id, sizeof(key_id),
135 "pkcs11:%s;type=public",
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");
169 * rsa_get_pub_key() - read a public key
171 * @keydir: Directory containing the key (PEM file) or key prefix (engine)
172 * @name Name of key file (will have a .crt extension)
173 * @engine Engine to use
174 * @evpp Returns EVP_PKEY object, or NULL on failure
175 * @return 0 if ok, -ve on error (in which case *evpp will be set to NULL)
177 static int rsa_get_pub_key(const char *keydir, const char *name,
178 ENGINE *engine, EVP_PKEY **evpp)
181 return rsa_engine_get_pub_key(keydir, name, engine, evpp);
182 return rsa_pem_get_pub_key(keydir, name, evpp);
186 * rsa_pem_get_priv_key() - read a private key from a .key file
188 * @keydir: Directory containing the key
189 * @name Name of key file (will have a .key extension)
190 * @evpp Returns EVP_PKEY object, or NULL on failure
191 * @return 0 if ok, -ve on error (in which case *evpp will be set to NULL)
193 static int rsa_pem_get_priv_key(const char *keydir, const char *name,
194 const char *keyfile, EVP_PKEY **evpp)
196 char path[1024] = {0};
204 snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
206 snprintf(path, sizeof(path), "%s", keyfile);
210 f = fopen(path, "r");
212 fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
213 path, strerror(errno));
217 if (!PEM_read_PrivateKey(f, evpp, NULL, path)) {
218 rsa_err("Failure reading private key");
228 * rsa_engine_get_priv_key() - read a private key from given engine
230 * @keydir: Key prefix
232 * @engine Engine to use
233 * @evpp Returns EVP_PKEY object, or NULL on failure
234 * @return 0 if ok, -ve on error (in which case *evpp will be set to NULL)
236 static int rsa_engine_get_priv_key(const char *keydir, const char *name,
238 ENGINE *engine, EVP_PKEY **evpp)
240 const char *engine_id;
242 EVP_PKEY *key = NULL;
247 engine_id = ENGINE_get_id(engine);
249 if (engine_id && !strcmp(engine_id, "pkcs11")) {
250 if (!keydir && !name) {
251 fprintf(stderr, "Please use 'keydir' with PKCS11\n");
255 if (strstr(keydir, "object="))
256 snprintf(key_id, sizeof(key_id),
257 "pkcs11:%s;type=private",
260 snprintf(key_id, sizeof(key_id),
261 "pkcs11:%s;object=%s;type=private",
264 snprintf(key_id, sizeof(key_id),
265 "pkcs11:object=%s;type=private",
267 } else if (engine_id) {
269 snprintf(key_id, sizeof(key_id),
273 snprintf(key_id, sizeof(key_id),
277 snprintf(key_id, sizeof(key_id), "%s", keyfile);
282 fprintf(stderr, "Engine not supported\n");
286 key = ENGINE_load_private_key(engine, key_id, NULL, NULL);
288 return rsa_err("Failure loading private key from engine");
296 * rsa_get_priv_key() - read a private key
298 * @keydir: Directory containing the key (PEM file) or key prefix (engine)
300 * @engine Engine to use for signing
301 * @evpp Returns EVP_PKEY object, or NULL on failure
302 * @return 0 if ok, -ve on error (in which case *evpp will be set to NULL)
304 static int rsa_get_priv_key(const char *keydir, const char *name,
305 const char *keyfile, ENGINE *engine, EVP_PKEY **evpp)
308 return rsa_engine_get_priv_key(keydir, name, keyfile, engine,
310 return rsa_pem_get_priv_key(keydir, name, keyfile, evpp);
313 static int rsa_init(void)
317 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
318 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
319 ret = SSL_library_init();
321 ret = OPENSSL_init_ssl(0, NULL);
324 fprintf(stderr, "Failure to init SSL library\n");
327 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
328 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
329 SSL_load_error_strings();
331 OpenSSL_add_all_algorithms();
332 OpenSSL_add_all_digests();
333 OpenSSL_add_all_ciphers();
339 static int rsa_engine_init(const char *engine_id, ENGINE **pe)
341 const char *key_pass;
345 ENGINE_load_builtin_engines();
347 e = ENGINE_by_id(engine_id);
349 fprintf(stderr, "Engine isn't available\n");
351 goto err_engine_by_id;
354 if (!ENGINE_init(e)) {
355 fprintf(stderr, "Couldn't initialize engine\n");
357 goto err_engine_init;
360 if (!ENGINE_set_default_RSA(e)) {
361 fprintf(stderr, "Couldn't set engine as default for RSA\n");
366 key_pass = getenv("MKIMAGE_SIGN_PIN");
368 if (!ENGINE_ctrl_cmd_string(e, "PIN", key_pass, 0)) {
369 fprintf(stderr, "Couldn't set PIN\n");
385 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
386 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
392 static void rsa_remove(void)
394 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
395 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
396 CRYPTO_cleanup_all_ex_data();
398 #ifdef HAVE_ERR_REMOVE_THREAD_STATE
399 ERR_remove_thread_state(NULL);
407 static void rsa_engine_remove(ENGINE *e)
415 static int rsa_sign_with_key(EVP_PKEY *pkey, struct padding_algo *padding_algo,
416 struct checksum_algo *checksum_algo,
417 const struct image_region region[], int region_count,
418 uint8_t **sigp, uint *sig_size)
427 size = EVP_PKEY_size(pkey);
430 fprintf(stderr, "Out of memory for signature (%zu bytes)\n",
436 context = EVP_MD_CTX_create();
438 ret = rsa_err("EVP context creation failed");
441 EVP_MD_CTX_init(context);
443 ckey = EVP_PKEY_CTX_new(pkey, NULL);
445 ret = rsa_err("EVP key context creation failed");
449 if (EVP_DigestSignInit(context, &ckey,
450 checksum_algo->calculate_sign(),
452 ret = rsa_err("Signer setup failed");
456 #ifdef CONFIG_FIT_RSASSA_PSS
457 if (padding_algo && !strcmp(padding_algo->name, "pss")) {
458 if (EVP_PKEY_CTX_set_rsa_padding(ckey,
459 RSA_PKCS1_PSS_PADDING) <= 0) {
460 ret = rsa_err("Signer padding setup failed");
464 #endif /* CONFIG_FIT_RSASSA_PSS */
466 for (i = 0; i < region_count; i++) {
467 if (!EVP_DigestSignUpdate(context, region[i].data,
469 ret = rsa_err("Signing data failed");
474 if (!EVP_DigestSignFinal(context, sig, &size)) {
475 ret = rsa_err("Could not obtain signature");
479 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
480 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
481 EVP_MD_CTX_cleanup(context);
483 EVP_MD_CTX_reset(context);
485 EVP_MD_CTX_destroy(context);
487 debug("Got signature: %zu bytes, expected %d\n", size, EVP_PKEY_size(pkey));
494 EVP_MD_CTX_destroy(context);
501 int rsa_sign(struct image_sign_info *info,
502 const struct image_region region[], int region_count,
503 uint8_t **sigp, uint *sig_len)
505 EVP_PKEY *pkey = NULL;
513 if (info->engine_id) {
514 ret = rsa_engine_init(info->engine_id, &e);
519 ret = rsa_get_priv_key(info->keydir, info->keyname, info->keyfile,
523 ret = rsa_sign_with_key(pkey, info->padding, info->checksum, region,
524 region_count, sigp, sig_len);
530 rsa_engine_remove(e);
539 rsa_engine_remove(e);
546 * rsa_get_exponent(): - Get the public exponent from an RSA key
548 static int rsa_get_exponent(RSA *key, uint64_t *e)
561 RSA_get0_key(key, NULL, &key_e, NULL);
562 if (BN_num_bits(key_e) > 64)
565 *e = BN_get_word(key_e);
567 if (BN_num_bits(key_e) < 33) {
572 bn_te = BN_dup(key_e);
576 if (!BN_rshift(bn_te, bn_te, 32))
579 if (!BN_mask_bits(bn_te, 32))
582 te = BN_get_word(bn_te);
595 * rsa_get_params(): - Get the important parameters of an RSA public key
597 int rsa_get_params(RSA *key, uint64_t *exponent, uint32_t *n0_invp,
598 BIGNUM **modulusp, BIGNUM **r_squaredp)
600 BIGNUM *big1, *big2, *big32, *big2_32;
601 BIGNUM *n, *r, *r_squared, *tmp;
603 BN_CTX *bn_ctx = BN_CTX_new();
606 /* Initialize BIGNUMs */
611 r_squared = BN_new();
615 if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 ||
617 fprintf(stderr, "Out of memory (bignum)\n");
621 if (0 != rsa_get_exponent(key, exponent))
624 RSA_get0_key(key, &key_n, NULL, NULL);
625 if (!BN_copy(n, key_n) || !BN_set_word(big1, 1L) ||
626 !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L))
630 if (!BN_exp(big2_32, big2, big32, bn_ctx))
633 /* Calculate n0_inv = -1 / n[0] mod 2^32 */
634 if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) ||
635 !BN_sub(tmp, big2_32, tmp))
637 *n0_invp = BN_get_word(tmp);
639 /* Calculate R = 2^(# of key bits) */
640 if (!BN_set_word(tmp, BN_num_bits(n)) ||
641 !BN_exp(r, big2, tmp, bn_ctx))
644 /* Calculate r_squared = R^2 mod n */
645 if (!BN_copy(r_squared, r) ||
646 !BN_mul(tmp, r_squared, r, bn_ctx) ||
647 !BN_mod(r_squared, tmp, n, bn_ctx))
651 *r_squaredp = r_squared;
660 fprintf(stderr, "Bignum operations failed\n");
667 int rsa_add_verify_data(struct image_sign_info *info, void *keydest)
669 BIGNUM *modulus, *r_squared;
677 EVP_PKEY *pkey = NULL;
680 debug("%s: Getting verification data\n", __func__);
681 if (info->engine_id) {
682 ret = rsa_engine_init(info->engine_id, &e);
686 ret = rsa_get_pub_key(info->keydir, info->keyname, e, &pkey);
688 goto err_get_pub_key;
689 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
690 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
691 rsa = EVP_PKEY_get1_RSA(pkey);
693 rsa = EVP_PKEY_get0_RSA(pkey);
695 ret = rsa_get_params(rsa, &exponent, &n0_inv, &modulus, &r_squared);
698 bits = BN_num_bits(modulus);
699 parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME);
700 if (parent == -FDT_ERR_NOTFOUND) {
701 parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME);
704 if (ret != -FDT_ERR_NOSPACE) {
705 fprintf(stderr, "Couldn't create signature node: %s\n",
706 fdt_strerror(parent));
713 /* Either create or overwrite the named key node */
714 snprintf(name, sizeof(name), "key-%s", info->keyname);
715 node = fdt_subnode_offset(keydest, parent, name);
716 if (node == -FDT_ERR_NOTFOUND) {
717 node = fdt_add_subnode(keydest, parent, name);
720 if (ret != -FDT_ERR_NOSPACE) {
721 fprintf(stderr, "Could not create key subnode: %s\n",
725 } else if (node < 0) {
726 fprintf(stderr, "Cannot select keys parent: %s\n",
732 ret = fdt_setprop_string(keydest, node, FIT_KEY_HINT,
736 ret = fdt_setprop_u32(keydest, node, "rsa,num-bits", bits);
738 ret = fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv);
740 ret = fdt_setprop_u64(keydest, node, "rsa,exponent", exponent);
743 ret = fdt_add_bignum(keydest, node, "rsa,modulus", modulus,
747 ret = fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared,
751 ret = fdt_setprop_string(keydest, node, FIT_ALGO_PROP,
754 if (!ret && info->require_keys) {
755 ret = fdt_setprop_string(keydest, node, FIT_KEY_REQUIRED,
762 ret = ret == -FDT_ERR_NOSPACE ? -ENOSPC : -EIO;
764 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
765 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
771 rsa_engine_remove(e);