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