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