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, struct checksum_algo *checksum_algo,
163
const struct image_region region[], int region_count,
164
uint8_t **sigp, uint *sig_size)
172
key = EVP_PKEY_new();
174
return rsa_err("EVP_PKEY object creation failed");
176
if (!EVP_PKEY_set1_RSA(key, rsa)) {
177
ret = rsa_err("EVP key setup failed");
181
size = EVP_PKEY_size(key);
184
fprintf(stderr, "Out of memory for signature (%d bytes)\n",
190
context = EVP_MD_CTX_create();
192
ret = rsa_err("EVP context creation failed");
195
EVP_MD_CTX_init(context);
196
if (!EVP_SignInit(context, checksum_algo->calculate_sign())) {
197
ret = rsa_err("Signer setup failed");
201
for (i = 0; i < region_count; i++) {
202
if (!EVP_SignUpdate(context, region[i].data, region[i].size)) {
203
ret = rsa_err("Signing data failed");
208
if (!EVP_SignFinal(context, sig, sig_size, key)) {
209
ret = rsa_err("Could not obtain signature");
212
EVP_MD_CTX_cleanup(context);
213
EVP_MD_CTX_destroy(context);
216
debug("Got signature: %d bytes, expected %d\n", *sig_size, size);
223
EVP_MD_CTX_destroy(context);
232
int rsa_sign(struct image_sign_info *info,
233
const struct image_region region[], int region_count,
234
uint8_t **sigp, uint *sig_len)
243
ret = rsa_get_priv_key(info->keydir, info->keyname, &rsa);
246
ret = rsa_sign_with_key(rsa, info->algo->checksum, region,
247
region_count, sigp, sig_len);
264
* rsa_get_params(): - Get the important parameters of an RSA public key
266
int rsa_get_params(RSA *key, uint32_t *n0_invp, BIGNUM **modulusp,
269
BIGNUM *big1, *big2, *big32, *big2_32;
270
BIGNUM *n, *r, *r_squared, *tmp;
271
BN_CTX *bn_ctx = BN_CTX_new();
274
/* Initialize BIGNUMs */
279
r_squared = BN_new();
283
if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 ||
285
fprintf(stderr, "Out of memory (bignum)\n");
289
if (!BN_copy(n, key->n) || !BN_set_word(big1, 1L) ||
290
!BN_set_word(big2, 2L) || !BN_set_word(big32, 32L))
294
if (!BN_exp(big2_32, big2, big32, bn_ctx))
297
/* Calculate n0_inv = -1 / n[0] mod 2^32 */
298
if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) ||
299
!BN_sub(tmp, big2_32, tmp))
301
*n0_invp = BN_get_word(tmp);
303
/* Calculate R = 2^(# of key bits) */
304
if (!BN_set_word(tmp, BN_num_bits(n)) ||
305
!BN_exp(r, big2, tmp, bn_ctx))
308
/* Calculate r_squared = R^2 mod n */
309
if (!BN_copy(r_squared, r) ||
310
!BN_mul(tmp, r_squared, r, bn_ctx) ||
311
!BN_mod(r_squared, tmp, n, bn_ctx))
315
*r_squaredp = r_squared;
324
fprintf(stderr, "Bignum operations failed\n");
331
static int fdt_add_bignum(void *blob, int noffset, const char *prop_name,
332
BIGNUM *num, int num_bits)
334
int nwords = num_bits / 32;
337
BIGNUM *tmp, *big2, *big32, *big2_32;
345
if (!tmp || !big2 || !big32 || !big2_32) {
346
fprintf(stderr, "Out of memory (bignum)\n");
351
fprintf(stderr, "Out of memory (bignum context)\n");
354
BN_set_word(big2, 2L);
355
BN_set_word(big32, 32L);
356
BN_exp(big2_32, big2, big32, ctx); /* B = 2^32 */
358
size = nwords * sizeof(uint32_t);
361
fprintf(stderr, "Out of memory (%d bytes)\n", size);
365
/* Write out modulus as big endian array of integers */
366
for (ptr = buf + nwords - 1; ptr >= buf; ptr--) {
367
BN_mod(tmp, num, big2_32, ctx); /* n = N mod B */
368
*ptr = cpu_to_fdt32(BN_get_word(tmp));
369
BN_rshift(num, num, 32); /* N = N/B */
372
ret = fdt_setprop(blob, noffset, prop_name, buf, size);
374
fprintf(stderr, "Failed to write public key to FIT\n");
386
int rsa_add_verify_data(struct image_sign_info *info, void *keydest)
388
BIGNUM *modulus, *r_squared;
396
debug("%s: Getting verification data\n", __func__);
397
ret = rsa_get_pub_key(info->keydir, info->keyname, &rsa);
400
ret = rsa_get_params(rsa, &n0_inv, &modulus, &r_squared);
403
bits = BN_num_bits(modulus);
404
parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME);
405
if (parent == -FDT_ERR_NOTFOUND) {
406
parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME);
408
fprintf(stderr, "Couldn't create signature node: %s\n",
409
fdt_strerror(parent));
414
/* Either create or overwrite the named key node */
415
snprintf(name, sizeof(name), "key-%s", info->keyname);
416
node = fdt_subnode_offset(keydest, parent, name);
417
if (node == -FDT_ERR_NOTFOUND) {
418
node = fdt_add_subnode(keydest, parent, name);
420
fprintf(stderr, "Could not create key subnode: %s\n",
424
} else if (node < 0) {
425
fprintf(stderr, "Cannot select keys parent: %s\n",
430
ret = fdt_setprop_string(keydest, node, "key-name-hint",
432
ret |= fdt_setprop_u32(keydest, node, "rsa,num-bits", bits);
433
ret |= fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv);
434
ret |= fdt_add_bignum(keydest, node, "rsa,modulus", modulus, bits);
435
ret |= fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared, bits);
436
ret |= fdt_setprop_string(keydest, node, FIT_ALGO_PROP,
438
if (info->require_keys) {
439
fdt_setprop_string(keydest, node, "required",