]> git.kernelconcepts.de Git - karo-tx-uboot.git/blob - lib/rsa/rsa-sign.c
Merge git://git.denx.de/u-boot-arm
[karo-tx-uboot.git] / lib / rsa / rsa-sign.c
1 /*
2  * Copyright (c) 2013, Google Inc.
3  *
4  * SPDX-License-Identifier:     GPL-2.0+
5  */
6
7 #include "mkimage.h"
8 #include <stdio.h>
9 #include <string.h>
10 #include <image.h>
11 #include <time.h>
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>
17
18 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
19 #define HAVE_ERR_REMOVE_THREAD_STATE
20 #endif
21
22 static int rsa_err(const char *msg)
23 {
24         unsigned long sslErr = ERR_get_error();
25
26         fprintf(stderr, "%s", msg);
27         fprintf(stderr, ": %s\n",
28                 ERR_error_string(sslErr, 0));
29
30         return -1;
31 }
32
33 /**
34  * rsa_get_pub_key() - read a public key from a .crt file
35  *
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)
40  */
41 static int rsa_get_pub_key(const char *keydir, const char *name, RSA **rsap)
42 {
43         char path[1024];
44         EVP_PKEY *key;
45         X509 *cert;
46         RSA *rsa;
47         FILE *f;
48         int ret;
49
50         *rsap = NULL;
51         snprintf(path, sizeof(path), "%s/%s.crt", keydir, name);
52         f = fopen(path, "r");
53         if (!f) {
54                 fprintf(stderr, "Couldn't open RSA certificate: '%s': %s\n",
55                         path, strerror(errno));
56                 return -EACCES;
57         }
58
59         /* Read the certificate */
60         cert = NULL;
61         if (!PEM_read_X509(f, &cert, NULL, NULL)) {
62                 rsa_err("Couldn't read certificate");
63                 ret = -EINVAL;
64                 goto err_cert;
65         }
66
67         /* Get the public key from the certificate. */
68         key = X509_get_pubkey(cert);
69         if (!key) {
70                 rsa_err("Couldn't read public key\n");
71                 ret = -EINVAL;
72                 goto err_pubkey;
73         }
74
75         /* Convert to a RSA_style key. */
76         rsa = EVP_PKEY_get1_RSA(key);
77         if (!rsa) {
78                 rsa_err("Couldn't convert to a RSA style key");
79                 goto err_rsa;
80         }
81         fclose(f);
82         EVP_PKEY_free(key);
83         X509_free(cert);
84         *rsap = rsa;
85
86         return 0;
87
88 err_rsa:
89         EVP_PKEY_free(key);
90 err_pubkey:
91         X509_free(cert);
92 err_cert:
93         fclose(f);
94         return ret;
95 }
96
97 /**
98  * rsa_get_priv_key() - read a private key from a .key file
99  *
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)
104  */
105 static int rsa_get_priv_key(const char *keydir, const char *name, RSA **rsap)
106 {
107         char path[1024];
108         RSA *rsa;
109         FILE *f;
110
111         *rsap = NULL;
112         snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
113         f = fopen(path, "r");
114         if (!f) {
115                 fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
116                         path, strerror(errno));
117                 return -ENOENT;
118         }
119
120         rsa = PEM_read_RSAPrivateKey(f, 0, NULL, path);
121         if (!rsa) {
122                 rsa_err("Failure reading private key");
123                 fclose(f);
124                 return -EPROTO;
125         }
126         fclose(f);
127         *rsap = rsa;
128
129         return 0;
130 }
131
132 static int rsa_init(void)
133 {
134         int ret;
135
136         ret = SSL_library_init();
137         if (!ret) {
138                 fprintf(stderr, "Failure to init SSL library\n");
139                 return -1;
140         }
141         SSL_load_error_strings();
142
143         OpenSSL_add_all_algorithms();
144         OpenSSL_add_all_digests();
145         OpenSSL_add_all_ciphers();
146
147         return 0;
148 }
149
150 static void rsa_remove(void)
151 {
152         CRYPTO_cleanup_all_ex_data();
153         ERR_free_strings();
154 #ifdef HAVE_ERR_REMOVE_THREAD_STATE
155         ERR_remove_thread_state(NULL);
156 #else
157         ERR_remove_state(0);
158 #endif
159         EVP_cleanup();
160 }
161
162 static int rsa_sign_with_key(RSA *rsa, const struct image_region region[],
163                 int region_count, uint8_t **sigp, uint *sig_size)
164 {
165         EVP_PKEY *key;
166         EVP_MD_CTX *context;
167         int size, ret = 0;
168         uint8_t *sig;
169         int i;
170
171         key = EVP_PKEY_new();
172         if (!key)
173                 return rsa_err("EVP_PKEY object creation failed");
174
175         if (!EVP_PKEY_set1_RSA(key, rsa)) {
176                 ret = rsa_err("EVP key setup failed");
177                 goto err_set;
178         }
179
180         size = EVP_PKEY_size(key);
181         sig = malloc(size);
182         if (!sig) {
183                 fprintf(stderr, "Out of memory for signature (%d bytes)\n",
184                         size);
185                 ret = -ENOMEM;
186                 goto err_alloc;
187         }
188
189         context = EVP_MD_CTX_create();
190         if (!context) {
191                 ret = rsa_err("EVP context creation failed");
192                 goto err_create;
193         }
194         EVP_MD_CTX_init(context);
195         if (!EVP_SignInit(context, EVP_sha1())) {
196                 ret = rsa_err("Signer setup failed");
197                 goto err_sign;
198         }
199
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");
203                         goto err_sign;
204                 }
205         }
206
207         if (!EVP_SignFinal(context, sig, sig_size, key)) {
208                 ret = rsa_err("Could not obtain signature");
209                 goto err_sign;
210         }
211         EVP_MD_CTX_cleanup(context);
212         EVP_MD_CTX_destroy(context);
213         EVP_PKEY_free(key);
214
215         debug("Got signature: %d bytes, expected %d\n", *sig_size, size);
216         *sigp = sig;
217         *sig_size = size;
218
219         return 0;
220
221 err_sign:
222         EVP_MD_CTX_destroy(context);
223 err_create:
224         free(sig);
225 err_alloc:
226 err_set:
227         EVP_PKEY_free(key);
228         return ret;
229 }
230
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)
234 {
235         RSA *rsa;
236         int ret;
237
238         ret = rsa_init();
239         if (ret)
240                 return ret;
241
242         ret = rsa_get_priv_key(info->keydir, info->keyname, &rsa);
243         if (ret)
244                 goto err_priv;
245         ret = rsa_sign_with_key(rsa, region, region_count, sigp, sig_len);
246         if (ret)
247                 goto err_sign;
248
249         RSA_free(rsa);
250         rsa_remove();
251
252         return ret;
253
254 err_sign:
255         RSA_free(rsa);
256 err_priv:
257         rsa_remove();
258         return ret;
259 }
260
261 /*
262  * rsa_get_params(): - Get the important parameters of an RSA public key
263  */
264 int rsa_get_params(RSA *key, uint32_t *n0_invp, BIGNUM **modulusp,
265                    BIGNUM **r_squaredp)
266 {
267         BIGNUM *big1, *big2, *big32, *big2_32;
268         BIGNUM *n, *r, *r_squared, *tmp;
269         BN_CTX *bn_ctx = BN_CTX_new();
270         int ret = 0;
271
272         /* Initialize BIGNUMs */
273         big1 = BN_new();
274         big2 = BN_new();
275         big32 = BN_new();
276         r = BN_new();
277         r_squared = BN_new();
278         tmp = BN_new();
279         big2_32 = BN_new();
280         n = BN_new();
281         if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 ||
282             !n) {
283                 fprintf(stderr, "Out of memory (bignum)\n");
284                 return -ENOMEM;
285         }
286
287         if (!BN_copy(n, key->n) || !BN_set_word(big1, 1L) ||
288             !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L))
289                 ret = -1;
290
291         /* big2_32 = 2^32 */
292         if (!BN_exp(big2_32, big2, big32, bn_ctx))
293                 ret = -1;
294
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))
298                 ret = -1;
299         *n0_invp = BN_get_word(tmp);
300
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))
304                 ret = -1;
305
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))
310                 ret = -1;
311
312         *modulusp = n;
313         *r_squaredp = r_squared;
314
315         BN_free(big1);
316         BN_free(big2);
317         BN_free(big32);
318         BN_free(r);
319         BN_free(tmp);
320         BN_free(big2_32);
321         if (ret) {
322                 fprintf(stderr, "Bignum operations failed\n");
323                 return -ENOMEM;
324         }
325
326         return ret;
327 }
328
329 static int fdt_add_bignum(void *blob, int noffset, const char *prop_name,
330                           BIGNUM *num, int num_bits)
331 {
332         int nwords = num_bits / 32;
333         int size;
334         uint32_t *buf, *ptr;
335         BIGNUM *tmp, *big2, *big32, *big2_32;
336         BN_CTX *ctx;
337         int ret;
338
339         tmp = BN_new();
340         big2 = BN_new();
341         big32 = BN_new();
342         big2_32 = BN_new();
343         if (!tmp || !big2 || !big32 || !big2_32) {
344                 fprintf(stderr, "Out of memory (bignum)\n");
345                 return -ENOMEM;
346         }
347         ctx = BN_CTX_new();
348         if (!tmp) {
349                 fprintf(stderr, "Out of memory (bignum context)\n");
350                 return -ENOMEM;
351         }
352         BN_set_word(big2, 2L);
353         BN_set_word(big32, 32L);
354         BN_exp(big2_32, big2, big32, ctx); /* B = 2^32 */
355
356         size = nwords * sizeof(uint32_t);
357         buf = malloc(size);
358         if (!buf) {
359                 fprintf(stderr, "Out of memory (%d bytes)\n", size);
360                 return -ENOMEM;
361         }
362
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 */
368         }
369
370         ret = fdt_setprop(blob, noffset, prop_name, buf, size);
371         if (ret) {
372                 fprintf(stderr, "Failed to write public key to FIT\n");
373                 return -ENOSPC;
374         }
375         free(buf);
376         BN_free(tmp);
377         BN_free(big2);
378         BN_free(big32);
379         BN_free(big2_32);
380
381         return ret;
382 }
383
384 int rsa_add_verify_data(struct image_sign_info *info, void *keydest)
385 {
386         BIGNUM *modulus, *r_squared;
387         uint32_t n0_inv;
388         int parent, node;
389         char name[100];
390         int ret;
391         int bits;
392         RSA *rsa;
393
394         debug("%s: Getting verification data\n", __func__);
395         ret = rsa_get_pub_key(info->keydir, info->keyname, &rsa);
396         if (ret)
397                 return ret;
398         ret = rsa_get_params(rsa, &n0_inv, &modulus, &r_squared);
399         if (ret)
400                 return ret;
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);
405                 if (parent < 0) {
406                         fprintf(stderr, "Couldn't create signature node: %s\n",
407                                 fdt_strerror(parent));
408                         return -EINVAL;
409                 }
410         }
411
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);
417                 if (node < 0) {
418                         fprintf(stderr, "Could not create key subnode: %s\n",
419                                 fdt_strerror(node));
420                         return -EINVAL;
421                 }
422         } else if (node < 0) {
423                 fprintf(stderr, "Cannot select keys parent: %s\n",
424                         fdt_strerror(node));
425                 return -ENOSPC;
426         }
427
428         ret = fdt_setprop_string(keydest, node, "key-name-hint",
429                                  info->keyname);
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,
435                                   info->algo->name);
436         if (info->require_keys) {
437                 fdt_setprop_string(keydest, node, "required",
438                                    info->require_keys);
439         }
440         BN_free(modulus);
441         BN_free(r_squared);
442         if (ret)
443                 return -EIO;
444
445         return 0;
446 }