xref: /openbmc/u-boot/lib/rsa/rsa-verify.c (revision 2a6e3869)
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 <fdtdec.h>
10 #include <asm/types.h>
11 #include <asm/byteorder.h>
12 #include <asm/errno.h>
13 #include <asm/types.h>
14 #include <asm/unaligned.h>
15 #else
16 #include "fdt_host.h"
17 #include "mkimage.h"
18 #include <fdt_support.h>
19 #endif
20 #include <rsa.h>
21 #include <sha1.h>
22 #include <sha256.h>
23 
24 #define UINT64_MULT32(v, multby)  (((uint64_t)(v)) * ((uint32_t)(multby)))
25 
26 #define get_unaligned_be32(a) fdt32_to_cpu(*(uint32_t *)a)
27 #define put_unaligned_be32(a, b) (*(uint32_t *)(b) = cpu_to_fdt32(a))
28 
29 /**
30  * subtract_modulus() - subtract modulus from the given value
31  *
32  * @key:	Key containing modulus to subtract
33  * @num:	Number to subtract modulus from, as little endian word array
34  */
35 static void subtract_modulus(const struct rsa_public_key *key, uint32_t num[])
36 {
37 	int64_t acc = 0;
38 	uint i;
39 
40 	for (i = 0; i < key->len; i++) {
41 		acc += (uint64_t)num[i] - key->modulus[i];
42 		num[i] = (uint32_t)acc;
43 		acc >>= 32;
44 	}
45 }
46 
47 /**
48  * greater_equal_modulus() - check if a value is >= modulus
49  *
50  * @key:	Key containing modulus to check
51  * @num:	Number to check against modulus, as little endian word array
52  * @return 0 if num < modulus, 1 if num >= modulus
53  */
54 static int greater_equal_modulus(const struct rsa_public_key *key,
55 				 uint32_t num[])
56 {
57 	uint32_t i;
58 
59 	for (i = key->len - 1; i >= 0; i--) {
60 		if (num[i] < key->modulus[i])
61 			return 0;
62 		if (num[i] > key->modulus[i])
63 			return 1;
64 	}
65 
66 	return 1;  /* equal */
67 }
68 
69 /**
70  * montgomery_mul_add_step() - Perform montgomery multiply-add step
71  *
72  * Operation: montgomery result[] += a * b[] / n0inv % modulus
73  *
74  * @key:	RSA key
75  * @result:	Place to put result, as little endian word array
76  * @a:		Multiplier
77  * @b:		Multiplicand, as little endian word array
78  */
79 static void montgomery_mul_add_step(const struct rsa_public_key *key,
80 		uint32_t result[], const uint32_t a, const uint32_t b[])
81 {
82 	uint64_t acc_a, acc_b;
83 	uint32_t d0;
84 	uint i;
85 
86 	acc_a = (uint64_t)a * b[0] + result[0];
87 	d0 = (uint32_t)acc_a * key->n0inv;
88 	acc_b = (uint64_t)d0 * key->modulus[0] + (uint32_t)acc_a;
89 	for (i = 1; i < key->len; i++) {
90 		acc_a = (acc_a >> 32) + (uint64_t)a * b[i] + result[i];
91 		acc_b = (acc_b >> 32) + (uint64_t)d0 * key->modulus[i] +
92 				(uint32_t)acc_a;
93 		result[i - 1] = (uint32_t)acc_b;
94 	}
95 
96 	acc_a = (acc_a >> 32) + (acc_b >> 32);
97 
98 	result[i - 1] = (uint32_t)acc_a;
99 
100 	if (acc_a >> 32)
101 		subtract_modulus(key, result);
102 }
103 
104 /**
105  * montgomery_mul() - Perform montgomery mutitply
106  *
107  * Operation: montgomery result[] = a[] * b[] / n0inv % modulus
108  *
109  * @key:	RSA key
110  * @result:	Place to put result, as little endian word array
111  * @a:		Multiplier, as little endian word array
112  * @b:		Multiplicand, as little endian word array
113  */
114 static void montgomery_mul(const struct rsa_public_key *key,
115 		uint32_t result[], uint32_t a[], const uint32_t b[])
116 {
117 	uint i;
118 
119 	for (i = 0; i < key->len; ++i)
120 		result[i] = 0;
121 	for (i = 0; i < key->len; ++i)
122 		montgomery_mul_add_step(key, result, a[i], b);
123 }
124 
125 /**
126  * pow_mod() - in-place public exponentiation
127  *
128  * @key:	RSA key
129  * @inout:	Big-endian word array containing value and result
130  */
131 static int pow_mod(const struct rsa_public_key *key, uint32_t *inout)
132 {
133 	uint32_t *result, *ptr;
134 	uint i;
135 
136 	/* Sanity check for stack size - key->len is in 32-bit words */
137 	if (key->len > RSA_MAX_KEY_BITS / 32) {
138 		debug("RSA key words %u exceeds maximum %d\n", key->len,
139 		      RSA_MAX_KEY_BITS / 32);
140 		return -EINVAL;
141 	}
142 
143 	uint32_t val[key->len], acc[key->len], tmp[key->len];
144 	result = tmp;  /* Re-use location. */
145 
146 	/* Convert from big endian byte array to little endian word array. */
147 	for (i = 0, ptr = inout + key->len - 1; i < key->len; i++, ptr--)
148 		val[i] = get_unaligned_be32(ptr);
149 
150 	montgomery_mul(key, acc, val, key->rr);  /* axx = a * RR / R mod M */
151 	for (i = 0; i < 16; i += 2) {
152 		montgomery_mul(key, tmp, acc, acc); /* tmp = acc^2 / R mod M */
153 		montgomery_mul(key, acc, tmp, tmp); /* acc = tmp^2 / R mod M */
154 	}
155 	montgomery_mul(key, result, acc, val);  /* result = XX * a / R mod M */
156 
157 	/* Make sure result < mod; result is at most 1x mod too large. */
158 	if (greater_equal_modulus(key, result))
159 		subtract_modulus(key, result);
160 
161 	/* Convert to bigendian byte array */
162 	for (i = key->len - 1, ptr = inout; (int)i >= 0; i--, ptr++)
163 		put_unaligned_be32(result[i], ptr);
164 	return 0;
165 }
166 
167 static int rsa_verify_key(const struct rsa_public_key *key, const uint8_t *sig,
168 			  const uint32_t sig_len, const uint8_t *hash,
169 			  struct checksum_algo *algo)
170 {
171 	const uint8_t *padding;
172 	int pad_len;
173 	int ret;
174 
175 	if (!key || !sig || !hash || !algo)
176 		return -EIO;
177 
178 	if (sig_len != (key->len * sizeof(uint32_t))) {
179 		debug("Signature is of incorrect length %d\n", sig_len);
180 		return -EINVAL;
181 	}
182 
183 	debug("Checksum algorithm: %s", algo->name);
184 
185 	/* Sanity check for stack size */
186 	if (sig_len > RSA_MAX_SIG_BITS / 8) {
187 		debug("Signature length %u exceeds maximum %d\n", sig_len,
188 		      RSA_MAX_SIG_BITS / 8);
189 		return -EINVAL;
190 	}
191 
192 	uint32_t buf[sig_len / sizeof(uint32_t)];
193 
194 	memcpy(buf, sig, sig_len);
195 
196 	ret = pow_mod(key, buf);
197 	if (ret)
198 		return ret;
199 
200 	padding = algo->rsa_padding;
201 	pad_len = algo->pad_len - algo->checksum_len;
202 
203 	/* Check pkcs1.5 padding bytes. */
204 	if (memcmp(buf, padding, pad_len)) {
205 		debug("In RSAVerify(): Padding check failed!\n");
206 		return -EINVAL;
207 	}
208 
209 	/* Check hash. */
210 	if (memcmp((uint8_t *)buf + pad_len, hash, sig_len - pad_len)) {
211 		debug("In RSAVerify(): Hash check failed!\n");
212 		return -EACCES;
213 	}
214 
215 	return 0;
216 }
217 
218 static void rsa_convert_big_endian(uint32_t *dst, const uint32_t *src, int len)
219 {
220 	int i;
221 
222 	for (i = 0; i < len; i++)
223 		dst[i] = fdt32_to_cpu(src[len - 1 - i]);
224 }
225 
226 static int rsa_verify_with_keynode(struct image_sign_info *info,
227 		const void *hash, uint8_t *sig, uint sig_len, int node)
228 {
229 	const void *blob = info->fdt_blob;
230 	struct rsa_public_key key;
231 	const void *modulus, *rr;
232 	int ret;
233 
234 	if (node < 0) {
235 		debug("%s: Skipping invalid node", __func__);
236 		return -EBADF;
237 	}
238 	if (!fdt_getprop(blob, node, "rsa,n0-inverse", NULL)) {
239 		debug("%s: Missing rsa,n0-inverse", __func__);
240 		return -EFAULT;
241 	}
242 	key.len = fdtdec_get_int(blob, node, "rsa,num-bits", 0);
243 	key.n0inv = fdtdec_get_int(blob, node, "rsa,n0-inverse", 0);
244 	modulus = fdt_getprop(blob, node, "rsa,modulus", NULL);
245 	rr = fdt_getprop(blob, node, "rsa,r-squared", NULL);
246 	if (!key.len || !modulus || !rr) {
247 		debug("%s: Missing RSA key info", __func__);
248 		return -EFAULT;
249 	}
250 
251 	/* Sanity check for stack size */
252 	if (key.len > RSA_MAX_KEY_BITS || key.len < RSA_MIN_KEY_BITS) {
253 		debug("RSA key bits %u outside allowed range %d..%d\n",
254 		      key.len, RSA_MIN_KEY_BITS, RSA_MAX_KEY_BITS);
255 		return -EFAULT;
256 	}
257 	key.len /= sizeof(uint32_t) * 8;
258 	uint32_t key1[key.len], key2[key.len];
259 
260 	key.modulus = key1;
261 	key.rr = key2;
262 	rsa_convert_big_endian(key.modulus, modulus, key.len);
263 	rsa_convert_big_endian(key.rr, rr, key.len);
264 	if (!key.modulus || !key.rr) {
265 		debug("%s: Out of memory", __func__);
266 		return -ENOMEM;
267 	}
268 
269 	debug("key length %d\n", key.len);
270 	ret = rsa_verify_key(&key, sig, sig_len, hash, info->algo->checksum);
271 	if (ret) {
272 		printf("%s: RSA failed to verify: %d\n", __func__, ret);
273 		return ret;
274 	}
275 
276 	return 0;
277 }
278 
279 int rsa_verify(struct image_sign_info *info,
280 	       const struct image_region region[], int region_count,
281 	       uint8_t *sig, uint sig_len)
282 {
283 	const void *blob = info->fdt_blob;
284 	/* Reserve memory for maximum checksum-length */
285 	uint8_t hash[info->algo->checksum->pad_len];
286 	int ndepth, noffset;
287 	int sig_node, node;
288 	char name[100];
289 	int ret;
290 
291 	/*
292 	 * Verify that the checksum-length does not exceed the
293 	 * rsa-signature-length
294 	 */
295 	if (info->algo->checksum->checksum_len >
296 	    info->algo->checksum->pad_len) {
297 		debug("%s: invlaid checksum-algorithm %s for %s\n",
298 		      __func__, info->algo->checksum->name, info->algo->name);
299 		return -EINVAL;
300 	}
301 
302 	sig_node = fdt_subnode_offset(blob, 0, FIT_SIG_NODENAME);
303 	if (sig_node < 0) {
304 		debug("%s: No signature node found\n", __func__);
305 		return -ENOENT;
306 	}
307 
308 	/* Calculate checksum with checksum-algorithm */
309 	info->algo->checksum->calculate(region, region_count, hash);
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