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