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