2 * Copyright (c) 2013, Google Inc.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of
7 * the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
26 #include <openssl/rsa.h>
27 #include <openssl/pem.h>
28 #include <openssl/err.h>
29 #include <openssl/ssl.h>
30 #include <openssl/evp.h>
32 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
33 #define HAVE_ERR_REMOVE_THREAD_STATE
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_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_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");
112 * rsa_get_priv_key() - read a private key from a .key file
114 * @keydir: Directory containins the key
115 * @name Name of key file (will have a .key extension)
116 * @rsap Returns RSA object, or NULL on failure
117 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
119 static int rsa_get_priv_key(const char *keydir, const char *name, RSA **rsap)
126 snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
127 f = fopen(path, "r");
129 fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
130 path, strerror(errno));
134 rsa = PEM_read_RSAPrivateKey(f, 0, NULL, path);
136 rsa_err("Failure reading private key");
146 static int rsa_init(void)
150 ret = SSL_library_init();
152 fprintf(stderr, "Failure to init SSL library\n");
155 SSL_load_error_strings();
157 OpenSSL_add_all_algorithms();
158 OpenSSL_add_all_digests();
159 OpenSSL_add_all_ciphers();
164 static void rsa_remove(void)
166 CRYPTO_cleanup_all_ex_data();
168 #ifdef HAVE_ERR_REMOVE_THREAD_STATE
169 ERR_remove_thread_state(NULL);
176 static int rsa_sign_with_key(RSA *rsa, const struct image_region region[],
177 int region_count, uint8_t **sigp, uint *sig_size)
185 key = EVP_PKEY_new();
187 return rsa_err("EVP_PKEY object creation failed");
189 if (!EVP_PKEY_set1_RSA(key, rsa)) {
190 ret = rsa_err("EVP key setup failed");
194 size = EVP_PKEY_size(key);
197 fprintf(stderr, "Out of memory for signature (%d bytes)\n",
203 context = EVP_MD_CTX_create();
205 ret = rsa_err("EVP context creation failed");
208 EVP_MD_CTX_init(context);
209 if (!EVP_SignInit(context, EVP_sha1())) {
210 ret = rsa_err("Signer setup failed");
214 for (i = 0; i < region_count; i++) {
215 if (!EVP_SignUpdate(context, region[i].data, region[i].size)) {
216 ret = rsa_err("Signing data failed");
221 if (!EVP_SignFinal(context, sig, sig_size, key)) {
222 ret = rsa_err("Could not obtain signature");
225 EVP_MD_CTX_cleanup(context);
226 EVP_MD_CTX_destroy(context);
229 debug("Got signature: %d bytes, expected %d\n", *sig_size, size);
236 EVP_MD_CTX_destroy(context);
245 int rsa_sign(struct image_sign_info *info,
246 const struct image_region region[], int region_count,
247 uint8_t **sigp, uint *sig_len)
256 ret = rsa_get_priv_key(info->keydir, info->keyname, &rsa);
259 ret = rsa_sign_with_key(rsa, region, region_count, sigp, sig_len);
276 * rsa_get_params(): - Get the important parameters of an RSA public key
278 int rsa_get_params(RSA *key, uint32_t *n0_invp, BIGNUM **modulusp,
281 BIGNUM *big1, *big2, *big32, *big2_32;
282 BIGNUM *n, *r, *r_squared, *tmp;
283 BN_CTX *bn_ctx = BN_CTX_new();
286 /* Initialize BIGNUMs */
291 r_squared = BN_new();
295 if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 ||
297 fprintf(stderr, "Out of memory (bignum)\n");
301 if (!BN_copy(n, key->n) || !BN_set_word(big1, 1L) ||
302 !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L))
306 if (!BN_exp(big2_32, big2, big32, bn_ctx))
309 /* Calculate n0_inv = -1 / n[0] mod 2^32 */
310 if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) ||
311 !BN_sub(tmp, big2_32, tmp))
313 *n0_invp = BN_get_word(tmp);
315 /* Calculate R = 2^(# of key bits) */
316 if (!BN_set_word(tmp, BN_num_bits(n)) ||
317 !BN_exp(r, big2, tmp, bn_ctx))
320 /* Calculate r_squared = R^2 mod n */
321 if (!BN_copy(r_squared, r) ||
322 !BN_mul(tmp, r_squared, r, bn_ctx) ||
323 !BN_mod(r_squared, tmp, n, bn_ctx))
327 *r_squaredp = r_squared;
336 fprintf(stderr, "Bignum operations failed\n");
343 static int fdt_add_bignum(void *blob, int noffset, const char *prop_name,
344 BIGNUM *num, int num_bits)
346 int nwords = num_bits / 32;
349 BIGNUM *tmp, *big2, *big32, *big2_32;
357 if (!tmp || !big2 || !big32 || !big2_32) {
358 fprintf(stderr, "Out of memory (bignum)\n");
363 fprintf(stderr, "Out of memory (bignum context)\n");
366 BN_set_word(big2, 2L);
367 BN_set_word(big32, 32L);
368 BN_exp(big2_32, big2, big32, ctx); /* B = 2^32 */
370 size = nwords * sizeof(uint32_t);
373 fprintf(stderr, "Out of memory (%d bytes)\n", size);
377 /* Write out modulus as big endian array of integers */
378 for (ptr = buf + nwords - 1; ptr >= buf; ptr--) {
379 BN_mod(tmp, num, big2_32, ctx); /* n = N mod B */
380 *ptr = cpu_to_fdt32(BN_get_word(tmp));
381 BN_rshift(num, num, 32); /* N = N/B */
384 ret = fdt_setprop(blob, noffset, prop_name, buf, size);
386 fprintf(stderr, "Failed to write public key to FIT\n");
398 int rsa_add_verify_data(struct image_sign_info *info, void *keydest)
400 BIGNUM *modulus, *r_squared;
408 debug("%s: Getting verification data\n", __func__);
409 ret = rsa_get_pub_key(info->keydir, info->keyname, &rsa);
412 ret = rsa_get_params(rsa, &n0_inv, &modulus, &r_squared);
415 bits = BN_num_bits(modulus);
416 parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME);
417 if (parent == -FDT_ERR_NOTFOUND) {
418 parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME);
420 fprintf(stderr, "Couldn't create signature node: %s\n",
421 fdt_strerror(parent));
426 /* Either create or overwrite the named key node */
427 snprintf(name, sizeof(name), "key-%s", info->keyname);
428 node = fdt_subnode_offset(keydest, parent, name);
429 if (node == -FDT_ERR_NOTFOUND) {
430 node = fdt_add_subnode(keydest, parent, name);
432 fprintf(stderr, "Could not create key subnode: %s\n",
436 } else if (node < 0) {
437 fprintf(stderr, "Cannot select keys parent: %s\n",
442 ret = fdt_setprop_string(keydest, node, "key-name-hint",
444 ret |= fdt_setprop_u32(keydest, node, "rsa,num-bits", bits);
445 ret |= fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv);
446 ret |= fdt_add_bignum(keydest, node, "rsa,modulus", modulus, bits);
447 ret |= fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared, bits);
448 ret |= fdt_setprop_string(keydest, node, FIT_ALGO_PROP,
450 if (info->require_keys) {
451 fdt_setprop_string(keydest, node, "required",