xref: /rk3399_rockchip-uboot/common/hash.c (revision 46fe2c04443f3d777791910da21649bb3ddf878f)
1 /*
2  * Copyright (c) 2012 The Chromium OS Authors.
3  *
4  * (C) Copyright 2011
5  * Joe Hershberger, National Instruments, joe.hershberger@ni.com
6  *
7  * (C) Copyright 2000
8  * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
9  *
10  * SPDX-License-Identifier:	GPL-2.0+
11  */
12 
13 #include <common.h>
14 #include <command.h>
15 #include <malloc.h>
16 #include <hw_sha.h>
17 #include <hash.h>
18 #include <u-boot/sha1.h>
19 #include <u-boot/sha256.h>
20 #include <asm/io.h>
21 #include <asm/errno.h>
22 
23 #ifdef CONFIG_SHA1
24 static int hash_init_sha1(struct hash_algo *algo, void **ctxp)
25 {
26 	sha1_context *ctx = malloc(sizeof(sha1_context));
27 	sha1_starts(ctx);
28 	*ctxp = ctx;
29 	return 0;
30 }
31 
32 static int hash_update_sha1(struct hash_algo *algo, void *ctx, const void *buf,
33 			    unsigned int size, int is_last)
34 {
35 	sha1_update((sha1_context *)ctx, buf, size);
36 	return 0;
37 }
38 
39 static int hash_finish_sha1(struct hash_algo *algo, void *ctx, void *dest_buf,
40 			    int size)
41 {
42 	if (size < algo->digest_size)
43 		return -1;
44 
45 	sha1_finish((sha1_context *)ctx, dest_buf);
46 	free(ctx);
47 	return 0;
48 }
49 #endif
50 
51 #ifdef CONFIG_SHA256
52 static int hash_init_sha256(struct hash_algo *algo, void **ctxp)
53 {
54 	sha256_context *ctx = malloc(sizeof(sha256_context));
55 	sha256_starts(ctx);
56 	*ctxp = ctx;
57 	return 0;
58 }
59 
60 static int hash_update_sha256(struct hash_algo *algo, void *ctx,
61 			      const void *buf, unsigned int size, int is_last)
62 {
63 	sha256_update((sha256_context *)ctx, buf, size);
64 	return 0;
65 }
66 
67 static int hash_finish_sha256(struct hash_algo *algo, void *ctx, void
68 			      *dest_buf, int size)
69 {
70 	if (size < algo->digest_size)
71 		return -1;
72 
73 	sha256_finish((sha256_context *)ctx, dest_buf);
74 	free(ctx);
75 	return 0;
76 }
77 #endif
78 
79 static int hash_init_crc32(struct hash_algo *algo, void **ctxp)
80 {
81 	uint32_t *ctx = malloc(sizeof(uint32_t));
82 	*ctx = 0;
83 	*ctxp = ctx;
84 	return 0;
85 }
86 
87 static int hash_update_crc32(struct hash_algo *algo, void *ctx,
88 			     const void *buf, unsigned int size, int is_last)
89 {
90 	*((uint32_t *)ctx) = crc32(*((uint32_t *)ctx), buf, size);
91 	return 0;
92 }
93 
94 static int hash_finish_crc32(struct hash_algo *algo, void *ctx, void *dest_buf,
95 			     int size)
96 {
97 	if (size < algo->digest_size)
98 		return -1;
99 
100 	*((uint32_t *)dest_buf) = *((uint32_t *)ctx);
101 	free(ctx);
102 	return 0;
103 }
104 
105 /*
106  * These are the hash algorithms we support. Chips which support accelerated
107  * crypto could perhaps add named version of these algorithms here. Note that
108  * algorithm names must be in lower case.
109  */
110 static struct hash_algo hash_algo[] = {
111 	/*
112 	 * CONFIG_SHA_HW_ACCEL is defined if hardware acceleration is
113 	 * available.
114 	 */
115 #ifdef CONFIG_SHA_HW_ACCEL
116 	{
117 		"sha1",
118 		SHA1_SUM_LEN,
119 		hw_sha1,
120 		CHUNKSZ_SHA1,
121 	}, {
122 		"sha256",
123 		SHA256_SUM_LEN,
124 		hw_sha256,
125 		CHUNKSZ_SHA256,
126 	},
127 #endif
128 #ifdef CONFIG_SHA1
129 	{
130 		"sha1",
131 		SHA1_SUM_LEN,
132 		sha1_csum_wd,
133 		CHUNKSZ_SHA1,
134 		hash_init_sha1,
135 		hash_update_sha1,
136 		hash_finish_sha1,
137 	},
138 #endif
139 #ifdef CONFIG_SHA256
140 	{
141 		"sha256",
142 		SHA256_SUM_LEN,
143 		sha256_csum_wd,
144 		CHUNKSZ_SHA256,
145 		hash_init_sha256,
146 		hash_update_sha256,
147 		hash_finish_sha256,
148 	},
149 #endif
150 	{
151 		"crc32",
152 		4,
153 		crc32_wd_buf,
154 		CHUNKSZ_CRC32,
155 		hash_init_crc32,
156 		hash_update_crc32,
157 		hash_finish_crc32,
158 	},
159 };
160 
161 #if defined(CONFIG_SHA256) || defined(CONFIG_CMD_SHA1SUM)
162 #define MULTI_HASH
163 #endif
164 
165 #if defined(CONFIG_HASH_VERIFY) || defined(CONFIG_CMD_HASH)
166 #define MULTI_HASH
167 #endif
168 
169 /* Try to minimize code size for boards that don't want much hashing */
170 #ifdef MULTI_HASH
171 #define multi_hash()	1
172 #else
173 #define multi_hash()	0
174 #endif
175 
176 /**
177  * store_result: Store the resulting sum to an address or variable
178  *
179  * @algo:		Hash algorithm being used
180  * @sum:		Hash digest (algo->digest_size bytes)
181  * @dest:		Destination, interpreted as a hex address if it starts
182  *			with * (or allow_env_vars is 0) or otherwise as an
183  *			environment variable.
184  * @allow_env_vars:	non-zero to permit storing the result to an
185  *			variable environment
186  */
187 static void store_result(struct hash_algo *algo, const uint8_t *sum,
188 			 const char *dest, int allow_env_vars)
189 {
190 	unsigned int i;
191 	int env_var = 0;
192 
193 	/*
194 	 * If environment variables are allowed, then we assume that 'dest'
195 	 * is an environment variable, unless it starts with *, in which
196 	 * case we assume it is an address. If not allowed, it is always an
197 	 * address. This is to support the crc32 command.
198 	 */
199 	if (allow_env_vars) {
200 		if (*dest == '*')
201 			dest++;
202 		else
203 			env_var = 1;
204 	}
205 
206 	if (env_var) {
207 		char str_output[HASH_MAX_DIGEST_SIZE * 2 + 1];
208 		char *str_ptr = str_output;
209 
210 		for (i = 0; i < algo->digest_size; i++) {
211 			sprintf(str_ptr, "%02x", sum[i]);
212 			str_ptr += 2;
213 		}
214 		*str_ptr = '\0';
215 		setenv(dest, str_output);
216 	} else {
217 		ulong addr;
218 		void *buf;
219 
220 		addr = simple_strtoul(dest, NULL, 16);
221 		buf = map_sysmem(addr, algo->digest_size);
222 		memcpy(buf, sum, algo->digest_size);
223 		unmap_sysmem(buf);
224 	}
225 }
226 
227 /**
228  * parse_verify_sum: Parse a hash verification parameter
229  *
230  * @algo:		Hash algorithm being used
231  * @verify_str:		Argument to parse. If it starts with * then it is
232  *			interpreted as a hex address containing the hash.
233  *			If the length is exactly the right number of hex digits
234  *			for the digest size, then we assume it is a hex digest.
235  *			Otherwise we assume it is an environment variable, and
236  *			look up its value (it must contain a hex digest).
237  * @vsum:		Returns binary digest value (algo->digest_size bytes)
238  * @allow_env_vars:	non-zero to permit storing the result to an environment
239  *			variable. If 0 then verify_str is assumed to be an
240  *			address, and the * prefix is not expected.
241  * @return 0 if ok, non-zero on error
242  */
243 static int parse_verify_sum(struct hash_algo *algo, char *verify_str,
244 			    uint8_t *vsum, int allow_env_vars)
245 {
246 	int env_var = 0;
247 
248 	/* See comment above in store_result() */
249 	if (allow_env_vars) {
250 		if (*verify_str == '*')
251 			verify_str++;
252 		else
253 			env_var = 1;
254 	}
255 
256 	if (!env_var) {
257 		ulong addr;
258 		void *buf;
259 
260 		addr = simple_strtoul(verify_str, NULL, 16);
261 		buf = map_sysmem(addr, algo->digest_size);
262 		memcpy(vsum, buf, algo->digest_size);
263 	} else {
264 		unsigned int i;
265 		char *vsum_str;
266 		int digits = algo->digest_size * 2;
267 
268 		/*
269 		 * As with the original code from sha1sum.c, we assume that a
270 		 * string which matches the digest size exactly is a hex
271 		 * string and not an environment variable.
272 		 */
273 		if (strlen(verify_str) == digits)
274 			vsum_str = verify_str;
275 		else {
276 			vsum_str = getenv(verify_str);
277 			if (vsum_str == NULL || strlen(vsum_str) != digits) {
278 				printf("Expected %d hex digits in env var\n",
279 				       digits);
280 				return 1;
281 			}
282 		}
283 
284 		for (i = 0; i < algo->digest_size; i++) {
285 			char *nullp = vsum_str + (i + 1) * 2;
286 			char end = *nullp;
287 
288 			*nullp = '\0';
289 			vsum[i] = simple_strtoul(vsum_str + (i * 2), NULL, 16);
290 			*nullp = end;
291 		}
292 	}
293 	return 0;
294 }
295 
296 int hash_lookup_algo(const char *algo_name, struct hash_algo **algop)
297 {
298 	int i;
299 
300 	for (i = 0; i < ARRAY_SIZE(hash_algo); i++) {
301 		if (!strcmp(algo_name, hash_algo[i].name)) {
302 			*algop = &hash_algo[i];
303 			return 0;
304 		}
305 	}
306 
307 	debug("Unknown hash algorithm '%s'\n", algo_name);
308 	return -EPROTONOSUPPORT;
309 }
310 
311 int hash_progressive_lookup_algo(const char *algo_name,
312 				 struct hash_algo **algop)
313 {
314 	int i;
315 
316 	for (i = 0; i < ARRAY_SIZE(hash_algo); i++) {
317 		if (!strcmp(algo_name, hash_algo[i].name)) {
318 			if (hash_algo[i].hash_init) {
319 				*algop = &hash_algo[i];
320 				return 0;
321 			}
322 		}
323 	}
324 
325 	debug("Unknown hash algorithm '%s'\n", algo_name);
326 	return -EPROTONOSUPPORT;
327 }
328 
329 void hash_show(struct hash_algo *algo, ulong addr, ulong len, uint8_t *output)
330 {
331 	int i;
332 
333 	printf("%s for %08lx ... %08lx ==> ", algo->name, addr, addr + len - 1);
334 	for (i = 0; i < algo->digest_size; i++)
335 		printf("%02x", output[i]);
336 }
337 
338 int hash_block(const char *algo_name, const void *data, unsigned int len,
339 	       uint8_t *output, int *output_size)
340 {
341 	struct hash_algo *algo;
342 	int ret;
343 
344 	ret = hash_lookup_algo(algo_name, &algo);
345 	if (ret)
346 		return ret;
347 
348 	if (output_size && *output_size < algo->digest_size) {
349 		debug("Output buffer size %d too small (need %d bytes)",
350 		      *output_size, algo->digest_size);
351 		return -ENOSPC;
352 	}
353 	if (output_size)
354 		*output_size = algo->digest_size;
355 	algo->hash_func_ws(data, len, output, algo->chunk_size);
356 
357 	return 0;
358 }
359 
360 int hash_command(const char *algo_name, int flags, cmd_tbl_t *cmdtp, int flag,
361 		 int argc, char * const argv[])
362 {
363 	ulong addr, len;
364 
365 	if ((argc < 2) || ((flags & HASH_FLAG_VERIFY) && (argc < 3)))
366 		return CMD_RET_USAGE;
367 
368 	addr = simple_strtoul(*argv++, NULL, 16);
369 	len = simple_strtoul(*argv++, NULL, 16);
370 
371 	if (multi_hash()) {
372 		struct hash_algo *algo;
373 		uint8_t output[HASH_MAX_DIGEST_SIZE];
374 		uint8_t vsum[HASH_MAX_DIGEST_SIZE];
375 		void *buf;
376 
377 		if (hash_lookup_algo(algo_name, &algo)) {
378 			printf("Unknown hash algorithm '%s'\n", algo_name);
379 			return CMD_RET_USAGE;
380 		}
381 		argc -= 2;
382 
383 		if (algo->digest_size > HASH_MAX_DIGEST_SIZE) {
384 			puts("HASH_MAX_DIGEST_SIZE exceeded\n");
385 			return 1;
386 		}
387 
388 		buf = map_sysmem(addr, len);
389 		algo->hash_func_ws(buf, len, output, algo->chunk_size);
390 		unmap_sysmem(buf);
391 
392 		/* Try to avoid code bloat when verify is not needed */
393 #ifdef CONFIG_HASH_VERIFY
394 		if (flags & HASH_FLAG_VERIFY) {
395 #else
396 		if (0) {
397 #endif
398 			if (parse_verify_sum(algo, *argv, vsum,
399 					flags & HASH_FLAG_ENV)) {
400 				printf("ERROR: %s does not contain a valid "
401 					"%s sum\n", *argv, algo->name);
402 				return 1;
403 			}
404 			if (memcmp(output, vsum, algo->digest_size) != 0) {
405 				int i;
406 
407 				hash_show(algo, addr, len, output);
408 				printf(" != ");
409 				for (i = 0; i < algo->digest_size; i++)
410 					printf("%02x", vsum[i]);
411 				puts(" ** ERROR **\n");
412 				return 1;
413 			}
414 		} else {
415 			hash_show(algo, addr, len, output);
416 			printf("\n");
417 
418 			if (argc) {
419 				store_result(algo, output, *argv,
420 					flags & HASH_FLAG_ENV);
421 			}
422 		}
423 
424 	/* Horrible code size hack for boards that just want crc32 */
425 	} else {
426 		ulong crc;
427 		ulong *ptr;
428 
429 		crc = crc32_wd(0, (const uchar *)addr, len, CHUNKSZ_CRC32);
430 
431 		printf("CRC32 for %08lx ... %08lx ==> %08lx\n",
432 				addr, addr + len - 1, crc);
433 
434 		if (argc >= 3) {
435 			ptr = (ulong *)simple_strtoul(argv[0], NULL, 16);
436 			*ptr = crc;
437 		}
438 	}
439 
440 	return 0;
441 }
442