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