xref: /rk3399_rockchip-uboot/lib/rsa/rsa-verify.c (revision 4a2b8db466479ddec6ee85f9fe9d7f934016be9a)
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 hw_crypto_rsa(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 /**
131  * rsa_verify_key() - Verify a signature against some data using RSA Key
132  *
133  * Verify a RSA PKCS1.5 signature against an expected hash using
134  * the RSA Key properties in prop structure.
135  *
136  * @prop:	Specifies key
137  * @sig:	Signature
138  * @sig_len:	Number of bytes in signature
139  * @hash:	Pointer to the expected hash
140  * @key_len:	Number of bytes in rsa key
141  * @algo:	Checksum algo structure having information on DER encoding etc.
142  * @return 0 if verified, -ve on error
143  */
144 static int rsa_verify_key(struct key_prop *prop, const uint8_t *sig,
145 			  const uint32_t sig_len, const uint8_t *hash,
146 			  const uint32_t key_len, struct checksum_algo *algo)
147 {
148 	int pad_len;
149 	int ret;
150 
151 	if (!prop || !sig || !hash || !algo)
152 		return -EIO;
153 
154 	if (sig_len != (prop->num_bits / 8)) {
155 		debug("Signature is of incorrect length %d\n", sig_len);
156 		return -EINVAL;
157 	}
158 
159 	debug("Checksum algorithm: %s", algo->name);
160 
161 	/* Sanity check for stack size */
162 	if (sig_len > RSA_MAX_SIG_BITS / 8) {
163 		debug("Signature length %u exceeds maximum %d\n", sig_len,
164 		      RSA_MAX_SIG_BITS / 8);
165 		return -EINVAL;
166 	}
167 
168 	uint8_t buf[sig_len];
169 
170 #if !defined(USE_HOSTCC)
171 #if CONFIG_IS_ENABLED(FIT_HW_CRYPTO)
172 	ret = hw_crypto_rsa(prop, sig, sig_len, key_len, buf);
173 #else
174 	struct udevice *mod_exp_dev;
175 
176 	ret = uclass_get_device(UCLASS_MOD_EXP, 0, &mod_exp_dev);
177 	if (ret) {
178 		printf("RSA: Can't find Modular Exp implementation\n");
179 		return -EINVAL;
180 	}
181 
182 	ret = rsa_mod_exp(mod_exp_dev, sig, sig_len, prop, buf);
183 #endif
184 #else
185 	ret = rsa_mod_exp_sw(sig, sig_len, prop, buf);
186 #endif
187 	if (ret) {
188 		debug("Error in Modular exponentation\n");
189 		return ret;
190 	}
191 
192 	pad_len = key_len - algo->checksum_len;
193 
194 	/* Check pkcs1.5 padding bytes. */
195 	ret = rsa_verify_padding(buf, pad_len, algo);
196 	if (ret) {
197 		debug("In RSAVerify(): Padding check failed!\n");
198 		return -EINVAL;
199 	}
200 
201 	/* Check hash. */
202 	if (memcmp((uint8_t *)buf + pad_len, hash, sig_len - pad_len)) {
203 		debug("In RSAVerify(): Hash check failed!\n");
204 		return -EACCES;
205 	}
206 
207 	return 0;
208 }
209 
210 /**
211  * rsa_verify_with_keynode() - Verify a signature against some data using
212  * information in node with prperties of RSA Key like modulus, exponent etc.
213  *
214  * Parse sign-node and fill a key_prop structure with properties of the
215  * key.  Verify a RSA PKCS1.5 signature against an expected hash using
216  * the properties parsed
217  *
218  * @info:	Specifies key and FIT information
219  * @hash:	Pointer to the expected hash
220  * @sig:	Signature
221  * @sig_len:	Number of bytes in signature
222  * @node:	Node having the RSA Key properties
223  * @return 0 if verified, -ve on error
224  */
225 static int rsa_verify_with_keynode(struct image_sign_info *info,
226 				   const void *hash, uint8_t *sig,
227 				   uint sig_len, int node)
228 {
229 	const void *blob = info->fdt_blob;
230 	struct key_prop prop;
231 	int length;
232 	int ret = 0;
233 
234 	if (node < 0) {
235 		debug("%s: Skipping invalid node", __func__);
236 		return -EBADF;
237 	}
238 
239 	prop.num_bits = fdtdec_get_int(blob, node, "rsa,num-bits", 0);
240 
241 	prop.n0inv = fdtdec_get_int(blob, node, "rsa,n0-inverse", 0);
242 
243 	prop.public_exponent = fdt_getprop(blob, node, "rsa,exponent", &length);
244 	if (!prop.public_exponent || length < sizeof(uint64_t))
245 		prop.public_exponent = NULL;
246 
247 	prop.exp_len = sizeof(uint64_t);
248 
249 	prop.modulus = fdt_getprop(blob, node, "rsa,modulus", NULL);
250 	prop.public_exponent_BN = fdt_getprop(blob, node, "rsa,exponent-BN", NULL);
251 
252 	prop.rr = fdt_getprop(blob, node, "rsa,r-squared", NULL);
253 
254 	if (!prop.num_bits || !prop.modulus) {
255 		debug("%s: Missing RSA key info", __func__);
256 		return -EFAULT;
257 	}
258 
259 #ifdef CONFIG_ROCKCHIP_CRYPTO_V1
260 	prop.factor_c = fdt_getprop(blob, node, "rsa,c", NULL);
261 	if (!prop.factor_c)
262 		return -EFAULT;
263 #else
264 	prop.factor_np = fdt_getprop(blob, node, "rsa,np", NULL);
265 	if (!prop.factor_np)
266 		return -EFAULT;
267 #endif
268 	ret = rsa_verify_key(&prop, sig, sig_len, hash,
269 			     info->crypto->key_len, info->checksum);
270 
271 	return ret;
272 }
273 
274 int rsa_verify(struct image_sign_info *info,
275 	       const struct image_region region[], int region_count,
276 	       uint8_t *sig, uint sig_len)
277 {
278 	const void *blob = info->fdt_blob;
279 	/* Reserve memory for maximum checksum-length */
280 	uint8_t hash[info->crypto->key_len];
281 	int ndepth, noffset;
282 	int sig_node, node;
283 	char name[100];
284 	int ret;
285 
286 	/*
287 	 * Verify that the checksum-length does not exceed the
288 	 * rsa-signature-length
289 	 */
290 	if (info->checksum->checksum_len >
291 	    info->crypto->key_len) {
292 		debug("%s: invlaid checksum-algorithm %s for %s\n",
293 		      __func__, info->checksum->name, info->crypto->name);
294 		return -EINVAL;
295 	}
296 
297 	sig_node = fdt_subnode_offset(blob, 0, FIT_SIG_NODENAME);
298 	if (sig_node < 0) {
299 		debug("%s: No signature node found\n", __func__);
300 		return -ENOENT;
301 	}
302 
303 	/* Calculate checksum with checksum-algorithm */
304 	ret = info->checksum->calculate(info->checksum->name,
305 					region, region_count, hash);
306 	if (ret < 0) {
307 		debug("%s: Error in checksum calculation\n", __func__);
308 		return -EINVAL;
309 	}
310 
311 	/* See if we must use a particular key */
312 	if (info->required_keynode != -1) {
313 		ret = rsa_verify_with_keynode(info, hash, sig, sig_len,
314 			info->required_keynode);
315 		if (!ret)
316 			return ret;
317 	}
318 
319 	/* Look for a key that matches our hint */
320 	snprintf(name, sizeof(name), "key-%s", info->keyname);
321 	node = fdt_subnode_offset(blob, sig_node, name);
322 	ret = rsa_verify_with_keynode(info, hash, sig, sig_len, node);
323 	if (!ret)
324 		return ret;
325 
326 	/* No luck, so try each of the keys in turn */
327 	for (ndepth = 0, noffset = fdt_next_node(info->fit, sig_node, &ndepth);
328 			(noffset >= 0) && (ndepth > 0);
329 			noffset = fdt_next_node(info->fit, noffset, &ndepth)) {
330 		if (ndepth == 1 && noffset != node) {
331 			ret = rsa_verify_with_keynode(info, hash, sig, sig_len,
332 						      noffset);
333 			if (!ret)
334 				break;
335 		}
336 	}
337 
338 	return ret;
339 }
340