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>
18 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
19 #define HAVE_ERR_REMOVE_THREAD_STATE
22 static int rsa_err(const char *msg)
24 unsigned long sslErr = ERR_get_error();
26 fprintf(stderr, "%s", msg);
27 fprintf(stderr, ": %s\n",
28 ERR_error_string(sslErr, 0));
34 * rsa_get_pub_key() - read a public key from a .crt file
36 * @keydir: Directory containins the key
37 * @name Name of key file (will have a .crt extension)
38 * @rsap Returns RSA object, or NULL on failure
39 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
41 static int rsa_get_pub_key(const char *keydir, const char *name, RSA **rsap)
51 snprintf(path, sizeof(path), "%s/%s.crt", keydir, name);
54 fprintf(stderr, "Couldn't open RSA certificate: '%s': %s\n",
55 path, strerror(errno));
59 /* Read the certificate */
61 if (!PEM_read_X509(f, &cert, NULL, NULL)) {
62 rsa_err("Couldn't read certificate");
67 /* Get the public key from the certificate. */
68 key = X509_get_pubkey(cert);
70 rsa_err("Couldn't read public key\n");
75 /* Convert to a RSA_style key. */
76 rsa = EVP_PKEY_get1_RSA(key);
78 rsa_err("Couldn't convert to a RSA style key");
98 * rsa_get_priv_key() - read a private key from a .key file
100 * @keydir: Directory containins the key
101 * @name Name of key file (will have a .key extension)
102 * @rsap Returns RSA object, or NULL on failure
103 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
105 static int rsa_get_priv_key(const char *keydir, const char *name, RSA **rsap)
112 snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
113 f = fopen(path, "r");
115 fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
116 path, strerror(errno));
120 rsa = PEM_read_RSAPrivateKey(f, 0, NULL, path);
122 rsa_err("Failure reading private key");
132 static int rsa_init(void)
136 ret = SSL_library_init();
138 fprintf(stderr, "Failure to init SSL library\n");
141 SSL_load_error_strings();
143 OpenSSL_add_all_algorithms();
144 OpenSSL_add_all_digests();
145 OpenSSL_add_all_ciphers();
150 static void rsa_remove(void)
152 CRYPTO_cleanup_all_ex_data();
154 #ifdef HAVE_ERR_REMOVE_THREAD_STATE
155 ERR_remove_thread_state(NULL);
162 static int rsa_sign_with_key(RSA *rsa, const struct image_region region[],
163 int region_count, uint8_t **sigp, uint *sig_size)
171 key = EVP_PKEY_new();
173 return rsa_err("EVP_PKEY object creation failed");
175 if (!EVP_PKEY_set1_RSA(key, rsa)) {
176 ret = rsa_err("EVP key setup failed");
180 size = EVP_PKEY_size(key);
183 fprintf(stderr, "Out of memory for signature (%d bytes)\n",
189 context = EVP_MD_CTX_create();
191 ret = rsa_err("EVP context creation failed");
194 EVP_MD_CTX_init(context);
195 if (!EVP_SignInit(context, EVP_sha1())) {
196 ret = rsa_err("Signer setup failed");
200 for (i = 0; i < region_count; i++) {
201 if (!EVP_SignUpdate(context, region[i].data, region[i].size)) {
202 ret = rsa_err("Signing data failed");
207 if (!EVP_SignFinal(context, sig, sig_size, key)) {
208 ret = rsa_err("Could not obtain signature");
211 EVP_MD_CTX_cleanup(context);
212 EVP_MD_CTX_destroy(context);
215 debug("Got signature: %d bytes, expected %d\n", *sig_size, size);
222 EVP_MD_CTX_destroy(context);
231 int rsa_sign(struct image_sign_info *info,
232 const struct image_region region[], int region_count,
233 uint8_t **sigp, uint *sig_len)
242 ret = rsa_get_priv_key(info->keydir, info->keyname, &rsa);
245 ret = rsa_sign_with_key(rsa, region, region_count, sigp, sig_len);
262 * rsa_get_params(): - Get the important parameters of an RSA public key
264 int rsa_get_params(RSA *key, uint32_t *n0_invp, BIGNUM **modulusp,
267 BIGNUM *big1, *big2, *big32, *big2_32;
268 BIGNUM *n, *r, *r_squared, *tmp;
269 BN_CTX *bn_ctx = BN_CTX_new();
272 /* Initialize BIGNUMs */
277 r_squared = BN_new();
281 if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 ||
283 fprintf(stderr, "Out of memory (bignum)\n");
287 if (!BN_copy(n, key->n) || !BN_set_word(big1, 1L) ||
288 !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L))
292 if (!BN_exp(big2_32, big2, big32, bn_ctx))
295 /* Calculate n0_inv = -1 / n[0] mod 2^32 */
296 if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) ||
297 !BN_sub(tmp, big2_32, tmp))
299 *n0_invp = BN_get_word(tmp);
301 /* Calculate R = 2^(# of key bits) */
302 if (!BN_set_word(tmp, BN_num_bits(n)) ||
303 !BN_exp(r, big2, tmp, bn_ctx))
306 /* Calculate r_squared = R^2 mod n */
307 if (!BN_copy(r_squared, r) ||
308 !BN_mul(tmp, r_squared, r, bn_ctx) ||
309 !BN_mod(r_squared, tmp, n, bn_ctx))
313 *r_squaredp = r_squared;
322 fprintf(stderr, "Bignum operations failed\n");
329 static int fdt_add_bignum(void *blob, int noffset, const char *prop_name,
330 BIGNUM *num, int num_bits)
332 int nwords = num_bits / 32;
335 BIGNUM *tmp, *big2, *big32, *big2_32;
343 if (!tmp || !big2 || !big32 || !big2_32) {
344 fprintf(stderr, "Out of memory (bignum)\n");
349 fprintf(stderr, "Out of memory (bignum context)\n");
352 BN_set_word(big2, 2L);
353 BN_set_word(big32, 32L);
354 BN_exp(big2_32, big2, big32, ctx); /* B = 2^32 */
356 size = nwords * sizeof(uint32_t);
359 fprintf(stderr, "Out of memory (%d bytes)\n", size);
363 /* Write out modulus as big endian array of integers */
364 for (ptr = buf + nwords - 1; ptr >= buf; ptr--) {
365 BN_mod(tmp, num, big2_32, ctx); /* n = N mod B */
366 *ptr = cpu_to_fdt32(BN_get_word(tmp));
367 BN_rshift(num, num, 32); /* N = N/B */
370 ret = fdt_setprop(blob, noffset, prop_name, buf, size);
372 fprintf(stderr, "Failed to write public key to FIT\n");
384 int rsa_add_verify_data(struct image_sign_info *info, void *keydest)
386 BIGNUM *modulus, *r_squared;
394 debug("%s: Getting verification data\n", __func__);
395 ret = rsa_get_pub_key(info->keydir, info->keyname, &rsa);
398 ret = rsa_get_params(rsa, &n0_inv, &modulus, &r_squared);
401 bits = BN_num_bits(modulus);
402 parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME);
403 if (parent == -FDT_ERR_NOTFOUND) {
404 parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME);
406 fprintf(stderr, "Couldn't create signature node: %s\n",
407 fdt_strerror(parent));
412 /* Either create or overwrite the named key node */
413 snprintf(name, sizeof(name), "key-%s", info->keyname);
414 node = fdt_subnode_offset(keydest, parent, name);
415 if (node == -FDT_ERR_NOTFOUND) {
416 node = fdt_add_subnode(keydest, parent, name);
418 fprintf(stderr, "Could not create key subnode: %s\n",
422 } else if (node < 0) {
423 fprintf(stderr, "Cannot select keys parent: %s\n",
428 ret = fdt_setprop_string(keydest, node, "key-name-hint",
430 ret |= fdt_setprop_u32(keydest, node, "rsa,num-bits", bits);
431 ret |= fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv);
432 ret |= fdt_add_bignum(keydest, node, "rsa,modulus", modulus, bits);
433 ret |= fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared, bits);
434 ret |= fdt_setprop_string(keydest, node, FIT_ALGO_PROP,
436 if (info->require_keys) {
437 fdt_setprop_string(keydest, node, "required",