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,
25 #include <openssl/rsa.h>
26 #include <openssl/pem.h>
27 #include <openssl/err.h>
28 #include <openssl/ssl.h>
29 #include <openssl/evp.h>
31 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
32 #define HAVE_ERR_REMOVE_THREAD_STATE
35 static int rsa_err(const char *msg)
37 unsigned long sslErr = ERR_get_error();
39 fprintf(stderr, "%s", msg);
40 fprintf(stderr, ": %s\n",
41 ERR_error_string(sslErr, 0));
47 * rsa_get_pub_key() - read a public key from a .crt file
49 * @keydir: Directory containins the key
50 * @name Name of key file (will have a .crt extension)
51 * @rsap Returns RSA object, or NULL on failure
52 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
54 static int rsa_get_pub_key(const char *keydir, const char *name, RSA **rsap)
64 snprintf(path, sizeof(path), "%s/%s.crt", keydir, name);
67 fprintf(stderr, "Couldn't open RSA certificate: '%s': %s\n",
68 path, strerror(errno));
72 /* Read the certificate */
74 if (!PEM_read_X509(f, &cert, NULL, NULL)) {
75 rsa_err("Couldn't read certificate");
80 /* Get the public key from the certificate. */
81 key = X509_get_pubkey(cert);
83 rsa_err("Couldn't read public key\n");
88 /* Convert to a RSA_style key. */
89 rsa = EVP_PKEY_get1_RSA(key);
91 rsa_err("Couldn't convert to a RSA style key");
111 * rsa_get_priv_key() - read a private key from a .key file
113 * @keydir: Directory containins the key
114 * @name Name of key file (will have a .key extension)
115 * @rsap Returns RSA object, or NULL on failure
116 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
118 static int rsa_get_priv_key(const char *keydir, const char *name, RSA **rsap)
125 snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
126 f = fopen(path, "r");
128 fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
129 path, strerror(errno));
133 rsa = PEM_read_RSAPrivateKey(f, 0, NULL, path);
135 rsa_err("Failure reading private key");
145 static int rsa_init(void)
149 ret = SSL_library_init();
151 fprintf(stderr, "Failure to init SSL library\n");
154 SSL_load_error_strings();
156 OpenSSL_add_all_algorithms();
157 OpenSSL_add_all_digests();
158 OpenSSL_add_all_ciphers();
163 static void rsa_remove(void)
165 CRYPTO_cleanup_all_ex_data();
167 #ifdef HAVE_ERR_REMOVE_THREAD_STATE
168 ERR_remove_thread_state(NULL);
175 static int rsa_sign_with_key(RSA *rsa, const struct image_region region[],
176 int region_count, uint8_t **sigp, uint *sig_size)
184 key = EVP_PKEY_new();
186 return rsa_err("EVP_PKEY object creation failed");
188 if (!EVP_PKEY_set1_RSA(key, rsa)) {
189 ret = rsa_err("EVP key setup failed");
193 size = EVP_PKEY_size(key);
196 fprintf(stderr, "Out of memory for signature (%d bytes)\n",
202 context = EVP_MD_CTX_create();
204 ret = rsa_err("EVP context creation failed");
207 EVP_MD_CTX_init(context);
208 if (!EVP_SignInit(context, EVP_sha1())) {
209 ret = rsa_err("Signer setup failed");
213 for (i = 0; i < region_count; i++) {
214 if (!EVP_SignUpdate(context, region[i].data, region[i].size)) {
215 ret = rsa_err("Signing data failed");
220 if (!EVP_SignFinal(context, sig, sig_size, key)) {
221 ret = rsa_err("Could not obtain signature");
224 EVP_MD_CTX_cleanup(context);
225 EVP_MD_CTX_destroy(context);
228 debug("Got signature: %d bytes, expected %d\n", *sig_size, size);
235 EVP_MD_CTX_destroy(context);
244 int rsa_sign(struct image_sign_info *info,
245 const struct image_region region[], int region_count,
246 uint8_t **sigp, uint *sig_len)
255 ret = rsa_get_priv_key(info->keydir, info->keyname, &rsa);
258 ret = rsa_sign_with_key(rsa, region, region_count, sigp, sig_len);
275 * rsa_get_params(): - Get the important parameters of an RSA public key
277 int rsa_get_params(RSA *key, uint32_t *n0_invp, BIGNUM **modulusp,
280 BIGNUM *big1, *big2, *big32, *big2_32;
281 BIGNUM *n, *r, *r_squared, *tmp;
282 BN_CTX *bn_ctx = BN_CTX_new();
285 /* Initialize BIGNUMs */
290 r_squared = BN_new();
294 if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 ||
296 fprintf(stderr, "Out of memory (bignum)\n");
300 if (!BN_copy(n, key->n) || !BN_set_word(big1, 1L) ||
301 !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L))
305 if (!BN_exp(big2_32, big2, big32, bn_ctx))
308 /* Calculate n0_inv = -1 / n[0] mod 2^32 */
309 if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) ||
310 !BN_sub(tmp, big2_32, tmp))
312 *n0_invp = BN_get_word(tmp);
314 /* Calculate R = 2^(# of key bits) */
315 if (!BN_set_word(tmp, BN_num_bits(n)) ||
316 !BN_exp(r, big2, tmp, bn_ctx))
319 /* Calculate r_squared = R^2 mod n */
320 if (!BN_copy(r_squared, r) ||
321 !BN_mul(tmp, r_squared, r, bn_ctx) ||
322 !BN_mod(r_squared, tmp, n, bn_ctx))
326 *r_squaredp = r_squared;
335 fprintf(stderr, "Bignum operations failed\n");
342 static int fdt_add_bignum(void *blob, int noffset, const char *prop_name,
343 BIGNUM *num, int num_bits)
345 int nwords = num_bits / 32;
348 BIGNUM *tmp, *big2, *big32, *big2_32;
356 if (!tmp || !big2 || !big32 || !big2_32) {
357 fprintf(stderr, "Out of memory (bignum)\n");
362 fprintf(stderr, "Out of memory (bignum context)\n");
365 BN_set_word(big2, 2L);
366 BN_set_word(big32, 32L);
367 BN_exp(big2_32, big2, big32, ctx); /* B = 2^32 */
369 size = nwords * sizeof(uint32_t);
372 fprintf(stderr, "Out of memory (%d bytes)\n", size);
376 /* Write out modulus as big endian array of integers */
377 for (ptr = buf + nwords - 1; ptr >= buf; ptr--) {
378 BN_mod(tmp, num, big2_32, ctx); /* n = N mod B */
379 *ptr = cpu_to_fdt32(BN_get_word(tmp));
380 BN_rshift(num, num, 32); /* N = N/B */
383 ret = fdt_setprop(blob, noffset, prop_name, buf, size);
385 fprintf(stderr, "Failed to write public key to FIT\n");
397 int rsa_add_verify_data(struct image_sign_info *info, void *keydest)
399 BIGNUM *modulus, *r_squared;
407 debug("%s: Getting verification data\n", __func__);
408 ret = rsa_get_pub_key(info->keydir, info->keyname, &rsa);
411 ret = rsa_get_params(rsa, &n0_inv, &modulus, &r_squared);
414 bits = BN_num_bits(modulus);
415 parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME);
416 if (parent == -FDT_ERR_NOTFOUND) {
417 parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME);
419 fprintf(stderr, "Couldn't create signature node: %s\n",
420 fdt_strerror(parent));
425 /* Either create or overwrite the named key node */
426 snprintf(name, sizeof(name), "key-%s", info->keyname);
427 node = fdt_subnode_offset(keydest, parent, name);
428 if (node == -FDT_ERR_NOTFOUND) {
429 node = fdt_add_subnode(keydest, parent, name);
431 fprintf(stderr, "Could not create key subnode: %s\n",
435 } else if (node < 0) {
436 fprintf(stderr, "Cannot select keys parent: %s\n",
441 ret = fdt_setprop_string(keydest, node, "key-name-hint",
443 ret |= fdt_setprop_u32(keydest, node, "rsa,num-bits", bits);
444 ret |= fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv);
445 ret |= fdt_add_bignum(keydest, node, "rsa,modulus", modulus, bits);
446 ret |= fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared, bits);
447 ret |= fdt_setprop_string(keydest, node, FIT_ALGO_PROP,
449 if (info->require_keys) {
450 fdt_setprop_string(keydest, node, "required",