Skip to contentSkip to conversation

tools: mkimage: bound external data reads in fit_import_data()

PATCH Superseded Aristo Chen 3 participants 21 messages Oct 11 – Oct 29

lore
Share & tools
lore
#0 lore raw

cover tools: mkimage: bound external data reads in fit_import_data()

fit_import_data() reads each image's external data at the offset and size the FIT declares, without checking them against the file. An offset past the end of the file makes mkimage -F segfault, and a size running past it silently imports whatever memory follows. U-Boot proper and SPL already bound these properties since the series linked below; this series adds the same check to mkimage.

Patch 2 makes the data-offset, data-position and data-size accessors reject a property that is not exactly one cell, as was already done for data-size-unciphered. This also affects U-Boot proper and SPL, and adds 60 bytes to the pine64_plus SPL. Patch 4 switches fit_import_data() to these accessors and adds the bounds check. Patch 1 keeps an existing test meaningful once the check is in place, and patches 3 and 5 add the new tests.

Aristo Chen (5):
test: py: keep the external payload when editing a FIT with fdtput
image-fit: check the length of the external data properties
test: boot: check the length of the external data properties
tools: mkimage: bound external data reads in fit_import_data()
test: py: cover invalid external data properties in fit_import_data()

 boot/image-fit.c                      |  21 ++++-
 test/boot/image.c                     |  44 ++++++++++
 test/py/tests/test_fit_import_data.py | 121 +++++++++++++++++++++++++-
 tools/fit_image.c                     |  41 ++++++---
 4 files changed, 209 insertions(+), 18 deletions(-)
Signature · 1 line
2.43.0
#1 lore raw

PATCH 1/5 test: py: keep the external payload when editing a FIT with fdtput

test_fit_import_data_missing_offset() builds an external-data FIT and removes one image's data-offset with fdtput. fdtput rewrites only the device tree, so the external payload behind it is dropped and the file shrinks to the bare FIT. The test still passed, but only because fit_import_data() reads the remaining image's data from beyond the end of the truncated file, which on Linux lands in the zero-filled rest of the mapped page rather than crashing. A bounds check on those reads, added next, rejects that image first and the test would stop exercising the case it was written for.

Add a helper that saves the payload before running fdtput and appends it again afterwards at the 4-byte alignment fit_import_data() expects, and use it in the test so that the edited FIT stays complete.

---
 test/py/tests/test_fit_import_data.py | 30 +++++++++++++++++++++++++--
 1 file changed, 28 insertions(+), 2 deletions(-)
test/py/tests/test_fit_import_data.py +28 -2
index efbbad14262..95f7114243e 100644
@@ -14,6 +14,7 @@ stages instead.
 """
 
 import os
+import struct
 import subprocess
 
 import pytest
@@ -59,6 +60,32 @@ BASE_ITS = '''
 '''
 
 
+def fdtput_keep_data(itb, *args, opts=()):
+    """Run fdtput on a FIT while keeping its external data
+
+    fdtput rewrites only the device tree and drops any external data that
+    follows it, so save that payload first and append it again afterwards
+    at the 4-byte alignment fit_import_data() expects.
+
+    Args:
+        itb (str): Filename of the FIT to edit
+        args (list of str): Node, property and values to pass to fdtput
+        opts (list of str): Options to pass before the filename
+    """
+    with open(itb, 'rb') as inf:
+        blob = inf.read()
+    totalsize = struct.unpack('>I', blob[4:8])[0]
+    payload = blob[(totalsize + 3) & ~3:]
+
+    subprocess.run(['fdtput'] + list(opts) + [itb] + list(args), check=True)
+
+    with open(itb, 'rb') as inf:
+        fdt = inf.read()
+    totalsize = struct.unpack('>I', fdt[4:8])[0]
+    with open(itb, 'wb') as outf:
+        outf.write(fdt.ljust((totalsize + 3) & ~3, b'\0') + payload)
+
+
 @pytest.mark.boardspec('sandbox')
 @pytest.mark.requiredtool('dtc')
 @pytest.mark.requiredtool('fdtput')
@@ -77,8 +104,7 @@ def test_fit_import_data_missing_offset(ubman):
     assert result.returncode == 0, result.stderr
 
     # Remove the offset so that only data-size is left on kernel-2
-    subprocess.run(['fdtput', '-d', itb, '/images/kernel-2', 'data-offset'],
-                   check=True)
+    fdtput_keep_data(itb, '/images/kernel-2', 'data-offset', opts=['-d'])
 
     # Re-processing must skip the malformed image in the import, so that
     # the hashing stage reports it; previously the stale pointer made the
Signature · 1 line
2.43.0
Reviewed-by on v1 1/5
#2 lore raw

Re: [PATCH v1 1/5] test: py: keep the external payload when editing a FIT with fdtput

Quoted 12 lines · Aristo Chen

test: py: keep the external payload when editing a FIT with fdtput

test_fit_import_data_missing_offset() builds an external-data FIT and removes one image's data-offset with fdtput. fdtput rewrites only the device tree, so the external payload behind it is dropped and the file shrinks to the bare FIT. The test still passed, but only because fit_import_data() reads the remaining image's data from beyond the end of the truncated file, which on Linux lands in the zero-filled rest of the mapped page rather than crashing. A bounds check on those reads, added next, rejects that image first and the test would stop exercising the case it was written for.

Quoted 8 lines

Add a helper that saves the payload before running fdtput and appends it again afterwards at the 4-byte alignment fit_import_data() expects, and use it in the test so that the edited FIT stays complete.

test/py/tests/test_fit_import_data.py | 30 ++++++++++++++++++++++++++++--

 1 file changed, 28 insertions(+), 2 deletions(-)
#3 lore raw

PATCH 2/5 image-fit: check the length of the external data properties

In reply to Aristo Chen

fit_image_get_data_offset(), fit_image_get_data_position() and fit_image_get_data_size() pass NULL as fdt_getprop()'s length argument, so they accept a property of any size and then dereference the first four bytes of it. A property shorter than that is read past its end, and the bytes that follow it in the FIT are returned to the caller. An empty data-size, for example, is read as the structure tag that follows it, a small number such as 2 or 3, and selects a few bytes of the external data instead of failing.

Ask for the length and require it to be exactly one fdt32_t, as commit c2b8eefd4e10 ("image-fit: check the length of the data-size-unciphered property") does for data-size-unciphered. Every caller already checks the return value and handles a failure like a missing property.

Fixes db1b79b886f0 ("splash: add support for loading splash from a FIT image")
Fixes a1be94b65410 ("SPL: Add FIT data-position property support")
---
 boot/image-fit.c | 21 ++++++++++++++++++---
 1 file changed, 18 insertions(+), 3 deletions(-)
boot/image-fit.c +18 -3
index e173108033b..0dc4d7840eb 100644
@@ -963,15 +963,20 @@ int fit_image_get_emb_data(const void *fit, int noffset, const void **data,
  * returns:
  *     0, on success
  *     -ENOENT if the property could not be found
+ *     -EINVAL if the property is not exactly one fdt32_t long
  */
 int fit_image_get_data_offset(const void *fit, int noffset, u32 *data_offset)
 {
 	const fdt32_t *val;
+	int len;
 
-	val = fdt_getprop(fit, noffset, FIT_DATA_OFFSET_PROP, NULL);
+	val = fdt_getprop(fit, noffset, FIT_DATA_OFFSET_PROP, &len);
 	if (!val)
 		return -ENOENT;
 
+	if (len != sizeof(*val))
+		return -EINVAL;
+
 	*data_offset = fdt32_to_cpu(*val);
 
 	return 0;
@@ -987,16 +992,21 @@ int fit_image_get_data_offset(const void *fit, int noffset, u32 *data_offset)
  * returns:
  *     0, on success
  *     -ENOENT if the property could not be found
+ *     -EINVAL if the property is not exactly one fdt32_t long
  */
 int fit_image_get_data_position(const void *fit, int noffset,
 				u32 *data_position)
 {
 	const fdt32_t *val;
+	int len;
 
-	val = fdt_getprop(fit, noffset, FIT_DATA_POSITION_PROP, NULL);
+	val = fdt_getprop(fit, noffset, FIT_DATA_POSITION_PROP, &len);
 	if (!val)
 		return -ENOENT;
 
+	if (len != sizeof(*val))
+		return -EINVAL;
+
 	*data_position = fdt32_to_cpu(*val);
 
 	return 0;
@@ -1012,15 +1022,20 @@ int fit_image_get_data_position(const void *fit, int noffset,
  * returns:
  *     0, on success
  *     -ENOENT if the property could not be found
+ *     -EINVAL if the property is not exactly one fdt32_t long
  */
 int fit_image_get_data_size(const void *fit, int noffset, u32 *data_size)
 {
 	const fdt32_t *val;
+	int len;
 
-	val = fdt_getprop(fit, noffset, FIT_DATA_SIZE_PROP, NULL);
+	val = fdt_getprop(fit, noffset, FIT_DATA_SIZE_PROP, &len);
 	if (!val)
 		return -ENOENT;
 
+	if (len != sizeof(*val))
+		return -EINVAL;
+
 	*data_size = fdt32_to_cpu(*val);
 
 	return 0;
Signature · 1 line
2.43.0
Reviewed-by on v1 2/5
#4 lore raw

Re: [PATCH v1 2/5] image-fit: check the length of the external data properties

Hi Aristo,

Quoted 29 lines · Aristo Chen

image-fit: check the length of the external data properties

fit_image_get_data_offset(), fit_image_get_data_position() and fit_image_get_data_size() pass NULL as fdt_getprop()'s length argument, so they accept a property of any size and then dereference the first four bytes of it. A property shorter than that is read past its end, and the bytes that follow it in the FIT are returned to the caller. An empty data-size, for example, is read as the structure tag that follows it, a small number such as 2 or 3, and selects a few bytes of the external data instead of failing.

Ask for the length and require it to be exactly one fdt32_t, as commit c2b8eefd4e10 ("image-fit: check the length of the data-size-unciphered property") does for data-size-unciphered. Every caller already checks the return value and handles a failure like a missing property.

Fixes db1b79b886f0 ("splash: add support for loading splash from a FIT image")
Fixes a1be94b65410 ("SPL: Add FIT data-position property support")

boot/image-fit.c | 21 ++++++++++++++++++---

 1 file changed, 18 insertions(+), 3 deletions(-)
boot/image-fit.c +0 -0
@@ -1012,15 +1022,20 @@ int fit_image_get_data_position(const void *fit, int noffset,
 int fit_image_get_data_size(const void *fit, int noffset, u32 *data_size)
 {
      const fdt32_t *val;

boot/image-fit.c int fit_image_get_data_position(const void *fit, int noffset, · line 1033

Quoted 10 lines
boot/image-fit.c +5 -1
+     int len;
 
-     val = fdt_getprop(fit, noffset, FIT_DATA_SIZE_PROP, NULL);
+     val = fdt_getprop(fit, noffset, FIT_DATA_SIZE_PROP, &len);
      if (!val)
              return -ENOENT;
 
+     if (len != sizeof(*val))
+             return -EINVAL;
+

Counting fit_image_get_data_size_unciphered(), this leaves four copies of the same body. Please can you add a small static helper, e.g. fit_get_u32_prop(fit, noffset, name, &val), and call it from each accessor? That would also win back some of the 60 bytes this adds to SPL. A follow-up patch is fine if you prefer to keep this one focused on the fix.

I checked the callers in image-fit.c, spl_fit.c, splash_source.c, socfpga_arria10.c and (after patch 4) fit_image.c. All of them treat a non-zero return as 'not present' or bail out, so -EINVAL is safe. There is one change in behaviour: if data-offset is also present, a malformed data-position now falls through to it rather than winning. That seems fine, since having both is already invalid.

#5 lore raw

Re: [PATCH v1 2/5] image-fit: check the length of the external data properties

Hi Simon,

Quoted 40 lines · Simon Glass

Hi Aristo,

Quoted 36 lines · Aristo Chen

image-fit: check the length of the external data properties

fit_image_get_data_offset(), fit_image_get_data_position() and fit_image_get_data_size() pass NULL as fdt_getprop()'s length argument, so they accept a property of any size and then dereference the first four bytes of it. A property shorter than that is read past its end, and the bytes that follow it in the FIT are returned to the caller. An empty data-size, for example, is read as the structure tag that follows it, a small number such as 2 or 3, and selects a few bytes of the external data instead of failing.

Ask for the length and require it to be exactly one fdt32_t, as commit c2b8eefd4e10 ("image-fit: check the length of the data-size-unciphered property") does for data-size-unciphered. Every caller already checks the return value and handles a failure like a missing property.

Fixes db1b79b886f0 ("splash: add support for loading splash from a FIT image")
Fixes a1be94b65410 ("SPL: Add FIT data-position property support")

boot/image-fit.c | 21 ++++++++++++++++++---

 1 file changed, 18 insertions(+), 3 deletions(-)
boot/image-fit.c +2 -1
@@ -1012,15 +1022,20 @@ int fit_image_get_data_position(const void *fit, int noffset,
 int fit_image_get_data_size(const void *fit, int noffset, u32 *data_size)
 {
      const fdt32_t *val;
+     int len;
 
-     val = fdt_getprop(fit, noffset, FIT_DATA_SIZE_PROP, NULL);
+     val = fdt_getprop(fit, noffset, FIT_DATA_SIZE_PROP, &len);
      if (!val)
              return -ENOENT;
 
Quoted 10 lines

boot/image-fit.c int fit_image_get_emb_data(const void *fit, int noffset, const void **data, · line 979

Quoted 3 lines
boot/image-fit.c +3 -0
+     if (len != sizeof(*val))
+             return -EINVAL;
+

Counting fit_image_get_data_size_unciphered(), this leaves four copies of the same body. Please can you add a small static helper, e.g. fit_get_u32_prop(fit, noffset, name, &val), and call it from each accessor? That would also win back some of the 60 bytes this adds to SPL. A follow-up patch is fine if you prefer to keep this one focused on the fix.

I will send the helper as a follow-up.

Quoted 7 lines

I checked the callers in image-fit.c, spl_fit.c, splash_source.c, socfpga_arria10.c and (after patch 4) fit_image.c. All of them treat a non-zero return as 'not present' or bail out, so -EINVAL is safe. There is one change in behaviour: if data-offset is also present, a malformed data-position now falls through to it rather than winning. That seems fine, since having both is already invalid.

Thanks for checking all the callers, and agreed on the data-position case.

Quoted 2 lines

Best regards,
Aristo

#6 lore raw

PATCH 3/5 test: boot: check the length of the external data properties

In reply to Aristo Chen

Build a minimal FIT with libfdt and check that fit_image_get_data_offset(), fit_image_get_data_position() and fit_image_get_data_size() return -EINVAL for an empty property and for one of two cells instead of reading them, while a single cell is still read and a missing property still gives -ENOENT.

---
 test/boot/image.c | 44 ++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 44 insertions(+)
test/boot/image.c +44 -0
index 2c6d9dcbc22..235053afede 100644
@@ -6,6 +6,7 @@
  * Written by Simon Glass <[email protected]>
  */
 
+#include <errno.h>
 #include <image.h>
 #include <test/ut.h>
 #include <linux/libfdt.h>
@@ -78,6 +79,49 @@ static int test_fit_conf_find_compat(struct unit_test_state *uts)
 }
 BOOTSTD_TEST(test_fit_conf_find_compat, 0);
 
+/* Test that external data properties must be exactly one cell long */
+static int test_fit_image_ext_data_len(struct unit_test_state *uts)
+{
+	static const struct {
+		const char *name;
+		int (*get)(const void *fit, int noffset, u32 *val);
+	} props[] = {
+		{ FIT_DATA_OFFSET_PROP, fit_image_get_data_offset },
+		{ FIT_DATA_POSITION_PROP, fit_image_get_data_position },
+		{ FIT_DATA_SIZE_PROP, fit_image_get_data_size },
+	};
+	fdt32_t cells[] = { cpu_to_fdt32(0x100), cpu_to_fdt32(0x200) };
+	int images, node, i;
+	char fit[512];
+	u32 val;
+
+	ut_assertok(fdt_create_empty_tree(fit, sizeof(fit)));
+	images = fdt_add_subnode(fit, 0, "images");
+	ut_assert(images >= 0);
+	node = fdt_add_subnode(fit, images, "kernel");
+	ut_assert(node >= 0);
+
+	for (i = 0; i < ARRAY_SIZE(props); i++) {
+		ut_asserteq(-ENOENT, props[i].get(fit, node, &val));
+
+		/* an empty or a two-cell property must not be read */
+		ut_assertok(fdt_setprop_empty(fit, node, props[i].name));
+		ut_asserteq(-EINVAL, props[i].get(fit, node, &val));
+		ut_assertok(fdt_setprop(fit, node, props[i].name, cells,
+					sizeof(cells)));
+		ut_asserteq(-EINVAL, props[i].get(fit, node, &val));
+
+		/* a single cell is read */
+		ut_assertok(fdt_setprop(fit, node, props[i].name, cells,
+					sizeof(cells[0])));
+		ut_assertok(props[i].get(fit, node, &val));
+		ut_asserteq(0x100, val);
+	}
+
+	return 0;
+}
+BOOTSTD_TEST(test_fit_image_ext_data_len, 0);
+
 /* Test of image phase */
 static int test_image_phase(struct unit_test_state *uts)
 {
Signature · 1 line
2.43.0
Reviewed-by on v1 3/5
#7 lore raw

Re: [PATCH v1 3/5] test: boot: check the length of the external data properties

Quoted 8 lines · Aristo Chen

test: boot: check the length of the external data properties

Build a minimal FIT with libfdt and check that fit_image_get_data_offset(), fit_image_get_data_position() and fit_image_get_data_size() return -EINVAL for an empty property and for one of two cells instead of reading them, while a single cell is still read and a missing property still gives -ENOENT.

Quoted 4 lines

test/boot/image.c | 44 ++++++++++++++++++++++++++++++++++++++++++++

 1 file changed, 44 insertions(+)
#8 lore raw

PATCH 4/5 tools: mkimage: bound external data reads in fit_import_data()

In reply to Aristo Chen

fit_import_data() reads each image's external data from the mapped FIT file at the offset and size the FIT itself declares, without checking that the region lies inside the file. A data-offset or data-position pointing past the end of the file, or a size reaching beyond it, makes mkimage read outside the mapping, crashing on re-process or silently importing unrelated memory as image data. An authored .its that declares external data properties hits the same path, since dtc produces no payload beyond the device tree.

Read the properties through fit_image_get_data_position(), fit_image_get_data_offset() and fit_image_get_data_size(), which return u32 since commit c4d81d062790 ("image-fit: Use unsigned types for external data properties"), so a value of 0xffffffff is no longer mistaken for a missing property. They fail for a property that is not exactly one cell, and the import then skips the image as if the property were missing, as it already did for a shorter one. Compute the file offset in 64 bits and require the whole region to lie within the mapped file before importing it, with an error naming the image and the offending values. An empty region reads nothing, so it is not checked:
mkimage -E -p places one past the end of the file when every image is empty, and such a FIT must still re-process.

---
 tools/fit_image.c | 41 +++++++++++++++++++++++++++++------------
 1 file changed, 29 insertions(+), 12 deletions(-)
tools/fit_image.c +29 -12
index b648e3e2514..f0f30e06bd9 100644
@@ -1033,9 +1033,9 @@ static int fit_import_data(struct image_tool_params *params, const char *fname)
 	     node >= 0;
 	     node = fdt_next_subnode(fdt, node)) {
 		const char *ext_data_prop = NULL;
-		void *data = NULL;
-		int buf_ptr;
-		int len;
+		uint64_t offset = 0;
+		u32 val;
+		u32 len;
 
 		/*
 		 * A source file must not combine image-data with external
@@ -1059,22 +1059,39 @@ static int fit_import_data(struct image_tool_params *params, const char *fname)
 		 * FIT_DATA_OFFSET_PROP and FIT_DATA_POSITION_PROP are never both present,
 		 *  but if they are, prefer FIT_DATA_OFFSET_PROP as it was there first
 		 */
-		buf_ptr = fdtdec_get_int(fdt, node, FIT_DATA_POSITION_PROP, -1);
-		if (buf_ptr != -1) {
+		if (!fit_image_get_data_position(fdt, node, &val)) {
 			ext_data_prop = FIT_DATA_POSITION_PROP;
-			data = old_fdt + buf_ptr;
+			offset = val;
 		}
-		buf_ptr = fdtdec_get_int(fdt, node, FIT_DATA_OFFSET_PROP, -1);
-		if (buf_ptr != -1) {
+		if (!fit_image_get_data_offset(fdt, node, &val)) {
 			ext_data_prop = FIT_DATA_OFFSET_PROP;
-			data = old_fdt + data_base + buf_ptr;
+			offset = data_base + (uint64_t)val;
 		}
-		len = fdtdec_get_int(fdt, node, FIT_DATA_SIZE_PROP, -1);
-		if (!data || len == -1)
+		if (!ext_data_prop || fit_image_get_data_size(fdt, node, &len))
 			continue;
+
+		/*
+		 * The offset and size come from the FIT itself, so make
+		 * sure the region lies within the mapped file before
+		 * reading it. An empty region reads nothing and may lie
+		 * past the end, as mkimage -E -p places it there when every
+		 * image is empty.
+		 */
+		if (len && (offset > (uint64_t)sbuf.st_size ||
+			    len > sbuf.st_size - offset)) {
+			fprintf(stderr,
+				"Error: image '%s': external data at file offset 0x%llx size 0x%x is outside the FIT file (size 0x%llx)\n",
+				fdt_get_name(fdt, node, NULL),
+				(unsigned long long)offset, len,
+				(unsigned long long)sbuf.st_size);
+			ret = -EINVAL;
+			goto err_munmap;
+		}
+
 		debug("Importing data size %x\n", len);
 
-		ret = fdt_setprop(fdt, node, FIT_DATA_PROP, data, len);
+		ret = fdt_setprop(fdt, node, FIT_DATA_PROP, old_fdt + offset,
+				  len);
 		if (ret) {
 			debug("%s: Failed to write property: %s\n", __func__,
 			      fdt_strerror(ret));
Signature · 1 line
2.43.0
Reviewed-by on v1 4/5
#9 lore raw
Quoted 24 lines · Aristo Chen

tools: mkimage: bound external data reads in fit_import_data()

fit_import_data() reads each image's external data from the mapped FIT file at the offset and size the FIT itself declares, without checking that the region lies inside the file. A data-offset or data-position pointing past the end of the file, or a size reaching beyond it, makes mkimage read outside the mapping, crashing on re-process or silently importing unrelated memory as image data. An authored .its that declares external data properties hits the same path, since dtc produces no payload beyond the device tree.

Read the properties through fit_image_get_data_position(), fit_image_get_data_offset() and fit_image_get_data_size(), which return u32 since commit c4d81d062790 ("image-fit: Use unsigned types for external data properties"), so a value of 0xffffffff is no longer mistaken for a missing property. They fail for a property that is not exactly one cell, and the import then skips the image as if the property were missing, as it already did for a shorter one. Compute the file offset in 64 bits and require the whole region to lie within the mapped file before importing it, with an error naming the image and the offending values. An empty region reads nothing, so it is not checked:
mkimage -E -p places one past the end of the file when every image is empty, and such a FIT must still re-process.

Quoted 4 lines

tools/fit_image.c | 41 +++++++++++++++++++++++++++++------------

 1 file changed, 29 insertions(+), 12 deletions(-)
#10 lore raw

PATCH 5/5 test: py: cover invalid external data properties in fit_import_data()

In reply to Aristo Chen

Build an external-data FIT, then point one image's data-offset far past the end of the file and, separately, make its data-size run a few bytes past the end, re-processing the result with mkimage -F each time. Both must be rejected with a diagnostic naming that image. Previously the first crashed mkimage and the second silently imported the bytes beyond the end of the file as image data.

Also check that a FIT whose images are all empty, which mkimage -E -p writes with data-position past the end of the file, still re-processes, since an empty region has nothing to read.

Finally, now that the import reads the properties through the FIT accessors, check that an empty data-offset or data-size is skipped like a missing property, so that the hashing stage reports the image instead of the import reading it from the bytes that follow it.

---
 test/py/tests/test_fit_import_data.py | 91 ++++++++++++++++++++++++++-
 1 file changed, 90 insertions(+), 1 deletion(-)
test/py/tests/test_fit_import_data.py +90 -1
index 95f7114243e..c6f03db17ad 100644
@@ -3,7 +3,7 @@
 #
 # Test mkimage import of external data in fit_import_data()
 
-"""Regression test for stale per-image state in fit_import_data().
+"""Regression tests for fit_import_data().
 
 The import loop used to keep the data pointer and external property name
 of the previous image, so an image node carrying data-size but neither
@@ -11,6 +11,11 @@ data-offset nor data-position imported the previous image's data and
 then made mkimage abort without printing any diagnostic. Such a node
 must be skipped by the import and reported by the later processing
 stages instead.
+
+The import also read each image's external data at the offset and size
+the FIT declares without checking them against the file, so a region
+reaching past the end of the file crashed mkimage or imported unrelated
+memory as image data. Such a region must be rejected before it is read.
 """
 
 import os
@@ -113,3 +118,87 @@ def test_fit_import_data_missing_offset(ubman):
                             capture_output=True, text=True)
     assert result.returncode != 0
     assert "Can't get image data/size" in result.stderr
+
+
[email protected]('sandbox')
[email protected]('dtc')
[email protected]('fdtput')
+def test_fit_import_data_out_of_range(ubman):
+    """External data outside the file must be rejected, not read"""
+    mkimage = os.path.join(ubman.config.build_dir, 'tools/mkimage')
+    params = {
+        'kernel1': fit_util.make_kernel(ubman, 'oob-kernel1.bin', 'first'),
+        'kernel2': fit_util.make_kernel(ubman, 'oob-kernel2.bin', 'second'),
+    }
+    its = fit_util.make_its(ubman, BASE_ITS, params, 'oob.its')
+    itb = fit_util.make_fname(ubman, 'oob.itb')
+
+    result = subprocess.run([mkimage, '-E', '-f', its, itb],
+                            capture_output=True, text=True)
+    assert result.returncode == 0, result.stderr
+
+    # Point kernel-2's data far past the end of the file
+    fdtput_keep_data(itb, '/images/kernel-2', 'data-offset', '0x40000000',
+                     opts=['-t', 'i'])
+    result = subprocess.run([mkimage, '-F', itb],
+                            capture_output=True, text=True)
+    assert result.returncode != 0
+    assert "image 'kernel-2': external data" in result.stderr
+    assert 'outside the FIT file' in result.stderr
+
+    # A size running just past the end of the file must be rejected too.
+    # kernel-2's data comes last, padded to 4 bytes, so 4 bytes more than
+    # its real size always reach past the end.
+    result = subprocess.run([mkimage, '-E', '-f', its, itb],
+                            capture_output=True, text=True)
+    assert result.returncode == 0, result.stderr
+    size = os.path.getsize(params['kernel2']) + 4
+    fdtput_keep_data(itb, '/images/kernel-2', 'data-size', f'{size:#x}',
+                     opts=['-t', 'i'])
+    result = subprocess.run([mkimage, '-F', itb],
+                            capture_output=True, text=True)
+    assert result.returncode != 0
+    assert "image 'kernel-2': external data" in result.stderr
+
+    # An empty region has nothing to read, so it is accepted even past the
+    # end of the file, which is where mkimage -E -p places it when every
+    # image is empty
+    for name in ('kernel1', 'kernel2'):
+        params[name] = fit_util.make_fname(ubman, f'oob-empty-{name}.bin')
+        with open(params[name], 'wb'):
+            pass
+    its = fit_util.make_its(ubman, BASE_ITS, params, 'oob-empty.its')
+    result = subprocess.run([mkimage, '-E', '-p', '0x1000', '-f', its, itb],
+                            capture_output=True, text=True)
+    assert result.returncode == 0, result.stderr
+    assert os.path.getsize(itb) < 0x1000
+    result = subprocess.run([mkimage, '-F', itb],
+                            capture_output=True, text=True)
+    assert result.returncode == 0, result.stderr
+
+
[email protected]('sandbox')
[email protected]('dtc')
[email protected]('fdtput')
+def test_fit_import_data_short_prop(ubman):
+    """An external data property shorter than one cell must not be read"""
+    mkimage = os.path.join(ubman.config.build_dir, 'tools/mkimage')
+    params = {
+        'kernel1': fit_util.make_kernel(ubman, 'short-kernel1.bin', 'first'),
+        'kernel2': fit_util.make_kernel(ubman, 'short-kernel2.bin', 'second'),
+    }
+    its = fit_util.make_its(ubman, BASE_ITS, params, 'short.its')
+    itb = fit_util.make_fname(ubman, 'short.itb')
+
+    # An empty property must be skipped like a missing one, so that the
+    # hashing stage reports the image, rather than read from the bytes
+    # that follow it, which would import a few bytes or the wrong data
+    for prop in ('data-offset', 'data-size'):
+        result = subprocess.run([mkimage, '-E', '-f', its, itb],
+                                capture_output=True, text=True)
+        assert result.returncode == 0, result.stderr
+        fdtput_keep_data(itb, '/images/kernel-2', prop)
+        result = subprocess.run([mkimage, '-F', itb],
+                                capture_output=True, text=True)
+        assert result.returncode != 0
+        assert "Can't get image data/size" in result.stderr
Signature · 1 line
2.43.0
#11 lore raw

Re: [PATCH v1 5/5] test: py: cover invalid external data properties in fit_import_data()

Hi Aristo,

Quoted 9 lines · Aristo Chen

test: py: cover invalid external data properties in fit_import_data()

Build an external-data FIT, then point one image's data-offset far past the end of the file and, separately, make its data-size run a few bytes past the end, re-processing the result with mkimage -F each time. Both must be rejected with a diagnostic naming that image. Previously the first crashed mkimage and the second silently imported the bytes beyond the end of the file as image data.

Quoted 8 lines

Also check that a FIT whose images are all empty, which mkimage -E -p writes with data-position past the end of the file, still re-processes, since an empty region has nothing to read.

Finally, now that the import reads the properties through the FIT accessors, check that an empty data-offset or data-size is skipped like a missing property, so that the hashing stage reports the image instead of the import reading it from the bytes that follow it.

I don't think this is quite right. Before patch 4 the import used fdtdec_get_int(), which already returns the default for a property shorter than an int (see the 'len >= sizeof(int)' check in lib/fdtdec_common.c). So the import never read an empty property, and patch 4's commit message says as much ('as it already did for a shorter one'). What this test actually guards is patch 2. Once the import skips the image, the hashing stage in tools/image-host.c calls fit_image_get_data(), which without patch 2 would read the following FDT tag as the offset or size and carry on. Please can you reword this paragraph to say so?

test/py/tests/test_fit_import_data.py def test_fit_import_data_missing_offset(ubman): · line 121

Quoted 12 lines

test/py/tests/test_fit_import_data.py | 91 ++++++++++++++++++++++++++++++++++-

 1 file changed, 90 insertions(+), 1 deletion(-)
test/py/tests/test_fit_import_data.py +4 -0
@@ -113,3 +118,87 @@ def test_fit_import_data_missing_offset(ubman):
+    # An empty property must be skipped like a missing one, so that the
+    # hashing stage reports the image, rather than read from the bytes
+    # that follow it, which would import a few bytes or the wrong data
+    for prop in ('data-offset', 'data-size'):

Same here: 'import a few bytes' was never possible for an empty property.

The case that patch 4 does change in fit_import_data() is a property longer than one cell. fdtdec_get_int() accepts it and uses the first cell, but the accessors now reject it. Please can you add a two-cell data-offset and data-size (e.g. fdtput -t i ... 0 0) so that the import change itself is covered? The test name and docstring could then be widened from 'shorter than one cell' to 'not exactly one cell'.

Regards,
Simon

#12 lore raw

Re: [PATCH v1 5/5] test: py: cover invalid external data properties in fit_import_data()

Hi Simon,

Quoted 22 lines · Simon Glass

Hi Aristo,

Quoted 9 lines · Aristo Chen

test: py: cover invalid external data properties in fit_import_data()

Build an external-data FIT, then point one image's data-offset far past the end of the file and, separately, make its data-size run a few bytes past the end, re-processing the result with mkimage -F each time. Both must be rejected with a diagnostic naming that image. Previously the first crashed mkimage and the second silently imported the bytes beyond the end of the file as image data.

Quoted 8 lines

Also check that a FIT whose images are all empty, which mkimage -E -p writes with data-position past the end of the file, still re-processes, since an empty region has nothing to read.

Finally, now that the import reads the properties through the FIT accessors, check that an empty data-offset or data-size is skipped like a missing property, so that the hashing stage reports the image instead of the import reading it from the bytes that follow it.

Quoted 10 lines

I don't think this is quite right. Before patch 4 the import used fdtdec_get_int(), which already returns the default for a property shorter than an int (see the 'len >= sizeof(int)' check in lib/fdtdec_common.c). So the import never read an empty property, and patch 4's commit message says as much ('as it already did for a shorter one'). What this test actually guards is patch 2. Once the import skips the image, the hashing stage in tools/image-host.c calls fit_image_get_data(), which without patch 2 would read the following FDT tag as the offset or size and carry on. Please can you reword this paragraph to say so?

Agreed that the import never read an empty property before patch 4. The empty cases only test patch 2 together with patch 4, though: they also pass before the series and with patch 2 alone, and fail only with patch 4 but not patch 2, where the import takes the next FDT tag as the value (an empty data-size imports 3 bytes) and mkimage succeeds. I checked all three with mkimage built at each point.

The skipped image is not reported by the hashing stage either, and my commit message was wrong there too. fit_cipher_data() runs before the hashing stage and calls fit_image_cipher_data() for every image, which fetches the embedded data with fit_image_get_emb_data() before it looks for a cipher node. That is where mkimage stops, with
"Can't get image data/size". Neither stage calls fit_image_get_data() or reads data-offset or data-size.

I will reword the paragraph for v2.

Quoted 7 lines
Quoted 6 lines

test/py/tests/test_fit_import_data.py | 91 ++++++++++++++++++++++++++++++++++-

 1 file changed, 90 insertions(+), 1 deletion(-)
Quoted 8 lines

test/py/tests/test_fit_import_data.py def test_fit_import_data_missing_offset(ubman): · line 121

Quoted 6 lines
test/py/tests/test_fit_import_data.py +4 -0
@@ -113,3 +118,87 @@ def test_fit_import_data_missing_offset(ubman):
+    # An empty property must be skipped like a missing one, so that the
+    # hashing stage reports the image, rather than read from the bytes
+    # that follow it, which would import a few bytes or the wrong data
+    for prop in ('data-offset', 'data-size'):

Same here: 'import a few bytes' was never possible for an empty property.

Right, only patch 4 without patch 2 does that, and no commit in the series has that combination. I will reword the comment as well.

Quoted 8 lines

The case that patch 4 does change in fit_import_data() is a property longer than one cell. fdtdec_get_int() accepts it and uses the first cell, but the accessors now reject it. Please can you add a two-cell data-offset and data-size (e.g. fdtput -t i ... 0 0) so that the import change itself is covered? The test name and docstring could then be widened from 'shorter than one cell' to 'not exactly one cell'.

Good idea. Before this series, data-offset = <0 0> imports the first kernel's data into the second one and data-size = <0 0> leaves the second one empty, both without an error. I will add both cases for v2

Quoted 3 lines

Regards,
Simon

Thanks for the review.

Best regards,
Aristo

#13 lore raw

v2 cover tools: mkimage: bound external data reads in fit_import_data()

In reply to Aristo Chen

fit_import_data() reads each image's external data at the offset and size the FIT declares, without checking them against the file. An offset past the end of the file makes mkimage -F segfault, and a size running past it silently imports whatever memory follows. U-Boot proper and SPL already bound these properties since the series linked below; this series adds the same check to mkimage.

Patch 2 makes the data-offset, data-position and data-size accessors reject a property that is not exactly one cell, as was already done for data-size-unciphered. This also affects U-Boot proper and SPL, and adds 60 bytes to the pine64_plus SPL. Patch 4 switches fit_import_data() to these accessors and adds the bounds check. Patch 1 keeps an existing test meaningful once the check is in place, and patches 3 and 5 add the new tests.

Link to v1:
https://lore.kernel.org/r/[email protected]

Changes in v2:
- Patch 5: also cover a data-offset and data-size of two cells, which the import used to take from their first cell, rename the test to test_fit_import_data_prop_len and reword its comment and the commit message accordingly (Simon)
- Patch 5: no longer claim that the hashing stage reports a skipped image (mkimage stops earlier, in the cipher pass), also in the comment of the existing test_fit_import_data_missing_offset()
- Collected Simon's Reviewed-by on patches 1-4, which are unchanged
- Rebased on current main

The shared helper Simon suggested for the single-cell accessors will follow as a separate patch.

Aristo Chen (5):
test: py: keep the external payload when editing a FIT with fdtput
image-fit: check the length of the external data properties
test: boot: check the length of the external data properties
tools: mkimage: bound external data reads in fit_import_data()
test: py: cover invalid external data properties in fit_import_data()

 boot/image-fit.c                      |  21 ++++-
 test/boot/image.c                     |  44 +++++++++
 test/py/tests/test_fit_import_data.py | 126 +++++++++++++++++++++++++-
 tools/fit_image.c                     |  41 ++++++---
 4 files changed, 213 insertions(+), 19 deletions(-)
Signature · 1 line
2.43.0
#14 lore raw

PATCH v2 1/5 test: py: keep the external payload when editing a FIT with fdtput

test_fit_import_data_missing_offset() builds an external-data FIT and removes one image's data-offset with fdtput. fdtput rewrites only the device tree, so the external payload behind it is dropped and the file shrinks to the bare FIT. The test still passed, but only because fit_import_data() reads the remaining image's data from beyond the end of the truncated file, which on Linux lands in the zero-filled rest of the mapped page rather than crashing. A bounds check on those reads, added next, rejects that image first and the test would stop exercising the case it was written for.

Add a helper that saves the payload before running fdtput and appends it again afterwards at the 4-byte alignment fit_import_data() expects, and use it in the test so that the edited FIT stays complete.

---
v2: no code changes, collected Reviewed-by

 test/py/tests/test_fit_import_data.py | 30 +++++++++++++++++++++++++--
 1 file changed, 28 insertions(+), 2 deletions(-)
test/py/tests/test_fit_import_data.py +28 -2
index efbbad14262..95f7114243e 100644
@@ -14,6 +14,7 @@ stages instead.
 """
 
 import os
+import struct
 import subprocess
 
 import pytest
@@ -59,6 +60,32 @@ BASE_ITS = '''
 '''
 
 
+def fdtput_keep_data(itb, *args, opts=()):
+    """Run fdtput on a FIT while keeping its external data
+
+    fdtput rewrites only the device tree and drops any external data that
+    follows it, so save that payload first and append it again afterwards
+    at the 4-byte alignment fit_import_data() expects.
+
+    Args:
+        itb (str): Filename of the FIT to edit
+        args (list of str): Node, property and values to pass to fdtput
+        opts (list of str): Options to pass before the filename
+    """
+    with open(itb, 'rb') as inf:
+        blob = inf.read()
+    totalsize = struct.unpack('>I', blob[4:8])[0]
+    payload = blob[(totalsize + 3) & ~3:]
+
+    subprocess.run(['fdtput'] + list(opts) + [itb] + list(args), check=True)
+
+    with open(itb, 'rb') as inf:
+        fdt = inf.read()
+    totalsize = struct.unpack('>I', fdt[4:8])[0]
+    with open(itb, 'wb') as outf:
+        outf.write(fdt.ljust((totalsize + 3) & ~3, b'\0') + payload)
+
+
 @pytest.mark.boardspec('sandbox')
 @pytest.mark.requiredtool('dtc')
 @pytest.mark.requiredtool('fdtput')
@@ -77,8 +104,7 @@ def test_fit_import_data_missing_offset(ubman):
     assert result.returncode == 0, result.stderr
 
     # Remove the offset so that only data-size is left on kernel-2
-    subprocess.run(['fdtput', '-d', itb, '/images/kernel-2', 'data-offset'],
-                   check=True)
+    fdtput_keep_data(itb, '/images/kernel-2', 'data-offset', opts=['-d'])
 
     # Re-processing must skip the malformed image in the import, so that
     # the hashing stage reports it; previously the stale pointer made the
Signature · 1 line
2.43.0
#15 lore raw

PATCH v2 2/5 image-fit: check the length of the external data properties

In reply to Aristo Chen

fit_image_get_data_offset(), fit_image_get_data_position() and fit_image_get_data_size() pass NULL as fdt_getprop()'s length argument, so they accept a property of any size and then dereference the first four bytes of it. A property shorter than that is read past its end, and the bytes that follow it in the FIT are returned to the caller. An empty data-size, for example, is read as the structure tag that follows it, a small number such as 2 or 3, and selects a few bytes of the external data instead of failing.

Ask for the length and require it to be exactly one fdt32_t, as commit c2b8eefd4e10 ("image-fit: check the length of the data-size-unciphered property") does for data-size-unciphered. Every caller already checks the return value and handles a failure like a missing property.

Fixes db1b79b886f0 ("splash: add support for loading splash from a FIT image")
Fixes a1be94b65410 ("SPL: Add FIT data-position property support")

---
v2: no code changes, collected Reviewed-by

 boot/image-fit.c | 21 ++++++++++++++++++---
 1 file changed, 18 insertions(+), 3 deletions(-)
boot/image-fit.c +18 -3
index 6ab6c6c7da9..fd625fe9a98 100644
@@ -963,15 +963,20 @@ int fit_image_get_emb_data(const void *fit, int noffset, const void **data,
  * returns:
  *     0, on success
  *     -ENOENT if the property could not be found
+ *     -EINVAL if the property is not exactly one fdt32_t long
  */
 int fit_image_get_data_offset(const void *fit, int noffset, u32 *data_offset)
 {
 	const fdt32_t *val;
+	int len;
 
-	val = fdt_getprop(fit, noffset, FIT_DATA_OFFSET_PROP, NULL);
+	val = fdt_getprop(fit, noffset, FIT_DATA_OFFSET_PROP, &len);
 	if (!val)
 		return -ENOENT;
 
+	if (len != sizeof(*val))
+		return -EINVAL;
+
 	*data_offset = fdt32_to_cpu(*val);
 
 	return 0;
@@ -987,16 +992,21 @@ int fit_image_get_data_offset(const void *fit, int noffset, u32 *data_offset)
  * returns:
  *     0, on success
  *     -ENOENT if the property could not be found
+ *     -EINVAL if the property is not exactly one fdt32_t long
  */
 int fit_image_get_data_position(const void *fit, int noffset,
 				u32 *data_position)
 {
 	const fdt32_t *val;
+	int len;
 
-	val = fdt_getprop(fit, noffset, FIT_DATA_POSITION_PROP, NULL);
+	val = fdt_getprop(fit, noffset, FIT_DATA_POSITION_PROP, &len);
 	if (!val)
 		return -ENOENT;
 
+	if (len != sizeof(*val))
+		return -EINVAL;
+
 	*data_position = fdt32_to_cpu(*val);
 
 	return 0;
@@ -1012,15 +1022,20 @@ int fit_image_get_data_position(const void *fit, int noffset,
  * returns:
  *     0, on success
  *     -ENOENT if the property could not be found
+ *     -EINVAL if the property is not exactly one fdt32_t long
  */
 int fit_image_get_data_size(const void *fit, int noffset, u32 *data_size)
 {
 	const fdt32_t *val;
+	int len;
 
-	val = fdt_getprop(fit, noffset, FIT_DATA_SIZE_PROP, NULL);
+	val = fdt_getprop(fit, noffset, FIT_DATA_SIZE_PROP, &len);
 	if (!val)
 		return -ENOENT;
 
+	if (len != sizeof(*val))
+		return -EINVAL;
+
 	*data_size = fdt32_to_cpu(*val);
 
 	return 0;
Signature · 1 line
2.43.0
#16 lore raw

PATCH v2 3/5 test: boot: check the length of the external data properties

In reply to Aristo Chen

Build a minimal FIT with libfdt and check that fit_image_get_data_offset(), fit_image_get_data_position() and fit_image_get_data_size() return -EINVAL for an empty property and for one of two cells instead of reading them, while a single cell is still read and a missing property still gives -ENOENT.

---
v2: no code changes, collected Reviewed-by

 test/boot/image.c | 44 ++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 44 insertions(+)
test/boot/image.c +44 -0
index 2c6d9dcbc22..235053afede 100644
@@ -6,6 +6,7 @@
  * Written by Simon Glass <[email protected]>
  */
 
+#include <errno.h>
 #include <image.h>
 #include <test/ut.h>
 #include <linux/libfdt.h>
@@ -78,6 +79,49 @@ static int test_fit_conf_find_compat(struct unit_test_state *uts)
 }
 BOOTSTD_TEST(test_fit_conf_find_compat, 0);
 
+/* Test that external data properties must be exactly one cell long */
+static int test_fit_image_ext_data_len(struct unit_test_state *uts)
+{
+	static const struct {
+		const char *name;
+		int (*get)(const void *fit, int noffset, u32 *val);
+	} props[] = {
+		{ FIT_DATA_OFFSET_PROP, fit_image_get_data_offset },
+		{ FIT_DATA_POSITION_PROP, fit_image_get_data_position },
+		{ FIT_DATA_SIZE_PROP, fit_image_get_data_size },
+	};
+	fdt32_t cells[] = { cpu_to_fdt32(0x100), cpu_to_fdt32(0x200) };
+	int images, node, i;
+	char fit[512];
+	u32 val;
+
+	ut_assertok(fdt_create_empty_tree(fit, sizeof(fit)));
+	images = fdt_add_subnode(fit, 0, "images");
+	ut_assert(images >= 0);
+	node = fdt_add_subnode(fit, images, "kernel");
+	ut_assert(node >= 0);
+
+	for (i = 0; i < ARRAY_SIZE(props); i++) {
+		ut_asserteq(-ENOENT, props[i].get(fit, node, &val));
+
+		/* an empty or a two-cell property must not be read */
+		ut_assertok(fdt_setprop_empty(fit, node, props[i].name));
+		ut_asserteq(-EINVAL, props[i].get(fit, node, &val));
+		ut_assertok(fdt_setprop(fit, node, props[i].name, cells,
+					sizeof(cells)));
+		ut_asserteq(-EINVAL, props[i].get(fit, node, &val));
+
+		/* a single cell is read */
+		ut_assertok(fdt_setprop(fit, node, props[i].name, cells,
+					sizeof(cells[0])));
+		ut_assertok(props[i].get(fit, node, &val));
+		ut_asserteq(0x100, val);
+	}
+
+	return 0;
+}
+BOOTSTD_TEST(test_fit_image_ext_data_len, 0);
+
 /* Test of image phase */
 static int test_image_phase(struct unit_test_state *uts)
 {
Signature · 1 line
2.43.0
#17 lore raw

PATCH v2 4/5 tools: mkimage: bound external data reads in fit_import_data()

In reply to Aristo Chen

fit_import_data() reads each image's external data from the mapped FIT file at the offset and size the FIT itself declares, without checking that the region lies inside the file. A data-offset or data-position pointing past the end of the file, or a size reaching beyond it, makes mkimage read outside the mapping, crashing on re-process or silently importing unrelated memory as image data. An authored .its that declares external data properties hits the same path, since dtc produces no payload beyond the device tree.

Read the properties through fit_image_get_data_position(), fit_image_get_data_offset() and fit_image_get_data_size(), which return u32 since commit c4d81d062790 ("image-fit: Use unsigned types for external data properties"), so a value of 0xffffffff is no longer mistaken for a missing property. They fail for a property that is not exactly one cell, and the import then skips the image as if the property were missing, as it already did for a shorter one. Compute the file offset in 64 bits and require the whole region to lie within the mapped file before importing it, with an error naming the image and the offending values. An empty region reads nothing, so it is not checked:
mkimage -E -p places one past the end of the file when every image is empty, and such a FIT must still re-process.

---
v2: no code changes, collected Reviewed-by

 tools/fit_image.c | 41 +++++++++++++++++++++++++++++------------
 1 file changed, 29 insertions(+), 12 deletions(-)
tools/fit_image.c +29 -12
index b648e3e2514..f0f30e06bd9 100644
@@ -1033,9 +1033,9 @@ static int fit_import_data(struct image_tool_params *params, const char *fname)
 	     node >= 0;
 	     node = fdt_next_subnode(fdt, node)) {
 		const char *ext_data_prop = NULL;
-		void *data = NULL;
-		int buf_ptr;
-		int len;
+		uint64_t offset = 0;
+		u32 val;
+		u32 len;
 
 		/*
 		 * A source file must not combine image-data with external
@@ -1059,22 +1059,39 @@ static int fit_import_data(struct image_tool_params *params, const char *fname)
 		 * FIT_DATA_OFFSET_PROP and FIT_DATA_POSITION_PROP are never both present,
 		 *  but if they are, prefer FIT_DATA_OFFSET_PROP as it was there first
 		 */
-		buf_ptr = fdtdec_get_int(fdt, node, FIT_DATA_POSITION_PROP, -1);
-		if (buf_ptr != -1) {
+		if (!fit_image_get_data_position(fdt, node, &val)) {
 			ext_data_prop = FIT_DATA_POSITION_PROP;
-			data = old_fdt + buf_ptr;
+			offset = val;
 		}
-		buf_ptr = fdtdec_get_int(fdt, node, FIT_DATA_OFFSET_PROP, -1);
-		if (buf_ptr != -1) {
+		if (!fit_image_get_data_offset(fdt, node, &val)) {
 			ext_data_prop = FIT_DATA_OFFSET_PROP;
-			data = old_fdt + data_base + buf_ptr;
+			offset = data_base + (uint64_t)val;
 		}
-		len = fdtdec_get_int(fdt, node, FIT_DATA_SIZE_PROP, -1);
-		if (!data || len == -1)
+		if (!ext_data_prop || fit_image_get_data_size(fdt, node, &len))
 			continue;
+
+		/*
+		 * The offset and size come from the FIT itself, so make
+		 * sure the region lies within the mapped file before
+		 * reading it. An empty region reads nothing and may lie
+		 * past the end, as mkimage -E -p places it there when every
+		 * image is empty.
+		 */
+		if (len && (offset > (uint64_t)sbuf.st_size ||
+			    len > sbuf.st_size - offset)) {
+			fprintf(stderr,
+				"Error: image '%s': external data at file offset 0x%llx size 0x%x is outside the FIT file (size 0x%llx)\n",
+				fdt_get_name(fdt, node, NULL),
+				(unsigned long long)offset, len,
+				(unsigned long long)sbuf.st_size);
+			ret = -EINVAL;
+			goto err_munmap;
+		}
+
 		debug("Importing data size %x\n", len);
 
-		ret = fdt_setprop(fdt, node, FIT_DATA_PROP, data, len);
+		ret = fdt_setprop(fdt, node, FIT_DATA_PROP, old_fdt + offset,
+				  len);
 		if (ret) {
 			debug("%s: Failed to write property: %s\n", __func__,
 			      fdt_strerror(ret));
Signature · 1 line
2.43.0
#18 lore raw

PATCH v2 5/5 test: py: cover invalid external data properties in fit_import_data()

In reply to Aristo Chen

Build an external-data FIT, then point one image's data-offset far past the end of the file and, separately, make its data-size run a few bytes past the end, re-processing the result with mkimage -F each time. Both must be rejected with a diagnostic naming that image. Previously the first crashed mkimage and the second silently imported the bytes beyond the end of the file as image data.

Also check that a FIT whose images are all empty, which mkimage -E -p writes with data-position past the end of the file, still re-processes, since an empty region has nothing to read.

Finally, check that a data-offset or data-size that is not exactly one cell is skipped like a missing property, so that mkimage finds no data for the image and fails. fdtdec_get_int() already ignored an empty property, so that case covers the length check the import now relies on in the accessors. A property of two cells used to be imported from its first cell, so that <0 0> made the image use another image's data or left it empty.

While at it, correct the comment in test_fit_import_data_missing_offset(), which said that the hashing stage reports the skipped image. mkimage stops before that stage, in the cipher pass, which runs first and fetches the data of every image.

---
v2: also cover a data-offset and data-size of two cells, rename the test to test_fit_import_data_prop_len and reword its comment and the last paragraph of the commit message, as suggested by Simon. Neither names the hashing stage any more, since mkimage stops in the cipher pass before reaching it, and the comment of the existing test_fit_import_data_missing_offset() is corrected too.

 test/py/tests/test_fit_import_data.py | 96 ++++++++++++++++++++++++++-
 1 file changed, 94 insertions(+), 2 deletions(-)
test/py/tests/test_fit_import_data.py +94 -2
index 95f7114243e..7ce59291953 100644
@@ -3,7 +3,7 @@
 #
 # Test mkimage import of external data in fit_import_data()
 
-"""Regression test for stale per-image state in fit_import_data().
+"""Regression tests for fit_import_data().
 
 The import loop used to keep the data pointer and external property name
 of the previous image, so an image node carrying data-size but neither
@@ -11,6 +11,11 @@ data-offset nor data-position imported the previous image's data and
 then made mkimage abort without printing any diagnostic. Such a node
 must be skipped by the import and reported by the later processing
 stages instead.
+
+The import also read each image's external data at the offset and size
+the FIT declares without checking them against the file, so a region
+reaching past the end of the file crashed mkimage or imported unrelated
+memory as image data. Such a region must be rejected before it is read.
 """
 
 import os
@@ -107,9 +112,96 @@ def test_fit_import_data_missing_offset(ubman):
     fdtput_keep_data(itb, '/images/kernel-2', 'data-offset', opts=['-d'])
 
     # Re-processing must skip the malformed image in the import, so that
-    # the hashing stage reports it; previously the stale pointer made the
+    # a later stage reports it; previously the stale pointer made the
     # import write kernel-1's data into kernel-2 and abort silently
     result = subprocess.run([mkimage, '-F', itb],
                             capture_output=True, text=True)
     assert result.returncode != 0
     assert "Can't get image data/size" in result.stderr
+
+
[email protected]('sandbox')
[email protected]('dtc')
[email protected]('fdtput')
+def test_fit_import_data_out_of_range(ubman):
+    """External data outside the file must be rejected, not read"""
+    mkimage = os.path.join(ubman.config.build_dir, 'tools/mkimage')
+    params = {
+        'kernel1': fit_util.make_kernel(ubman, 'oob-kernel1.bin', 'first'),
+        'kernel2': fit_util.make_kernel(ubman, 'oob-kernel2.bin', 'second'),
+    }
+    its = fit_util.make_its(ubman, BASE_ITS, params, 'oob.its')
+    itb = fit_util.make_fname(ubman, 'oob.itb')
+
+    result = subprocess.run([mkimage, '-E', '-f', its, itb],
+                            capture_output=True, text=True)
+    assert result.returncode == 0, result.stderr
+
+    # Point kernel-2's data far past the end of the file
+    fdtput_keep_data(itb, '/images/kernel-2', 'data-offset', '0x40000000',
+                     opts=['-t', 'i'])
+    result = subprocess.run([mkimage, '-F', itb],
+                            capture_output=True, text=True)
+    assert result.returncode != 0
+    assert "image 'kernel-2': external data" in result.stderr
+    assert 'outside the FIT file' in result.stderr
+
+    # A size running just past the end of the file must be rejected too.
+    # kernel-2's data comes last, padded to 4 bytes, so 4 bytes more than
+    # its real size always reach past the end.
+    result = subprocess.run([mkimage, '-E', '-f', its, itb],
+                            capture_output=True, text=True)
+    assert result.returncode == 0, result.stderr
+    size = os.path.getsize(params['kernel2']) + 4
+    fdtput_keep_data(itb, '/images/kernel-2', 'data-size', f'{size:#x}',
+                     opts=['-t', 'i'])
+    result = subprocess.run([mkimage, '-F', itb],
+                            capture_output=True, text=True)
+    assert result.returncode != 0
+    assert "image 'kernel-2': external data" in result.stderr
+
+    # An empty region has nothing to read, so it is accepted even past the
+    # end of the file, which is where mkimage -E -p places it when every
+    # image is empty
+    for name in ('kernel1', 'kernel2'):
+        params[name] = fit_util.make_fname(ubman, f'oob-empty-{name}.bin')
+        with open(params[name], 'wb'):
+            pass
+    its = fit_util.make_its(ubman, BASE_ITS, params, 'oob-empty.its')
+    result = subprocess.run([mkimage, '-E', '-p', '0x1000', '-f', its, itb],
+                            capture_output=True, text=True)
+    assert result.returncode == 0, result.stderr
+    assert os.path.getsize(itb) < 0x1000
+    result = subprocess.run([mkimage, '-F', itb],
+                            capture_output=True, text=True)
+    assert result.returncode == 0, result.stderr
+
+
[email protected]('sandbox')
[email protected]('dtc')
[email protected]('fdtput')
+def test_fit_import_data_prop_len(ubman):
+    """An external data property that is not exactly one cell is not read"""
+    mkimage = os.path.join(ubman.config.build_dir, 'tools/mkimage')
+    params = {
+        'kernel1': fit_util.make_kernel(ubman, 'len-kernel1.bin', 'first'),
+        'kernel2': fit_util.make_kernel(ubman, 'len-kernel2.bin', 'second'),
+    }
+    its = fit_util.make_its(ubman, BASE_ITS, params, 'len.its')
+    itb = fit_util.make_fname(ubman, 'len.itb')
+
+    # A property that is not exactly one cell must be skipped like a
+    # missing one, so that mkimage finds no data for the image and fails.
+    # An empty one must not be read from the bytes that follow it, and one
+    # of two cells must not be taken from its first cell.
+    for prop in ('data-offset', 'data-size'):
+        for cells in ([], ['0', '0']):
+            result = subprocess.run([mkimage, '-E', '-f', its, itb],
+                                    capture_output=True, text=True)
+            assert result.returncode == 0, result.stderr
+            fdtput_keep_data(itb, '/images/kernel-2', prop, *cells,
+                             opts=['-t', 'i'])
+            result = subprocess.run([mkimage, '-F', itb],
+                                    capture_output=True, text=True)
+            assert result.returncode != 0
+            assert "Can't get image data/size" in result.stderr
Signature · 1 line
2.43.0
Reviewed-by on v2 5/5
#19 lore raw

Re: [PATCH v2 5/5] test: py: cover invalid external data properties in fit_import_data()

Quoted 26 lines · Aristo Chen

test: py: cover invalid external data properties in fit_import_data()

Build an external-data FIT, then point one image's data-offset far past the end of the file and, separately, make its data-size run a few bytes past the end, re-processing the result with mkimage -F each time. Both must be rejected with a diagnostic naming that image. Previously the first crashed mkimage and the second silently imported the bytes beyond the end of the file as image data.

Also check that a FIT whose images are all empty, which mkimage -E -p writes with data-position past the end of the file, still re-processes, since an empty region has nothing to read.

Finally, check that a data-offset or data-size that is not exactly one cell is skipped like a missing property, so that mkimage finds no data for the image and fails. fdtdec_get_int() already ignored an empty property, so that case covers the length check the import now relies on in the accessors. A property of two cells used to be imported from its first cell, so that <0 0> made the image use another image's data or left it empty.

While at it, correct the comment in test_fit_import_data_missing_offset(), which said that the hashing stage reports the skipped image. mkimage stops before that stage, in the cipher pass, which runs first and fetches the data of every image.

Quoted 4 lines
 test/py/tests/test_fit_import_data.py | 96 ++++++++++++++++++++++++++++++++++-
 1 file changed, 94 insertions(+), 2 deletions(-)
#20 lore raw
In reply to Aristo Chen
Quoted 8 lines · Aristo Chen

fit_import_data() reads each image's external data at the offset and size the FIT declares, without checking them against the file. An offset past the end of the file makes mkimage -F segfault, and a size running past it silently imports whatever memory follows. U-Boot proper and SPL already bound these properties since the series linked below; this series adds the same check to mkimage.

[...]

Applied to u-boot/main, thanks!

[1/5] test: py: keep the external payload when editing a FIT with fdtput

      commit: 2db652e41249b6c11c12d251ef6d82ff741ab0d5
[2/5] image-fit: check the length of the external data properties
      commit: 164a2d9c9533404559cdd1527be7174a936313b5
[3/5] test: boot: check the length of the external data properties
      commit: 44c6d8c287bd21f9ddf6c3b2c657ccf380a67db0
[4/5] tools: mkimage: bound external data reads in fit_import_data()
      commit: f8b5bfc60d16cae86dd2fe49deb1bcd146d24f10
[5/5] test: py: cover invalid external data properties in fit_import_data()
      commit: 5da0f00c237d50ab82de59d1c03512131979fc09
Signature · 1 line
Tom