1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (c) 2013, Google Inc.
4  */
5 
6 #ifndef USE_HOSTCC
7 #include <common.h>
8 #include <fdtdec.h>
9 #include <log.h>
10 #include <malloc.h>
11 #include <asm/types.h>
12 #include <asm/byteorder.h>
13 #include <linux/errno.h>
14 #include <asm/types.h>
15 #include <asm/unaligned.h>
16 #include <dm.h>
17 #else
18 #include "fdt_host.h"
19 #include "mkimage.h"
20 #include <fdt_support.h>
21 #endif
22 #include <linux/kconfig.h>
23 #include <u-boot/rsa-mod-exp.h>
24 #include <u-boot/rsa.h>
25 
26 /* Default public exponent for backward compatibility */
27 #define RSA_DEFAULT_PUBEXP	65537
28 
29 /**
30  * rsa_verify_padding() - Verify RSA message padding is valid
31  *
32  * Verify a RSA message's padding is consistent with PKCS1.5
33  * padding as described in the RSA PKCS#1 v2.1 standard.
34  *
35  * @msg:	Padded message
36  * @pad_len:	Number of expected padding bytes
37  * @algo:	Checksum algo structure having information on DER encoding etc.
38  * Return: 0 on success, != 0 on failure
39  */
rsa_verify_padding(const uint8_t * msg,const int pad_len,struct checksum_algo * algo)40 static int rsa_verify_padding(const uint8_t *msg, const int pad_len,
41 			      struct checksum_algo *algo)
42 {
43 	int ff_len;
44 	int ret;
45 
46 	/* first byte must be 0x00 */
47 	ret = *msg++;
48 	/* second byte must be 0x01 */
49 	ret |= *msg++ ^ 0x01;
50 	/* next ff_len bytes must be 0xff */
51 	ff_len = pad_len - algo->der_len - 3;
52 	ret |= *msg ^ 0xff;
53 	ret |= memcmp(msg, msg+1, ff_len-1);
54 	msg += ff_len;
55 	/* next byte must be 0x00 */
56 	ret |= *msg++;
57 	/* next der_len bytes must match der_prefix */
58 	ret |= memcmp(msg, algo->der_prefix, algo->der_len);
59 
60 	return ret;
61 }
62 
padding_pkcs_15_verify(struct image_sign_info * info,const uint8_t * msg,int msg_len,const uint8_t * hash,int hash_len)63 int padding_pkcs_15_verify(struct image_sign_info *info,
64 			   const uint8_t *msg, int msg_len,
65 			   const uint8_t *hash, int hash_len)
66 {
67 	struct checksum_algo *checksum = info->checksum;
68 	int ret, pad_len = msg_len - checksum->checksum_len;
69 
70 	/* Check pkcs1.5 padding bytes */
71 	ret = rsa_verify_padding(msg, pad_len, checksum);
72 	if (ret) {
73 		debug("In RSAVerify(): Padding check failed!\n");
74 		return -EINVAL;
75 	}
76 
77 	/* Check hash */
78 	if (memcmp((uint8_t *)msg + pad_len, hash, msg_len - pad_len)) {
79 		debug("In RSAVerify(): Hash check failed!\n");
80 		return -EACCES;
81 	}
82 
83 	return 0;
84 }
85 
86 #ifndef USE_HOSTCC
87 U_BOOT_PADDING_ALGO(pkcs_15) = {
88 	.name = "pkcs-1.5",
89 	.verify = padding_pkcs_15_verify,
90 };
91 #endif
92 
93 #if CONFIG_IS_ENABLED(FIT_RSASSA_PSS)
u32_i2osp(uint32_t val,uint8_t * buf)94 static void u32_i2osp(uint32_t val, uint8_t *buf)
95 {
96 	buf[0] = (uint8_t)((val >> 24) & 0xff);
97 	buf[1] = (uint8_t)((val >> 16) & 0xff);
98 	buf[2] = (uint8_t)((val >>  8) & 0xff);
99 	buf[3] = (uint8_t)((val >>  0) & 0xff);
100 }
101 
102 /**
103  * mask_generation_function1() - generate an octet string
104  *
105  * Generate an octet string used to check rsa signature.
106  * It use an input octet string and a hash function.
107  *
108  * @checksum:	A Hash function
109  * @seed:	Specifies an input variable octet string
110  * @seed_len:	Size of the input octet string
111  * @output:	Specifies the output octet string
112  * @output_len:	Size of the output octet string
113  * Return: 0 if the octet string was correctly generated, others on error
114  */
mask_generation_function1(struct checksum_algo * checksum,const uint8_t * seed,int seed_len,uint8_t * output,int output_len)115 static int mask_generation_function1(struct checksum_algo *checksum,
116 				     const uint8_t *seed, int seed_len,
117 				     uint8_t *output, int output_len)
118 {
119 	struct image_region region[2];
120 	int ret = 0, i, i_output = 0, region_count = 2;
121 	uint32_t counter = 0;
122 	uint8_t buf_counter[4], *tmp;
123 	int hash_len = checksum->checksum_len;
124 
125 	memset(output, 0, output_len);
126 
127 	region[0].data = seed;
128 	region[0].size = seed_len;
129 	region[1].data = &buf_counter[0];
130 	region[1].size = 4;
131 
132 	tmp = malloc(hash_len);
133 	if (!tmp) {
134 		debug("%s: can't allocate array tmp\n", __func__);
135 		ret = -ENOMEM;
136 		goto out;
137 	}
138 
139 	while (i_output < output_len) {
140 		u32_i2osp(counter, &buf_counter[0]);
141 
142 		ret = checksum->calculate(checksum->name,
143 					  region, region_count,
144 					  tmp);
145 		if (ret < 0) {
146 			debug("%s: Error in checksum calculation\n", __func__);
147 			goto out;
148 		}
149 
150 		i = 0;
151 		while ((i_output < output_len) && (i < hash_len)) {
152 			output[i_output] = tmp[i];
153 			i_output++;
154 			i++;
155 		}
156 
157 		counter++;
158 	}
159 
160 out:
161 	free(tmp);
162 
163 	return ret;
164 }
165 
compute_hash_prime(struct checksum_algo * checksum,const uint8_t * pad,int pad_len,const uint8_t * hash,int hash_len,const uint8_t * salt,int salt_len,uint8_t * hprime)166 static int compute_hash_prime(struct checksum_algo *checksum,
167 			      const uint8_t *pad, int pad_len,
168 			      const uint8_t *hash, int hash_len,
169 			      const uint8_t *salt, int salt_len,
170 			      uint8_t *hprime)
171 {
172 	struct image_region region[3];
173 	int ret, region_count = 3;
174 
175 	region[0].data = pad;
176 	region[0].size = pad_len;
177 	region[1].data = hash;
178 	region[1].size = hash_len;
179 	region[2].data = salt;
180 	region[2].size = salt_len;
181 
182 	ret = checksum->calculate(checksum->name, region, region_count, hprime);
183 	if (ret < 0) {
184 		debug("%s: Error in checksum calculation\n", __func__);
185 		goto out;
186 	}
187 
188 out:
189 	return ret;
190 }
191 
192 /*
193  * padding_pss_verify() - verify the pss padding of a signature
194  *
195  * Works with any salt length
196  *
197  * msg is a concatenation of : masked_db + h + 0xbc
198  * Once unmasked, db is a concatenation of : [0x00]* + 0x01 + salt
199  * Length of 0-padding at begin of db depends on salt length.
200  *
201  * @info:	Specifies key and FIT information
202  * @msg:	byte array of message, len equal to msg_len
203  * @msg_len:	Message length
204  * @hash:	Pointer to the expected hash
205  * @hash_len:	Length of the hash
206  *
207  * Return:	0 if padding is correct, non-zero otherwise
208  */
padding_pss_verify(struct image_sign_info * info,const uint8_t * msg,int msg_len,const uint8_t * hash,int hash_len)209 int padding_pss_verify(struct image_sign_info *info,
210 		       const uint8_t *msg, int msg_len,
211 		       const uint8_t *hash, int hash_len)
212 {
213 	const uint8_t *masked_db = NULL;
214 	uint8_t *db_mask = NULL;
215 	uint8_t *db = NULL;
216 	int db_len = msg_len - hash_len - 1;
217 	const uint8_t *h = NULL;
218 	uint8_t *hprime = NULL;
219 	int h_len = hash_len;
220 	uint8_t *db_nopad = NULL, *salt = NULL;
221 	int db_padlen, salt_len;
222 	uint8_t pad_zero[8] = { 0 };
223 	int ret, i, leftmost_bits = 1;
224 	uint8_t leftmost_mask;
225 	struct checksum_algo *checksum = info->checksum;
226 
227 	if (db_len <= 0)
228 		return -EINVAL;
229 
230 	/* first, allocate everything */
231 	db_mask = malloc(db_len);
232 	db = malloc(db_len);
233 	hprime = malloc(hash_len);
234 	if (!db_mask || !db || !hprime) {
235 		printf("%s: can't allocate some buffer\n", __func__);
236 		ret = -ENOMEM;
237 		goto out;
238 	}
239 
240 	/* step 4: check if the last byte is 0xbc */
241 	if (msg[msg_len - 1] != 0xbc) {
242 		printf("%s: invalid pss padding (0xbc is missing)\n", __func__);
243 		ret = -EINVAL;
244 		goto out;
245 	}
246 
247 	/* step 5 */
248 	masked_db = &msg[0];
249 	h = &msg[db_len];
250 
251 	/* step 6 */
252 	leftmost_mask = (0xff >> (8 - leftmost_bits)) << (8 - leftmost_bits);
253 	if (masked_db[0] & leftmost_mask) {
254 		printf("%s: invalid pss padding ", __func__);
255 		printf("(leftmost bit of maskedDB not zero)\n");
256 		ret = -EINVAL;
257 		goto out;
258 	}
259 
260 	/* step 7 */
261 	mask_generation_function1(checksum, h, h_len, db_mask, db_len);
262 
263 	/* step 8 */
264 	for (i = 0; i < db_len; i++)
265 		db[i] = masked_db[i] ^ db_mask[i];
266 
267 	/* step 9 */
268 	db[0] &= 0xff >> leftmost_bits;
269 
270 	/* step 10 */
271 	db_padlen = 0;
272 	while (db[db_padlen] == 0x00 && db_padlen < (db_len - 1))
273 		db_padlen++;
274 	db_nopad = &db[db_padlen];
275 	if (db_nopad[0] != 0x01) {
276 		printf("%s: invalid pss padding ", __func__);
277 		printf("(leftmost byte of db after 0-padding isn't 0x01)\n");
278 		ret = EINVAL;
279 		goto out;
280 	}
281 
282 	/* step 11 */
283 	salt_len = db_len - db_padlen - 1;
284 	salt = &db_nopad[1];
285 
286 	/* step 12 & 13 */
287 	compute_hash_prime(checksum, pad_zero, 8,
288 			   hash, hash_len,
289 			   salt, salt_len, hprime);
290 
291 	/* step 14 */
292 	ret = memcmp(h, hprime, hash_len);
293 
294 out:
295 	free(hprime);
296 	free(db);
297 	free(db_mask);
298 
299 	return ret;
300 }
301 
302 #ifndef USE_HOSTCC
303 U_BOOT_PADDING_ALGO(pss) = {
304 	.name = "pss",
305 	.verify = padding_pss_verify,
306 };
307 #endif
308 
309 #endif
310 
311 /**
312  * rsa_verify_key() - Verify a signature against some data using RSA Key
313  *
314  * Verify a RSA PKCS1.5 signature against an expected hash using
315  * the RSA Key properties in prop structure.
316  *
317  * @info:	Specifies key and FIT information
318  * @prop:	Specifies key
319  * @sig:	Signature
320  * @sig_len:	Number of bytes in signature
321  * @hash:	Pointer to the expected hash
322  * @key_len:	Number of bytes in rsa key
323  * Return: 0 if verified, -ve on error
324  */
rsa_verify_key(struct image_sign_info * info,struct key_prop * prop,const uint8_t * sig,const uint32_t sig_len,const uint8_t * hash,const uint32_t key_len)325 static int rsa_verify_key(struct image_sign_info *info,
326 			  struct key_prop *prop, const uint8_t *sig,
327 			  const uint32_t sig_len, const uint8_t *hash,
328 			  const uint32_t key_len)
329 {
330 	int ret;
331 #if !defined(USE_HOSTCC)
332 	struct udevice *mod_exp_dev;
333 #endif
334 	struct checksum_algo *checksum = info->checksum;
335 	struct padding_algo *padding = info->padding;
336 	int hash_len;
337 
338 	if (!prop || !sig || !hash || !checksum || !padding)
339 		return -EIO;
340 
341 	if (sig_len != (prop->num_bits / 8)) {
342 		debug("Signature is of incorrect length %d\n", sig_len);
343 		return -EINVAL;
344 	}
345 
346 	debug("Checksum algorithm: %s", checksum->name);
347 
348 	/* Sanity check for stack size */
349 	if (sig_len > RSA_MAX_SIG_BITS / 8) {
350 		debug("Signature length %u exceeds maximum %d\n", sig_len,
351 		      RSA_MAX_SIG_BITS / 8);
352 		return -EINVAL;
353 	}
354 
355 	uint8_t buf[sig_len];
356 	hash_len = checksum->checksum_len;
357 
358 #if !defined(USE_HOSTCC)
359 	ret = uclass_get_device(UCLASS_MOD_EXP, 0, &mod_exp_dev);
360 	if (ret) {
361 		printf("RSA: Can't find Modular Exp implementation\n");
362 		return -EINVAL;
363 	}
364 
365 	ret = rsa_mod_exp(mod_exp_dev, sig, sig_len, prop, buf);
366 #else
367 	ret = rsa_mod_exp_sw(sig, sig_len, prop, buf);
368 #endif
369 	if (ret) {
370 		debug("Error in Modular exponentation\n");
371 		return ret;
372 	}
373 
374 	ret = padding->verify(info, buf, key_len, hash, hash_len);
375 	if (ret) {
376 		debug("In RSAVerify(): padding check failed!\n");
377 		return ret;
378 	}
379 
380 	return 0;
381 }
382 
383 /**
384  * rsa_verify_with_pkey() - Verify a signature against some data using
385  * only modulus and exponent as RSA key properties.
386  * @info:	Specifies key information
387  * @hash:	Pointer to the expected hash
388  * @sig:	Signature
389  * @sig_len:	Number of bytes in signature
390  *
391  * Parse a RSA public key blob in DER format pointed to in @info and fill
392  * a key_prop structure with properties of the key. Then verify a RSA PKCS1.5
393  * signature against an expected hash using the calculated properties.
394  *
395  * Return	0 if verified, -ve on error
396  */
rsa_verify_with_pkey(struct image_sign_info * info,const void * hash,uint8_t * sig,uint sig_len)397 int rsa_verify_with_pkey(struct image_sign_info *info,
398 			 const void *hash, uint8_t *sig, uint sig_len)
399 {
400 	struct key_prop *prop;
401 	int ret;
402 
403 	if (!CONFIG_IS_ENABLED(RSA_VERIFY_WITH_PKEY))
404 		return -EACCES;
405 
406 	/* Public key is self-described to fill key_prop */
407 	ret = rsa_gen_key_prop(info->key, info->keylen, &prop);
408 	if (ret) {
409 		debug("Generating necessary parameter for decoding failed\n");
410 		return ret;
411 	}
412 
413 	ret = rsa_verify_key(info, prop, sig, sig_len, hash,
414 			     info->crypto->key_len);
415 
416 	rsa_free_key_prop(prop);
417 
418 	return ret;
419 }
420 
421 #if CONFIG_IS_ENABLED(FIT_SIGNATURE)
422 /**
423  * rsa_verify_with_keynode() - Verify a signature against some data using
424  * information in node with prperties of RSA Key like modulus, exponent etc.
425  *
426  * Parse sign-node and fill a key_prop structure with properties of the
427  * key.  Verify a RSA PKCS1.5 signature against an expected hash using
428  * the properties parsed
429  *
430  * @info:	Specifies key and FIT information
431  * @hash:	Pointer to the expected hash
432  * @sig:	Signature
433  * @sig_len:	Number of bytes in signature
434  * @node:	Node having the RSA Key properties
435  * Return: 0 if verified, -ve on error
436  */
rsa_verify_with_keynode(struct image_sign_info * info,const void * hash,uint8_t * sig,uint sig_len,int node)437 static int rsa_verify_with_keynode(struct image_sign_info *info,
438 				   const void *hash, uint8_t *sig,
439 				   uint sig_len, int node)
440 {
441 	const void *blob = info->fdt_blob;
442 	struct key_prop prop;
443 	int length;
444 	int ret = 0;
445 	const char *algo;
446 
447 	if (node < 0) {
448 		debug("%s: Skipping invalid node", __func__);
449 		return -EBADF;
450 	}
451 
452 	algo = fdt_getprop(blob, node, "algo", NULL);
453 	if (strcmp(info->name, algo)) {
454 		debug("%s: Wrong algo: have %s, expected %s", __func__,
455 		      info->name, algo);
456 		return -EFAULT;
457 	}
458 
459 	prop.num_bits = fdtdec_get_int(blob, node, "rsa,num-bits", 0);
460 
461 	prop.n0inv = fdtdec_get_int(blob, node, "rsa,n0-inverse", 0);
462 
463 	prop.public_exponent = fdt_getprop(blob, node, "rsa,exponent", &length);
464 	if (!prop.public_exponent || length < sizeof(uint64_t))
465 		prop.public_exponent = NULL;
466 
467 	prop.exp_len = sizeof(uint64_t);
468 
469 	prop.modulus = fdt_getprop(blob, node, "rsa,modulus", NULL);
470 
471 	prop.rr = fdt_getprop(blob, node, "rsa,r-squared", NULL);
472 
473 	if (!prop.num_bits || !prop.modulus || !prop.rr) {
474 		debug("%s: Missing RSA key info", __func__);
475 		return -EFAULT;
476 	}
477 
478 	ret = rsa_verify_key(info, &prop, sig, sig_len, hash,
479 			     info->crypto->key_len);
480 
481 	return ret;
482 }
483 #else
rsa_verify_with_keynode(struct image_sign_info * info,const void * hash,uint8_t * sig,uint sig_len,int node)484 static int rsa_verify_with_keynode(struct image_sign_info *info,
485 				   const void *hash, uint8_t *sig,
486 				   uint sig_len, int node)
487 {
488 	return -EACCES;
489 }
490 #endif
491 
rsa_verify_hash(struct image_sign_info * info,const uint8_t * hash,uint8_t * sig,uint sig_len)492 int rsa_verify_hash(struct image_sign_info *info,
493 		    const uint8_t *hash, uint8_t *sig, uint sig_len)
494 {
495 	int ret = -EACCES;
496 
497 	/*
498 	 * Since host tools, like mkimage, make use of openssl library for
499 	 * RSA encryption, rsa_verify_with_pkey()/rsa_gen_key_prop() are
500 	 * of no use and should not be compiled in.
501 	 */
502 	if (!tools_build() && CONFIG_IS_ENABLED(RSA_VERIFY_WITH_PKEY) &&
503 			!info->fdt_blob) {
504 		/* don't rely on fdt properties */
505 		ret = rsa_verify_with_pkey(info, hash, sig, sig_len);
506 		if (ret)
507 			debug("%s: rsa_verify_with_pkey() failed\n", __func__);
508 		return ret;
509 	}
510 
511 	if (CONFIG_IS_ENABLED(FIT_SIGNATURE)) {
512 		const void *blob = info->fdt_blob;
513 		int ndepth, noffset;
514 		int sig_node, node;
515 		char name[100];
516 
517 		sig_node = fdt_subnode_offset(blob, 0, FIT_SIG_NODENAME);
518 		if (sig_node < 0) {
519 			debug("%s: No signature node found\n", __func__);
520 			return -ENOENT;
521 		}
522 
523 		/* See if we must use a particular key */
524 		if (info->required_keynode != -1) {
525 			ret = rsa_verify_with_keynode(info, hash, sig, sig_len,
526 						      info->required_keynode);
527 			if (ret)
528 				debug("%s: Failed to verify required_keynode\n",
529 				      __func__);
530 			return ret;
531 		}
532 
533 		/* Look for a key that matches our hint */
534 		snprintf(name, sizeof(name), "key-%s", info->keyname);
535 		node = fdt_subnode_offset(blob, sig_node, name);
536 		ret = rsa_verify_with_keynode(info, hash, sig, sig_len, node);
537 		if (!ret)
538 			return ret;
539 		debug("%s: Could not verify key '%s', trying all\n", __func__,
540 		      name);
541 
542 		/* No luck, so try each of the keys in turn */
543 		for (ndepth = 0, noffset = fdt_next_node(blob, sig_node,
544 							 &ndepth);
545 		     (noffset >= 0) && (ndepth > 0);
546 		     noffset = fdt_next_node(blob, noffset, &ndepth)) {
547 			if (ndepth == 1 && noffset != node) {
548 				ret = rsa_verify_with_keynode(info, hash,
549 							      sig, sig_len,
550 							      noffset);
551 				if (!ret)
552 					break;
553 			}
554 		}
555 	}
556 	debug("%s: Failed to verify by any means\n", __func__);
557 
558 	return ret;
559 }
560 
rsa_verify(struct image_sign_info * info,const struct image_region region[],int region_count,uint8_t * sig,uint sig_len)561 int rsa_verify(struct image_sign_info *info,
562 	       const struct image_region region[], int region_count,
563 	       uint8_t *sig, uint sig_len)
564 {
565 	/* Reserve memory for maximum checksum-length */
566 	uint8_t hash[info->crypto->key_len];
567 	int ret;
568 
569 	/*
570 	 * Verify that the checksum-length does not exceed the
571 	 * rsa-signature-length
572 	 */
573 	if (info->checksum->checksum_len >
574 	    info->crypto->key_len) {
575 		debug("%s: invalid checksum-algorithm %s for %s\n",
576 		      __func__, info->checksum->name, info->crypto->name);
577 		return -EINVAL;
578 	}
579 
580 	/* Calculate checksum with checksum-algorithm */
581 	ret = info->checksum->calculate(info->checksum->name,
582 					region, region_count, hash);
583 	if (ret < 0) {
584 		debug("%s: Error in checksum calculation\n", __func__);
585 		return -EINVAL;
586 	}
587 
588 	return rsa_verify_hash(info, hash, sig, sig_len);
589 }
590 
591 #ifndef USE_HOSTCC
592 
593 U_BOOT_CRYPTO_ALGO(rsa2048) = {
594 	.name = "rsa2048",
595 	.key_len = RSA2048_BYTES,
596 	.verify = rsa_verify,
597 };
598 
599 U_BOOT_CRYPTO_ALGO(rsa3072) = {
600 	.name = "rsa3072",
601 	.key_len = RSA3072_BYTES,
602 	.verify = rsa_verify,
603 };
604 
605 U_BOOT_CRYPTO_ALGO(rsa4096) = {
606 	.name = "rsa4096",
607 	.key_len = RSA4096_BYTES,
608 	.verify = rsa_verify,
609 };
610 
611 #endif
612