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 <generated/autoconf.h>
13 #include <openssl/bn.h>
14 #include <openssl/rsa.h>
15 #include <openssl/pem.h>
16 #include <openssl/err.h>
17 #include <openssl/ssl.h>
18 #include <openssl/evp.h>
19 #include <openssl/engine.h>
20
21 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
22 #define HAVE_ERR_REMOVE_THREAD_STATE
23 #endif
24
25 #if OPENSSL_VERSION_NUMBER < 0x10100000L
RSA_get0_key(const RSA * r,const BIGNUM ** n,const BIGNUM ** e,const BIGNUM ** d)26 static void RSA_get0_key(const RSA *r,
27 const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
28 {
29 if (n != NULL)
30 *n = r->n;
31 if (e != NULL)
32 *e = r->e;
33 if (d != NULL)
34 *d = r->d;
35 }
36 #endif
37
rsa_err(const char * msg)38 static int rsa_err(const char *msg)
39 {
40 unsigned long sslErr = ERR_get_error();
41
42 fprintf(stderr, "%s", msg);
43 fprintf(stderr, ": %s\n",
44 ERR_error_string(sslErr, 0));
45
46 return -1;
47 }
48
49 /**
50 * rsa_pem_get_pub_key() - read a public key from a .crt file
51 *
52 * @keydir: Directory containins the key
53 * @name Name of key file (will have a .crt extension)
54 * @rsap Returns RSA object, or NULL on failure
55 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
56 */
rsa_pem_get_pub_key(const char * keydir,const char * name,RSA ** rsap)57 static int rsa_pem_get_pub_key(const char *keydir, const char *name, RSA **rsap)
58 {
59 char path[1024];
60 EVP_PKEY *key;
61 X509 *cert;
62 RSA *rsa;
63 FILE *f;
64 int ret;
65
66 *rsap = NULL;
67 snprintf(path, sizeof(path), "%s/%s.crt", keydir, name);
68 f = fopen(path, "r");
69 if (!f) {
70 fprintf(stderr, "Couldn't open RSA certificate: '%s': %s\n",
71 path, strerror(errno));
72 return -EACCES;
73 }
74
75 /* Read the certificate */
76 cert = NULL;
77 if (!PEM_read_X509(f, &cert, NULL, NULL)) {
78 rsa_err("Couldn't read certificate");
79 ret = -EINVAL;
80 goto err_cert;
81 }
82
83 /* Get the public key from the certificate. */
84 key = X509_get_pubkey(cert);
85 if (!key) {
86 rsa_err("Couldn't read public key\n");
87 ret = -EINVAL;
88 goto err_pubkey;
89 }
90
91 /* Convert to a RSA_style key. */
92 rsa = EVP_PKEY_get1_RSA(key);
93 if (!rsa) {
94 rsa_err("Couldn't convert to a RSA style key");
95 ret = -EINVAL;
96 goto err_rsa;
97 }
98 fclose(f);
99 EVP_PKEY_free(key);
100 X509_free(cert);
101 *rsap = rsa;
102
103 return 0;
104
105 err_rsa:
106 EVP_PKEY_free(key);
107 err_pubkey:
108 X509_free(cert);
109 err_cert:
110 fclose(f);
111 return ret;
112 }
113
114 /**
115 * rsa_engine_get_pub_key() - read a public key from given engine
116 *
117 * @keydir: Key prefix
118 * @name Name of key
119 * @engine Engine to use
120 * @rsap Returns RSA object, or NULL on failure
121 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
122 */
rsa_engine_get_pub_key(const char * keydir,const char * name,ENGINE * engine,RSA ** rsap)123 static int rsa_engine_get_pub_key(const char *keydir, const char *name,
124 ENGINE *engine, RSA **rsap)
125 {
126 const char *engine_id;
127 char key_id[1024];
128 EVP_PKEY *key;
129 RSA *rsa;
130 int ret;
131
132 *rsap = NULL;
133
134 engine_id = ENGINE_get_id(engine);
135
136 if (engine_id && !strcmp(engine_id, "pkcs11")) {
137 if (keydir)
138 snprintf(key_id, sizeof(key_id),
139 "pkcs11:%s;object=%s;type=public",
140 keydir, name);
141 else
142 snprintf(key_id, sizeof(key_id),
143 "pkcs11:object=%s;type=public",
144 name);
145 } else {
146 fprintf(stderr, "Engine not supported\n");
147 return -ENOTSUP;
148 }
149
150 key = ENGINE_load_public_key(engine, key_id, NULL, NULL);
151 if (!key)
152 return rsa_err("Failure loading public key from engine");
153
154 /* Convert to a RSA_style key. */
155 rsa = EVP_PKEY_get1_RSA(key);
156 if (!rsa) {
157 rsa_err("Couldn't convert to a RSA style key");
158 ret = -EINVAL;
159 goto err_rsa;
160 }
161
162 EVP_PKEY_free(key);
163 *rsap = rsa;
164
165 return 0;
166
167 err_rsa:
168 EVP_PKEY_free(key);
169 return ret;
170 }
171
172 /**
173 * rsa_get_pub_key() - read a public key
174 *
175 * @keydir: Directory containing the key (PEM file) or key prefix (engine)
176 * @name Name of key file (will have a .crt extension)
177 * @engine Engine to use
178 * @rsap Returns RSA object, or NULL on failure
179 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
180 */
rsa_get_pub_key(const char * keydir,const char * name,ENGINE * engine,RSA ** rsap)181 static int rsa_get_pub_key(const char *keydir, const char *name,
182 ENGINE *engine, RSA **rsap)
183 {
184 if (engine)
185 return rsa_engine_get_pub_key(keydir, name, engine, rsap);
186 return rsa_pem_get_pub_key(keydir, name, rsap);
187 }
188
189 /**
190 * rsa_pem_get_priv_key() - read a private key from a .key file
191 *
192 * @keydir: Directory containing the key
193 * @name Name of key file (will have a .key extension)
194 * @rsap Returns RSA object, or NULL on failure
195 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
196 */
rsa_pem_get_priv_key(const char * keydir,const char * name,RSA ** rsap)197 static int rsa_pem_get_priv_key(const char *keydir, const char *name,
198 RSA **rsap)
199 {
200 char path[1024];
201 RSA *rsa;
202 FILE *f;
203
204 *rsap = NULL;
205 snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
206 f = fopen(path, "r");
207 if (!f) {
208 fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
209 path, strerror(errno));
210 return -ENOENT;
211 }
212
213 rsa = PEM_read_RSAPrivateKey(f, 0, NULL, path);
214 if (!rsa) {
215 rsa_err("Failure reading private key");
216 fclose(f);
217 return -EPROTO;
218 }
219 fclose(f);
220 *rsap = rsa;
221
222 return 0;
223 }
224
225 /**
226 * rsa_engine_get_priv_key() - read a private key from given engine
227 *
228 * @keydir: Key prefix
229 * @name Name of key
230 * @engine Engine to use
231 * @rsap Returns RSA object, or NULL on failure
232 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
233 */
rsa_engine_get_priv_key(const char * keydir,const char * name,ENGINE * engine,RSA ** rsap)234 static int rsa_engine_get_priv_key(const char *keydir, const char *name,
235 ENGINE *engine, RSA **rsap)
236 {
237 const char *engine_id;
238 char key_id[1024];
239 EVP_PKEY *key;
240 RSA *rsa;
241 int ret;
242
243 *rsap = NULL;
244
245 engine_id = ENGINE_get_id(engine);
246
247 if (engine_id && !strcmp(engine_id, "pkcs11")) {
248 if (keydir)
249 snprintf(key_id, sizeof(key_id),
250 "pkcs11:%s;object=%s;type=private",
251 keydir, name);
252 else
253 snprintf(key_id, sizeof(key_id),
254 "pkcs11:object=%s;type=private",
255 name);
256 } else {
257 fprintf(stderr, "Engine not supported\n");
258 return -ENOTSUP;
259 }
260
261 key = ENGINE_load_private_key(engine, key_id, NULL, NULL);
262 if (!key)
263 return rsa_err("Failure loading private key from engine");
264
265 /* Convert to a RSA_style key. */
266 rsa = EVP_PKEY_get1_RSA(key);
267 if (!rsa) {
268 rsa_err("Couldn't convert to a RSA style key");
269 ret = -EINVAL;
270 goto err_rsa;
271 }
272
273 EVP_PKEY_free(key);
274 *rsap = rsa;
275
276 return 0;
277
278 err_rsa:
279 EVP_PKEY_free(key);
280 return ret;
281 }
282
283 /**
284 * rsa_get_priv_key() - read a private key
285 *
286 * @keydir: Directory containing the key (PEM file) or key prefix (engine)
287 * @name Name of key
288 * @engine Engine to use for signing
289 * @rsap Returns RSA object, or NULL on failure
290 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
291 */
rsa_get_priv_key(const char * keydir,const char * name,ENGINE * engine,RSA ** rsap)292 static int rsa_get_priv_key(const char *keydir, const char *name,
293 ENGINE *engine, RSA **rsap)
294 {
295 if (engine)
296 return rsa_engine_get_priv_key(keydir, name, engine, rsap);
297 return rsa_pem_get_priv_key(keydir, name, rsap);
298 }
299
rsa_init(void)300 static int rsa_init(void)
301 {
302 int ret;
303
304 #if OPENSSL_VERSION_NUMBER < 0x10100000L
305 ret = SSL_library_init();
306 #else
307 ret = OPENSSL_init_ssl(0, NULL);
308 #endif
309 if (!ret) {
310 fprintf(stderr, "Failure to init SSL library\n");
311 return -1;
312 }
313 #if OPENSSL_VERSION_NUMBER < 0x10100000L
314 SSL_load_error_strings();
315
316 OpenSSL_add_all_algorithms();
317 OpenSSL_add_all_digests();
318 OpenSSL_add_all_ciphers();
319 #endif
320
321 return 0;
322 }
323
rsa_engine_init(const char * engine_id,ENGINE ** pe)324 static int rsa_engine_init(const char *engine_id, ENGINE **pe)
325 {
326 ENGINE *e;
327 int ret;
328
329 ENGINE_load_builtin_engines();
330
331 e = ENGINE_by_id(engine_id);
332 if (!e) {
333 fprintf(stderr, "Engine isn't available\n");
334 ret = -1;
335 goto err_engine_by_id;
336 }
337
338 if (!ENGINE_init(e)) {
339 fprintf(stderr, "Couldn't initialize engine\n");
340 ret = -1;
341 goto err_engine_init;
342 }
343
344 if (!ENGINE_set_default_RSA(e)) {
345 fprintf(stderr, "Couldn't set engine as default for RSA\n");
346 ret = -1;
347 goto err_set_rsa;
348 }
349
350 *pe = e;
351
352 return 0;
353
354 err_set_rsa:
355 ENGINE_finish(e);
356 err_engine_init:
357 ENGINE_free(e);
358 err_engine_by_id:
359 #if OPENSSL_VERSION_NUMBER < 0x10100000L
360 ENGINE_cleanup();
361 #endif
362 return ret;
363 }
364
rsa_remove(void)365 static void rsa_remove(void)
366 {
367 #if OPENSSL_VERSION_NUMBER < 0x10100000L
368 CRYPTO_cleanup_all_ex_data();
369 ERR_free_strings();
370 #ifdef HAVE_ERR_REMOVE_THREAD_STATE
371 ERR_remove_thread_state(NULL);
372 #else
373 ERR_remove_state(0);
374 #endif
375 EVP_cleanup();
376 #endif
377 }
378
rsa_engine_remove(ENGINE * e)379 static void rsa_engine_remove(ENGINE *e)
380 {
381 if (e) {
382 ENGINE_finish(e);
383 ENGINE_free(e);
384 }
385 }
386
387 /*
388 * With this data2sign.bin, we can provide it to who real holds the RAS-private
389 * key to sign current fit image. Then we replace the signature in fit image
390 * with a valid one.
391 */
gen_data2sign(const struct image_region region[],int region_count)392 static int gen_data2sign(const struct image_region region[], int region_count)
393 {
394 char *file = "data2sign.bin";
395 FILE *fd;
396 int i;
397
398 fd = fopen(file, "wb");
399 if (!fd) {
400 fprintf(stderr, "Failed to create %s: %s\n",
401 file, strerror(errno));
402 return -ENOENT;
403 }
404
405 for (i = 0; i < region_count; i++)
406 fwrite(region[i].data, region[i].size, 1, fd);
407
408 fclose(fd);
409
410 return 0;
411 }
412
rsa_sign_with_key(RSA * rsa,struct padding_algo * padding_algo,struct checksum_algo * checksum_algo,const struct image_region region[],int region_count,uint8_t ** sigp,uint * sig_size)413 static int rsa_sign_with_key(RSA *rsa, struct padding_algo *padding_algo,
414 struct checksum_algo *checksum_algo,
415 const struct image_region region[], int region_count,
416 uint8_t **sigp, uint *sig_size)
417 {
418 EVP_PKEY *key;
419 EVP_PKEY_CTX *ckey;
420 EVP_MD_CTX *context;
421 int ret = 0;
422 size_t size;
423 uint8_t *sig;
424 int i;
425
426 key = EVP_PKEY_new();
427 if (!key)
428 return rsa_err("EVP_PKEY object creation failed");
429
430 if (!EVP_PKEY_set1_RSA(key, rsa)) {
431 ret = rsa_err("EVP key setup failed");
432 goto err_set;
433 }
434
435 size = EVP_PKEY_size(key);
436 sig = malloc(size);
437 if (!sig) {
438 fprintf(stderr, "Out of memory for signature (%zu bytes)\n",
439 size);
440 ret = -ENOMEM;
441 goto err_alloc;
442 }
443
444 context = EVP_MD_CTX_create();
445 if (!context) {
446 ret = rsa_err("EVP context creation failed");
447 goto err_create;
448 }
449 EVP_MD_CTX_init(context);
450
451 ckey = EVP_PKEY_CTX_new(key, NULL);
452 if (!ckey) {
453 ret = rsa_err("EVP key context creation failed");
454 goto err_create;
455 }
456
457 if (EVP_DigestSignInit(context, &ckey,
458 checksum_algo->calculate_sign(),
459 NULL, key) <= 0) {
460 ret = rsa_err("Signer setup failed");
461 goto err_sign;
462 }
463
464 #ifdef CONFIG_FIT_ENABLE_RSASSA_PSS_SUPPORT
465 if (padding_algo && !strcmp(padding_algo->name, "pss")) {
466 if (EVP_PKEY_CTX_set_rsa_padding(ckey,
467 RSA_PKCS1_PSS_PADDING) <= 0) {
468 ret = rsa_err("Signer padding setup failed");
469 goto err_sign;
470 }
471 }
472 #endif /* CONFIG_FIT_ENABLE_RSASSA_PSS_SUPPORT */
473
474 for (i = 0; i < region_count; i++) {
475 if (!EVP_DigestSignUpdate(context, region[i].data,
476 region[i].size)) {
477 ret = rsa_err("Signing data failed");
478 goto err_sign;
479 }
480 }
481
482 if (!EVP_DigestSignFinal(context, sig, &size)) {
483 ret = rsa_err("Could not obtain signature");
484 goto err_sign;
485 }
486
487 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
488 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x02070000fL)
489 EVP_MD_CTX_cleanup(context);
490 #else
491 EVP_MD_CTX_reset(context);
492 #endif
493 EVP_MD_CTX_destroy(context);
494 EVP_PKEY_free(key);
495
496 debug("Got signature: %d bytes, expected %zu\n", *sig_size, size);
497 *sigp = sig;
498 *sig_size = size;
499
500 gen_data2sign(region, region_count);
501
502 return 0;
503
504 err_sign:
505 EVP_MD_CTX_destroy(context);
506 err_create:
507 free(sig);
508 err_alloc:
509 err_set:
510 EVP_PKEY_free(key);
511 return ret;
512 }
513
rsa_sign(struct image_sign_info * info,const struct image_region region[],int region_count,uint8_t ** sigp,uint * sig_len)514 int rsa_sign(struct image_sign_info *info,
515 const struct image_region region[], int region_count,
516 uint8_t **sigp, uint *sig_len)
517 {
518 RSA *rsa;
519 ENGINE *e = NULL;
520 int ret;
521
522 ret = rsa_init();
523 if (ret)
524 return ret;
525
526 if (info->engine_id) {
527 ret = rsa_engine_init(info->engine_id, &e);
528 if (ret)
529 goto err_engine;
530 }
531
532 ret = rsa_get_priv_key(info->keydir, info->keyname, e, &rsa);
533 if (ret)
534 goto err_priv;
535 ret = rsa_sign_with_key(rsa, info->padding, info->checksum, region,
536 region_count, sigp, sig_len);
537 if (ret)
538 goto err_sign;
539
540 RSA_free(rsa);
541 if (info->engine_id)
542 rsa_engine_remove(e);
543 rsa_remove();
544
545 return ret;
546
547 err_sign:
548 RSA_free(rsa);
549 err_priv:
550 if (info->engine_id)
551 rsa_engine_remove(e);
552 err_engine:
553 rsa_remove();
554 return ret;
555 }
556
557 /*
558 * rsa_get_exponent(): - Get the public exponent from an RSA key
559 */
rsa_get_exponent(RSA * key,uint64_t * e)560 static int rsa_get_exponent(RSA *key, uint64_t *e)
561 {
562 int ret;
563 BIGNUM *bn_te;
564 const BIGNUM *key_e;
565 uint64_t te;
566
567 ret = -EINVAL;
568 bn_te = NULL;
569
570 if (!e)
571 goto cleanup;
572
573 RSA_get0_key(key, NULL, &key_e, NULL);
574 if (BN_num_bits(key_e) > 64)
575 goto cleanup;
576
577 *e = BN_get_word(key_e);
578
579 if (BN_num_bits(key_e) < 33) {
580 ret = 0;
581 goto cleanup;
582 }
583
584 bn_te = BN_dup(key_e);
585 if (!bn_te)
586 goto cleanup;
587
588 if (!BN_rshift(bn_te, bn_te, 32))
589 goto cleanup;
590
591 if (!BN_mask_bits(bn_te, 32))
592 goto cleanup;
593
594 te = BN_get_word(bn_te);
595 te <<= 32;
596 *e |= te;
597 ret = 0;
598
599 cleanup:
600 if (bn_te)
601 BN_free(bn_te);
602
603 return ret;
604 }
605
606 /*
607 * rsa_get_params(): - Get the important parameters of an RSA public key
608 */
rsa_get_params(RSA * key,uint64_t * exponent,uint32_t * n0_invp,BIGNUM ** modulusp,BIGNUM ** exponent_BN,BIGNUM ** r_squaredp,BIGNUM ** c_factorp,BIGNUM ** np_factorp)609 int rsa_get_params(RSA *key, uint64_t *exponent, uint32_t *n0_invp,
610 BIGNUM **modulusp, BIGNUM **exponent_BN, BIGNUM **r_squaredp,
611 BIGNUM **c_factorp, BIGNUM **np_factorp)
612 {
613 BIGNUM *big1, *big2, *big32, *big2_32, *big4100, *big2180, *big4228;
614 BIGNUM *n, *e, *r, *r_squared, *tmp, *c_factor, *np_factor;
615 const BIGNUM *key_n, *key_e;
616 BN_CTX *bn_ctx = BN_CTX_new();
617 int ret = 0;
618
619 /* Initialize BIGNUMs */
620 big1 = BN_new();
621 big2 = BN_new();
622 big32 = BN_new();
623 big4100 = BN_new();
624 big2180 = BN_new();
625 big4228 = BN_new();
626
627 r = BN_new();
628 r_squared = BN_new();
629 c_factor = BN_new();
630 np_factor = BN_new();
631 tmp = BN_new();
632 big2_32 = BN_new();
633 n = BN_new();
634 e = BN_new();
635 if (!big1 || !big2 || !big32 || !big4100 || !big2180 || !big4228 || !r ||
636 !r_squared || !tmp || !big2_32 || !n || !e ||
637 !c_factor || !np_factor) {
638 fprintf(stderr, "Out of memory (bignum)\n");
639 return -ENOMEM;
640 }
641
642 if (0 != rsa_get_exponent(key, exponent))
643 ret = -1;
644
645 RSA_get0_key(key, &key_n, &key_e, NULL);
646 if (!BN_copy(n, key_n) || !BN_copy(e, key_e) ||
647 !BN_set_word(big1, 1L) ||
648 !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L) ||
649 !BN_set_word(big4100, 4100L) || !BN_set_word(big2180, 2180L) ||
650 !BN_set_word(big4228, 4228L))
651 ret = -1;
652
653 /* big2_32 = 2^32 */
654 if (!BN_exp(big2_32, big2, big32, bn_ctx))
655 ret = -1;
656
657 /* Calculate n0_inv = -1 / n[0] mod 2^32 */
658 if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) ||
659 !BN_sub(tmp, big2_32, tmp))
660 ret = -1;
661 *n0_invp = BN_get_word(tmp);
662
663 /* Calculate R = 2^(# of key bits) */
664 if (!BN_set_word(tmp, BN_num_bits(n)) ||
665 !BN_exp(r, big2, tmp, bn_ctx))
666 ret = -1;
667
668 /* Calculate r_squared = R^2 mod n */
669 if (!BN_copy(r_squared, r) ||
670 !BN_mul(tmp, r_squared, r, bn_ctx) ||
671 !BN_mod(r_squared, tmp, n, bn_ctx))
672 ret = -1;
673
674 /* Calculate c_factor = 2^4100 mod n */
675 if (!BN_exp(tmp, big2, big4100, bn_ctx) ||
676 !BN_mod(c_factor, tmp, n, bn_ctx))
677 ret = -1;
678
679 /* Calculate np_factor = 2^2180 div n */
680 if (BN_num_bits(n) == 2048) {
681 if (!BN_exp(tmp, big2, big2180, bn_ctx) ||
682 !BN_div(np_factor, NULL, tmp, n, bn_ctx))
683 ret = -1;
684 } else {/* Calculate 4096 np_factor = 2^4228 div n */
685 if (!BN_exp(tmp, big2, big4228, bn_ctx) ||
686 !BN_div(np_factor, NULL, tmp, n, bn_ctx))
687 ret = -1;
688 }
689
690 *modulusp = n;
691 *exponent_BN = e;
692 *r_squaredp = r_squared;
693 *c_factorp = c_factor;
694 *np_factorp = np_factor;
695
696 BN_free(big1);
697 BN_free(big2);
698 BN_free(big32);
699 BN_free(big4100);
700 BN_free(big2180);
701 BN_free(big4228);
702 BN_free(r);
703 BN_free(tmp);
704 BN_free(big2_32);
705 if (ret) {
706 fprintf(stderr, "Bignum operations failed\n");
707 return -ENOMEM;
708 }
709
710 return ret;
711 }
712
rsa_convert_big_endian(uint32_t * dst,const uint32_t * src,int total_len,int convert_len)713 static void rsa_convert_big_endian(uint32_t *dst, const uint32_t *src,
714 int total_len, int convert_len)
715 {
716 int total_wd, convert_wd, i;
717
718 if (total_len < convert_len)
719 convert_len = total_len;
720
721 total_wd = total_len / sizeof(uint32_t);
722 convert_wd = convert_len / sizeof(uint32_t);
723 for (i = 0; i < convert_wd; i++)
724 dst[i] = fdt32_to_cpu(src[total_wd - 1 - i]);
725 }
726
rsa_set_key_hash(void * keydest,int key_node,int key_len,const char * csum_algo)727 static int rsa_set_key_hash(void *keydest, int key_node,
728 int key_len, const char *csum_algo)
729 {
730 const void *rsa_n, *rsa_e, *rsa_c, *rsa_np;
731 void *n, *e, *c, *np;
732 uint8_t value[FIT_MAX_HASH_LEN];
733 char hash_c[] = "hash@c";
734 char hash_np[] = "hash@np";
735 char *rsa_key;
736 int hash_node;
737 int value_len;
738 int ret = -ENOSPC;
739
740 rsa_key = calloc(key_len * 3, sizeof(char));
741 if (!rsa_key)
742 return -ENOSPC;
743
744 rsa_n = fdt_getprop(keydest, key_node, "rsa,modulus", NULL);
745 rsa_e = fdt_getprop(keydest, key_node, "rsa,exponent-BN", NULL);
746 rsa_c = fdt_getprop(keydest, key_node, "rsa,c", NULL);
747 rsa_np = fdt_getprop(keydest, key_node, "rsa,np", NULL);
748 if (!rsa_c || !rsa_np || !rsa_n || !rsa_e)
749 goto err_nospc;
750
751 n = rsa_key;
752 e = rsa_key + CONFIG_RSA_N_SIZE;
753 rsa_convert_big_endian(n, rsa_n, key_len, CONFIG_RSA_N_SIZE);
754 rsa_convert_big_endian(e, rsa_e, key_len, CONFIG_RSA_E_SIZE);
755
756 /* hash@c node: n, e, c */
757 c = rsa_key + CONFIG_RSA_N_SIZE + CONFIG_RSA_E_SIZE;
758 rsa_convert_big_endian(c, rsa_c, key_len, CONFIG_RSA_C_SIZE);
759 hash_node = fdt_add_subnode(keydest, key_node, hash_c);
760 if (hash_node < 0)
761 goto err_nospc;
762 ret = calculate_hash(rsa_key, key_len * 3, csum_algo, value, &value_len);
763 if (ret)
764 goto err_nospc;
765 ret = fdt_setprop(keydest, hash_node, FIT_VALUE_PROP, value, value_len);
766 if (ret)
767 goto err_nospc;
768 ret = fdt_setprop_string(keydest, hash_node, FIT_ALGO_PROP, csum_algo);
769 if (ret < 0)
770 goto err_nospc;
771
772 /* hash@np node: n, e, np */
773 np = rsa_key + CONFIG_RSA_N_SIZE + CONFIG_RSA_E_SIZE;
774 rsa_convert_big_endian(np, rsa_np, key_len, CONFIG_RSA_C_SIZE);
775 hash_node = fdt_add_subnode(keydest, key_node, hash_np);
776 if (hash_node < 0)
777 goto err_nospc;
778
779 ret = calculate_hash(rsa_key, CONFIG_RSA_N_SIZE + CONFIG_RSA_E_SIZE + CONFIG_RSA_C_SIZE,
780 csum_algo, value, &value_len);
781 if (ret)
782 goto err_nospc;
783 ret = fdt_setprop(keydest, hash_node, FIT_VALUE_PROP, value, value_len);
784 if (ret < 0)
785 goto err_nospc;
786 ret = fdt_setprop_string(keydest, hash_node, FIT_ALGO_PROP, csum_algo);
787
788 err_nospc:
789 if (rsa_key)
790 free(rsa_key);
791
792 return ret ? -ENOSPC : 0;
793 }
794
fdt_add_bignum(void * blob,int noffset,const char * prop_name,BIGNUM * num,int num_bits)795 static int fdt_add_bignum(void *blob, int noffset, const char *prop_name,
796 BIGNUM *num, int num_bits)
797 {
798 int nwords = num_bits / 32;
799 int size;
800 uint32_t *buf, *ptr;
801 BIGNUM *tmp, *big2, *big32, *big2_32;
802 BN_CTX *ctx;
803 int ret;
804
805 tmp = BN_new();
806 big2 = BN_new();
807 big32 = BN_new();
808 big2_32 = BN_new();
809 if (!tmp || !big2 || !big32 || !big2_32) {
810 fprintf(stderr, "Out of memory (bignum)\n");
811 return -ENOMEM;
812 }
813 ctx = BN_CTX_new();
814 if (!tmp) {
815 fprintf(stderr, "Out of memory (bignum context)\n");
816 return -ENOMEM;
817 }
818 BN_set_word(big2, 2L);
819 BN_set_word(big32, 32L);
820 BN_exp(big2_32, big2, big32, ctx); /* B = 2^32 */
821
822 size = nwords * sizeof(uint32_t);
823 buf = malloc(size);
824 if (!buf) {
825 fprintf(stderr, "Out of memory (%d bytes)\n", size);
826 return -ENOMEM;
827 }
828
829 /* Write out modulus as big endian array of integers */
830 for (ptr = buf + nwords - 1; ptr >= buf; ptr--) {
831 BN_mod(tmp, num, big2_32, ctx); /* n = N mod B */
832 *ptr = cpu_to_fdt32(BN_get_word(tmp));
833 BN_rshift(num, num, 32); /* N = N/B */
834 }
835
836 /*
837 * We try signing with successively increasing size values, so this
838 * might fail several times
839 */
840 ret = fdt_setprop(blob, noffset, prop_name, buf, size);
841 if (ret)
842 return -FDT_ERR_NOSPACE;
843 free(buf);
844 BN_free(tmp);
845 BN_free(big2);
846 BN_free(big32);
847 BN_free(big2_32);
848
849 return ret;
850 }
851
rsa_add_verify_data(struct image_sign_info * info,void * keydest)852 int rsa_add_verify_data(struct image_sign_info *info, void *keydest)
853 {
854 BIGNUM *modulus, *exponent_BN, *r_squared, *c_factor, *np_factor;
855 uint64_t exponent;
856 uint32_t n0_inv;
857 int parent, node;
858 char name[100];
859 int ret;
860 int bits;
861 RSA *rsa;
862 ENGINE *e = NULL;
863
864 debug("%s: Getting verification data\n", __func__);
865 if (info->engine_id) {
866 ret = rsa_engine_init(info->engine_id, &e);
867 if (ret)
868 return ret;
869 }
870 ret = rsa_get_pub_key(info->keydir, info->keyname, e, &rsa);
871 if (ret)
872 goto err_get_pub_key;
873 ret = rsa_get_params(rsa, &exponent, &n0_inv, &modulus,
874 &exponent_BN, &r_squared, &c_factor, &np_factor);
875 if (ret)
876 goto err_get_params;
877 bits = BN_num_bits(modulus);
878 parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME);
879 if (parent == -FDT_ERR_NOTFOUND) {
880 parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME);
881 if (parent < 0) {
882 ret = parent;
883 if (ret != -FDT_ERR_NOSPACE) {
884 fprintf(stderr, "Couldn't create signature node: %s\n",
885 fdt_strerror(parent));
886 }
887 }
888 }
889 if (ret)
890 goto done;
891
892 /* Either create or overwrite the named key node */
893 snprintf(name, sizeof(name), "key-%s", info->keyname);
894 node = fdt_subnode_offset(keydest, parent, name);
895 if (node == -FDT_ERR_NOTFOUND) {
896 node = fdt_add_subnode(keydest, parent, name);
897 if (node < 0) {
898 ret = node;
899 if (ret != -FDT_ERR_NOSPACE) {
900 fprintf(stderr, "Could not create key subnode: %s\n",
901 fdt_strerror(node));
902 }
903 }
904 } else if (node < 0) {
905 fprintf(stderr, "Cannot select keys parent: %s\n",
906 fdt_strerror(node));
907 ret = node;
908 }
909
910 if (!ret) {
911 ret = fdt_setprop_string(keydest, node, "key-name-hint",
912 info->keyname);
913 }
914 if (!ret)
915 ret = fdt_setprop_u32(keydest, node, "rsa,num-bits", bits);
916 if (!ret)
917 ret = fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv);
918 if (!ret) {
919 ret = fdt_setprop_u64(keydest, node, "rsa,exponent", exponent);
920 }
921 if (!ret) {
922 ret = fdt_add_bignum(keydest, node, "rsa,exponent-BN",
923 exponent_BN, bits);
924 }
925 if (!ret) {
926 ret = fdt_add_bignum(keydest, node, "rsa,modulus", modulus,
927 bits);
928 }
929 if (!ret) {
930 ret = fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared,
931 bits);
932 }
933 if (!ret) {
934 ret = fdt_add_bignum(keydest, node, "rsa,c", c_factor,
935 bits);
936 }
937 if (!ret) {
938 ret = fdt_add_bignum(keydest, node, "rsa,np", np_factor,
939 bits);
940 }
941 if (!ret) {
942 ret = fdt_setprop_string(keydest, node, FIT_ALGO_PROP,
943 info->name);
944 }
945 if (!ret && info->require_keys) {
946 ret = fdt_setprop_string(keydest, node, "required",
947 info->require_keys);
948 }
949 if (!ret) {
950 ret = rsa_set_key_hash(keydest, node, info->crypto->key_len,
951 info->checksum->name);
952 }
953 done:
954 BN_free(modulus);
955 BN_free(r_squared);
956 if (ret)
957 ret = ret == -FDT_ERR_NOSPACE ? -ENOSPC : -EIO;
958 err_get_params:
959 RSA_free(rsa);
960 err_get_pub_key:
961 if (info->engine_id)
962 rsa_engine_remove(e);
963
964 return ret;
965 }
966