Skip to contentSkip to conversation

fdt: Check return value and len of fdt_get_name() calls

PATCH Superseded Anton Ivanov 3 participants 39 messages May 22 – Jun 13 Device tree

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 fdt: Check return value and len of fdt_get_name() calls

From: Binarly Vulnerability Research <[email protected]>

fdt_get_name() in scripts/dtc/libfdt/fdt_ro.c can return a null pointer. This happens when the fdt_ro_probe_() or fdt_check_node_offset_() check fails, as well as when the '!can_assume(LATEST) && fdt_version(fdt) < 0x10' condition is true and the FDT node name doesn't contain the '/' character:

	const char *fdt_get_name(const void *fdt, int nodeoffset, int *len)
	{
		const struct fdt_node_header *nh = fdt_offset_ptr_(fdt, nodeoffset);
		const char *nameptr;
		int err;

		if (((err = fdt_ro_probe_(fdt)) < 0)
			|| ((err = fdt_check_node_offset_(fdt, nodeoffset)) < 0))
				goto fail;

		nameptr = nh->name;

		if (!can_assume(LATEST) && fdt_version(fdt) < 0x10) {
			/*
			* For old FDT versions, match the naming conventions of V16:
			* give only the leaf name (after all /). The actual tree
			* contents are loosely checked.
			*/
			const char *leaf;
			leaf = strrchr(nameptr, '/');
			if (leaf == NULL) {
				err = -FDT_ERR_BADSTRUCTURE;
				goto fail;
			}
			nameptr = leaf+1;
		}

		if (len)
			*len = strlen(nameptr);

		return nameptr;

	fail:
		if (len)
			*len = err;
		return NULL;
	}

The fdt_get_name() function is used in fdt_find_regions() in boot/fdt_region.c:

	int fdt_find_regions(const void *fdt, char * const inc[], int inc_count,
				char * const exc_prop[], int exc_prop_count,
				struct fdt_region region[], int max_regions,
				char *path, int path_len, int add_string_tab)
	{
		int stack[FDT_MAX_DEPTH] = { 0 };
		char *end;
		int nextoffset = 0;
		uint32_t tag;
		int count = 0;
		int start = -1;
		int depth = -1;
		int want = 0;
		int base = fdt_off_dt_struct(fdt);
		bool expect_end = false;

		end = path;
		*end = '\0';
		do {
			const struct fdt_property *prop;
			const char *name;
			const char *str;
			int include = 0;
			int stop_at = 0;
			int offset;
			int len;

			offset = nextoffset;
			tag = fdt_next_tag(fdt, offset, &nextoffset);
			stop_at = nextoffset;

			/* If we see two root nodes, something is wrong */
			if (expect_end && tag != FDT_END)
				return -FDT_ERR_BADLAYOUT;

			switch (tag) {
			case FDT_PROP:
				include = want >= 2;
				stop_at = offset;
				prop = fdt_get_property_by_offset(fdt, offset, NULL);
				str = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
				if (!str)
					return -FDT_ERR_BADSTRUCTURE;
				if (str_in_list(str, exc_prop, exc_prop_count))
					include = 0;
				break;

			case FDT_NOP:
				include = want >= 2;
				stop_at = offset;
				break;

			case FDT_BEGIN_NODE:
				depth++;
				if (depth == FDT_MAX_DEPTH)
					return -FDT_ERR_BADSTRUCTURE;
				name = fdt_get_name(fdt, offset, &len);

				/* The root node must have an empty name */
				if (!depth && *name)
					return -FDT_ERR_BADLAYOUT;
				if (end - path + 2 + len >= path_len)
					return -FDT_ERR_NOSPACE;
				if (end != path + 1)
					*end++ = '/';
				strcpy(end, name);
				end += len;
				stack[depth] = want;
				if (want == 1)
					stop_at = offset;
				if (str_in_list(path, inc, inc_count))
					want = 2;
				else if (want)
					want--;
				else
					stop_at = offset;
				include = want;
				break;
			...

There is no check that the value returned by fdt_get_name() is not null, which leads to a null pointer dereference (at *name and strcpy(end, name)) and a potential stack overflow of the 'end' buffer. However, if the strcpy call succeeds, the subsequent 'end += len' decreases the 'end' pointer, since 'len' is set to the negative error code returned by fdt_get_name(). As a result, the next iteration of the loop writes data to a stack location before the start of the 'path' buffer, which can be used to overwrite the return address of fdt_find_regions() and achieve code execution in the context of the bootloader. This attack is possible when the page at address 0x0 is mapped, which is common for embedded devices, so the strcpy() call doesn't fail.

The same lack of validation exists in fdt_next_region() in boot/fdt_region.c, fdt_check_full() in scripts/dtc/libfdt/fdt_ro.c, and display_fdt_by_regions() in tools/fdtgrep.c.

Fix: Validate both the returned pointer and the length before use.

---
 boot/fdt_region.c           | 4 ++++
 scripts/dtc/libfdt/fdt_ro.c | 2 ++
 tools/fdtgrep.c             | 2 ++
 3 files changed, 8 insertions(+)
boot/fdt_region.c +4 -0
index 295ea08ac91..95706b872f4 100644
@@ -86,6 +86,8 @@ int fdt_find_regions(const void *fdt, char * const inc[], int inc_count,
 			if (depth == FDT_MAX_DEPTH)
 				return -FDT_ERR_BADSTRUCTURE;
 			name = fdt_get_name(fdt, offset, &len);
+			if (!name || len < 0)
+				return -FDT_ERR_BADSTRUCTURE;
 
 			/* The root node must have an empty name */
 			if (!depth && *name)
@@ -553,6 +555,8 @@ int fdt_next_region(const void *fdt,
 			if (p.depth == FDT_MAX_DEPTH)
 				return -FDT_ERR_BADSTRUCTURE;
 			name = fdt_get_name(fdt, offset, &len);
+			if (!name || len < 0)
+				return -FDT_ERR_BADSTRUCTURE;
 			if (p.end - path + 2 + len >= path_len)
 				return -FDT_ERR_NOSPACE;
 
scripts/dtc/libfdt/fdt_ro.c +2 -0
index 3e7e26b4398..82f90eb46f6 100644
@@ -940,6 +940,8 @@ int fdt_check_full(const void *fdt, size_t bufsize)
 				int len;
 
 				name = fdt_get_name(fdt, offset, &len);
+				if (!name || len < 0)
+					return -FDT_ERR_BADSTRUCTURE;
 				if (*name || len)
 					return -FDT_ERR_BADLAYOUT;
 			}
tools/fdtgrep.c +2 -0
index b4c041070f5..ab8ee939e97 100644
@@ -355,6 +355,8 @@ static int display_fdt_by_regions(struct display_info *disp, const void *blob,
 
 		case FDT_BEGIN_NODE:
 			name = fdt_get_name(blob, offset, &len);
+			if (!name || len < 0)
+				return -FDT_ERR_BADSTRUCTURE;
 			fprintf(f, "%*s%s {", depth++ * shift, "",
 				*name ? name : "/");
 			break;
Signature · 1 line
2.53.0
#1 lore raw

PATCH 1/1 image-fit-sig: Check that the strings region is within bounds

From: Binarly Vulnerability Research <[email protected]>

The fit_config_check_sig() function in boot/image-fit-sig.c builds a list of FDT regions that cover the parts of the FIT that must be hashed for the signature verification. Once the structure regions have been collected, the function adds one extra region for the string table, using the 'hashed-strings' property:

	/* Add the strings */
	strings = fdt_getprop(fit, noffset, "hashed-strings", NULL);
	if (strings) {
		/*
			* The strings region offset must be a static 0x0.
			* This is set in tool/image-host.c
			*/
		fdt_regions[count].offset = fdt_off_dt_strings(fit);
		fdt_regions[count].size = fdt32_to_cpu(strings[1]);
		count++;
	}

	/* Allocate the region list on the stack */
	struct image_region region[count];

	fit_region_make_list(fit, fdt_regions, count, region);
	if (info.crypto->verify(&info, region, count, fit_value,
				fit_value_len)) {
		*err_msgp = "Verification failed";
		return -1;
	}

'strings' is a pointer to the raw bytes of the 'hashed-strings' property in the FIT. No check is performed on strings[1], and it is assigned verbatim as the size of the strings region. The fit_region_make_list() function then copies the size verbatim into the 'region' array:

	for (i = 0; i < count; i++) {
		debug("%10x %10x\n", fdt_regions[i].offset,
				fdt_regions[i].size);
		region[i].data = fit + fdt_regions[i].offset;
		region[i].size = fdt_regions[i].size;
	}

info.crypto->verify for 'sha1,rsa2048' is rsa_verify(), located in lib/rsa/rsa-verify.c, which calls hash_calculate() defined in lib/hash-checksum.c:

	for (i = 0; i < region_count - 1; i++) {
		ret = algo->hash_update(algo, ctx, region[i].data,
					region[i].size, 0);
		if (ret)
			return ret;
	}

hash_update_sha1(), defined in common/hash.c, takes the per-region size as an unsigned int and feeds it directly to sha1_update(). With an attacker-chosen value such as 0xFFFFFFFF, the SHA update reads nearly four gigabytes from fit + fdt_off_dt_strings(fit), walking well past the end of the FIT image and into unmapped memory.

Fix: Validate that the declared size is non-negative and fits within the FIT before adding the strings region to the list. The offset itself is already validated by fdt_check_header().

---
 boot/image-fit-sig.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)
boot/image-fit-sig.c +12 -2
index 433df20281f..bdfb5e3eb7c 100644
@@ -512,8 +512,18 @@ static int fit_config_check_sig(const void *fit, int noffset, int conf_noffset,
 		 * The strings region offset must be a static 0x0.
 		 * This is set in tool/image-host.c
 		 */
-		fdt_regions[count].offset = fdt_off_dt_strings(fit);
-		fdt_regions[count].size = fdt32_to_cpu(strings[1]);
+		int offset = fdt_off_dt_strings(fit);
+		int size = fdt32_to_cpu(strings[1]);
+		/*
+		 * The offset should be already validated by fdt_check_header();
+		 * validate the size here.
+		 */
+		if (size < 0 || size > fdt_totalsize(fit) - offset) {
+			*err_msgp = "Strings region is out of bounds";
+			return -1;
+		}
+		fdt_regions[count].offset = offset;
+		fdt_regions[count].size = size;
 		count++;
 	}
 
Signature · 1 line
2.53.0
#2 lore raw

PATCH v2 1/1 image-fit-sig: Validate hashed-strings region size

From: Binarly Vulnerability Research <[email protected]>

fit_config_check_sig() reads the hashed-strings property and uses its size value without validation when building the region list for signature verification. A crafted FIT image can specify an arbitrary size, causing the hash calculation to read beyond the end of the FIT image.

Validate that the declared strings region fits within the FIT before adding it to the region list.

---
Changes in v2:
- Rewrite commit message to be concise per maintainer feedback

 boot/image-fit-sig.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)
boot/image-fit-sig.c +12 -2
index 433df20281f..bdfb5e3eb7c 100644
@@ -512,8 +512,18 @@ static int fit_config_check_sig(const void *fit, int noffset, int conf_noffset,
 		 * The strings region offset must be a static 0x0.
 		 * This is set in tool/image-host.c
 		 */
-		fdt_regions[count].offset = fdt_off_dt_strings(fit);
-		fdt_regions[count].size = fdt32_to_cpu(strings[1]);
+		int offset = fdt_off_dt_strings(fit);
+		int size = fdt32_to_cpu(strings[1]);
+		/*
+		 * The offset should be already validated by fdt_check_header();
+		 * validate the size here.
+		 */
+		if (size < 0 || size > fdt_totalsize(fit) - offset) {
+			*err_msgp = "Strings region is out of bounds";
+			return -1;
+		}
+		fdt_regions[count].offset = offset;
+		fdt_regions[count].size = size;
 		count++;
 	}
 
Signature · 1 line
2.53.0
#3 lore raw

PATCH v3 1/1 image-fit-sig: Validate hashed-strings region size

fit_config_check_sig() reads the hashed-strings property and uses its size value without validation when building the region list for signature verification. A crafted FIT image can specify an arbitrary size, causing the hash calculation to read beyond the end of the FIT image.

Validate that the declared strings region fits within the FIT before adding it to the region list.

---
Changes in v3:
- Update From and Signed-off-by to personal email

Changes in v2:
- Rewrite commit message to be concise per maintainer feedback

 boot/image-fit-sig.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)
boot/image-fit-sig.c +12 -2
index 433df20281f..bdfb5e3eb7c 100644
@@ -512,8 +512,18 @@ static int fit_config_check_sig(const void *fit, int noffset, int conf_noffset,
 		 * The strings region offset must be a static 0x0.
 		 * This is set in tool/image-host.c
 		 */
-		fdt_regions[count].offset = fdt_off_dt_strings(fit);
-		fdt_regions[count].size = fdt32_to_cpu(strings[1]);
+		int offset = fdt_off_dt_strings(fit);
+		int size = fdt32_to_cpu(strings[1]);
+		/*
+		 * The offset should be already validated by fdt_check_header();
+		 * validate the size here.
+		 */
+		if (size < 0 || size > fdt_totalsize(fit) - offset) {
+			*err_msgp = "Strings region is out of bounds";
+			return -1;
+		}
+		fdt_regions[count].offset = offset;
+		fdt_regions[count].size = size;
 		count++;
 	}
 
Signature · 1 line
2.53.0
#4 lore raw

Re: [PATCH v3] image-fit-sig: Validate hashed-strings region size

Hi Anton,

Quoted 23 lines · Anton Ivanov

image-fit-sig: Validate hashed-strings region size

fit_config_check_sig() reads the hashed-strings property and uses its size value without validation when building the region list for signature verification. A crafted FIT image can specify an arbitrary size, causing the hash calculation to read beyond the end of the FIT image.

Validate that the declared strings region fits within the FIT before adding it to the region list.

boot/image-fit-sig.c | 14 ++++++++++++--

 1 file changed, 12 insertions(+), 2 deletions(-)
boot/image-fit-sig.c +0 -2
@@ -512,8 +512,18 @@ static int fit_config_check_sig(const void *fit, int noffset, int conf_noffset,
               * The strings region offset must be a static 0x0.
               * This is set in tool/image-host.c
               */
-             fdt_regions[count].offset = fdt_off_dt_strings(fit);
-             fdt_regions[count].size = fdt32_to_cpu(strings[1]);

boot/image-fit-sig.c static int fit_config_check_sig(const void *fit, int noffset, int conf_noffset, · line 524

Quoted 10 lines
boot/image-fit-sig.c +10 -0
+             int offset = fdt_off_dt_strings(fit);
+             int size = fdt32_to_cpu(strings[1]);
+             /*
+              * The offset should be already validated by fdt_check_header();
+              * validate the size here.
+              */
+             if (size < 0 || size > fdt_totalsize(fit) - offset) {
+                     *err_msgp = "Strings region is out of bounds";
+                     return -1;
+             }

Thanks for fixing this.

tools/image-host.c writes string_size = fdt_size_dt_strings(fit), so the tighter bound here is fdt_size_dt_strings(fit) rather than fdt_totalsize(fit) - offset. The latter still permits a crafted size that overlaps the structs block while staying within the FIT.

Also, fdt_getprop() is called with a NULL lenp on line 509, so strings[1] is read without first checking that the property is at least 2 * sizeof(fdt32_t) bytes long. A crafted FIT could shorten hashed-strings to make that read go past the property - please can you validate the property length too while you are here.

fdt_off_dt_strings() and fdt32_to_cpu() both return uint32_t, so the locals would be better as uint32_t (and the size < 0 check then goes away). Please move them up with the other locals rather than declaring them mid-block.

Since this is a security fix, please mention in the commit message that the OOB read is reachable during signature verification of an untrusted FIT, and add a test in test/boot/ (or extend an existing one) that feeds a FIT with an oversized hashed-strings size and checks that verification fails cleanly.

Regards,
Simon

#5 lore raw

Re: [PATCH v3] image-fit-sig: Validate hashed-strings region size

Thank you for the feedback – all the comments have now been addressed.

Quoted 3 lines

Since this is a security fix, please mention in the commit message that the OOB read is reachable during signature verification of an untrusted FIT

We did it for all five patches, since they are all security fixes.

Quoted 3 lines

and add a test in test/boot/ (or extend an existing
one) that feeds a FIT with an oversized hashed-strings size and checks that verification fails cleanly

We added the test for this, as well as for the patch with the subject "image-fit: Validate external data offset and size". The other three patches have no additional tests as they are basic sanity checks with no logical validation to exercise.

Thank you,
Anton

Quoted 66 lines · Simon Glass

Hi Anton,

boot/image-fit-sig.c static int fit_config_check_sig(const void *fit,

Quoted 18 lines · Anton Ivanov

image-fit-sig: Validate hashed-strings region size

fit_config_check_sig() reads the hashed-strings property and uses its size value without validation when building the region list for signature verification. A crafted FIT image can specify an arbitrary size, causing the hash calculation to read beyond the end of the FIT image.

Validate that the declared strings region fits within the FIT before adding it to the region list.

boot/image-fit-sig.c | 14 ++++++++++++--

 1 file changed, 12 insertions(+), 2 deletions(-)
boot/image-fit-sig.c +0 -0
@@ -512,8 +512,18 @@ static int fit_config_check_sig(const void *fit,

int noffset, int conf_noffset,

boot/image-fit-sig.c static int fit_config_check_sig(const void *fit, int noffset, int conf_noffset,

Quoted 9 lines
boot/image-fit-sig.c +4 -2
               * The strings region offset must be a static 0x0.
               * This is set in tool/image-host.c
               */
-             fdt_regions[count].offset = fdt_off_dt_strings(fit);
-             fdt_regions[count].size = fdt32_to_cpu(strings[1]);
+             int offset = fdt_off_dt_strings(fit);
+             int size = fdt32_to_cpu(strings[1]);
+             /*
+              * The offset should be already validated by

fdt_check_header();

boot/image-fit-sig.c static int fit_config_check_sig(const void *fit, int noffset, int conf_noffset, · line 524

Quoted 6 lines
boot/image-fit-sig.c +6 -0
+              * validate the size here.
+              */
+             if (size < 0 || size > fdt_totalsize(fit) - offset) {
+                     *err_msgp = "Strings region is out of bounds";
+                     return -1;
+             }

Thanks for fixing this.

tools/image-host.c writes string_size = fdt_size_dt_strings(fit), so the tighter bound here is fdt_size_dt_strings(fit) rather than fdt_totalsize(fit) - offset. The latter still permits a crafted size that overlaps the structs block while staying within the FIT.

Also, fdt_getprop() is called with a NULL lenp on line 509, so strings[1] is read without first checking that the property is at least 2 * sizeof(fdt32_t) bytes long. A crafted FIT could shorten hashed-strings to make that read go past the property - please can you validate the property length too while you are here.

fdt_off_dt_strings() and fdt32_to_cpu() both return uint32_t, so the locals would be better as uint32_t (and the size < 0 check then goes away). Please move them up with the other locals rather than declaring them mid-block.

Since this is a security fix, please mention in the commit message that the OOB read is reachable during signature verification of an untrusted FIT, and add a test in test/boot/ (or extend an existing one) that feeds a FIT with an oversized hashed-strings size and checks that verification fails cleanly.

Regards,
Simon

#6 lore raw

PATCH v4 1/1 image-fit-sig: Validate hashed-strings region size

In reply to Anton Ivanov

fit_config_check_sig() reads the hashed-strings property and uses its size value without validation when building the region list for signature verification. A crafted FIT image can specify an arbitrary size, causing the hash calculation to read beyond the end of the FIT image. The property length is also not checked, so a truncated hashed-strings property causes strings[1] to be read past the end of the property. This may result in the out-of-bounds read during signature verification of an untrusted FIT.

Validate both the property length and that the declared strings region fits within bounds before adding it to the region list.

---
Changes in v4:
- Bound the strings region against fdt_size_dt_strings(fit), which is what tools/image-host.c actually writes
- Validate the hashed-strings property length before reading strings[1]
- Make size as uint32_t to match fdt32_to_cpu() and drop redundant size < 0 check
- Move size variable up with the other locals rather than declaring it mid-block
- Add test cases that feed modified hashed-strings sizes and check that verification fails cleanly
- Clarify vulnerability reachability in the commit message

Changes in v3:
- Update From and Signed-off-by to personal email

Changes in v2:
- Rewrite commit message to be concise per maintainer feedback

 boot/image-fit-sig.c        | 19 +++++++++++++++++--
 test/py/tests/test_vboot.py | 26 ++++++++++++++++++++++++++
 2 files changed, 43 insertions(+), 2 deletions(-)
boot/image-fit-sig.c +17 -2
index 433df20281f..9b5ab754561 100644
@@ -452,6 +452,8 @@ static int fit_config_check_sig(const void *fit, int noffset, int conf_noffset,
 	int max_regions;
 	char path[200];
 	int count;
+	int len;
+	uint32_t size;
 
 	debug("%s: fdt=%p, conf='%s', sig='%s'\n", __func__, key_blob,
 	      fit_get_name(fit, noffset, NULL),
@@ -506,14 +508,27 @@ static int fit_config_check_sig(const void *fit, int noffset, int conf_noffset,
 	}
 
 	/* Add the strings */
-	strings = fdt_getprop(fit, noffset, "hashed-strings", NULL);
+	strings = fdt_getprop(fit, noffset, "hashed-strings", &len);
 	if (strings) {
+		if (len < (int)(2 * sizeof(fdt32_t))) {
+			*err_msgp = "Invalid hashed-strings property";
+			return -1;
+		}
+		size = fdt32_to_cpu(strings[1]);
+		/*
+		 * The offset should be already validated by fdt_check_header();
+		 * validate the size here.
+		 */
+		if (size > fdt_size_dt_strings(fit)) {
+			*err_msgp = "Strings region is out of bounds";
+			return -1;
+		}
 		/*
 		 * The strings region offset must be a static 0x0.
 		 * This is set in tool/image-host.c
 		 */
 		fdt_regions[count].offset = fdt_off_dt_strings(fit);
-		fdt_regions[count].size = fdt32_to_cpu(strings[1]);
+		fdt_regions[count].size = size;
 		count++;
 	}
 
test/py/tests/test_vboot.py +26 -0
index 55518bed07e..8fa8f2d59cf 100644
@@ -415,6 +415,32 @@ def test_vboot(ubman, name, sha_algo, padding, sign_options, required,
             ubman, [fit_check_sign, '-f', fit, '-k', dtb],
             1, 'Failed to verify required signature')
 
+        # Create a new properly signed fit and replace hashed-strings
+        # size property
+        make_fit('sign-configs-%s%s.its' % (sha_algo, padding), ubman, mkimage, dtc_args, datadir, fit)
+        sign_fit(sha_algo, sign_options)
+        utils.run_and_log(ubman, 'fdtput -t x %s %s hashed-strings 0' %
+                          (fit, sig_node))
+        run_bootm(sha_algo, 'Signed config with truncated hashed-strings',
+                  'Invalid hashed-strings property', False)
+        ubman.log.action('%s: Check truncated hashed-strings property' % sha_algo)
+
+        # size_dt_strings is at offset 32 in the FDT header
+        with open(fit, 'rb') as handle:
+            handle.seek(32)
+            size_dt_strings = struct.unpack(">I", handle.read(4))[0]
+        utils.run_and_log(ubman, 'fdtput -t x %s %s hashed-strings 0 %#x' %
+                          (fit, sig_node, size_dt_strings + 1))
+        run_bootm(sha_algo, 'Signed config with overflowed hashed-strings size',
+                  'Strings region is out of bounds', False)
+        ubman.log.action('%s: Check overflowed hashed-strings size' % sha_algo)
+
+        utils.run_and_log(ubman, 'fdtput -t x %s %s hashed-strings 0 %#x' %
+                          (fit, sig_node, size_dt_strings))
+        run_bootm(sha_algo, 'Signed config with in-bounds hashed-strings size',
+                  'Bad Data Hash', False)
+        ubman.log.action('%s: Check in-bounds hashed-strings size' % sha_algo)
+
     def test_required_key(sha_algo, padding, sign_options):
         """Test verified boot with the given hash algorithm.
 
Signature · 1 line
2.53.0
#7 lore raw

Re: [PATCH v4] image-fit-sig: Validate hashed-strings region size

Quoted 9 lines · Anton Ivanov

fit_config_check_sig() reads the hashed-strings property and uses its size value without validation when building the region list for signature verification. A crafted FIT image can specify an arbitrary size, causing the hash calculation to read beyond the end of the FIT image. The property length is also not checked, so a truncated hashed-strings property causes strings[1] to be read past the end of the property. This may result in the out-of-bounds read during signature verification of an untrusted FIT.

Quoted 4 lines

Validate both the property length and that the declared strings region fits within bounds before adding it to the region list.

Applied to u-boot/next, thanks!

Signature · 1 line
Tom
#8 lore raw

PATCH 1/1 fdt_region: Check the return value of fdt_get_property_by_offset() calls

In reply to Anton Ivanov

From: Binarly Vulnerability Research <[email protected]>

The fdt_find_regions() function in boot/fdt_region.c walks the FDT structure block one tag at a time, building the list of regions to feed into the signature hash. When it sees an FDT_PROP tag it reads the property header to retrieve the property name:

	case FDT_PROP:
		include = want >= 2;
		stop_at = offset;
		prop = fdt_get_property_by_offset(fdt, offset, NULL);
		str = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));

fdt_get_property_by_offset() in scripts/dtc/libfdt/fdt_ro.c explicitly returns NULL for any FDT with 'fdt_version < 0x10':

const struct fdt_property *fdt_get_property_by_offset(const void *fdt,

						      int offset,
						      int *lenp)
	{
		/* Prior to version 16, properties may need realignment
		* and this API does not work. fdt_getprop_*() will, however. */

		if (!can_assume(LATEST) && fdt_version(fdt) < 0x10) {
			if (lenp)
				*lenp = -FDT_ERR_BADVERSION;
			return NULL;
		}

		return fdt_get_property_by_offset_(fdt, offset, lenp);
	}

A FIT image with a version less than 0x10 causes 'prop' to be null on the very first FDT_PROP tag the iterator reaches. The next line dereferences prop->nameoff, which leads to a null pointer dereference on platforms where the zero page is not mapped.

The same lack of validation exists in fdt_add_alias_regions() and in fdt_next_region() in boot/fdt_region.c.

Fix: Validate the returned pointer before use.

---
 boot/fdt_region.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
boot/fdt_region.c +10 -0
index 295ea08ac91..0a9d47bb2bd 100644
@@ -69,6 +69,8 @@ int fdt_find_regions(const void *fdt, char * const inc[], int inc_count,
 			include = want >= 2;
 			stop_at = offset;
 			prop = fdt_get_property_by_offset(fdt, offset, NULL);
+			if (!prop)
+				return -FDT_ERR_BADSTRUCTURE;
 			str = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
 			if (!str)
 				return -FDT_ERR_BADSTRUCTURE;
@@ -271,7 +273,11 @@ int fdt_add_alias_regions(const void *fdt, struct fdt_region *region, int count,
 		int target, next;
 
 		prop = fdt_get_property_by_offset(fdt, offset, NULL);
+		if (!prop)
+			return -FDT_ERR_BADSTRUCTURE;
 		name = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
+		if (!name)
+			return -FDT_ERR_BADSTRUCTURE;
 		target = fdt_path_offset(fdt, name);
 		if (!region_list_contains_offset(info, fdt, target))
 			continue;
@@ -520,7 +526,11 @@ int fdt_next_region(const void *fdt,
 		case FDT_PROP:
 			stop_at = offset;
 			prop = fdt_get_property_by_offset(fdt, offset, NULL);
+			if (!prop)
+				return -FDT_ERR_BADSTRUCTURE;
 			str = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
+			if (!str)
+				return -FDT_ERR_BADSTRUCTURE;
 			val = h_include(priv, fdt, last_node, FDT_IS_PROP, str,
 					    strlen(str) + 1);
 			if (val == -1) {
Signature · 1 line
2.53.0
#9 lore raw

PATCH v2 1/1 fdt_region: Check return value of fdt_get_property_by_offset() calls

From: Binarly Vulnerability Research <[email protected]>

fdt_get_property_by_offset() returns NULL for FDT with version less than 0x10. Callers in fdt_find_regions(), fdt_add_alias_regions(), and fdt_next_region() dereference the result without checking, leading to a NULL pointer dereference.

Add NULL checks before accessing the returned property pointer. Also add a missing NULL check for fdt_string() in fdt_add_alias_regions() and fdt_next_region().

---
Changes in v2:
- Rewrite commit message to be concise per maintainer feedback

 boot/fdt_region.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
boot/fdt_region.c +10 -0
index 295ea08ac91..0a9d47bb2bd 100644
@@ -69,6 +69,8 @@ int fdt_find_regions(const void *fdt, char * const inc[], int inc_count,
 			include = want >= 2;
 			stop_at = offset;
 			prop = fdt_get_property_by_offset(fdt, offset, NULL);
+			if (!prop)
+				return -FDT_ERR_BADSTRUCTURE;
 			str = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
 			if (!str)
 				return -FDT_ERR_BADSTRUCTURE;
@@ -271,7 +273,11 @@ int fdt_add_alias_regions(const void *fdt, struct fdt_region *region, int count,
 		int target, next;
 
 		prop = fdt_get_property_by_offset(fdt, offset, NULL);
+		if (!prop)
+			return -FDT_ERR_BADSTRUCTURE;
 		name = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
+		if (!name)
+			return -FDT_ERR_BADSTRUCTURE;
 		target = fdt_path_offset(fdt, name);
 		if (!region_list_contains_offset(info, fdt, target))
 			continue;
@@ -520,7 +526,11 @@ int fdt_next_region(const void *fdt,
 		case FDT_PROP:
 			stop_at = offset;
 			prop = fdt_get_property_by_offset(fdt, offset, NULL);
+			if (!prop)
+				return -FDT_ERR_BADSTRUCTURE;
 			str = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
+			if (!str)
+				return -FDT_ERR_BADSTRUCTURE;
 			val = h_include(priv, fdt, last_node, FDT_IS_PROP, str,
 					    strlen(str) + 1);
 			if (val == -1) {
Signature · 1 line
2.53.0
#10 lore raw

PATCH v3 1/1 fdt_region: Check return value of fdt_get_property_by_offset() calls

fdt_get_property_by_offset() returns NULL for FDT with version less than 0x10. Callers in fdt_find_regions(), fdt_add_alias_regions(), and fdt_next_region() dereference the result without checking, leading to a NULL pointer dereference.

Add NULL checks before accessing the returned property pointer. Also add a missing NULL check for fdt_string() in fdt_add_alias_regions() and fdt_next_region().

---
Changes in v3:
- Update From and Signed-off-by to personal email

Changes in v2:
- Rewrite commit message to be concise per maintainer feedback

 boot/fdt_region.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
boot/fdt_region.c +10 -0
index 295ea08ac91..0a9d47bb2bd 100644
@@ -69,6 +69,8 @@ int fdt_find_regions(const void *fdt, char * const inc[], int inc_count,
 			include = want >= 2;
 			stop_at = offset;
 			prop = fdt_get_property_by_offset(fdt, offset, NULL);
+			if (!prop)
+				return -FDT_ERR_BADSTRUCTURE;
 			str = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
 			if (!str)
 				return -FDT_ERR_BADSTRUCTURE;
@@ -271,7 +273,11 @@ int fdt_add_alias_regions(const void *fdt, struct fdt_region *region, int count,
 		int target, next;
 
 		prop = fdt_get_property_by_offset(fdt, offset, NULL);
+		if (!prop)
+			return -FDT_ERR_BADSTRUCTURE;
 		name = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
+		if (!name)
+			return -FDT_ERR_BADSTRUCTURE;
 		target = fdt_path_offset(fdt, name);
 		if (!region_list_contains_offset(info, fdt, target))
 			continue;
@@ -520,7 +526,11 @@ int fdt_next_region(const void *fdt,
 		case FDT_PROP:
 			stop_at = offset;
 			prop = fdt_get_property_by_offset(fdt, offset, NULL);
+			if (!prop)
+				return -FDT_ERR_BADSTRUCTURE;
 			str = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
+			if (!str)
+				return -FDT_ERR_BADSTRUCTURE;
 			val = h_include(priv, fdt, last_node, FDT_IS_PROP, str,
 					    strlen(str) + 1);
 			if (val == -1) {
Signature · 1 line
2.53.0
Reviewed-by on v3 1/1
#11 lore raw

Re: [PATCH v3] fdt_region: Check return value of fdt_get_property_by_offset() calls

Quoted 7 lines · Anton Ivanov

fdt_region: Check return value of fdt_get_property_by_offset() calls

fdt_get_property_by_offset() returns NULL for FDT with version less than 0x10. Callers in fdt_find_regions(), fdt_add_alias_regions(), and fdt_next_region() dereference the result without checking, leading to a NULL pointer dereference.

Quoted 8 lines

Add NULL checks before accessing the returned property pointer. Also add a missing NULL check for fdt_string() in fdt_add_alias_regions() and fdt_next_region().

boot/fdt_region.c | 10 ++++++++++

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

PATCH v4 1/1 fdt_region: Check return value of fdt_get_property_by_offset() calls

In reply to Anton Ivanov

fdt_get_property_by_offset() returns NULL for FDT with version less than 0x10. fdt_find_regions() dereferences the result without checking, leading to a NULL pointer dereference during signature verification of an untrusted FIT. fdt_add_alias_regions() and fdt_next_region() also lack validation.

Add NULL checks before accessing the returned property pointer. Also add a missing NULL check for fdt_string() in fdt_add_alias_regions() and fdt_next_region().

---
Changes in v4:
- Clarify vulnerability reachability in the commit message

Changes in v3:
- Update From and Signed-off-by to personal email

Changes in v2:
- Rewrite commit message to be concise per maintainer feedback

 boot/fdt_region.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
boot/fdt_region.c +10 -0
index 295ea08ac91..0a9d47bb2bd 100644
@@ -69,6 +69,8 @@ int fdt_find_regions(const void *fdt, char * const inc[], int inc_count,
 			include = want >= 2;
 			stop_at = offset;
 			prop = fdt_get_property_by_offset(fdt, offset, NULL);
+			if (!prop)
+				return -FDT_ERR_BADSTRUCTURE;
 			str = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
 			if (!str)
 				return -FDT_ERR_BADSTRUCTURE;
@@ -271,7 +273,11 @@ int fdt_add_alias_regions(const void *fdt, struct fdt_region *region, int count,
 		int target, next;
 
 		prop = fdt_get_property_by_offset(fdt, offset, NULL);
+		if (!prop)
+			return -FDT_ERR_BADSTRUCTURE;
 		name = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
+		if (!name)
+			return -FDT_ERR_BADSTRUCTURE;
 		target = fdt_path_offset(fdt, name);
 		if (!region_list_contains_offset(info, fdt, target))
 			continue;
@@ -520,7 +526,11 @@ int fdt_next_region(const void *fdt,
 		case FDT_PROP:
 			stop_at = offset;
 			prop = fdt_get_property_by_offset(fdt, offset, NULL);
+			if (!prop)
+				return -FDT_ERR_BADSTRUCTURE;
 			str = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
+			if (!str)
+				return -FDT_ERR_BADSTRUCTURE;
 			val = h_include(priv, fdt, last_node, FDT_IS_PROP, str,
 					    strlen(str) + 1);
 			if (val == -1) {
Signature · 1 line
2.53.0
#13 lore raw

Re: [PATCH v4] fdt_region: Check return value of fdt_get_property_by_offset() calls

Quoted 11 lines · Anton Ivanov

fdt_get_property_by_offset() returns NULL for FDT with version less than 0x10. fdt_find_regions() dereferences the result without checking, leading to a NULL pointer dereference during signature verification of an untrusted FIT. fdt_add_alias_regions() and fdt_next_region() also lack validation.

Add NULL checks before accessing the returned property pointer. Also add a missing NULL check for fdt_string() in fdt_add_alias_regions() and fdt_next_region().

Applied to u-boot/next, thanks!

Signature · 1 line
Tom
#14 lore raw

PATCH 1/1 image-fit: Check that external data is in bounds

In reply to Anton Ivanov

From: Binarly Vulnerability Research <[email protected]>

The fit_image_get_data() function in boot/image-fit.c resolves the address and size of an image's payload. For "external" data, i.e. images that declare data-position or data-offset rather than carrying an inline 'data' property, it takes both the offset and the size straight from FIT properties and returns them to the caller:

	int fit_image_get_data(const void *fit, int noffset, const void **data,
				size_t *size)
	{
		bool external_data = false;
		int offset;
		int len;
		int ret;

		if (!fit_image_get_data_position(fit, noffset, &offset)) {
			external_data = true;
		} else if (!fit_image_get_data_offset(fit, noffset, &offset)) {
			external_data = true;
			/*
			* For FIT with external data, figure out where
			* the external images start. This is the base
			* for the data-offset properties in each image.
			*/
			offset += ((fdt_totalsize(fit) + 3) & ~3);
		}

		if (external_data) {
			debug("External Data\n");
			ret = fit_image_get_data_size(fit, noffset, &len);
			if (!ret) {
				*data = fit + offset;
				*size = len;
			}
		} else {
			ret = fit_image_get_emb_data(fit, noffset, data, size);
		}

		return ret;
	}

All three properties (data-position, data-offset, and data-size) are attacker-controlled, and there is no validation of the size against the FIT image bounds. Moreover, all three properties may take negative values since they are read as signed int (although during the hash calculation they are later cast to unsigned int).

The obtained 'data' and 'size' are then used to calculate the hash of the image for signature verification. 'info->crypto->verify' for 'sha1,rsa2048' is rsa_verify(), located in lib/rsa/rsa-verify.c, which calls 'info->checksum->calculate' (set to hash_calculate() for SHA-based algorithms in boot/image-sig.c), defined in lib/hash-checksum.c:

	for (i = 0; i < region_count - 1; i++) {
		ret = algo->hash_update(algo, ctx, region[i].data,
					region[i].size, 0);
		if (ret)
			return ret;
	}

hash_update_sha1(), defined in common/hash.c, takes the per-region address and size as an unsigned int and feeds it directly to sha1_update(). If an attacker manipulates data-position or data-offset, it is possible to trigger an out-of-bounds read by pointing the region address beyond the mapped memory. Similarly, with data-size manipulation, an out-of-bounds read can be triggered by specifying a large region size that causes the hash calculation to read beyond the intended memory region.

Fix: Validate the external data offset and size. Validate that the external data is within the bounds of the FIT.

---
 boot/image-fit.c | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)
boot/image-fit.c +16 -0
index b0fcaf6e17f..4d0e8ffc79f 100644
@@ -1084,8 +1084,24 @@ int fit_image_get_data(const void *fit, int noffset, const void **data,
 
 	if (external_data) {
 		debug("External Data\n");
+		if (offset < 0 || offset > UINTPTR_MAX - (uintptr_t)fit) {
+			printf("Invalid external data offset: %d\n", offset);
+			return -1;
+		}
+
 		ret = fit_image_get_data_size(fit, noffset, &len);
 		if (!ret) {
+			if (len < 0) {
+				printf("Invalid external data size: %d\n", len);
+				return -1;
+			}
+#if CONFIG_IS_ENABLED(FIT_SIGNATURE)
+			if (len > CONFIG_VAL(FIT_SIGNATURE_MAX_SIZE) - offset) {
+				printf("FIT external data is out of bounds (offset=%d, size=%d)\n",
+				       offset, len);
+				return -1;
+			}
+#endif
 			*data = fit + offset;
 			*size = len;
 		}
Signature · 1 line
2.53.0
#15 lore raw

PATCH v2 1/1 image-fit: Validate external data offset and size

From: Binarly Vulnerability Research <[email protected]>

fit_image_get_data() uses the data-position, data-offset, and data-size FIT properties without bounds checking. A crafted FIT image can specify values that cause out-of-bounds reads during hash calculation for signature verification.

Validate that the external data offset and size are non-negative, and that the data region fits within the FIT image bounds.

---
Changes in v2:
- Rewrite commit message to be concise per maintainer feedback

 boot/image-fit.c | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)
boot/image-fit.c +16 -0
index b0fcaf6e17f..4d0e8ffc79f 100644
@@ -1084,8 +1084,24 @@ int fit_image_get_data(const void *fit, int noffset, const void **data,
 
 	if (external_data) {
 		debug("External Data\n");
+		if (offset < 0 || offset > UINTPTR_MAX - (uintptr_t)fit) {
+			printf("Invalid external data offset: %d\n", offset);
+			return -1;
+		}
+
 		ret = fit_image_get_data_size(fit, noffset, &len);
 		if (!ret) {
+			if (len < 0) {
+				printf("Invalid external data size: %d\n", len);
+				return -1;
+			}
+#if CONFIG_IS_ENABLED(FIT_SIGNATURE)
+			if (len > CONFIG_VAL(FIT_SIGNATURE_MAX_SIZE) - offset) {
+				printf("FIT external data is out of bounds (offset=%d, size=%d)\n",
+				       offset, len);
+				return -1;
+			}
+#endif
 			*data = fit + offset;
 			*size = len;
 		}
Signature · 1 line
2.53.0
#16 lore raw

PATCH v3 1/1 image-fit: Validate external data offset and size

fit_image_get_data() uses the data-position, data-offset, and data-size FIT properties without bounds checking. A crafted FIT image can specify values that cause out-of-bounds reads during hash calculation for signature verification.

Validate that the external data offset and size are non-negative, and that the data region fits within the FIT image bounds.

---
Changes in v3:
- Update From and Signed-off-by to personal email

Changes in v2:
- Rewrite commit message to be concise per maintainer feedback

 boot/image-fit.c | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)
boot/image-fit.c +16 -0
index b0fcaf6e17f..4d0e8ffc79f 100644
@@ -1084,8 +1084,24 @@ int fit_image_get_data(const void *fit, int noffset, const void **data,
 
 	if (external_data) {
 		debug("External Data\n");
+		if (offset < 0 || offset > UINTPTR_MAX - (uintptr_t)fit) {
+			printf("Invalid external data offset: %d\n", offset);
+			return -1;
+		}
+
 		ret = fit_image_get_data_size(fit, noffset, &len);
 		if (!ret) {
+			if (len < 0) {
+				printf("Invalid external data size: %d\n", len);
+				return -1;
+			}
+#if CONFIG_IS_ENABLED(FIT_SIGNATURE)
+			if (len > CONFIG_VAL(FIT_SIGNATURE_MAX_SIZE) - offset) {
+				printf("FIT external data is out of bounds (offset=%d, size=%d)\n",
+				       offset, len);
+				return -1;
+			}
+#endif
 			*data = fit + offset;
 			*size = len;
 		}
Signature · 1 line
2.53.0
#17 lore raw

PATCH v4 1/1 image-fit: Validate external data offset and size

fit_image_get_data() uses the data-position, data-offset, and data-size FIT properties without bounds checking. A crafted FIT image can specify values that cause out-of-bounds read during signature verification of an untrusted FIT.

Validate that the external data offset and size are non-negative, and that the data region fits within the FIT image bounds.

---
Changes in v4:
- Add test for external data bounds validation
- Clarify vulnerability reachability in the commit message

Changes in v3:
- Update From and Signed-off-by to personal email

Changes in v2:
- Rewrite commit message to be concise per maintainer feedback

 boot/image-fit.c            |  16 ++++
 test/py/tests/test_vboot.py | 165 ++++++++++++++++++++++++++++++++++++
 2 files changed, 181 insertions(+)
boot/image-fit.c +16 -0
index b0fcaf6e17f..b657142f626 100644
@@ -1084,8 +1084,24 @@ int fit_image_get_data(const void *fit, int noffset, const void **data,
 
 	if (external_data) {
 		debug("External Data\n");
+		if (offset < 0 || offset > UINTPTR_MAX - (uintptr_t)fit) {
+			printf("Invalid external data offset: %d\n", offset);
+			return -1;
+		}
+
 		ret = fit_image_get_data_size(fit, noffset, &len);
 		if (!ret) {
+			if (len < 0) {
+				printf("Invalid external data size: %d\n", len);
+				return -1;
+			}
+#if CONFIG_IS_ENABLED(FIT_SIGNATURE)
+			if (len > CONFIG_VAL(FIT_SIGNATURE_MAX_SIZE) - offset) {
+				printf("FIT external data is out of bounds (offset=%d, size=%d)\n",
+				       offset, len);
+				return -1;
+			}
+#endif
 			*data = fit + offset;
 			*size = len;
 		}
test/py/tests/test_vboot.py +165 -0

171 lines not on this page · raw message

Signature · 1 line
2.53.0
#18 lore raw

Re: [PATCH v4] image-fit: Validate external data offset and size

For this fix, offset/len could be made uint32_t, as was done in the patch titled "image-fit-sig: Validate hashed-strings region size", but this would require changing the prototypes of fit_image_get_data_position(), fit_image_get_data_offset() and fit_image_get_data_size(). Please confirm whether this is acceptable.

Thank you,
Anton

Quoted 256 lines · Anton Ivanov

fit_image_get_data() uses the data-position, data-offset, and data-size FIT properties without bounds checking. A crafted FIT image can specify values that cause out-of-bounds read during signature verification of an untrusted FIT.

Validate that the external data offset and size are non-negative, and that the data region fits within the FIT image bounds.

---
Changes in v4:
- Add test for external data bounds validation
- Clarify vulnerability reachability in the commit message

Changes in v3:
- Update From and Signed-off-by to personal email

Changes in v2:
- Rewrite commit message to be concise per maintainer feedback

 boot/image-fit.c            |  16 ++++
 test/py/tests/test_vboot.py | 165 ++++++++++++++++++++++++++++++++++++
 2 files changed, 181 insertions(+)
boot/image-fit.c +11 -0
index b0fcaf6e17f..b657142f626 100644
@@ -1084,8 +1084,24 @@ int fit_image_get_data(const void *fit, int
 noffset, const void **data,
 
        if (external_data) {
                debug("External Data\n");
+               if (offset < 0 || offset > UINTPTR_MAX - (uintptr_t)fit) {
+                       printf("Invalid external data offset: %d\n",
 offset);
+                       return -1;
+               }
+
                ret = fit_image_get_data_size(fit, noffset, &len);
                if (!ret) {
+                       if (len < 0) {
+                               printf("Invalid external data size: %d\n",
 len);
+                               return -1;
+                       }
+#if CONFIG_IS_ENABLED(FIT_SIGNATURE)
+                       if (len > CONFIG_VAL(FIT_SIGNATURE_MAX_SIZE) -

offset) {
+ printf("FIT external data is out of bounds
(offset=%d, size=%d)\n",

boot/image-fit.c +4 -0
+                                      offset, len);
+                               return -1;
+                       }
+#endif
                        *data = fit + offset;
                        *size = len;
                }
test/py/tests/test_vboot.py +9 -0
index 55518bed07e..85a1bd56af6 100644
@@ -563,6 +563,171 @@ def test_vboot(ubman, name, sha_algo, padding,
 sign_options, required,
         ubman.restart_uboot()
 
 
[email protected]('sandbox')
[email protected]('fit_signature')
[email protected]('dtc')
[email protected]('fdtput')
[email protected]('openssl')
+def test_vboot_ext_data_bounds(ubman):
+    """Test that malformed external-data properties are rejected.
+
+    A signed FIT with external data exposes 'data-position',

'data-offset' and
+ 'data-size' properties. U-Boot must validate these before hashing the
image
+ components, otherwise a crafted FIT could trigger an out-of-bounds
access

test/py/tests/test_vboot.py +3 -0
+    during signature verification.
+
+    These checks are independent of the hashing algorithm, so a single

signing

test/py/tests/test_vboot.py +3 -0
+    configuration is enough.
+
+    This works using sandbox only as it needs to update the device tree

used

test/py/tests/test_vboot.py +8 -0
+    by U-Boot to hold public keys from the signing process.
+    """
+    sha_algo = 'sha256'
+
+    def run_bootm(test_type, expect_string):
+        """Run a 'bootm' command in U-Boot and expect it to fail.
+
+        This always starts a fresh U-Boot instance since the device tree

may

test/py/tests/test_vboot.py +8 -0
+        contain a new public key.
+
+        Args:
+            test_type: A string identifying the test type.
+            expect_string: A string which is expected in the output.
+        """
+        ubman.restart_uboot()
+        with ubman.log.section('Verified boot %s %s' % (sha_algo,

test_type)):

test/py/tests/test_vboot.py +6 -0
+            output = ubman.run_command_list(
+                ['host load hostfs - 100 %s' % fit,
+                 'fdt addr 100',
+                 'bootm 100'])
+        assert expect_string in ''.join(output)
+        assert 'sandbox: continuing, as we cannot run' not in

''.join(output)

test/py/tests/test_vboot.py +24 -0
+
+    def sign_fit(options):
+        """Sign the FIT
+
+        Signs the FIT and writes the signature into it. It also writes the
+        public key into the dtb.
+
+        Args:
+            options: Options to provide to mkimage.
+        """
+        args = [mkimage, '-F', '-k', tmpdir, '-K', dtb, '-r', fit]
+        if options:
+            args += options.split(' ')
+        ubman.log.action('%s: Sign images' % sha_algo)
+        utils.run_and_log(ubman, args)
+
+    def create_rsa_pair(name):
+        """Generate a new RSA key pair and certificate.
+
+        Args:
+            name: Name of the key (e.g. 'dev')
+        """
+        public_exponent = 65537
+        utils.run_and_log(ubman, 'openssl genpkey -algorithm RSA -out

%s%s.key '

test/py/tests/test_vboot.py +6 -0
+                     '-pkeyopt rsa_keygen_bits:2048 '
+                     '-pkeyopt rsa_keygen_pubexp:%d' %
+                     (tmpdir, name, public_exponent))
+
+        # Create a certificate containing the public key
+        utils.run_and_log(ubman, 'openssl req -batch -new -x509 -key

%s%s.key '

test/py/tests/test_vboot.py +11 -0
+                          '-out %s%s.crt' % (tmpdir, name, tmpdir, name))
+
+    def set_external_data(prop, value):
+        """Set an external-data property of the kernel image.
+
+        Args:
+            prop: Property name
+            value: The new value of the property
+        """
+        utils.run_and_log(
+            ubman, 'fdtput -t x %s /images/kernel %s %#x' % (fit, prop,

value)

test/py/tests/test_vboot.py +6 -0
+        )
+
+    def make_signed_fit():
+        """Build a fresh signed FIT with external data.
+
+        sign_fit() overwrites the FIT, so a new one is built before each

test

test/py/tests/test_vboot.py +3 -0
+        case mutates its external-data properties.
+        """
+        make_fit('sign-configs-%s.its' % sha_algo, ubman, mkimage,

dtc_args,

test/py/tests/test_vboot.py +4 -0
+                 datadir, fit)
+        sign_fit('-E')
+
+    tmpdir = os.path.join(ubman.config.result_dir, 'ext-data-bounds') +

'/'

test/py/tests/test_vboot.py +10 -0
+    if not os.path.exists(tmpdir):
+        os.mkdir(tmpdir)
+    datadir = ubman.config.source_dir + '/test/py/tests/vboot/'
+    fit = '%stest.fit' % tmpdir
+    mkimage = ubman.config.build_dir + '/tools/mkimage'
+    dtc_args = '-I dts -O dtb -i %s' % tmpdir
+    dtb = '%ssandbox-u-boot.dtb' % tmpdir
+
+    bcfg = ubman.config.buildconfig
+    max_size = int(bcfg.get('config_fit_signature_max_size', 0x10000000),

0)

test/py/tests/test_vboot.py +16 -0
+
+    create_rsa_pair('dev')
+
+    # Create a kernel image filled with zeroes
+    with open('%stest-kernel.bin' % tmpdir, 'wb') as fd:
+        fd.write(500 * b'\0')
+
+    testcases = [
+        ('negative data-position',
+         {'data-position': 0xFFFFFFFF}, 'Invalid external data offset'),
+        ('negative data-offset',
+         {'data-offset': 0x80000000}, 'Invalid external data offset'),
+        ('negative data-size',
+         {'data-size': 0xFFFFFFFF}, 'Invalid external data size'),
+        ('off-bounds data-position',
+         {'data-position': 0x7FFFFFFF}, 'FIT external data is out of

bounds'),

test/py/tests/test_vboot.py +2 -0
+        ('off-bounds data-offset',
+         {'data-offset': 0x10000000}, 'FIT external data is out of

bounds'),

test/py/tests/test_vboot.py +33 -0
+        ('oversized data-size',
+         {'data-size': 0x7FFFFFFF}, 'FIT external data is out of bounds'),
+        ('off-bounds data-position',
+         {'data-position': max_size + 1, 'data-size': 0},
+         'FIT external data is out of bounds'),
+        ('off-bounds data-offset',
+         {'data-offset': max_size + 1, 'data-size': 0},
+         'FIT external data is out of bounds'),
+        ('oversized data-size',
+         {'data-position': 0x0, 'data-size': max_size + 1},
+         'FIT external data is out of bounds'),
+        ('in-bounds data-position',
+         {'data-position': max_size, 'data-size': 0}, 'Bad Data Hash'),
+        ('in-bounds data-offset',
+         {'data-offset': max_size, 'data-size': 0}, 'Bad Data Hash'),
+        ('in-bounds data-size',
+         {'data-position': 0x0, 'data-size': max_size}, 'Bad Data Hash'),
+    ]
+
+    # We need to use our own device tree file. Remember to restore it
+    # afterwards.
+    old_dtb = ubman.config.dtb
+    try:
+        ubman.config.dtb = dtb
+
+        # Compile our device tree files for kernel and U-Boot. These are
+        # regenerated here since mkimage will modify them (by adding a
+        # public key) below.
+        dtc('sandbox-kernel.dts', ubman, dtc_args, datadir, tmpdir, dtb)
+        dtc('sandbox-u-boot.dts', ubman, dtc_args, datadir, tmpdir, dtb)
+
+        ubman.log.action(
+            '%s: Test signed FIT with malformed external-data properties'

% sha_algo)

test/py/tests/test_vboot.py +11 -1
+        for desc, props, expect_string in testcases:
+            make_signed_fit()
+            for prop, value in props.items():
+                set_external_data(prop, value)
+            run_bootm('Signed config with %s' % desc, expect_string)
+    finally:
+        # Go back to the original U-Boot with the correct dtb.
+        ubman.config.dtb = old_dtb
+        ubman.restart_uboot()
+
+
 TESTDATA_IN = [
     ['sha1-basic', 'sha1', '', None, False],
     ['sha1-pad', 'sha1', '', '-E -p 0x10000', False],
--

2.53.0

#19 lore raw

Re: [PATCH v4] image-fit: Validate external data offset and size

In reply to Anton Ivanov

Hi Anton,

Quoted 7 lines · Anton Ivanov

image-fit: Validate external data offset and size

fit_image_get_data() uses the data-position, data-offset, and data-size FIT properties without bounds checking. A crafted FIT image can specify values that cause out-of-bounds read during signature verification of an untrusted FIT.

Quoted 8 lines

Validate that the external data offset and size are non-negative, and that the data region fits within the FIT image bounds.

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

 test/py/tests/test_vboot.py | 165 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 181 insertions(+)

I think I have lost track of the versions here. But we are now on v4.

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

Quoted 9 lines
boot/image-fit.c +4 -0
@@ -1087,8 +1087,24 @@ int fit_image_get_data(const void *fit, int noffset, const void **data,
 
      if (external_data) {
              debug("External Data\n");
+             if (offset < 0 || offset > UINTPTR_MAX - (uintptr_t)fit) {
+                     printf("Invalid external data offset: %d\n", offset);
+                     return -1;
+             }

The offset < 0 check is after the offset += ((fdt_totalsize(fit) + 3) & ~3) addition on line 1082, so we could have a signed-overflow window is still open

Should return -EINVAL as -1 is actually -EPERM

On your uint32_t question: yes, that's the right direction, but it may be best as a separate patch. Changing the prototypes of fit_image_get_data_position(), fit_image_get_data_offset() and fit_image_get_data_size() to use uint32_t matches what was done for
image-fit-sig: Validate hashed-strings region size. Please go ahead - it lets you drop the < 0 checks and do the bound arithmetic safely in unsigned. The callers I checked pass the result through as integers, so the churn should be small.

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

Quoted 9 lines
boot/image-fit.c +7 -0
@@ -1087,8 +1087,24 @@ int fit_image_get_data(const void *fit, int noffset, const void **data,
+#if CONFIG_IS_ENABLED(FIT_SIGNATURE)
+                     if (len > CONFIG_VAL(FIT_SIGNATURE_MAX_SIZE) - offset) {
+                             printf("FIT external data is out of bounds (offset=%d, size=%d)\n",
+                                    offset, len);
+                             return -1;
+                     }
+#endif

Please split into two checks so the subtraction can't underflow (if (offset > max || len > max - offset)), drop the FIT_SIGNATURE gate so non-signature callers are protected too, and use if (CONFIG_IS_ENABLED(...)) rather than #if if you keep any config gate.

test/py/tests/test_vboot.py def test_vboot(ubman, name, sha_algo, padding, sign_options, required, · line 564

Quoted 4 lines
test/py/tests/test_vboot.py +2 -0
@@ -563,6 +563,171 @@ def test_vboot(ubman, name, sha_algo, padding, sign_options, required,
+        ('off-bounds data-position',
+         {'data-position': 0x7FFFFFFF}, 'FIT external data is out of bounds'),

lower-case hex

Regards,
Simon

#20 lore raw

Re: [PATCH v4] image-fit: Validate external data offset and size

Hi Simon,

Thank you for the review. The feedback is addressed in v5.

Quoted 2 lines

On your uint32_t question: yes, that's the right direction, but it may be best as a separate patch.

Agreed - we'll be happy to follow up with that as a separate patch once this one is merged.

Quoted 3 lines

drop the FIT_SIGNATURE gate so
non-signature callers are protected too, and use if (CONFIG_IS_ENABLED(...)) rather than #if if you keep any config gate.

As we understand it, non-signed FITs can only be checked against the valid addressable range. For signed FITs, we can also check that (offset + len) does not exceed FIT_SIGNATURE_MAX_SIZE. We cannot use CONFIG_IS_ENABLED(...) rather than #if because FIT_SIGNATURE_MAX_SIZE depends on FIT_SIGNATURE. Therefore, CONFIG_VAL(FIT_SIGNATURE_MAX_SIZE) is undefined when signing is disabled, and referencing it here would result in a compilation error.

Thank you,
Anton

Quoted 79 lines · Simon Glass

Hi Anton,

Quoted 7 lines · Anton Ivanov

image-fit: Validate external data offset and size

fit_image_get_data() uses the data-position, data-offset, and data-size FIT properties without bounds checking. A crafted FIT image can specify values that cause out-of-bounds read during signature verification of an untrusted FIT.

Quoted 7 lines

Validate that the external data offset and size are non-negative, and that the data region fits within the FIT image bounds.

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

 test/py/tests/test_vboot.py | 165

++++++++++++++++++++++++++++++++++++++++++++

Quoted 1 line
 2 files changed, 181 insertions(+)

I think I have lost track of the versions here. But we are now on v4.

boot/image-fit.c int fit_image_get_data(const void *fit, int

Quoted 2 lines
boot/image-fit.c +0 -0
@@ -1087,8 +1087,24 @@ int fit_image_get_data(const void *fit, int

noffset, const void **data,

boot/image-fit.c int fit_image_get_data(const void *fit, int noffset, const void **data,

Quoted 5 lines
boot/image-fit.c +2 -0
      if (external_data) {
              debug("External Data\n");
+             if (offset < 0 || offset > UINTPTR_MAX - (uintptr_t)fit) {
+                     printf("Invalid external data offset: %d\n",

offset);

boot/image-fit.c int fit_image_get_data(const void *fit, int · line 1092

Quoted 2 lines
boot/image-fit.c +2 -0
+                     return -1;
+             }

The offset < 0 check is after the offset += ((fdt_totalsize(fit) + 3) & ~3) addition on line 1082, so we could have a signed-overflow window is still open

Should return -EINVAL as -1 is actually -EPERM

On your uint32_t question: yes, that's the right direction, but it may be best as a separate patch. Changing the prototypes of fit_image_get_data_position(), fit_image_get_data_offset() and fit_image_get_data_size() to use uint32_t matches what was done for
image-fit-sig: Validate hashed-strings region size. Please go ahead - it lets you drop the < 0 checks and do the bound arithmetic safely in unsigned. The callers I checked pass the result through as integers, so the churn should be small.

boot/image-fit.c int fit_image_get_data(const void *fit, int

Quoted 2 lines
boot/image-fit.c +0 -0
@@ -1087,8 +1087,24 @@ int fit_image_get_data(const void *fit, int

noffset, const void **data,

boot/image-fit.c int fit_image_get_data(const void *fit, int · line 1088

Quoted 2 lines
boot/image-fit.c +2 -0
+#if CONFIG_IS_ENABLED(FIT_SIGNATURE)
+                     if (len > CONFIG_VAL(FIT_SIGNATURE_MAX_SIZE) -

offset) {

boot/image-fit.c int fit_image_get_data(const void *fit, int · line 1089

Quoted 1 line
boot/image-fit.c +1 -0
+                             printf("FIT external data is out of bounds

(offset=%d, size=%d)\n",

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

Quoted 4 lines
boot/image-fit.c +4 -0
+                                    offset, len);
+                             return -1;
+                     }
+#endif

Please split into two checks so the subtraction can't underflow (if (offset > max || len > max - offset)), drop the FIT_SIGNATURE gate so non-signature callers are protected too, and use if (CONFIG_IS_ENABLED(...)) rather than #if if you keep any config gate.

test/py/tests/test_vboot.py def test_vboot(ubman, name, sha_algo, padding,

Quoted 2 lines
test/py/tests/test_vboot.py +0 -0
@@ -563,6 +563,171 @@ def test_vboot(ubman, name, sha_algo, padding,

sign_options, required,

test/py/tests/test_vboot.py def test_vboot(ubman, name, sha_algo, padding, · line 564

Quoted 2 lines
test/py/tests/test_vboot.py +2 -0
+        ('off-bounds data-position',
+         {'data-position': 0x7FFFFFFF}, 'FIT external data is out of

bounds'),

lower-case hex

Regards,
Simon

#21 lore raw

PATCH v5 1/1 image-fit: Validate external data offset and size

In reply to Anton Ivanov

fit_image_get_data() uses the data-position, data-offset, and data-size FIT properties without bounds checking. A crafted FIT image can specify values that cause out-of-bounds read during signature verification of an untrusted FIT.

Validate that the external data offset and size are non-negative, and that the data region fits within the FIT image bounds.

---
Changes in v5:
- Guard the data-offset addition against INT_MAX overflow before adding the aligned FIT size
- Always bounds-check the offset and size against the addressable range; additionally cap them at FIT_SIGNATURE_MAX_SIZE for signed FITs
- Return -EINVAL instead of -1 on validation failures

Changes in v4:
- Add test for external data bounds validation
- Clarify vulnerability reachability in the commit message

Changes in v3:
- Update From and Signed-off-by to personal email

Changes in v2:
- Rewrite commit message to be concise per maintainer feedback

 boot/image-fit.c            |  53 +++++++++++-
 test/py/tests/test_vboot.py | 165 ++++++++++++++++++++++++++++++++++++
 2 files changed, 216 insertions(+), 2 deletions(-)
boot/image-fit.c +51 -2
index b0fcaf6e17f..a26450914d4 100644
@@ -1069,23 +1069,72 @@ int fit_image_get_data(const void *fit, int noffset, const void **data,
 	int offset;
 	int len;
 	int ret;
+	size_t fdt_total_size_aligned;
+	uintptr_t max_offset;
 
 	if (!fit_image_get_data_position(fit, noffset, &offset)) {
+		if (offset < 0) {
+			printf("Invalid external data position: %d\n", offset);
+			return -EINVAL;
+		}
+
 		external_data = true;
 	} else if (!fit_image_get_data_offset(fit, noffset, &offset)) {
-		external_data = true;
 		/*
 		 * For FIT with external data, figure out where
 		 * the external images start. This is the base
 		 * for the data-offset properties in each image.
 		 */
-		offset += ((fdt_totalsize(fit) + 3) & ~3);
+		fdt_total_size_aligned = ((fdt_totalsize(fit) + 3) & ~3);
+		/* The resulting offset cannot exceed INT_MAX */
+		if (offset < 0 || fdt_total_size_aligned > INT_MAX - offset) {
+			printf("Invalid external data offset: %d\n", offset);
+			return -EINVAL;
+		}
+		offset += fdt_total_size_aligned;
+
+		external_data = true;
 	}
 
 	if (external_data) {
 		debug("External Data\n");
+
+		max_offset = UINTPTR_MAX - (uintptr_t)fit;
+		/* Check that external data offset is within the addressable range */
+		if (offset > max_offset) {
+			printf("Invalid external data offset: %d\n", offset);
+			return -EINVAL;
+		}
+
 		ret = fit_image_get_data_size(fit, noffset, &len);
 		if (!ret) {
+			if (len < 0) {
+				printf("Invalid external data size: %d\n", len);
+				return -EINVAL;
+			}
+			/*
+			 * For non-signed FIT images, we can only check that
+			 * (offset + len) doesn't exceed the addressable range.
+			 * For signed FITs, we can additionally check that
+			 * (offset + len) doesn't exceed the allowed FIT image
+			 * maximum size.
+			 */
+			if (len > max_offset - offset
+			/*
+			 * #if (not a runtime if) is required: FIT_SIGNATURE_MAX_SIZE
+			 * depends on FIT_SIGNATURE, so CONFIG_VAL(FIT_SIGNATURE_MAX_SIZE)
+			 * is undefined when signing is disabled and referencing it
+			 * here would fail to compile.
+			 */
+#if CONFIG_IS_ENABLED(FIT_SIGNATURE)
+			    || offset > CONFIG_VAL(FIT_SIGNATURE_MAX_SIZE) ||
+			    len > CONFIG_VAL(FIT_SIGNATURE_MAX_SIZE) - offset
+#endif
+			) {
+				printf("FIT external data is out of bounds (offset=%d, size=%d)\n",
+				       offset, len);
+				return -EINVAL;
+			}
 			*data = fit + offset;
 			*size = len;
 		}
test/py/tests/test_vboot.py +165 -0

171 lines not on this page · raw message

Signature · 1 line
2.53.0
Reviewed-by on v5 1/1
#22 lore raw

Re: [PATCH v5] image-fit: Validate external data offset and size

Quoted 7 lines · Anton Ivanov

image-fit: Validate external data offset and size

fit_image_get_data() uses the data-position, data-offset, and data-size FIT properties without bounds checking. A crafted FIT image can specify values that cause out-of-bounds read during signature verification of an untrusted FIT.

Quoted 8 lines

Validate that the external data offset and size are non-negative, and that the data region fits within the FIT image bounds.

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

 test/py/tests/test_vboot.py | 165 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 216 insertions(+), 2 deletions(-)
#23 lore raw

Re: [PATCH v5] image-fit: Validate external data offset and size

In reply to Anton Ivanov
Quoted 10 lines · Anton Ivanov

fit_image_get_data() uses the data-position, data-offset, and data-size FIT properties without bounds checking. A crafted FIT image can specify values that cause out-of-bounds read during signature verification of an untrusted FIT.

Validate that the external data offset and size are non-negative, and that the data region fits within the FIT image bounds.

Applied to u-boot/next, thanks!

Signature · 1 line
Tom
#24 lore raw

PATCH 1/1 image-fit: Check nesting depth in fdt_check_no_at()

In reply to Anton Ivanov

From: Binarly Vulnerability Research <[email protected]>

The fdt_check_no_at(), located in boot/image-fit.c, is a helper that guards against libfdt's unit-address ambiguity; it scans the FIT tree and rejects any node whose name contains an '@':

	static int fdt_check_no_at(const void *fit, int parent)
	{
		const char *name;
		int node;
		int ret;

		name = fdt_get_name(fit, parent, NULL);
		if (!name || strchr(name, '@'))
			return -EADDRNOTAVAIL;

		fdt_for_each_subnode(node, fit, parent) {
			ret = fdt_check_no_at(fit, node);
			if (ret)
				return ret;
		}

		return 0;
	}

The function is recursive: for every subnode, it calls itself, and its termination condition is "no more subnodes".

It is called from the fit_check_format() (boot/image-fit.c):

	int fit_check_format(const void *fit, ulong size)
	{
		int ret;

		/* A FIT image must be a valid FDT */
		ret = fdt_check_header(fit);
		if (ret) {
			log_debug("Wrong FIT format: not a flattened device tree (err=%d)\n",
				ret);
			return -ENOEXEC;
		}

		if (CONFIG_IS_ENABLED(FIT_FULL_CHECK)) {
			/*
			* If we are not given the size, make do with calculating it.
			* This is not as secure, so we should consider a flag to
			* control this.
			*/
			if (size == IMAGE_SIZE_INVAL)
				size = fdt_totalsize(fit);
			ret = fdt_check_full(fit, size);
			if (ret)
				ret = -EINVAL;

			/*
			* U-Boot stopped using unit addressed in 2017. Since libfdt
			* can match nodes ignoring any unit address, signature
			* verification can see the wrong node if one is inserted with
			* the same name as a valid node but with a unit address
			* attached. Protect against this by disallowing unit addresses.
			*/
			if (!ret && CONFIG_IS_ENABLED(FIT_SIGNATURE)) {
				ret = fdt_check_no_at(fit, 0);
				...

The only guard executed prior to fdt_check_no_at() that validates the nesting depth of the FIT tree is in fdt_check_full():

	case FDT_BEGIN_NODE:
		depth++;
		if (depth > INT_MAX)
			return -FDT_ERR_BADSTRUCTURE;

It is only checked that the depth does not exceed INT_MAX, which means it is theoretically possible to create a FIT image with a depth of 2147483647 (if the device has enough RAM to support it). Each call to fdt_check_no_at() consumes 16 bytes of stack space (one 'const char *' and two int local variables, and a return address), while introducing a nested entry in the FIT requires 12 bytes (FDT_BEGIN_NODE -- 4 bytes, node name -- at least 4 bytes, and FDT_END_NODE -- 4 bytes). The stack is therefore guaranteed to be exhausted on any RAM size available.

Fix: Validate the nesting depth of the FIT tree.

---
 boot/image-fit.c | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)
boot/image-fit.c +9 -4
index b0fcaf6e17f..0e225ecd0c2 100644
@@ -41,6 +41,7 @@ DECLARE_GLOBAL_DATA_PTR;
 #include <bootm.h>
 #include <image.h>
 #include <bootstage.h>
+#include <fdt_region.h>
 #include <upl.h>
 #include <u-boot/crc.h>
 
@@ -1643,20 +1644,24 @@ int fit_image_check_comp(const void *fit, int noffset, uint8_t comp)
  *
  * @fit: FIT to check
  * @parent: Parent node to check
- * Return: 0 if OK, -EADDRNOTAVAIL is a node has a name containing '@'
+ * @depth: Current recursion depth
+ * Return: 0 if OK, or error value
  */
-static int fdt_check_no_at(const void *fit, int parent)
+static int fdt_check_no_at(const void *fit, int parent, int depth)
 {
 	const char *name;
 	int node;
 	int ret;
 
+	if (depth >= FDT_MAX_DEPTH)
+		return -FDT_ERR_BADSTRUCTURE;
+
 	name = fdt_get_name(fit, parent, NULL);
 	if (!name || strchr(name, '@'))
 		return -EADDRNOTAVAIL;
 
 	fdt_for_each_subnode(node, fit, parent) {
-		ret = fdt_check_no_at(fit, node);
+		ret = fdt_check_no_at(fit, node, depth + 1);
 		if (ret)
 			return ret;
 	}
@@ -1696,7 +1701,7 @@ int fit_check_format(const void *fit, ulong size)
 		 * attached. Protect against this by disallowing unit addresses.
 		 */
 		if (!ret && CONFIG_IS_ENABLED(FIT_SIGNATURE)) {
-			ret = fdt_check_no_at(fit, 0);
+			ret = fdt_check_no_at(fit, 0, 0);
 
 			if (ret) {
 				log_debug("FIT check error %d\n", ret);
Signature · 1 line
2.53.0
#25 lore raw

PATCH v2 1/1 image-fit: Limit recursion depth in fdt_check_no_at()

From: Binarly Vulnerability Research <[email protected]>

fdt_check_no_at() recurses into every subnode without a depth limit. A deeply nested FIT image can exhaust the stack and crash U-Boot.

Add a depth check using FDT_MAX_DEPTH to bound the recursion.

---
Changes in v2:
- Rewrite commit message to be concise per maintainer feedback

 boot/image-fit.c | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)
boot/image-fit.c +9 -4
index b0fcaf6e17f..0e225ecd0c2 100644
@@ -41,6 +41,7 @@ DECLARE_GLOBAL_DATA_PTR;
 #include <bootm.h>
 #include <image.h>
 #include <bootstage.h>
+#include <fdt_region.h>
 #include <upl.h>
 #include <u-boot/crc.h>
 
@@ -1643,20 +1644,24 @@ int fit_image_check_comp(const void *fit, int noffset, uint8_t comp)
  *
  * @fit: FIT to check
  * @parent: Parent node to check
- * Return: 0 if OK, -EADDRNOTAVAIL is a node has a name containing '@'
+ * @depth: Current recursion depth
+ * Return: 0 if OK, or error value
  */
-static int fdt_check_no_at(const void *fit, int parent)
+static int fdt_check_no_at(const void *fit, int parent, int depth)
 {
 	const char *name;
 	int node;
 	int ret;
 
+	if (depth >= FDT_MAX_DEPTH)
+		return -FDT_ERR_BADSTRUCTURE;
+
 	name = fdt_get_name(fit, parent, NULL);
 	if (!name || strchr(name, '@'))
 		return -EADDRNOTAVAIL;
 
 	fdt_for_each_subnode(node, fit, parent) {
-		ret = fdt_check_no_at(fit, node);
+		ret = fdt_check_no_at(fit, node, depth + 1);
 		if (ret)
 			return ret;
 	}
@@ -1696,7 +1701,7 @@ int fit_check_format(const void *fit, ulong size)
 		 * attached. Protect against this by disallowing unit addresses.
 		 */
 		if (!ret && CONFIG_IS_ENABLED(FIT_SIGNATURE)) {
-			ret = fdt_check_no_at(fit, 0);
+			ret = fdt_check_no_at(fit, 0, 0);
 
 			if (ret) {
 				log_debug("FIT check error %d\n", ret);
Signature · 1 line
2.53.0
#26 lore raw

PATCH v3 1/1 image-fit: Limit recursion depth in fdt_check_no_at()

fdt_check_no_at() recurses into every subnode without a depth limit. A deeply nested FIT image can exhaust the stack and crash U-Boot.

Add a depth check using FDT_MAX_DEPTH to bound the recursion.

---
Changes in v3:
- Update From and Signed-off-by to personal email

Changes in v2:
- Rewrite commit message to be concise per maintainer feedback

 boot/image-fit.c | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)
boot/image-fit.c +9 -4
index b0fcaf6e17f..0e225ecd0c2 100644
@@ -41,6 +41,7 @@ DECLARE_GLOBAL_DATA_PTR;
 #include <bootm.h>
 #include <image.h>
 #include <bootstage.h>
+#include <fdt_region.h>
 #include <upl.h>
 #include <u-boot/crc.h>
 
@@ -1643,20 +1644,24 @@ int fit_image_check_comp(const void *fit, int noffset, uint8_t comp)
  *
  * @fit: FIT to check
  * @parent: Parent node to check
- * Return: 0 if OK, -EADDRNOTAVAIL is a node has a name containing '@'
+ * @depth: Current recursion depth
+ * Return: 0 if OK, or error value
  */
-static int fdt_check_no_at(const void *fit, int parent)
+static int fdt_check_no_at(const void *fit, int parent, int depth)
 {
 	const char *name;
 	int node;
 	int ret;
 
+	if (depth >= FDT_MAX_DEPTH)
+		return -FDT_ERR_BADSTRUCTURE;
+
 	name = fdt_get_name(fit, parent, NULL);
 	if (!name || strchr(name, '@'))
 		return -EADDRNOTAVAIL;
 
 	fdt_for_each_subnode(node, fit, parent) {
-		ret = fdt_check_no_at(fit, node);
+		ret = fdt_check_no_at(fit, node, depth + 1);
 		if (ret)
 			return ret;
 	}
@@ -1696,7 +1701,7 @@ int fit_check_format(const void *fit, ulong size)
 		 * attached. Protect against this by disallowing unit addresses.
 		 */
 		if (!ret && CONFIG_IS_ENABLED(FIT_SIGNATURE)) {
-			ret = fdt_check_no_at(fit, 0);
+			ret = fdt_check_no_at(fit, 0, 0);
 
 			if (ret) {
 				log_debug("FIT check error %d\n", ret);
Signature · 1 line
2.53.0
#27 lore raw

PATCH v4 1/1 image-fit: Limit recursion depth in fdt_check_no_at()

fdt_check_no_at() recurses into every subnode without a depth limit. A deeply nested FIT image can exhaust the stack and crash U-Boot during signature verification of an untrusted FIT.

Add a depth check using FDT_MAX_DEPTH to bound the recursion.

---
Changes in v4:
- Clarify vulnerability reachability in the commit message

Changes in v3:
- Update From and Signed-off-by to personal email

Changes in v2:
- Rewrite commit message to be concise per maintainer feedback

 boot/image-fit.c | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)
boot/image-fit.c +9 -4
index b0fcaf6e17f..0e225ecd0c2 100644
@@ -41,6 +41,7 @@ DECLARE_GLOBAL_DATA_PTR;
 #include <bootm.h>
 #include <image.h>
 #include <bootstage.h>
+#include <fdt_region.h>
 #include <upl.h>
 #include <u-boot/crc.h>
 
@@ -1643,20 +1644,24 @@ int fit_image_check_comp(const void *fit, int noffset, uint8_t comp)
  *
  * @fit: FIT to check
  * @parent: Parent node to check
- * Return: 0 if OK, -EADDRNOTAVAIL is a node has a name containing '@'
+ * @depth: Current recursion depth
+ * Return: 0 if OK, or error value
  */
-static int fdt_check_no_at(const void *fit, int parent)
+static int fdt_check_no_at(const void *fit, int parent, int depth)
 {
 	const char *name;
 	int node;
 	int ret;
 
+	if (depth >= FDT_MAX_DEPTH)
+		return -FDT_ERR_BADSTRUCTURE;
+
 	name = fdt_get_name(fit, parent, NULL);
 	if (!name || strchr(name, '@'))
 		return -EADDRNOTAVAIL;
 
 	fdt_for_each_subnode(node, fit, parent) {
-		ret = fdt_check_no_at(fit, node);
+		ret = fdt_check_no_at(fit, node, depth + 1);
 		if (ret)
 			return ret;
 	}
@@ -1696,7 +1701,7 @@ int fit_check_format(const void *fit, ulong size)
 		 * attached. Protect against this by disallowing unit addresses.
 		 */
 		if (!ret && CONFIG_IS_ENABLED(FIT_SIGNATURE)) {
-			ret = fdt_check_no_at(fit, 0);
+			ret = fdt_check_no_at(fit, 0, 0);
 
 			if (ret) {
 				log_debug("FIT check error %d\n", ret);
Signature · 1 line
2.53.0
#28 lore raw

Re: [PATCH v4] image-fit: Limit recursion depth in fdt_check_no_at()

Quoted 7 lines · Anton Ivanov

fdt_check_no_at() recurses into every subnode without a depth limit. A deeply nested FIT image can exhaust the stack and crash U-Boot during signature verification of an untrusted FIT.

Add a depth check using FDT_MAX_DEPTH to bound the recursion.

Applied to u-boot/next, thanks!

Signature · 1 line
Tom
#29 lore raw
In reply to Anton Ivanov
Quoted 146 lines · Anton Ivanov

From: Binarly Vulnerability Research <[email protected]>

fdt_get_name() in scripts/dtc/libfdt/fdt_ro.c can return a null pointer. This happens when the fdt_ro_probe_() or fdt_check_node_offset_() check fails, as well as when the '!can_assume(LATEST) && fdt_version(fdt) < 0x10' condition is true and the FDT node name doesn't contain the '/' character:

	const char *fdt_get_name(const void *fdt, int nodeoffset, int *len)
	{
		const struct fdt_node_header *nh = fdt_offset_ptr_(fdt, nodeoffset);
		const char *nameptr;
		int err;

		if (((err = fdt_ro_probe_(fdt)) < 0)
			|| ((err = fdt_check_node_offset_(fdt, nodeoffset)) < 0))
				goto fail;

		nameptr = nh->name;

		if (!can_assume(LATEST) && fdt_version(fdt) < 0x10) {
			/*
			* For old FDT versions, match the naming conventions of V16:
			* give only the leaf name (after all /). The actual tree
			* contents are loosely checked.
			*/
			const char *leaf;
			leaf = strrchr(nameptr, '/');
			if (leaf == NULL) {
				err = -FDT_ERR_BADSTRUCTURE;
				goto fail;
			}
			nameptr = leaf+1;
		}

		if (len)
			*len = strlen(nameptr);

		return nameptr;

	fail:
		if (len)
			*len = err;
		return NULL;
	}

The fdt_get_name() function is used in fdt_find_regions() in boot/fdt_region.c:

	int fdt_find_regions(const void *fdt, char * const inc[], int inc_count,
				char * const exc_prop[], int exc_prop_count,
				struct fdt_region region[], int max_regions,
				char *path, int path_len, int add_string_tab)
	{
		int stack[FDT_MAX_DEPTH] = { 0 };
		char *end;
		int nextoffset = 0;
		uint32_t tag;
		int count = 0;
		int start = -1;
		int depth = -1;
		int want = 0;
		int base = fdt_off_dt_struct(fdt);
		bool expect_end = false;

		end = path;
		*end = '\0';
		do {
			const struct fdt_property *prop;
			const char *name;
			const char *str;
			int include = 0;
			int stop_at = 0;
			int offset;
			int len;

			offset = nextoffset;
			tag = fdt_next_tag(fdt, offset, &nextoffset);
			stop_at = nextoffset;

			/* If we see two root nodes, something is wrong */
			if (expect_end && tag != FDT_END)
				return -FDT_ERR_BADLAYOUT;

			switch (tag) {
			case FDT_PROP:
				include = want >= 2;
				stop_at = offset;
				prop = fdt_get_property_by_offset(fdt, offset, NULL);
				str = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
				if (!str)
					return -FDT_ERR_BADSTRUCTURE;
				if (str_in_list(str, exc_prop, exc_prop_count))
					include = 0;
				break;

			case FDT_NOP:
				include = want >= 2;
				stop_at = offset;
				break;

			case FDT_BEGIN_NODE:
				depth++;
				if (depth == FDT_MAX_DEPTH)
					return -FDT_ERR_BADSTRUCTURE;
				name = fdt_get_name(fdt, offset, &len);

				/* The root node must have an empty name */
				if (!depth && *name)
					return -FDT_ERR_BADLAYOUT;
				if (end - path + 2 + len >= path_len)
					return -FDT_ERR_NOSPACE;
				if (end != path + 1)
					*end++ = '/';
				strcpy(end, name);
				end += len;
				stack[depth] = want;
				if (want == 1)
					stop_at = offset;
				if (str_in_list(path, inc, inc_count))
					want = 2;
				else if (want)
					want--;
				else
					stop_at = offset;
				include = want;
				break;
			...

There is no check that the value returned by fdt_get_name() is not null, which leads to a null pointer dereference (at *name and strcpy(end, name)) and a potential stack overflow of the 'end' buffer. However, if the strcpy call succeeds, the subsequent 'end += len' decreases the 'end' pointer, since 'len' is set to the negative error code returned by fdt_get_name(). As a result, the next iteration of the loop writes data to a stack location before the start of the 'path' buffer, which can be used to overwrite the return address of fdt_find_regions() and achieve code execution in the context of the bootloader. This attack is possible when the page at address 0x0 is mapped, which is common for embedded devices, so the strcpy() call doesn't fail.

The same lack of validation exists in fdt_next_region() in boot/fdt_region.c, fdt_check_full() in scripts/dtc/libfdt/fdt_ro.c, and display_fdt_by_regions() in tools/fdtgrep.c.

Quoted 8 lines

Fix: Validate both the returned pointer and the length before use.

---
 boot/fdt_region.c           | 4 ++++
 scripts/dtc/libfdt/fdt_ro.c | 2 ++
 tools/fdtgrep.c             | 2 ++
 3 files changed, 8 insertions(+)

So scripts/dtc/libfdt/fdt_ro.c comes from https://github.com/dgibson/dtc
and should be sent upstream there too (and all of scripts/dtc/ is, for reference for the other patches), so that we don't drop this part when re-syncing later via the linux kernel.

Next, please rewrite the commit message to be concise and follow best practices and examples found throughout the codebase. This applies to all of the patches you posted, thanks.

Signature · 1 line
Tom
#30 lore raw

PATCH v2 1/1 fdt: Check return value of fdt_get_name() calls

From: Binarly Vulnerability Research <[email protected]>

fdt_get_name() can return NULL and set len to a negative error code. fdt_find_regions() does not check for this, leading to a potential NULL pointer dereference and a buffer out-of-bounds write. fdt_next_region(), fdt_check_full(), and display_fdt_by_regions() also lack validation.

Add NULL checks and propagate the error code from fdt_get_name() to the caller.

---
Changes in v2:
- Rewrite commit message to be concise per maintainer feedback
- Don't mask fdt_get_name() returned error

 boot/fdt_region.c           | 5 +++++
 scripts/dtc/libfdt/fdt_ro.c | 3 +++
 tools/fdtgrep.c             | 3 +++
 3 files changed, 11 insertions(+)
boot/fdt_region.c +5 -0
index 295ea08ac91..f0f2568955c 100644
@@ -86,6 +86,8 @@ int fdt_find_regions(const void *fdt, char * const inc[], int inc_count,
 			if (depth == FDT_MAX_DEPTH)
 				return -FDT_ERR_BADSTRUCTURE;
 			name = fdt_get_name(fdt, offset, &len);
+			if (!name)
+				return len;
 
 			/* The root node must have an empty name */
 			if (!depth && *name)
@@ -553,6 +555,9 @@ int fdt_next_region(const void *fdt,
 			if (p.depth == FDT_MAX_DEPTH)
 				return -FDT_ERR_BADSTRUCTURE;
 			name = fdt_get_name(fdt, offset, &len);
+			if (!name)
+				return len;
+
 			if (p.end - path + 2 + len >= path_len)
 				return -FDT_ERR_NOSPACE;
 
scripts/dtc/libfdt/fdt_ro.c +3 -0
index 3e7e26b4398..d7b424c658f 100644
@@ -940,6 +940,9 @@ int fdt_check_full(const void *fdt, size_t bufsize)
 				int len;
 
 				name = fdt_get_name(fdt, offset, &len);
+				if (!name)
+					return len;
+
 				if (*name || len)
 					return -FDT_ERR_BADLAYOUT;
 			}
tools/fdtgrep.c +3 -0
index b4c041070f5..dba7240001f 100644
@@ -355,6 +355,9 @@ static int display_fdt_by_regions(struct display_info *disp, const void *blob,
 
 		case FDT_BEGIN_NODE:
 			name = fdt_get_name(blob, offset, &len);
+			if (!name)
+				return len;
+
 			fprintf(f, "%*s%s {", depth++ * shift, "",
 				*name ? name : "/");
 			break;
Signature · 1 line
2.53.0
#31 lore raw

Re: [PATCH v2] fdt: Check return value of fdt_get_name() calls

Hi Anton,

Quoted 2 lines · Anton Ivanov

From: Binarly Vulnerability Research <[email protected]>

Is this a person? If so, can you use his/her name? As it stands it seems like an orgnisation rather than a person.

Quoted 15 lines

fdt_get_name() can return NULL and set len to a negative error code. fdt_find_regions() does not check for this, leading to a potential NULL pointer dereference and a buffer out-of-bounds write. fdt_next_region(), fdt_check_full(), and display_fdt_by_regions() also lack validation.

Add NULL checks and propagate the error code from fdt_get_name() to the caller.

---
Changes in v2:
- Rewrite commit message to be concise per maintainer feedback
- Don't mask fdt_get_name() returned error

Quoted 5 lines
 boot/fdt_region.c           | 5 +++++
 scripts/dtc/libfdt/fdt_ro.c | 3 +++
 tools/fdtgrep.c             | 3 +++
 3 files changed, 11 insertions(+)

Regards,
Simon

#32 lore raw

Re: [PATCH v2] fdt: Check return value of fdt_get_name() calls

Hi Simon,

Quoted 2 lines

Is this a person? If so, can you use his/her name? As it stands it seems like an orgnisation rather than a person.

We changed it to personal email in all the patches.

Thank you,
Anton

Quoted 33 lines · Simon Glass

Hi Anton,

Quoted 2 lines · Anton Ivanov

From: Binarly Vulnerability Research <[email protected]>

Is this a person? If so, can you use his/her name? As it stands it seems like an orgnisation rather than a person.

Quoted 15 lines

fdt_get_name() can return NULL and set len to a negative error code. fdt_find_regions() does not check for this, leading to a potential NULL pointer dereference and a buffer out-of-bounds write. fdt_next_region(), fdt_check_full(), and display_fdt_by_regions() also lack validation.

Add NULL checks and propagate the error code from fdt_get_name() to the caller.

---
Changes in v2:
- Rewrite commit message to be concise per maintainer feedback
- Don't mask fdt_get_name() returned error

Quoted 5 lines
 boot/fdt_region.c           | 5 +++++
 scripts/dtc/libfdt/fdt_ro.c | 3 +++
 tools/fdtgrep.c             | 3 +++
 3 files changed, 11 insertions(+)

Regards,
Simon

#33 lore raw

PATCH v3 1/1 fdt: Check return value of fdt_get_name() calls

In reply to Anton Ivanov

fdt_get_name() can return NULL and set len to a negative error code. fdt_find_regions() does not check for this, leading to a potential NULL pointer dereference and a buffer out-of-bounds write. fdt_next_region(), fdt_check_full(), and display_fdt_by_regions() also lack validation.

Add NULL checks and propagate the error code from fdt_get_name() to the caller.

---
Changes in v3:
- Update From and Signed-off-by to personal email

Changes in v2:
- Rewrite commit message to be concise per maintainer feedback
- Don't mask fdt_get_name() returned error

 boot/fdt_region.c           | 5 +++++
 scripts/dtc/libfdt/fdt_ro.c | 3 +++
 tools/fdtgrep.c             | 3 +++
 3 files changed, 11 insertions(+)
boot/fdt_region.c +5 -0
index 295ea08ac91..f0f2568955c 100644
@@ -86,6 +86,8 @@ int fdt_find_regions(const void *fdt, char * const inc[], int inc_count,
 			if (depth == FDT_MAX_DEPTH)
 				return -FDT_ERR_BADSTRUCTURE;
 			name = fdt_get_name(fdt, offset, &len);
+			if (!name)
+				return len;
 
 			/* The root node must have an empty name */
 			if (!depth && *name)
@@ -553,6 +555,9 @@ int fdt_next_region(const void *fdt,
 			if (p.depth == FDT_MAX_DEPTH)
 				return -FDT_ERR_BADSTRUCTURE;
 			name = fdt_get_name(fdt, offset, &len);
+			if (!name)
+				return len;
+
 			if (p.end - path + 2 + len >= path_len)
 				return -FDT_ERR_NOSPACE;
 
scripts/dtc/libfdt/fdt_ro.c +3 -0
index 3e7e26b4398..d7b424c658f 100644
@@ -940,6 +940,9 @@ int fdt_check_full(const void *fdt, size_t bufsize)
 				int len;
 
 				name = fdt_get_name(fdt, offset, &len);
+				if (!name)
+					return len;
+
 				if (*name || len)
 					return -FDT_ERR_BADLAYOUT;
 			}
tools/fdtgrep.c +3 -0
index b4c041070f5..dba7240001f 100644
@@ -355,6 +355,9 @@ static int display_fdt_by_regions(struct display_info *disp, const void *blob,
 
 		case FDT_BEGIN_NODE:
 			name = fdt_get_name(blob, offset, &len);
+			if (!name)
+				return len;
+
 			fprintf(f, "%*s%s {", depth++ * shift, "",
 				*name ? name : "/");
 			break;
Signature · 1 line
2.53.0
#34 lore raw

PATCH v4 1/1 fdt: Check return value of fdt_get_name() calls

fdt_get_name() can return NULL and set len to a negative error code. fdt_find_regions() does not check for this, leading to a potential NULL pointer dereference and a buffer out-of-bounds write during signature verification of an untrusted FIT. fdt_next_region(), fdt_check_full(), and display_fdt_by_regions() also lack validation.

Add NULL checks and propagate the error code from fdt_get_name() to the caller.

---
Changes in v4:
- Clarify vulnerability reachability in the commit message

Changes in v3:
- Update From and Signed-off-by to personal email

Changes in v2:
- Rewrite commit message to be concise per maintainer feedback
- Don't mask fdt_get_name() returned error

 boot/fdt_region.c           | 5 +++++
 scripts/dtc/libfdt/fdt_ro.c | 3 +++
 tools/fdtgrep.c             | 3 +++
 3 files changed, 11 insertions(+)
boot/fdt_region.c +5 -0
index 295ea08ac91..f0f2568955c 100644
@@ -86,6 +86,8 @@ int fdt_find_regions(const void *fdt, char * const inc[], int inc_count,
 			if (depth == FDT_MAX_DEPTH)
 				return -FDT_ERR_BADSTRUCTURE;
 			name = fdt_get_name(fdt, offset, &len);
+			if (!name)
+				return len;
 
 			/* The root node must have an empty name */
 			if (!depth && *name)
@@ -553,6 +555,9 @@ int fdt_next_region(const void *fdt,
 			if (p.depth == FDT_MAX_DEPTH)
 				return -FDT_ERR_BADSTRUCTURE;
 			name = fdt_get_name(fdt, offset, &len);
+			if (!name)
+				return len;
+
 			if (p.end - path + 2 + len >= path_len)
 				return -FDT_ERR_NOSPACE;
 
scripts/dtc/libfdt/fdt_ro.c +3 -0
index 3e7e26b4398..d7b424c658f 100644
@@ -940,6 +940,9 @@ int fdt_check_full(const void *fdt, size_t bufsize)
 				int len;
 
 				name = fdt_get_name(fdt, offset, &len);
+				if (!name)
+					return len;
+
 				if (*name || len)
 					return -FDT_ERR_BADLAYOUT;
 			}
tools/fdtgrep.c +3 -0
index b4c041070f5..dba7240001f 100644
@@ -355,6 +355,9 @@ static int display_fdt_by_regions(struct display_info *disp, const void *blob,
 
 		case FDT_BEGIN_NODE:
 			name = fdt_get_name(blob, offset, &len);
+			if (!name)
+				return len;
+
 			fprintf(f, "%*s%s {", depth++ * shift, "",
 				*name ? name : "/");
 			break;
Signature · 1 line
2.53.0
Reviewed-by on v4 1/1
#35 lore raw

Re: [PATCH v4] fdt: Check return value of fdt_get_name() calls

Quoted 11 lines · Anton Ivanov

fdt: Check return value of fdt_get_name() calls

fdt_get_name() can return NULL and set len to a negative error code. fdt_find_regions() does not check for this, leading to a potential NULL pointer dereference and a buffer out-of-bounds write during signature verification of an untrusted FIT. fdt_next_region(), fdt_check_full(), and display_fdt_by_regions() also lack validation.

Add NULL checks and propagate the error code from fdt_get_name() to the caller.

Quoted 6 lines

boot/fdt_region.c | 5 +++++

 scripts/dtc/libfdt/fdt_ro.c | 3 +++
 tools/fdtgrep.c             | 3 +++
 3 files changed, 11 insertions(+)

(a test would be nice!)

#36 lore raw

Re: [PATCH v4] fdt: Check return value of fdt_get_name() calls

In reply to Anton Ivanov
Quoted 11 lines · Anton Ivanov

fdt_get_name() can return NULL and set len to a negative error code. fdt_find_regions() does not check for this, leading to a potential NULL pointer dereference and a buffer out-of-bounds write during signature verification of an untrusted FIT. fdt_next_region(), fdt_check_full(), and display_fdt_by_regions() also lack validation.

Add NULL checks and propagate the error code from fdt_get_name() to the caller.

Applied to u-boot/next, thanks!

Signature · 1 line
Tom
#37 lore raw
In reply to Tom Rini
Quoted 4 lines

So scripts/dtc/libfdt/fdt_ro.c comes from https://github.com/dgibson/dtc
and should be sent upstream there too (and all of scripts/dtc/ is, for reference for the other patches), so that we don't drop this part when re-syncing later via the linux kernel.

The patch for fdt_check_full() was added in the upstream dtc code back in 2022:
https://github.com/dgibson/dtc/commit/fda71da26e7fa00966a58afeb2114269b5512e59

It was never ported to U-Boot, most likely because the function was moved from fdt_ro.c to the fdt_check.c.
Linux kernel does not use fdt_check_full(), and thus it is not affected.

We also updated the BRLY-2026-037_BRLY-2026-038.patch to align with the current dtc logic:
https://github.com/dgibson/dtc/commit/50454658f2b5c8968ccd7856d94020c893a4be46

Quoted 3 lines

Next, please rewrite the commit message to be concise and follow best practices and examples found throughout the codebase. This applies to all of the patches you posted, thanks.

We sent the new version of patches with the updated commit messages.

Thank you,
Anton

Quoted 180 lines · Tom Rini
Quoted 11 lines · Anton Ivanov

From: Binarly Vulnerability Research <[email protected]>

fdt_get_name() in scripts/dtc/libfdt/fdt_ro.c can return a null pointer. This happens when the fdt_ro_probe_() or fdt_check_node_offset_() check fails, as well as when the '!can_assume(LATEST) && fdt_version(fdt) < 0x10' condition is true and the FDT node name doesn't contain the '/' character:

const char *fdt_get_name(const void *fdt, int nodeoffset, int *len) {
const struct fdt_node_header *nh = fdt_offset_ptr_(fdt,

nodeoffset);

Quoted 5 lines
              const char *nameptr;
              int err;

              if (((err = fdt_ro_probe_(fdt)) < 0)
                      || ((err = fdt_check_node_offset_(fdt,

nodeoffset)) < 0))

Quoted 7 lines
                              goto fail;

              nameptr = nh->name;

              if (!can_assume(LATEST) && fdt_version(fdt) < 0x10) {
                      /*
                      * For old FDT versions, match the naming

conventions of V16:

Quoted 1 line

* give only the leaf name (after all /). The

actual tree

Quoted 22 lines
                      * contents are loosely checked.
                      */
                      const char *leaf;
                      leaf = strrchr(nameptr, '/');
                      if (leaf == NULL) {
                              err = -FDT_ERR_BADSTRUCTURE;
                              goto fail;
                      }
                      nameptr = leaf+1;
              }

              if (len)
                      *len = strlen(nameptr);

              return nameptr;

      fail:
              if (len)
                      *len = err;
              return NULL;
      }
Quoted 4 lines

The fdt_get_name() function is used in fdt_find_regions() in boot/fdt_region.c:

      int fdt_find_regions(const void *fdt, char * const inc[], int

inc_count,

Quoted 1 line
                              char * const exc_prop[], int

exc_prop_count,

Quoted 1 line
                              struct fdt_region region[], int

max_regions,

Quoted 1 line

char *path, int path_len, int

add_string_tab)

Quoted 28 lines
      {
              int stack[FDT_MAX_DEPTH] = { 0 };
              char *end;
              int nextoffset = 0;
              uint32_t tag;
              int count = 0;
              int start = -1;
              int depth = -1;
              int want = 0;
              int base = fdt_off_dt_struct(fdt);
              bool expect_end = false;

              end = path;
              *end = '\0';
              do {
                      const struct fdt_property *prop;
                      const char *name;
                      const char *str;
                      int include = 0;
                      int stop_at = 0;
                      int offset;
                      int len;

                      offset = nextoffset;
                      tag = fdt_next_tag(fdt, offset, &nextoffset);
                      stop_at = nextoffset;

                      /* If we see two root nodes, something is wrong */
Quoted 8 lines
                      if (expect_end && tag != FDT_END)
                              return -FDT_ERR_BADLAYOUT;

                      switch (tag) {
                      case FDT_PROP:
                              include = want >= 2;
                              stop_at = offset;
                              prop = fdt_get_property_by_offset(fdt,

offset, NULL);

Quoted 1 line

str = fdt_string(fdt,

fdt32_to_cpu(prop->nameoff));

Quoted 3 lines
                              if (!str)
                                      return -FDT_ERR_BADSTRUCTURE;
                              if (str_in_list(str, exc_prop,

exc_prop_count))

Quoted 53 lines
                                      include = 0;
                              break;

                      case FDT_NOP:
                              include = want >= 2;
                              stop_at = offset;
                              break;

                      case FDT_BEGIN_NODE:
                              depth++;
                              if (depth == FDT_MAX_DEPTH)
                                      return -FDT_ERR_BADSTRUCTURE;
                              name = fdt_get_name(fdt, offset, &len);

                              /* The root node must have an empty name */
                              if (!depth && *name)
                                      return -FDT_ERR_BADLAYOUT;
                              if (end - path + 2 + len >= path_len)
                                      return -FDT_ERR_NOSPACE;
                              if (end != path + 1)
                                      *end++ = '/';
                              strcpy(end, name);
                              end += len;
                              stack[depth] = want;
                              if (want == 1)
                                      stop_at = offset;
                              if (str_in_list(path, inc, inc_count))
                                      want = 2;
                              else if (want)
                                      want--;
                              else
                                      stop_at = offset;
                              include = want;
                              break;
                      ...

There is no check that the value returned by fdt_get_name() is not null, which leads to a null pointer dereference (at *name and strcpy(end, name)) and a potential stack overflow of the 'end' buffer. However, if the strcpy call succeeds, the subsequent 'end += len' decreases the 'end' pointer, since 'len' is set to the negative error code returned by fdt_get_name(). As a result, the next iteration of the loop writes data to a stack location before the start of the 'path' buffer, which can be used to overwrite the return address of fdt_find_regions() and achieve code execution in the context of the bootloader. This attack is possible when the page at address 0x0 is mapped, which is common for embedded devices, so the strcpy() call doesn't fail.

The same lack of validation exists in fdt_next_region() in boot/fdt_region.c, fdt_check_full() in scripts/dtc/libfdt/fdt_ro.c, and display_fdt_by_regions() in tools/fdtgrep.c.

Quoted 8 lines

Fix: Validate both the returned pointer and the length before use.

---
 boot/fdt_region.c           | 4 ++++
 scripts/dtc/libfdt/fdt_ro.c | 2 ++
 tools/fdtgrep.c             | 2 ++
 3 files changed, 8 insertions(+)

So scripts/dtc/libfdt/fdt_ro.c comes from https://github.com/dgibson/dtc
and should be sent upstream there too (and all of scripts/dtc/ is, for reference for the other patches), so that we don't drop this part when re-syncing later via the linux kernel.

Next, please rewrite the commit message to be concise and follow best practices and examples found throughout the codebase. This applies to all of the patches you posted, thanks.

--
Tom

#38 lore raw
Quoted 9 lines · Anton Ivanov
Quoted 4 lines

So scripts/dtc/libfdt/fdt_ro.c comes from https://github.com/dgibson/dtc
and should be sent upstream there too (and all of scripts/dtc/ is, for reference for the other patches), so that we don't drop this part when re-syncing later via the linux kernel.

The patch for fdt_check_full() was added in the upstream dtc code back in 2022:
https://github.com/dgibson/dtc/commit/fda71da26e7fa00966a58afeb2114269b5512e59

Quoted 7 lines

It was never ported to U-Boot, most likely because the function was moved from fdt_ro.c to the fdt_check.c.
Linux kernel does not use fdt_check_full(), and thus it is not affected.

We also updated the BRLY-2026-037_BRLY-2026-038.patch to align with the current dtc logic:
https://github.com/dgibson/dtc/commit/50454658f2b5c8968ccd7856d94020c893a4be46

Thanks for explaining. A bit more of a detailed rework needs to be done then, I'll go look at that.

Quoted 5 lines
Quoted 3 lines

Next, please rewrite the commit message to be concise and follow best practices and examples found throughout the codebase. This applies to all of the patches you posted, thanks.

We sent the new version of patches with the updated commit messages.

Thanks.

Signature · 1 line
Tom