2 * Copyright (c) 2013, Google Inc.
4 * SPDX-License-Identifier: GPL-2.0+
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 static int rsa_err(const char *msg)
25 unsigned long sslErr = ERR_get_error();
27 fprintf(stderr, "%s", msg);
28 fprintf(stderr, ": %s\n",
29 ERR_error_string(sslErr, 0));
35 * rsa_pem_get_pub_key() - read a public key from a .crt file
37 * @keydir: Directory containins the key
38 * @name Name of key file (will have a .crt extension)
39 * @rsap Returns RSA object, or NULL on failure
40 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
42 static int rsa_pem_get_pub_key(const char *keydir, const char *name, RSA **rsap)
52 snprintf(path, sizeof(path), "%s/%s.crt", keydir, name);
55 fprintf(stderr, "Couldn't open RSA certificate: '%s': %s\n",
56 path, strerror(errno));
60 /* Read the certificate */
62 if (!PEM_read_X509(f, &cert, NULL, NULL)) {
63 rsa_err("Couldn't read certificate");
68 /* Get the public key from the certificate. */
69 key = X509_get_pubkey(cert);
71 rsa_err("Couldn't read public key\n");
76 /* Convert to a RSA_style key. */
77 rsa = EVP_PKEY_get1_RSA(key);
79 rsa_err("Couldn't convert to a RSA style key");
100 * rsa_engine_get_pub_key() - read a public key from given engine
102 * @keydir: Key prefix
104 * @engine Engine to use
105 * @rsap Returns RSA object, or NULL on failure
106 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
108 static int rsa_engine_get_pub_key(const char *keydir, const char *name,
109 ENGINE *engine, RSA **rsap)
111 const char *engine_id;
119 engine_id = ENGINE_get_id(engine);
121 if (engine_id && !strcmp(engine_id, "pkcs11")) {
123 snprintf(key_id, sizeof(key_id),
124 "pkcs11:%s;object=%s;type=public",
127 snprintf(key_id, sizeof(key_id),
128 "pkcs11:object=%s;type=public",
131 fprintf(stderr, "Engine not supported\n");
135 key = ENGINE_load_public_key(engine, key_id, NULL, NULL);
137 return rsa_err("Failure loading public key from engine");
139 /* Convert to a RSA_style key. */
140 rsa = EVP_PKEY_get1_RSA(key);
142 rsa_err("Couldn't convert to a RSA style key");
158 * rsa_get_pub_key() - read a public key
160 * @keydir: Directory containing the key (PEM file) or key prefix (engine)
161 * @name Name of key file (will have a .crt extension)
162 * @engine Engine to use
163 * @rsap Returns RSA object, or NULL on failure
164 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
166 static int rsa_get_pub_key(const char *keydir, const char *name,
167 ENGINE *engine, RSA **rsap)
170 return rsa_engine_get_pub_key(keydir, name, engine, rsap);
171 return rsa_pem_get_pub_key(keydir, name, rsap);
175 * rsa_pem_get_priv_key() - read a private key from a .key file
177 * @keydir: Directory containing the key
178 * @name Name of key file (will have a .key extension)
179 * @rsap Returns RSA object, or NULL on failure
180 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
182 static int rsa_pem_get_priv_key(const char *keydir, const char *name,
190 snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
191 f = fopen(path, "r");
193 fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
194 path, strerror(errno));
198 rsa = PEM_read_RSAPrivateKey(f, 0, NULL, path);
200 rsa_err("Failure reading private key");
211 * rsa_engine_get_priv_key() - read a private key from given engine
213 * @keydir: Key prefix
215 * @engine Engine to use
216 * @rsap Returns RSA object, or NULL on failure
217 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
219 static int rsa_engine_get_priv_key(const char *keydir, const char *name,
220 ENGINE *engine, RSA **rsap)
222 const char *engine_id;
230 engine_id = ENGINE_get_id(engine);
232 if (engine_id && !strcmp(engine_id, "pkcs11")) {
234 snprintf(key_id, sizeof(key_id),
235 "pkcs11:%s;object=%s;type=private",
238 snprintf(key_id, sizeof(key_id),
239 "pkcs11:object=%s;type=private",
242 fprintf(stderr, "Engine not supported\n");
246 key = ENGINE_load_private_key(engine, key_id, NULL, NULL);
248 return rsa_err("Failure loading private key from engine");
250 /* Convert to a RSA_style key. */
251 rsa = EVP_PKEY_get1_RSA(key);
253 rsa_err("Couldn't convert to a RSA style key");
269 * rsa_get_priv_key() - read a private key
271 * @keydir: Directory containing the key (PEM file) or key prefix (engine)
273 * @engine Engine to use for signing
274 * @rsap Returns RSA object, or NULL on failure
275 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
277 static int rsa_get_priv_key(const char *keydir, const char *name,
278 ENGINE *engine, RSA **rsap)
281 return rsa_engine_get_priv_key(keydir, name, engine, rsap);
282 return rsa_pem_get_priv_key(keydir, name, rsap);
285 static int rsa_init(void)
289 ret = SSL_library_init();
291 fprintf(stderr, "Failure to init SSL library\n");
294 SSL_load_error_strings();
296 OpenSSL_add_all_algorithms();
297 OpenSSL_add_all_digests();
298 OpenSSL_add_all_ciphers();
303 static int rsa_engine_init(const char *engine_id, ENGINE **pe)
308 ENGINE_load_builtin_engines();
310 e = ENGINE_by_id(engine_id);
312 fprintf(stderr, "Engine isn't available\n");
314 goto err_engine_by_id;
317 if (!ENGINE_init(e)) {
318 fprintf(stderr, "Couldn't initialize engine\n");
320 goto err_engine_init;
323 if (!ENGINE_set_default_RSA(e)) {
324 fprintf(stderr, "Couldn't set engine as default for RSA\n");
342 static void rsa_remove(void)
344 CRYPTO_cleanup_all_ex_data();
346 #ifdef HAVE_ERR_REMOVE_THREAD_STATE
347 ERR_remove_thread_state(NULL);
354 static void rsa_engine_remove(ENGINE *e)
362 static int rsa_sign_with_key(RSA *rsa, struct checksum_algo *checksum_algo,
363 const struct image_region region[], int region_count,
364 uint8_t **sigp, uint *sig_size)
372 key = EVP_PKEY_new();
374 return rsa_err("EVP_PKEY object creation failed");
376 if (!EVP_PKEY_set1_RSA(key, rsa)) {
377 ret = rsa_err("EVP key setup failed");
381 size = EVP_PKEY_size(key);
384 fprintf(stderr, "Out of memory for signature (%d bytes)\n",
390 context = EVP_MD_CTX_create();
392 ret = rsa_err("EVP context creation failed");
395 EVP_MD_CTX_init(context);
396 if (!EVP_SignInit(context, checksum_algo->calculate_sign())) {
397 ret = rsa_err("Signer setup failed");
401 for (i = 0; i < region_count; i++) {
402 if (!EVP_SignUpdate(context, region[i].data, region[i].size)) {
403 ret = rsa_err("Signing data failed");
408 if (!EVP_SignFinal(context, sig, sig_size, key)) {
409 ret = rsa_err("Could not obtain signature");
412 EVP_MD_CTX_cleanup(context);
413 EVP_MD_CTX_destroy(context);
416 debug("Got signature: %d bytes, expected %d\n", *sig_size, size);
423 EVP_MD_CTX_destroy(context);
432 int rsa_sign(struct image_sign_info *info,
433 const struct image_region region[], int region_count,
434 uint8_t **sigp, uint *sig_len)
444 if (info->engine_id) {
445 ret = rsa_engine_init(info->engine_id, &e);
450 ret = rsa_get_priv_key(info->keydir, info->keyname, e, &rsa);
453 ret = rsa_sign_with_key(rsa, info->checksum, region,
454 region_count, sigp, sig_len);
460 rsa_engine_remove(e);
469 rsa_engine_remove(e);
476 * rsa_get_exponent(): - Get the public exponent from an RSA key
478 static int rsa_get_exponent(RSA *key, uint64_t *e)
490 if (BN_num_bits(key->e) > 64)
493 *e = BN_get_word(key->e);
495 if (BN_num_bits(key->e) < 33) {
500 bn_te = BN_dup(key->e);
504 if (!BN_rshift(bn_te, bn_te, 32))
507 if (!BN_mask_bits(bn_te, 32))
510 te = BN_get_word(bn_te);
523 * rsa_get_params(): - Get the important parameters of an RSA public key
525 int rsa_get_params(RSA *key, uint64_t *exponent, uint32_t *n0_invp,
526 BIGNUM **modulusp, BIGNUM **r_squaredp)
528 BIGNUM *big1, *big2, *big32, *big2_32;
529 BIGNUM *n, *r, *r_squared, *tmp;
530 BN_CTX *bn_ctx = BN_CTX_new();
533 /* Initialize BIGNUMs */
538 r_squared = BN_new();
542 if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 ||
544 fprintf(stderr, "Out of memory (bignum)\n");
548 if (0 != rsa_get_exponent(key, exponent))
551 if (!BN_copy(n, key->n) || !BN_set_word(big1, 1L) ||
552 !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L))
556 if (!BN_exp(big2_32, big2, big32, bn_ctx))
559 /* Calculate n0_inv = -1 / n[0] mod 2^32 */
560 if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) ||
561 !BN_sub(tmp, big2_32, tmp))
563 *n0_invp = BN_get_word(tmp);
565 /* Calculate R = 2^(# of key bits) */
566 if (!BN_set_word(tmp, BN_num_bits(n)) ||
567 !BN_exp(r, big2, tmp, bn_ctx))
570 /* Calculate r_squared = R^2 mod n */
571 if (!BN_copy(r_squared, r) ||
572 !BN_mul(tmp, r_squared, r, bn_ctx) ||
573 !BN_mod(r_squared, tmp, n, bn_ctx))
577 *r_squaredp = r_squared;
586 fprintf(stderr, "Bignum operations failed\n");
593 static int fdt_add_bignum(void *blob, int noffset, const char *prop_name,
594 BIGNUM *num, int num_bits)
596 int nwords = num_bits / 32;
599 BIGNUM *tmp, *big2, *big32, *big2_32;
607 if (!tmp || !big2 || !big32 || !big2_32) {
608 fprintf(stderr, "Out of memory (bignum)\n");
613 fprintf(stderr, "Out of memory (bignum context)\n");
616 BN_set_word(big2, 2L);
617 BN_set_word(big32, 32L);
618 BN_exp(big2_32, big2, big32, ctx); /* B = 2^32 */
620 size = nwords * sizeof(uint32_t);
623 fprintf(stderr, "Out of memory (%d bytes)\n", size);
627 /* Write out modulus as big endian array of integers */
628 for (ptr = buf + nwords - 1; ptr >= buf; ptr--) {
629 BN_mod(tmp, num, big2_32, ctx); /* n = N mod B */
630 *ptr = cpu_to_fdt32(BN_get_word(tmp));
631 BN_rshift(num, num, 32); /* N = N/B */
635 * We try signing with successively increasing size values, so this
636 * might fail several times
638 ret = fdt_setprop(blob, noffset, prop_name, buf, size);
640 return -FDT_ERR_NOSPACE;
650 int rsa_add_verify_data(struct image_sign_info *info, void *keydest)
652 BIGNUM *modulus, *r_squared;
662 debug("%s: Getting verification data\n", __func__);
663 if (info->engine_id) {
664 ret = rsa_engine_init(info->engine_id, &e);
668 ret = rsa_get_pub_key(info->keydir, info->keyname, e, &rsa);
670 goto err_get_pub_key;
671 ret = rsa_get_params(rsa, &exponent, &n0_inv, &modulus, &r_squared);
674 bits = BN_num_bits(modulus);
675 parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME);
676 if (parent == -FDT_ERR_NOTFOUND) {
677 parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME);
680 if (ret != -FDT_ERR_NOSPACE) {
681 fprintf(stderr, "Couldn't create signature node: %s\n",
682 fdt_strerror(parent));
689 /* Either create or overwrite the named key node */
690 snprintf(name, sizeof(name), "key-%s", info->keyname);
691 node = fdt_subnode_offset(keydest, parent, name);
692 if (node == -FDT_ERR_NOTFOUND) {
693 node = fdt_add_subnode(keydest, parent, name);
696 if (ret != -FDT_ERR_NOSPACE) {
697 fprintf(stderr, "Could not create key subnode: %s\n",
701 } else if (node < 0) {
702 fprintf(stderr, "Cannot select keys parent: %s\n",
708 ret = fdt_setprop_string(keydest, node, "key-name-hint",
712 ret = fdt_setprop_u32(keydest, node, "rsa,num-bits", bits);
714 ret = fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv);
716 ret = fdt_setprop_u64(keydest, node, "rsa,exponent", exponent);
719 ret = fdt_add_bignum(keydest, node, "rsa,modulus", modulus,
723 ret = fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared,
727 ret = fdt_setprop_string(keydest, node, FIT_ALGO_PROP,
730 if (!ret && info->require_keys) {
731 ret = fdt_setprop_string(keydest, node, "required",
738 ret = ret == -FDT_ERR_NOSPACE ? -ENOSPC : -EIO;
743 rsa_engine_remove(e);