1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright (c) 2013, Google Inc.
6 #define OPENSSL_API_COMPAT 0x10101000L
14 #include <u-boot/fdt-libcrypto.h>
15 #include <openssl/bn.h>
16 #include <openssl/ec.h>
17 #include <openssl/rsa.h>
18 #include <openssl/pem.h>
19 #include <openssl/err.h>
20 #include <openssl/ssl.h>
21 #include <openssl/evp.h>
22 #include <openssl/engine.h>
24 static int rsa_err(const char *msg)
26 unsigned long sslErr = ERR_get_error();
28 fprintf(stderr, "%s", msg);
29 fprintf(stderr, ": %s\n",
30 ERR_error_string(sslErr, 0));
36 * rsa_pem_get_pub_key() - read a public key from a .crt file
38 * @keydir: Directory containins the key
39 * @name Name of key file (will have a .crt extension)
40 * @evpp Returns EVP_PKEY object, or NULL on failure
41 * Return: 0 if ok, -ve on error (in which case *evpp will be set to NULL)
43 static int rsa_pem_get_pub_key(const char *keydir, const char *name, EVP_PKEY **evpp)
55 snprintf(path, sizeof(path), "%s/%s.crt", keydir, name);
58 fprintf(stderr, "Couldn't open RSA certificate: '%s': %s\n",
59 path, strerror(errno));
63 /* Read the certificate */
65 if (!PEM_read_X509(f, &cert, NULL, NULL)) {
66 rsa_err("Couldn't read certificate");
71 /* Get the public key from the certificate. */
72 key = X509_get_pubkey(cert);
74 rsa_err("Couldn't read public key\n");
93 * rsa_engine_get_pub_key() - read a public key from given engine
97 * @engine Engine to use
98 * @evpp Returns EVP_PKEY object, or NULL on failure
99 * Return: 0 if ok, -ve on error (in which case *evpp will be set to NULL)
101 static int rsa_engine_get_pub_key(const char *keydir, const char *name,
102 ENGINE *engine, EVP_PKEY **evpp)
104 const char *engine_id;
106 EVP_PKEY *key = NULL;
113 engine_id = ENGINE_get_id(engine);
115 if (engine_id && !strcmp(engine_id, "pkcs11")) {
117 if (strstr(keydir, "object="))
118 snprintf(key_id, sizeof(key_id),
119 "pkcs11:%s;type=public",
122 snprintf(key_id, sizeof(key_id),
123 "pkcs11:%s;object=%s;type=public",
126 snprintf(key_id, sizeof(key_id),
127 "pkcs11:object=%s;type=public",
129 } else if (engine_id) {
131 snprintf(key_id, sizeof(key_id),
135 snprintf(key_id, sizeof(key_id),
139 fprintf(stderr, "Engine not supported\n");
143 key = ENGINE_load_public_key(engine, key_id, NULL, NULL);
145 return rsa_err("Failure loading public key from engine");
153 * rsa_get_pub_key() - read a public key
155 * @keydir: Directory containing the key (PEM file) or key prefix (engine)
156 * @name Name of key file (will have a .crt extension)
157 * @engine Engine to use
158 * @evpp Returns EVP_PKEY object, or NULL on failure
159 * Return: 0 if ok, -ve on error (in which case *evpp will be set to NULL)
161 static int rsa_get_pub_key(const char *keydir, const char *name,
162 ENGINE *engine, EVP_PKEY **evpp)
165 return rsa_engine_get_pub_key(keydir, name, engine, evpp);
166 return rsa_pem_get_pub_key(keydir, name, evpp);
170 * rsa_pem_get_priv_key() - read a private key from a .key file
172 * @keydir: Directory containing the key
173 * @name Name of key file (will have a .key extension)
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_pem_get_priv_key(const char *keydir, const char *name,
178 const char *keyfile, EVP_PKEY **evpp)
180 char path[1024] = {0};
188 snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
190 snprintf(path, sizeof(path), "%s", keyfile);
194 f = fopen(path, "r");
196 fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
197 path, strerror(errno));
201 if (!PEM_read_PrivateKey(f, evpp, NULL, path)) {
202 rsa_err("Failure reading private key");
212 * rsa_engine_get_priv_key() - read a private key from given engine
214 * @keydir: Key prefix
216 * @engine Engine to use
217 * @evpp Returns EVP_PKEY object, or NULL on failure
218 * Return: 0 if ok, -ve on error (in which case *evpp will be set to NULL)
220 static int rsa_engine_get_priv_key(const char *keydir, const char *name,
222 ENGINE *engine, EVP_PKEY **evpp)
224 const char *engine_id;
226 EVP_PKEY *key = NULL;
231 engine_id = ENGINE_get_id(engine);
233 if (engine_id && !strcmp(engine_id, "pkcs11")) {
234 if (!keydir && !name) {
235 fprintf(stderr, "Please use 'keydir' with PKCS11\n");
239 if (strstr(keydir, "object="))
240 snprintf(key_id, sizeof(key_id),
241 "pkcs11:%s;type=private",
244 snprintf(key_id, sizeof(key_id),
245 "pkcs11:%s;object=%s;type=private",
248 snprintf(key_id, sizeof(key_id),
249 "pkcs11:object=%s;type=private",
251 } else if (engine_id) {
253 snprintf(key_id, sizeof(key_id),
257 snprintf(key_id, sizeof(key_id),
261 snprintf(key_id, sizeof(key_id), "%s", keyfile);
266 fprintf(stderr, "Engine not supported\n");
270 key = ENGINE_load_private_key(engine, key_id, NULL, NULL);
272 return rsa_err("Failure loading private key from engine");
280 * rsa_get_priv_key() - read a private key
282 * @keydir: Directory containing the key (PEM file) or key prefix (engine)
284 * @engine Engine to use for signing
285 * @evpp Returns EVP_PKEY object, or NULL on failure
286 * Return: 0 if ok, -ve on error (in which case *evpp will be set to NULL)
288 static int rsa_get_priv_key(const char *keydir, const char *name,
289 const char *keyfile, ENGINE *engine, EVP_PKEY **evpp)
292 return rsa_engine_get_priv_key(keydir, name, keyfile, engine,
294 return rsa_pem_get_priv_key(keydir, name, keyfile, evpp);
297 static int rsa_init(void)
301 ret = OPENSSL_init_ssl(0, NULL);
303 fprintf(stderr, "Failure to init SSL library\n");
310 static int rsa_engine_init(const char *engine_id, ENGINE **pe)
312 const char *key_pass;
316 ENGINE_load_builtin_engines();
318 e = ENGINE_by_id(engine_id);
320 fprintf(stderr, "Engine isn't available\n");
324 if (!ENGINE_init(e)) {
325 fprintf(stderr, "Couldn't initialize engine\n");
327 goto err_engine_init;
330 if (!ENGINE_set_default_RSA(e)) {
331 fprintf(stderr, "Couldn't set engine as default for RSA\n");
336 key_pass = getenv("MKIMAGE_SIGN_PIN");
338 if (!ENGINE_ctrl_cmd_string(e, "PIN", key_pass, 0)) {
339 fprintf(stderr, "Couldn't set PIN\n");
357 static void rsa_engine_remove(ENGINE *e)
365 static int rsa_sign_with_key(EVP_PKEY *pkey, struct padding_algo *padding_algo,
366 struct checksum_algo *checksum_algo,
367 const struct image_region region[], int region_count,
368 uint8_t **sigp, uint *sig_size)
377 size = EVP_PKEY_size(pkey);
380 fprintf(stderr, "Out of memory for signature (%zu bytes)\n",
386 context = EVP_MD_CTX_create();
388 ret = rsa_err("EVP context creation failed");
391 EVP_MD_CTX_init(context);
393 ckey = EVP_PKEY_CTX_new(pkey, NULL);
395 ret = rsa_err("EVP key context creation failed");
399 if (EVP_DigestSignInit(context, &ckey,
400 checksum_algo->calculate_sign(),
402 ret = rsa_err("Signer setup failed");
406 if (CONFIG_IS_ENABLED(FIT_RSASSA_PSS) && padding_algo &&
407 !strcmp(padding_algo->name, "pss")) {
408 if (EVP_PKEY_CTX_set_rsa_padding(ckey,
409 RSA_PKCS1_PSS_PADDING) <= 0) {
410 ret = rsa_err("Signer padding setup failed");
415 for (i = 0; i < region_count; i++) {
416 if (!EVP_DigestSignUpdate(context, region[i].data,
418 ret = rsa_err("Signing data failed");
423 if (!EVP_DigestSignFinal(context, sig, &size)) {
424 ret = rsa_err("Could not obtain signature");
428 EVP_MD_CTX_reset(context);
429 EVP_MD_CTX_destroy(context);
431 debug("Got signature: %zu bytes, expected %d\n", size, EVP_PKEY_size(pkey));
438 EVP_MD_CTX_destroy(context);
445 int rsa_sign(struct image_sign_info *info,
446 const struct image_region region[], int region_count,
447 uint8_t **sigp, uint *sig_len)
449 EVP_PKEY *pkey = NULL;
457 if (info->engine_id) {
458 ret = rsa_engine_init(info->engine_id, &e);
463 ret = rsa_get_priv_key(info->keydir, info->keyname, info->keyfile,
467 ret = rsa_sign_with_key(pkey, info->padding, info->checksum, region,
468 region_count, sigp, sig_len);
474 rsa_engine_remove(e);
482 rsa_engine_remove(e);
487 * rsa_get_exponent(): - Get the public exponent from an RSA key
489 static int rsa_get_exponent(RSA *key, uint64_t *e)
502 RSA_get0_key(key, NULL, &key_e, NULL);
503 if (BN_num_bits(key_e) > 64)
506 *e = BN_get_word(key_e);
508 if (BN_num_bits(key_e) < 33) {
513 bn_te = BN_dup(key_e);
517 if (!BN_rshift(bn_te, bn_te, 32))
520 if (!BN_mask_bits(bn_te, 32))
523 te = BN_get_word(bn_te);
536 * rsa_get_params(): - Get the important parameters of an RSA public key
538 int rsa_get_params(RSA *key, uint64_t *exponent, uint32_t *n0_invp,
539 BIGNUM **modulusp, BIGNUM **r_squaredp)
541 BIGNUM *big1, *big2, *big32, *big2_32;
542 BIGNUM *n, *r, *r_squared, *tmp;
544 BN_CTX *bn_ctx = BN_CTX_new();
547 /* Initialize BIGNUMs */
552 r_squared = BN_new();
556 if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 ||
558 fprintf(stderr, "Out of memory (bignum)\n");
562 if (0 != rsa_get_exponent(key, exponent))
565 RSA_get0_key(key, &key_n, NULL, NULL);
566 if (!BN_copy(n, key_n) || !BN_set_word(big1, 1L) ||
567 !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L))
571 if (!BN_exp(big2_32, big2, big32, bn_ctx))
574 /* Calculate n0_inv = -1 / n[0] mod 2^32 */
575 if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) ||
576 !BN_sub(tmp, big2_32, tmp))
578 *n0_invp = BN_get_word(tmp);
580 /* Calculate R = 2^(# of key bits) */
581 if (!BN_set_word(tmp, BN_num_bits(n)) ||
582 !BN_exp(r, big2, tmp, bn_ctx))
585 /* Calculate r_squared = R^2 mod n */
586 if (!BN_copy(r_squared, r) ||
587 !BN_mul(tmp, r_squared, r, bn_ctx) ||
588 !BN_mod(r_squared, tmp, n, bn_ctx))
592 *r_squaredp = r_squared;
601 fprintf(stderr, "Bignum operations failed\n");
608 int rsa_add_verify_data(struct image_sign_info *info, void *keydest)
610 BIGNUM *modulus, *r_squared;
618 EVP_PKEY *pkey = NULL;
621 debug("%s: Getting verification data\n", __func__);
622 if (info->engine_id) {
623 ret = rsa_engine_init(info->engine_id, &e);
627 ret = rsa_get_pub_key(info->keydir, info->keyname, e, &pkey);
629 goto err_get_pub_key;
631 rsa = (RSA *)EVP_PKEY_get0_RSA(pkey);
632 ret = rsa_get_params(rsa, &exponent, &n0_inv, &modulus, &r_squared);
635 bits = BN_num_bits(modulus);
636 parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME);
637 if (parent == -FDT_ERR_NOTFOUND) {
638 parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME);
641 if (ret != -FDT_ERR_NOSPACE) {
642 fprintf(stderr, "Couldn't create signature node: %s\n",
643 fdt_strerror(parent));
650 /* Either create or overwrite the named key node */
651 snprintf(name, sizeof(name), "key-%s", info->keyname);
652 node = fdt_subnode_offset(keydest, parent, name);
653 if (node == -FDT_ERR_NOTFOUND) {
654 node = fdt_add_subnode(keydest, parent, name);
657 if (ret != -FDT_ERR_NOSPACE) {
658 fprintf(stderr, "Could not create key subnode: %s\n",
662 } else if (node < 0) {
663 fprintf(stderr, "Cannot select keys parent: %s\n",
669 ret = fdt_setprop_string(keydest, node, FIT_KEY_HINT,
673 ret = fdt_setprop_u32(keydest, node, "rsa,num-bits", bits);
675 ret = fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv);
677 ret = fdt_setprop_u64(keydest, node, "rsa,exponent", exponent);
680 ret = fdt_add_bignum(keydest, node, "rsa,modulus", modulus,
684 ret = fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared,
688 ret = fdt_setprop_string(keydest, node, FIT_ALGO_PROP,
691 if (!ret && info->require_keys) {
692 ret = fdt_setprop_string(keydest, node, FIT_KEY_REQUIRED,
699 ret = ret == -FDT_ERR_NOSPACE ? -ENOSPC : -EIO;
704 rsa_engine_remove(e);