tools: Fix return code of fit_image_process_sig()
[oweals/u-boot.git] / tools / image-host.c
1 /*
2  * Copyright (c) 2013, Google Inc.
3  *
4  * (C) Copyright 2008 Semihalf
5  *
6  * (C) Copyright 2000-2006
7  * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
8  *
9  * SPDX-License-Identifier:     GPL-2.0+
10  */
11
12 #include "mkimage.h"
13 #include <bootm.h>
14 #include <image.h>
15 #include <version.h>
16
17 /**
18  * fit_set_hash_value - set hash value in requested has node
19  * @fit: pointer to the FIT format image header
20  * @noffset: hash node offset
21  * @value: hash value to be set
22  * @value_len: hash value length
23  *
24  * fit_set_hash_value() attempts to set hash value in a node at offset
25  * given and returns operation status to the caller.
26  *
27  * returns
28  *     0, on success
29  *     -1, on failure
30  */
31 static int fit_set_hash_value(void *fit, int noffset, uint8_t *value,
32                                 int value_len)
33 {
34         int ret;
35
36         ret = fdt_setprop(fit, noffset, FIT_VALUE_PROP, value, value_len);
37         if (ret) {
38                 printf("Can't set hash '%s' property for '%s' node(%s)\n",
39                        FIT_VALUE_PROP, fit_get_name(fit, noffset, NULL),
40                        fdt_strerror(ret));
41                 return ret == -FDT_ERR_NOSPACE ? -ENOSPC : -EIO;
42         }
43
44         return 0;
45 }
46
47 /**
48  * fit_image_process_hash - Process a single subnode of the images/ node
49  *
50  * Check each subnode and process accordingly. For hash nodes we generate
51  * a hash of the supplised data and store it in the node.
52  *
53  * @fit:        pointer to the FIT format image header
54  * @image_name: name of image being processes (used to display errors)
55  * @noffset:    subnode offset
56  * @data:       data to process
57  * @size:       size of data in bytes
58  * @return 0 if ok, -1 on error
59  */
60 static int fit_image_process_hash(void *fit, const char *image_name,
61                 int noffset, const void *data, size_t size)
62 {
63         uint8_t value[FIT_MAX_HASH_LEN];
64         const char *node_name;
65         int value_len;
66         char *algo;
67         int ret;
68
69         node_name = fit_get_name(fit, noffset, NULL);
70
71         if (fit_image_hash_get_algo(fit, noffset, &algo)) {
72                 printf("Can't get hash algo property for '%s' hash node in '%s' image node\n",
73                        node_name, image_name);
74                 return -ENOENT;
75         }
76
77         if (calculate_hash(data, size, algo, value, &value_len)) {
78                 printf("Unsupported hash algorithm (%s) for '%s' hash node in '%s' image node\n",
79                        algo, node_name, image_name);
80                 return -EPROTONOSUPPORT;
81         }
82
83         ret = fit_set_hash_value(fit, noffset, value, value_len);
84         if (ret) {
85                 printf("Can't set hash value for '%s' hash node in '%s' image node\n",
86                        node_name, image_name);
87                 return ret;
88         }
89
90         return 0;
91 }
92
93 /**
94  * fit_image_write_sig() - write the signature to a FIT
95  *
96  * This writes the signature and signer data to the FIT.
97  *
98  * @fit: pointer to the FIT format image header
99  * @noffset: hash node offset
100  * @value: signature value to be set
101  * @value_len: signature value length
102  * @comment: Text comment to write (NULL for none)
103  *
104  * returns
105  *     0, on success
106  *     -FDT_ERR_..., on failure
107  */
108 static int fit_image_write_sig(void *fit, int noffset, uint8_t *value,
109                 int value_len, const char *comment, const char *region_prop,
110                 int region_proplen)
111 {
112         int string_size;
113         int ret;
114
115         /*
116          * Get the current string size, before we update the FIT and add
117          * more
118          */
119         string_size = fdt_size_dt_strings(fit);
120
121         ret = fdt_setprop(fit, noffset, FIT_VALUE_PROP, value, value_len);
122         if (!ret) {
123                 ret = fdt_setprop_string(fit, noffset, "signer-name",
124                                          "mkimage");
125         }
126         if (!ret) {
127                 ret = fdt_setprop_string(fit, noffset, "signer-version",
128                                   PLAIN_VERSION);
129         }
130         if (comment && !ret)
131                 ret = fdt_setprop_string(fit, noffset, "comment", comment);
132         if (!ret)
133                 ret = fit_set_timestamp(fit, noffset, time(NULL));
134         if (region_prop && !ret) {
135                 uint32_t strdata[2];
136
137                 ret = fdt_setprop(fit, noffset, "hashed-nodes",
138                                    region_prop, region_proplen);
139                 strdata[0] = 0;
140                 strdata[1] = cpu_to_fdt32(string_size);
141                 if (!ret) {
142                         ret = fdt_setprop(fit, noffset, "hashed-strings",
143                                           strdata, sizeof(strdata));
144                 }
145         }
146
147         return ret;
148 }
149
150 static int fit_image_setup_sig(struct image_sign_info *info,
151                 const char *keydir, void *fit, const char *image_name,
152                 int noffset, const char *require_keys)
153 {
154         const char *node_name;
155         char *algo_name;
156
157         node_name = fit_get_name(fit, noffset, NULL);
158         if (fit_image_hash_get_algo(fit, noffset, &algo_name)) {
159                 printf("Can't get algo property for '%s' signature node in '%s' image node\n",
160                        node_name, image_name);
161                 return -1;
162         }
163
164         memset(info, '\0', sizeof(*info));
165         info->keydir = keydir;
166         info->keyname = fdt_getprop(fit, noffset, "key-name-hint", NULL);
167         info->fit = fit;
168         info->node_offset = noffset;
169         info->algo = image_get_sig_algo(algo_name);
170         info->require_keys = require_keys;
171         if (!info->algo) {
172                 printf("Unsupported signature algorithm (%s) for '%s' signature node in '%s' image node\n",
173                        algo_name, node_name, image_name);
174                 return -1;
175         }
176
177         return 0;
178 }
179
180 /**
181  * fit_image_process_sig- Process a single subnode of the images/ node
182  *
183  * Check each subnode and process accordingly. For signature nodes we
184  * generate a signed hash of the supplised data and store it in the node.
185  *
186  * @keydir:     Directory containing keys to use for signing
187  * @keydest:    Destination FDT blob to write public keys into
188  * @fit:        pointer to the FIT format image header
189  * @image_name: name of image being processes (used to display errors)
190  * @noffset:    subnode offset
191  * @data:       data to process
192  * @size:       size of data in bytes
193  * @comment:    Comment to add to signature nodes
194  * @require_keys: Mark all keys as 'required'
195  * @return 0 if ok, -1 on error
196  */
197 static int fit_image_process_sig(const char *keydir, void *keydest,
198                 void *fit, const char *image_name,
199                 int noffset, const void *data, size_t size,
200                 const char *comment, int require_keys)
201 {
202         struct image_sign_info info;
203         struct image_region region;
204         const char *node_name;
205         uint8_t *value;
206         uint value_len;
207         int ret;
208
209         if (fit_image_setup_sig(&info, keydir, fit, image_name, noffset,
210                                 require_keys ? "image" : NULL))
211                 return -1;
212
213         node_name = fit_get_name(fit, noffset, NULL);
214         region.data = data;
215         region.size = size;
216         ret = info.algo->sign(&info, &region, 1, &value, &value_len);
217         if (ret) {
218                 printf("Failed to sign '%s' signature node in '%s' image node: %d\n",
219                        node_name, image_name, ret);
220
221                 /* We allow keys to be missing */
222                 if (ret == -ENOENT)
223                         return 0;
224                 return -1;
225         }
226
227         ret = fit_image_write_sig(fit, noffset, value, value_len, comment,
228                         NULL, 0);
229         if (ret) {
230                 if (ret == -FDT_ERR_NOSPACE)
231                         return -ENOSPC;
232                 printf("Can't write signature for '%s' signature node in '%s' conf node: %s\n",
233                        node_name, image_name, fdt_strerror(ret));
234                 return -1;
235         }
236         free(value);
237
238         /* Get keyname again, as FDT has changed and invalidated our pointer */
239         info.keyname = fdt_getprop(fit, noffset, "key-name-hint", NULL);
240
241         ret = info.algo->add_verify_data(&info, keydest);
242
243         /* Write the public key into the supplied FDT file; this might fail
244          * several times, since we try signing with successively increasing
245          * size values */
246         if (keydest && ret)
247                 return ret;
248
249         return 0;
250 }
251
252 /**
253  * fit_image_add_verification_data() - calculate/set verig. data for image node
254  *
255  * This adds hash and signature values for an component image node.
256  *
257  * All existing hash subnodes are checked, if algorithm property is set to
258  * one of the supported hash algorithms, hash value is computed and
259  * corresponding hash node property is set, for example:
260  *
261  * Input component image node structure:
262  *
263  * o image@1 (at image_noffset)
264  *   | - data = [binary data]
265  *   o hash@1
266  *     |- algo = "sha1"
267  *
268  * Output component image node structure:
269  *
270  * o image@1 (at image_noffset)
271  *   | - data = [binary data]
272  *   o hash@1
273  *     |- algo = "sha1"
274  *     |- value = sha1(data)
275  *
276  * For signature details, please see doc/uImage.FIT/signature.txt
277  *
278  * @keydir      Directory containing *.key and *.crt files (or NULL)
279  * @keydest     FDT Blob to write public keys into (NULL if none)
280  * @fit:        Pointer to the FIT format image header
281  * @image_noffset: Requested component image node
282  * @comment:    Comment to add to signature nodes
283  * @require_keys: Mark all keys as 'required'
284  * @return: 0 on success, <0 on failure
285  */
286 int fit_image_add_verification_data(const char *keydir, void *keydest,
287                 void *fit, int image_noffset, const char *comment,
288                 int require_keys)
289 {
290         const char *image_name;
291         const void *data;
292         size_t size;
293         int noffset;
294
295         /* Get image data and data length */
296         if (fit_image_get_data(fit, image_noffset, &data, &size)) {
297                 printf("Can't get image data/size\n");
298                 return -1;
299         }
300
301         image_name = fit_get_name(fit, image_noffset, NULL);
302
303         /* Process all hash subnodes of the component image node */
304         for (noffset = fdt_first_subnode(fit, image_noffset);
305              noffset >= 0;
306              noffset = fdt_next_subnode(fit, noffset)) {
307                 const char *node_name;
308                 int ret = 0;
309
310                 /*
311                  * Check subnode name, must be equal to "hash" or "signature".
312                  * Multiple hash nodes require unique unit node
313                  * names, e.g. hash@1, hash@2, signature@1, etc.
314                  */
315                 node_name = fit_get_name(fit, noffset, NULL);
316                 if (!strncmp(node_name, FIT_HASH_NODENAME,
317                              strlen(FIT_HASH_NODENAME))) {
318                         ret = fit_image_process_hash(fit, image_name, noffset,
319                                                 data, size);
320                 } else if (IMAGE_ENABLE_SIGN && keydir &&
321                            !strncmp(node_name, FIT_SIG_NODENAME,
322                                 strlen(FIT_SIG_NODENAME))) {
323                         ret = fit_image_process_sig(keydir, keydest,
324                                 fit, image_name, noffset, data, size,
325                                 comment, require_keys);
326                 }
327                 if (ret)
328                         return ret;
329         }
330
331         return 0;
332 }
333
334 struct strlist {
335         int count;
336         char **strings;
337 };
338
339 static void strlist_init(struct strlist *list)
340 {
341         memset(list, '\0', sizeof(*list));
342 }
343
344 static void strlist_free(struct strlist *list)
345 {
346         int i;
347
348         for (i = 0; i < list->count; i++)
349                 free(list->strings[i]);
350         free(list->strings);
351 }
352
353 static int strlist_add(struct strlist *list, const char *str)
354 {
355         char *dup;
356
357         dup = strdup(str);
358         list->strings = realloc(list->strings,
359                                 (list->count + 1) * sizeof(char *));
360         if (!list || !str)
361                 return -1;
362         list->strings[list->count++] = dup;
363
364         return 0;
365 }
366
367 static const char *fit_config_get_image_list(void *fit, int noffset,
368                 int *lenp, int *allow_missingp)
369 {
370         static const char default_list[] = FIT_KERNEL_PROP "\0"
371                         FIT_FDT_PROP;
372         const char *prop;
373
374         /* If there is an "image" property, use that */
375         prop = fdt_getprop(fit, noffset, "sign-images", lenp);
376         if (prop) {
377                 *allow_missingp = 0;
378                 return *lenp ? prop : NULL;
379         }
380
381         /* Default image list */
382         *allow_missingp = 1;
383         *lenp = sizeof(default_list);
384
385         return default_list;
386 }
387
388 static int fit_config_get_hash_list(void *fit, int conf_noffset,
389                                     int sig_offset, struct strlist *node_inc)
390 {
391         int allow_missing;
392         const char *prop, *iname, *end;
393         const char *conf_name, *sig_name;
394         char name[200], path[200];
395         int image_count;
396         int ret, len;
397
398         conf_name = fit_get_name(fit, conf_noffset, NULL);
399         sig_name = fit_get_name(fit, sig_offset, NULL);
400
401         /*
402          * Build a list of nodes we need to hash. We always need the root
403          * node and the configuration.
404          */
405         strlist_init(node_inc);
406         snprintf(name, sizeof(name), "%s/%s", FIT_CONFS_PATH, conf_name);
407         if (strlist_add(node_inc, "/") ||
408             strlist_add(node_inc, name))
409                 goto err_mem;
410
411         /* Get a list of images that we intend to sign */
412         prop = fit_config_get_image_list(fit, sig_offset, &len,
413                                         &allow_missing);
414         if (!prop)
415                 return 0;
416
417         /* Locate the images */
418         end = prop + len;
419         image_count = 0;
420         for (iname = prop; iname < end; iname += strlen(iname) + 1) {
421                 int noffset;
422                 int image_noffset;
423                 int hash_count;
424
425                 image_noffset = fit_conf_get_prop_node(fit, conf_noffset,
426                                                        iname);
427                 if (image_noffset < 0) {
428                         printf("Failed to find image '%s' in  configuration '%s/%s'\n",
429                                iname, conf_name, sig_name);
430                         if (allow_missing)
431                                 continue;
432
433                         return -ENOENT;
434                 }
435
436                 ret = fdt_get_path(fit, image_noffset, path, sizeof(path));
437                 if (ret < 0)
438                         goto err_path;
439                 if (strlist_add(node_inc, path))
440                         goto err_mem;
441
442                 snprintf(name, sizeof(name), "%s/%s", FIT_CONFS_PATH,
443                          conf_name);
444
445                 /* Add all this image's hashes */
446                 hash_count = 0;
447                 for (noffset = fdt_first_subnode(fit, image_noffset);
448                      noffset >= 0;
449                      noffset = fdt_next_subnode(fit, noffset)) {
450                         const char *name = fit_get_name(fit, noffset, NULL);
451
452                         if (strncmp(name, FIT_HASH_NODENAME,
453                                     strlen(FIT_HASH_NODENAME)))
454                                 continue;
455                         ret = fdt_get_path(fit, noffset, path, sizeof(path));
456                         if (ret < 0)
457                                 goto err_path;
458                         if (strlist_add(node_inc, path))
459                                 goto err_mem;
460                         hash_count++;
461                 }
462
463                 if (!hash_count) {
464                         printf("Failed to find any hash nodes in configuration '%s/%s' image '%s' - without these it is not possible to verify this image\n",
465                                conf_name, sig_name, iname);
466                         return -ENOMSG;
467                 }
468
469                 image_count++;
470         }
471
472         if (!image_count) {
473                 printf("Failed to find any images for configuration '%s/%s'\n",
474                        conf_name, sig_name);
475                 return -ENOMSG;
476         }
477
478         return 0;
479
480 err_mem:
481         printf("Out of memory processing configuration '%s/%s'\n", conf_name,
482                sig_name);
483         return -ENOMEM;
484
485 err_path:
486         printf("Failed to get path for image '%s' in configuration '%s/%s': %s\n",
487                iname, conf_name, sig_name, fdt_strerror(ret));
488         return -ENOENT;
489 }
490
491 static int fit_config_get_data(void *fit, int conf_noffset, int noffset,
492                 struct image_region **regionp, int *region_countp,
493                 char **region_propp, int *region_proplen)
494 {
495         char * const exc_prop[] = {"data"};
496         struct strlist node_inc;
497         struct image_region *region;
498         struct fdt_region fdt_regions[100];
499         const char *conf_name, *sig_name;
500         char path[200];
501         int count, i;
502         char *region_prop;
503         int ret, len;
504
505         conf_name = fit_get_name(fit, conf_noffset, NULL);
506         sig_name = fit_get_name(fit, conf_noffset, NULL);
507         debug("%s: conf='%s', sig='%s'\n", __func__, conf_name, sig_name);
508
509         /* Get a list of nodes we want to hash */
510         ret = fit_config_get_hash_list(fit, conf_noffset, noffset, &node_inc);
511         if (ret)
512                 return ret;
513
514         /* Get a list of regions to hash */
515         count = fdt_find_regions(fit, node_inc.strings, node_inc.count,
516                         exc_prop, ARRAY_SIZE(exc_prop),
517                         fdt_regions, ARRAY_SIZE(fdt_regions),
518                         path, sizeof(path), 1);
519         if (count < 0) {
520                 printf("Failed to hash configuration '%s/%s': %s\n", conf_name,
521                        sig_name, fdt_strerror(ret));
522                 return -EIO;
523         }
524         if (count == 0) {
525                 printf("No data to hash for configuration '%s/%s': %s\n",
526                        conf_name, sig_name, fdt_strerror(ret));
527                 return -EINVAL;
528         }
529
530         /* Build our list of data blocks */
531         region = fit_region_make_list(fit, fdt_regions, count, NULL);
532         if (!region) {
533                 printf("Out of memory hashing configuration '%s/%s'\n",
534                        conf_name, sig_name);
535                 return -ENOMEM;
536         }
537
538         /* Create a list of all hashed properties */
539         debug("Hash nodes:\n");
540         for (i = len = 0; i < node_inc.count; i++) {
541                 debug("   %s\n", node_inc.strings[i]);
542                 len += strlen(node_inc.strings[i]) + 1;
543         }
544         region_prop = malloc(len);
545         if (!region_prop) {
546                 printf("Out of memory setting up regions for configuration '%s/%s'\n",
547                        conf_name, sig_name);
548                 return -ENOMEM;
549         }
550         for (i = len = 0; i < node_inc.count;
551              len += strlen(node_inc.strings[i]) + 1, i++)
552                 strcpy(region_prop + len, node_inc.strings[i]);
553         strlist_free(&node_inc);
554
555         *region_countp = count;
556         *regionp = region;
557         *region_propp = region_prop;
558         *region_proplen = len;
559
560         return 0;
561 }
562
563 static int fit_config_process_sig(const char *keydir, void *keydest,
564                 void *fit, const char *conf_name, int conf_noffset,
565                 int noffset, const char *comment, int require_keys)
566 {
567         struct image_sign_info info;
568         const char *node_name;
569         struct image_region *region;
570         char *region_prop;
571         int region_proplen;
572         int region_count;
573         uint8_t *value;
574         uint value_len;
575         int ret;
576
577         node_name = fit_get_name(fit, noffset, NULL);
578         if (fit_config_get_data(fit, conf_noffset, noffset, &region,
579                                 &region_count, &region_prop, &region_proplen))
580                 return -1;
581
582         if (fit_image_setup_sig(&info, keydir, fit, conf_name, noffset,
583                                 require_keys ? "conf" : NULL))
584                 return -1;
585
586         ret = info.algo->sign(&info, region, region_count, &value, &value_len);
587         free(region);
588         if (ret) {
589                 printf("Failed to sign '%s' signature node in '%s' conf node\n",
590                        node_name, conf_name);
591
592                 /* We allow keys to be missing */
593                 if (ret == -ENOENT)
594                         return 0;
595                 return -1;
596         }
597
598         ret = fit_image_write_sig(fit, noffset, value, value_len, comment,
599                                 region_prop, region_proplen);
600         if (ret) {
601                 if (ret == -FDT_ERR_NOSPACE)
602                         return -ENOSPC;
603                 printf("Can't write signature for '%s' signature node in '%s' conf node: %s\n",
604                        node_name, conf_name, fdt_strerror(ret));
605                 return -1;
606         }
607         free(value);
608         free(region_prop);
609
610         /* Get keyname again, as FDT has changed and invalidated our pointer */
611         info.keyname = fdt_getprop(fit, noffset, "key-name-hint", NULL);
612
613         /* Write the public key into the supplied FDT file */
614         if (keydest) {
615                 ret = info.algo->add_verify_data(&info, keydest);
616                 if (ret == -ENOSPC)
617                         return -ENOSPC;
618                 if (ret) {
619                         printf("Failed to add verification data for '%s' signature node in '%s' image node\n",
620                                node_name, conf_name);
621                 }
622                 return ret;
623         }
624
625         return 0;
626 }
627
628 static int fit_config_add_verification_data(const char *keydir, void *keydest,
629                 void *fit, int conf_noffset, const char *comment,
630                 int require_keys)
631 {
632         const char *conf_name;
633         int noffset;
634
635         conf_name = fit_get_name(fit, conf_noffset, NULL);
636
637         /* Process all hash subnodes of the configuration node */
638         for (noffset = fdt_first_subnode(fit, conf_noffset);
639              noffset >= 0;
640              noffset = fdt_next_subnode(fit, noffset)) {
641                 const char *node_name;
642                 int ret = 0;
643
644                 node_name = fit_get_name(fit, noffset, NULL);
645                 if (!strncmp(node_name, FIT_SIG_NODENAME,
646                              strlen(FIT_SIG_NODENAME))) {
647                         ret = fit_config_process_sig(keydir, keydest,
648                                 fit, conf_name, conf_noffset, noffset, comment,
649                                 require_keys);
650                 }
651                 if (ret)
652                         return ret;
653         }
654
655         return 0;
656 }
657
658 int fit_add_verification_data(const char *keydir, void *keydest, void *fit,
659                               const char *comment, int require_keys)
660 {
661         int images_noffset, confs_noffset;
662         int noffset;
663         int ret;
664
665         /* Find images parent node offset */
666         images_noffset = fdt_path_offset(fit, FIT_IMAGES_PATH);
667         if (images_noffset < 0) {
668                 printf("Can't find images parent node '%s' (%s)\n",
669                        FIT_IMAGES_PATH, fdt_strerror(images_noffset));
670                 return images_noffset;
671         }
672
673         /* Process its subnodes, print out component images details */
674         for (noffset = fdt_first_subnode(fit, images_noffset);
675              noffset >= 0;
676              noffset = fdt_next_subnode(fit, noffset)) {
677                 /*
678                  * Direct child node of the images parent node,
679                  * i.e. component image node.
680                  */
681                 ret = fit_image_add_verification_data(keydir, keydest,
682                                 fit, noffset, comment, require_keys);
683                 if (ret)
684                         return ret;
685         }
686
687         /* If there are no keys, we can't sign configurations */
688         if (!IMAGE_ENABLE_SIGN || !keydir)
689                 return 0;
690
691         /* Find configurations parent node offset */
692         confs_noffset = fdt_path_offset(fit, FIT_CONFS_PATH);
693         if (confs_noffset < 0) {
694                 printf("Can't find images parent node '%s' (%s)\n",
695                        FIT_CONFS_PATH, fdt_strerror(confs_noffset));
696                 return -ENOENT;
697         }
698
699         /* Process its subnodes, print out component images details */
700         for (noffset = fdt_first_subnode(fit, confs_noffset);
701              noffset >= 0;
702              noffset = fdt_next_subnode(fit, noffset)) {
703                 ret = fit_config_add_verification_data(keydir, keydest,
704                                                        fit, noffset, comment,
705                                                        require_keys);
706                 if (ret)
707                         return ret;
708         }
709
710         return 0;
711 }
712
713 #ifdef CONFIG_FIT_SIGNATURE
714 int fit_check_sign(const void *fit, const void *key)
715 {
716         int cfg_noffset;
717         int ret;
718
719         cfg_noffset = fit_conf_get_node(fit, NULL);
720         if (!cfg_noffset)
721                 return -1;
722
723         printf("Verifying Hash Integrity ... ");
724         ret = fit_config_verify(fit, cfg_noffset);
725         if (ret)
726                 return ret;
727         ret = bootm_host_load_images(fit, cfg_noffset);
728
729         return ret;
730 }
731 #endif