xref: /rk3399_rockchip-uboot/lib/rsa/rsa-sign.c (revision e091b6c996a68a6a0faa2bd3ffdd90b3ba5f44ce)
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
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 
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  */
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  */
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  */
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  */
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  */
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  */
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 
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 
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 
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 
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  */
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 
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 
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  */
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  */
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;
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 
626 	r = BN_new();
627 	r_squared = BN_new();
628 	c_factor = BN_new();
629 	np_factor = BN_new();
630 	tmp = BN_new();
631 	big2_32 = BN_new();
632 	n = BN_new();
633 	e = BN_new();
634 	if (!big1 || !big2 || !big32 || !big4100 || !big2180 || !r ||
635 	    !r_squared || !tmp || !big2_32 || !n || !e ||
636 	    !c_factor || !np_factor) {
637 		fprintf(stderr, "Out of memory (bignum)\n");
638 		return -ENOMEM;
639 	}
640 
641 	if (0 != rsa_get_exponent(key, exponent))
642 		ret = -1;
643 
644 	RSA_get0_key(key, &key_n, &key_e, NULL);
645 	if (!BN_copy(n, key_n) || !BN_copy(e, key_e) ||
646 	    !BN_set_word(big1, 1L) ||
647 	    !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L) ||
648 	    !BN_set_word(big4100, 4100L) || !BN_set_word(big2180, 2180L))
649 		ret = -1;
650 
651 	/* big2_32 = 2^32 */
652 	if (!BN_exp(big2_32, big2, big32, bn_ctx))
653 		ret = -1;
654 
655 	/* Calculate n0_inv = -1 / n[0] mod 2^32 */
656 	if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) ||
657 	    !BN_sub(tmp, big2_32, tmp))
658 		ret = -1;
659 	*n0_invp = BN_get_word(tmp);
660 
661 	/* Calculate R = 2^(# of key bits) */
662 	if (!BN_set_word(tmp, BN_num_bits(n)) ||
663 	    !BN_exp(r, big2, tmp, bn_ctx))
664 		ret = -1;
665 
666 	/* Calculate r_squared = R^2 mod n */
667 	if (!BN_copy(r_squared, r) ||
668 	    !BN_mul(tmp, r_squared, r, bn_ctx) ||
669 	    !BN_mod(r_squared, tmp, n, bn_ctx))
670 		ret = -1;
671 
672 	/* Calculate c_factor = 2^4100 mod n */
673 	if (!BN_exp(tmp, big2, big4100, bn_ctx) ||
674 	    !BN_mod(c_factor, tmp, n, bn_ctx))
675 		ret = -1;
676 
677 	/* Calculate np_factor = 2^2180 div n */
678 	if (!BN_exp(tmp, big2, big2180, bn_ctx) ||
679 	    !BN_div(np_factor, NULL, tmp, n, bn_ctx))
680 		ret = -1;
681 
682 	*modulusp = n;
683 	*exponent_BN = e;
684 	*r_squaredp = r_squared;
685 	*c_factorp = c_factor;
686 	*np_factorp = np_factor;
687 
688 	BN_free(big1);
689 	BN_free(big2);
690 	BN_free(big32);
691 	BN_free(big4100);
692 	BN_free(big2180);
693 	BN_free(r);
694 	BN_free(tmp);
695 	BN_free(big2_32);
696 	if (ret) {
697 		fprintf(stderr, "Bignum operations failed\n");
698 		return -ENOMEM;
699 	}
700 
701 	return ret;
702 }
703 
704 static void rsa_convert_big_endian(uint32_t *dst, const uint32_t *src,
705 				   int total_len, int convert_len)
706 {
707 	int total_wd, convert_wd, i;
708 
709 	if (total_len < convert_len)
710 		convert_len = total_len;
711 
712 	total_wd = total_len / sizeof(uint32_t);
713 	convert_wd = convert_len / sizeof(uint32_t);
714 	for (i = 0; i < convert_wd; i++)
715 		dst[i] = fdt32_to_cpu(src[total_wd - 1 - i]);
716 }
717 
718 static int rsa_set_key_hash(void *keydest, int key_node,
719 			    int key_len, const char *csum_algo)
720 {
721 	const void *rsa_n, *rsa_e, *rsa_c, *rsa_np;
722 	void *n, *e, *c, *np;
723 	uint8_t value[FIT_MAX_HASH_LEN];
724 	char hash_c[] = "hash@c";
725 	char hash_np[] = "hash@np";
726 	char *rsa_key;
727 	int hash_node;
728 	int value_len;
729 	int ret = -ENOSPC;
730 
731 	rsa_key = calloc(key_len * 3, sizeof(char));
732 	if (!rsa_key)
733 		return -ENOSPC;
734 
735 	rsa_n = fdt_getprop(keydest, key_node, "rsa,modulus", NULL);
736 	rsa_e = fdt_getprop(keydest, key_node, "rsa,exponent-BN", NULL);
737 	rsa_c = fdt_getprop(keydest, key_node, "rsa,c", NULL);
738 	rsa_np = fdt_getprop(keydest, key_node, "rsa,np", NULL);
739 	if (!rsa_c || !rsa_np || !rsa_n || !rsa_e)
740 		goto err_nospc;
741 
742 	n = rsa_key;
743 	e = rsa_key + CONFIG_RSA_N_SIZE;
744 	rsa_convert_big_endian(n, rsa_n, key_len, CONFIG_RSA_N_SIZE);
745 	rsa_convert_big_endian(e, rsa_e, key_len, CONFIG_RSA_E_SIZE);
746 
747 	/* hash@c node: n, e, c */
748 	c = rsa_key + CONFIG_RSA_N_SIZE + CONFIG_RSA_E_SIZE;
749 	rsa_convert_big_endian(c, rsa_c, key_len, CONFIG_RSA_C_SIZE);
750 	hash_node = fdt_add_subnode(keydest, key_node, hash_c);
751 	if (hash_node < 0)
752 		goto err_nospc;
753 	ret = calculate_hash(rsa_key, key_len * 3, csum_algo, value, &value_len);
754 	if (ret)
755 		goto err_nospc;
756 	ret = fdt_setprop(keydest, hash_node, FIT_VALUE_PROP, value, value_len);
757 	if (ret)
758 		goto err_nospc;
759 	ret = fdt_setprop_string(keydest, hash_node, FIT_ALGO_PROP, csum_algo);
760 	if (ret < 0)
761 		goto err_nospc;
762 
763 	/* hash@np node: n, e, np */
764 	np = rsa_key + CONFIG_RSA_N_SIZE + CONFIG_RSA_E_SIZE;
765 	rsa_convert_big_endian(np, rsa_np, key_len, CONFIG_RSA_C_SIZE);
766 	hash_node = fdt_add_subnode(keydest, key_node, hash_np);
767 	if (hash_node < 0)
768 		goto err_nospc;
769 
770 	ret = calculate_hash(rsa_key, CONFIG_RSA_N_SIZE + CONFIG_RSA_E_SIZE + CONFIG_RSA_C_SIZE,
771 			     csum_algo, value, &value_len);
772 	if (ret)
773 		goto err_nospc;
774 	ret = fdt_setprop(keydest, hash_node, FIT_VALUE_PROP, value, value_len);
775 	if (ret < 0)
776 		goto err_nospc;
777 	ret = fdt_setprop_string(keydest, hash_node, FIT_ALGO_PROP, csum_algo);
778 
779 err_nospc:
780 	if (rsa_key)
781 		free(rsa_key);
782 
783 	return ret ? -ENOSPC : 0;
784 }
785 
786 static int fdt_add_bignum(void *blob, int noffset, const char *prop_name,
787 			  BIGNUM *num, int num_bits)
788 {
789 	int nwords = num_bits / 32;
790 	int size;
791 	uint32_t *buf, *ptr;
792 	BIGNUM *tmp, *big2, *big32, *big2_32;
793 	BN_CTX *ctx;
794 	int ret;
795 
796 	tmp = BN_new();
797 	big2 = BN_new();
798 	big32 = BN_new();
799 	big2_32 = BN_new();
800 	if (!tmp || !big2 || !big32 || !big2_32) {
801 		fprintf(stderr, "Out of memory (bignum)\n");
802 		return -ENOMEM;
803 	}
804 	ctx = BN_CTX_new();
805 	if (!tmp) {
806 		fprintf(stderr, "Out of memory (bignum context)\n");
807 		return -ENOMEM;
808 	}
809 	BN_set_word(big2, 2L);
810 	BN_set_word(big32, 32L);
811 	BN_exp(big2_32, big2, big32, ctx); /* B = 2^32 */
812 
813 	size = nwords * sizeof(uint32_t);
814 	buf = malloc(size);
815 	if (!buf) {
816 		fprintf(stderr, "Out of memory (%d bytes)\n", size);
817 		return -ENOMEM;
818 	}
819 
820 	/* Write out modulus as big endian array of integers */
821 	for (ptr = buf + nwords - 1; ptr >= buf; ptr--) {
822 		BN_mod(tmp, num, big2_32, ctx); /* n = N mod B */
823 		*ptr = cpu_to_fdt32(BN_get_word(tmp));
824 		BN_rshift(num, num, 32); /*  N = N/B */
825 	}
826 
827 	/*
828 	 * We try signing with successively increasing size values, so this
829 	 * might fail several times
830 	 */
831 	ret = fdt_setprop(blob, noffset, prop_name, buf, size);
832 	if (ret)
833 		return -FDT_ERR_NOSPACE;
834 	free(buf);
835 	BN_free(tmp);
836 	BN_free(big2);
837 	BN_free(big32);
838 	BN_free(big2_32);
839 
840 	return ret;
841 }
842 
843 int rsa_add_verify_data(struct image_sign_info *info, void *keydest)
844 {
845 	BIGNUM *modulus, *exponent_BN, *r_squared, *c_factor, *np_factor;
846 	uint64_t exponent;
847 	uint32_t n0_inv;
848 	int parent, node;
849 	char name[100];
850 	int ret;
851 	int bits;
852 	RSA *rsa;
853 	ENGINE *e = NULL;
854 
855 	debug("%s: Getting verification data\n", __func__);
856 	if (info->engine_id) {
857 		ret = rsa_engine_init(info->engine_id, &e);
858 		if (ret)
859 			return ret;
860 	}
861 	ret = rsa_get_pub_key(info->keydir, info->keyname, e, &rsa);
862 	if (ret)
863 		goto err_get_pub_key;
864 	ret = rsa_get_params(rsa, &exponent, &n0_inv, &modulus,
865 			     &exponent_BN, &r_squared, &c_factor, &np_factor);
866 	if (ret)
867 		goto err_get_params;
868 	bits = BN_num_bits(modulus);
869 	parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME);
870 	if (parent == -FDT_ERR_NOTFOUND) {
871 		parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME);
872 		if (parent < 0) {
873 			ret = parent;
874 			if (ret != -FDT_ERR_NOSPACE) {
875 				fprintf(stderr, "Couldn't create signature node: %s\n",
876 					fdt_strerror(parent));
877 			}
878 		}
879 	}
880 	if (ret)
881 		goto done;
882 
883 	/* Either create or overwrite the named key node */
884 	snprintf(name, sizeof(name), "key-%s", info->keyname);
885 	node = fdt_subnode_offset(keydest, parent, name);
886 	if (node == -FDT_ERR_NOTFOUND) {
887 		node = fdt_add_subnode(keydest, parent, name);
888 		if (node < 0) {
889 			ret = node;
890 			if (ret != -FDT_ERR_NOSPACE) {
891 				fprintf(stderr, "Could not create key subnode: %s\n",
892 					fdt_strerror(node));
893 			}
894 		}
895 	} else if (node < 0) {
896 		fprintf(stderr, "Cannot select keys parent: %s\n",
897 			fdt_strerror(node));
898 		ret = node;
899 	}
900 
901 	if (!ret) {
902 		ret = fdt_setprop_string(keydest, node, "key-name-hint",
903 				 info->keyname);
904 	}
905 	if (!ret)
906 		ret = fdt_setprop_u32(keydest, node, "rsa,num-bits", bits);
907 	if (!ret)
908 		ret = fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv);
909 	if (!ret) {
910 		ret = fdt_setprop_u64(keydest, node, "rsa,exponent", exponent);
911 	}
912 	if (!ret) {
913 		ret = fdt_add_bignum(keydest, node, "rsa,exponent-BN",
914 				     exponent_BN, bits);
915 	}
916 	if (!ret) {
917 		ret = fdt_add_bignum(keydest, node, "rsa,modulus", modulus,
918 				     bits);
919 	}
920 	if (!ret) {
921 		ret = fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared,
922 				     bits);
923 	}
924 	if (!ret) {
925 		ret = fdt_add_bignum(keydest, node, "rsa,c", c_factor,
926 				     bits);
927 	}
928 	if (!ret) {
929 		ret = fdt_add_bignum(keydest, node, "rsa,np", np_factor,
930 				     bits);
931 	}
932 	if (!ret) {
933 		ret = fdt_setprop_string(keydest, node, FIT_ALGO_PROP,
934 					 info->name);
935 	}
936 	if (!ret && info->require_keys) {
937 		ret = fdt_setprop_string(keydest, node, "required",
938 					 info->require_keys);
939 	}
940 	if (!ret) {
941 		ret = rsa_set_key_hash(keydest, node, info->crypto->key_len,
942 				       info->checksum->name);
943 	}
944 done:
945 	BN_free(modulus);
946 	BN_free(r_squared);
947 	if (ret)
948 		ret = ret == -FDT_ERR_NOSPACE ? -ENOSPC : -EIO;
949 err_get_params:
950 	RSA_free(rsa);
951 err_get_pub_key:
952 	if (info->engine_id)
953 		rsa_engine_remove(e);
954 
955 	return ret;
956 }
957