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 static void RSA_get0_key(const RSA *r,
25 const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
36 static int rsa_err(const char *msg)
38 unsigned long sslErr = ERR_get_error();
40 fprintf(stderr, "%s", msg);
41 fprintf(stderr, ": %s\n",
42 ERR_error_string(sslErr, 0));
48 * rsa_pem_get_pub_key() - read a public key from a .crt file
50 * @keydir: Directory containins the key
51 * @name Name of key file (will have a .crt extension)
52 * @rsap Returns RSA object, or NULL on failure
53 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
55 static int rsa_pem_get_pub_key(const char *keydir, const char *name, RSA **rsap)
65 snprintf(path, sizeof(path), "%s/%s.crt", keydir, name);
68 fprintf(stderr, "Couldn't open RSA certificate: '%s': %s\n",
69 path, strerror(errno));
73 /* Read the certificate */
75 if (!PEM_read_X509(f, &cert, NULL, NULL)) {
76 rsa_err("Couldn't read certificate");
81 /* Get the public key from the certificate. */
82 key = X509_get_pubkey(cert);
84 rsa_err("Couldn't read public key\n");
89 /* Convert to a RSA_style key. */
90 rsa = EVP_PKEY_get1_RSA(key);
92 rsa_err("Couldn't convert to a RSA style key");
113 * rsa_engine_get_pub_key() - read a public key from given engine
115 * @keydir: Key prefix
117 * @engine Engine to use
118 * @rsap Returns RSA object, or NULL on failure
119 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
121 static int rsa_engine_get_pub_key(const char *keydir, const char *name,
122 ENGINE *engine, RSA **rsap)
124 const char *engine_id;
132 engine_id = ENGINE_get_id(engine);
134 if (engine_id && !strcmp(engine_id, "pkcs11")) {
136 snprintf(key_id, sizeof(key_id),
137 "pkcs11:%s;object=%s;type=public",
140 snprintf(key_id, sizeof(key_id),
141 "pkcs11:object=%s;type=public",
144 fprintf(stderr, "Engine not supported\n");
148 key = ENGINE_load_public_key(engine, key_id, NULL, NULL);
150 return rsa_err("Failure loading public key from engine");
152 /* Convert to a RSA_style key. */
153 rsa = EVP_PKEY_get1_RSA(key);
155 rsa_err("Couldn't convert to a RSA style key");
171 * rsa_get_pub_key() - read a public key
173 * @keydir: Directory containing the key (PEM file) or key prefix (engine)
174 * @name Name of key file (will have a .crt extension)
175 * @engine Engine to use
176 * @rsap Returns RSA object, or NULL on failure
177 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
179 static int rsa_get_pub_key(const char *keydir, const char *name,
180 ENGINE *engine, RSA **rsap)
183 return rsa_engine_get_pub_key(keydir, name, engine, rsap);
184 return rsa_pem_get_pub_key(keydir, name, rsap);
188 * rsa_pem_get_priv_key() - read a private key from a .key file
190 * @keydir: Directory containing the key
191 * @name Name of key file (will have a .key extension)
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_pem_get_priv_key(const char *keydir, const char *name,
203 snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
204 f = fopen(path, "r");
206 fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
207 path, strerror(errno));
211 rsa = PEM_read_RSAPrivateKey(f, 0, NULL, path);
213 rsa_err("Failure reading private key");
224 * rsa_engine_get_priv_key() - read a private key from given engine
226 * @keydir: Key prefix
228 * @engine Engine to use
229 * @rsap Returns RSA object, or NULL on failure
230 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
232 static int rsa_engine_get_priv_key(const char *keydir, const char *name,
233 ENGINE *engine, RSA **rsap)
235 const char *engine_id;
243 engine_id = ENGINE_get_id(engine);
245 if (engine_id && !strcmp(engine_id, "pkcs11")) {
247 snprintf(key_id, sizeof(key_id),
248 "pkcs11:%s;object=%s;type=private",
251 snprintf(key_id, sizeof(key_id),
252 "pkcs11:object=%s;type=private",
255 fprintf(stderr, "Engine not supported\n");
259 key = ENGINE_load_private_key(engine, key_id, NULL, NULL);
261 return rsa_err("Failure loading private key from engine");
263 /* Convert to a RSA_style key. */
264 rsa = EVP_PKEY_get1_RSA(key);
266 rsa_err("Couldn't convert to a RSA style key");
282 * rsa_get_priv_key() - read a private key
284 * @keydir: Directory containing the key (PEM file) or key prefix (engine)
286 * @engine Engine to use for signing
287 * @rsap Returns RSA object, or NULL on failure
288 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
290 static int rsa_get_priv_key(const char *keydir, const char *name,
291 ENGINE *engine, RSA **rsap)
294 return rsa_engine_get_priv_key(keydir, name, engine, rsap);
295 return rsa_pem_get_priv_key(keydir, name, rsap);
298 static int rsa_init(void)
302 #if OPENSSL_VERSION_NUMBER < 0x10100000L
303 ret = SSL_library_init();
305 ret = OPENSSL_init_ssl(0, NULL);
308 fprintf(stderr, "Failure to init SSL library\n");
311 #if OPENSSL_VERSION_NUMBER < 0x10100000L
312 SSL_load_error_strings();
314 OpenSSL_add_all_algorithms();
315 OpenSSL_add_all_digests();
316 OpenSSL_add_all_ciphers();
322 static int rsa_engine_init(const char *engine_id, ENGINE **pe)
327 ENGINE_load_builtin_engines();
329 e = ENGINE_by_id(engine_id);
331 fprintf(stderr, "Engine isn't available\n");
333 goto err_engine_by_id;
336 if (!ENGINE_init(e)) {
337 fprintf(stderr, "Couldn't initialize engine\n");
339 goto err_engine_init;
342 if (!ENGINE_set_default_RSA(e)) {
343 fprintf(stderr, "Couldn't set engine as default for RSA\n");
357 #if OPENSSL_VERSION_NUMBER < 0x10100000L
363 static void rsa_remove(void)
365 #if OPENSSL_VERSION_NUMBER < 0x10100000L
366 CRYPTO_cleanup_all_ex_data();
368 #ifdef HAVE_ERR_REMOVE_THREAD_STATE
369 ERR_remove_thread_state(NULL);
377 static void rsa_engine_remove(ENGINE *e)
385 static int rsa_sign_with_key(RSA *rsa, struct checksum_algo *checksum_algo,
386 const struct image_region region[], int region_count,
387 uint8_t **sigp, uint *sig_size)
395 key = EVP_PKEY_new();
397 return rsa_err("EVP_PKEY object creation failed");
399 if (!EVP_PKEY_set1_RSA(key, rsa)) {
400 ret = rsa_err("EVP key setup failed");
404 size = EVP_PKEY_size(key);
407 fprintf(stderr, "Out of memory for signature (%d bytes)\n",
413 context = EVP_MD_CTX_create();
415 ret = rsa_err("EVP context creation failed");
418 EVP_MD_CTX_init(context);
419 if (!EVP_SignInit(context, checksum_algo->calculate_sign())) {
420 ret = rsa_err("Signer setup failed");
424 for (i = 0; i < region_count; i++) {
425 if (!EVP_SignUpdate(context, region[i].data, region[i].size)) {
426 ret = rsa_err("Signing data failed");
431 if (!EVP_SignFinal(context, sig, sig_size, key)) {
432 ret = rsa_err("Could not obtain signature");
435 #if OPENSSL_VERSION_NUMBER < 0x10100000L
436 EVP_MD_CTX_cleanup(context);
438 EVP_MD_CTX_reset(context);
440 EVP_MD_CTX_destroy(context);
443 debug("Got signature: %d bytes, expected %d\n", *sig_size, size);
450 EVP_MD_CTX_destroy(context);
459 int rsa_sign(struct image_sign_info *info,
460 const struct image_region region[], int region_count,
461 uint8_t **sigp, uint *sig_len)
471 if (info->engine_id) {
472 ret = rsa_engine_init(info->engine_id, &e);
477 ret = rsa_get_priv_key(info->keydir, info->keyname, e, &rsa);
480 ret = rsa_sign_with_key(rsa, info->checksum, region,
481 region_count, sigp, sig_len);
487 rsa_engine_remove(e);
496 rsa_engine_remove(e);
503 * rsa_get_exponent(): - Get the public exponent from an RSA key
505 static int rsa_get_exponent(RSA *key, uint64_t *e)
518 RSA_get0_key(key, NULL, &key_e, NULL);
519 if (BN_num_bits(key_e) > 64)
522 *e = BN_get_word(key_e);
524 if (BN_num_bits(key_e) < 33) {
529 bn_te = BN_dup(key_e);
533 if (!BN_rshift(bn_te, bn_te, 32))
536 if (!BN_mask_bits(bn_te, 32))
539 te = BN_get_word(bn_te);
552 * rsa_get_params(): - Get the important parameters of an RSA public key
554 int rsa_get_params(RSA *key, uint64_t *exponent, uint32_t *n0_invp,
555 BIGNUM **modulusp, BIGNUM **r_squaredp)
557 BIGNUM *big1, *big2, *big32, *big2_32;
558 BIGNUM *n, *r, *r_squared, *tmp;
560 BN_CTX *bn_ctx = BN_CTX_new();
563 /* Initialize BIGNUMs */
568 r_squared = BN_new();
572 if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 ||
574 fprintf(stderr, "Out of memory (bignum)\n");
578 if (0 != rsa_get_exponent(key, exponent))
581 RSA_get0_key(key, &key_n, NULL, NULL);
582 if (!BN_copy(n, key_n) || !BN_set_word(big1, 1L) ||
583 !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L))
587 if (!BN_exp(big2_32, big2, big32, bn_ctx))
590 /* Calculate n0_inv = -1 / n[0] mod 2^32 */
591 if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) ||
592 !BN_sub(tmp, big2_32, tmp))
594 *n0_invp = BN_get_word(tmp);
596 /* Calculate R = 2^(# of key bits) */
597 if (!BN_set_word(tmp, BN_num_bits(n)) ||
598 !BN_exp(r, big2, tmp, bn_ctx))
601 /* Calculate r_squared = R^2 mod n */
602 if (!BN_copy(r_squared, r) ||
603 !BN_mul(tmp, r_squared, r, bn_ctx) ||
604 !BN_mod(r_squared, tmp, n, bn_ctx))
608 *r_squaredp = r_squared;
617 fprintf(stderr, "Bignum operations failed\n");
624 static int fdt_add_bignum(void *blob, int noffset, const char *prop_name,
625 BIGNUM *num, int num_bits)
627 int nwords = num_bits / 32;
630 BIGNUM *tmp, *big2, *big32, *big2_32;
640 * Note: This code assumes that all of the above succeed, or all fail.
641 * In practice memory allocations generally do not fail (unless the
642 * process is killed), so it does not seem worth handling each of these
643 * as a separate case. Technicaly this could leak memory on failure,
644 * but a) it won't happen in practice, and b) it doesn't matter as we
645 * will immediately exit with a failure code.
647 if (!tmp || !big2 || !big32 || !big2_32) {
648 fprintf(stderr, "Out of memory (bignum)\n");
653 fprintf(stderr, "Out of memory (bignum context)\n");
656 BN_set_word(big2, 2L);
657 BN_set_word(big32, 32L);
658 BN_exp(big2_32, big2, big32, ctx); /* B = 2^32 */
660 size = nwords * sizeof(uint32_t);
663 fprintf(stderr, "Out of memory (%d bytes)\n", size);
667 /* Write out modulus as big endian array of integers */
668 for (ptr = buf + nwords - 1; ptr >= buf; ptr--) {
669 BN_mod(tmp, num, big2_32, ctx); /* n = N mod B */
670 *ptr = cpu_to_fdt32(BN_get_word(tmp));
671 BN_rshift(num, num, 32); /* N = N/B */
675 * We try signing with successively increasing size values, so this
676 * might fail several times
678 ret = fdt_setprop(blob, noffset, prop_name, buf, size);
685 return ret ? -FDT_ERR_NOSPACE : 0;
688 int rsa_add_verify_data(struct image_sign_info *info, void *keydest)
690 BIGNUM *modulus, *r_squared;
700 debug("%s: Getting verification data\n", __func__);
701 if (info->engine_id) {
702 ret = rsa_engine_init(info->engine_id, &e);
706 ret = rsa_get_pub_key(info->keydir, info->keyname, e, &rsa);
708 goto err_get_pub_key;
709 ret = rsa_get_params(rsa, &exponent, &n0_inv, &modulus, &r_squared);
712 bits = BN_num_bits(modulus);
713 parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME);
714 if (parent == -FDT_ERR_NOTFOUND) {
715 parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME);
718 if (ret != -FDT_ERR_NOSPACE) {
719 fprintf(stderr, "Couldn't create signature node: %s\n",
720 fdt_strerror(parent));
727 /* Either create or overwrite the named key node */
728 snprintf(name, sizeof(name), "key-%s", info->keyname);
729 node = fdt_subnode_offset(keydest, parent, name);
730 if (node == -FDT_ERR_NOTFOUND) {
731 node = fdt_add_subnode(keydest, parent, name);
734 if (ret != -FDT_ERR_NOSPACE) {
735 fprintf(stderr, "Could not create key subnode: %s\n",
739 } else if (node < 0) {
740 fprintf(stderr, "Cannot select keys parent: %s\n",
746 ret = fdt_setprop_string(keydest, node, "key-name-hint",
750 ret = fdt_setprop_u32(keydest, node, "rsa,num-bits", bits);
752 ret = fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv);
754 ret = fdt_setprop_u64(keydest, node, "rsa,exponent", exponent);
757 ret = fdt_add_bignum(keydest, node, "rsa,modulus", modulus,
761 ret = fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared,
765 ret = fdt_setprop_string(keydest, node, FIT_ALGO_PROP,
768 if (!ret && info->require_keys) {
769 ret = fdt_setprop_string(keydest, node, "required",
776 ret = ret == -FDT_ERR_NOSPACE ? -ENOSPC : -EIO;
781 rsa_engine_remove(e);