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