Skip to contentSkip to conversation

mtd: ubi: Check lengths and PEB numbers read from flash

PATCH In review Ana Bobillo 2 participants 13 messages Nov 3 – Nov 11

Subsystems (3)
lore
Share & tools
lore
#0 lore raw

cover mtd: ubi: Check lengths and PEB numbers read from flash

UBI takes the sizes and PEB numbers it works with from headers on the flash and from the fastmap. This series checks six of them that are used without a bound, in the UBI core and in the SPL loader.

Patch 1: validate_vid_hdr() does not check that a VID header's data_size fits in a LEB, which Linux has done since commit 281fda27673f ("UBI: Validate data_size"), and ubi_compare_lebs() reads data_size bytes into ubi->peb_buf, which holds one PEB. Apply the Linux check. A new sandbox test (dm ubi_vid_hdr_data_size) writes a static volume of one full LEB on the sandbox NAND, checks that it attaches and reads back, then rewrites its VID header with a data_size one byte over the
LEB: 'ubi part' attaches it without the fix and refuses it with it.

Patches 2 and 3 are for the SPL loader in drivers/mtd/ubispl. ubi_load_block() reads data_size bytes of a PEB to the load address without checking data_size against the LEB size, and ubi_attach_fastmap() uses the PEB numbers of the fastmap's used list and EBA tables as indexes into the fm_used bitmap without checking them against the PEB count. Both now treat an out-of-range value as corruption, so the loader moves on to another copy of the LEB or to a full scan, as it already does when a CRC does not match.

Patches 4 and 5 are for the fastmap code of the UBI core. ubi_attach_fastmap() hands the PEB numbers of the fastmap's lists to ubi_wl_init(), which uses them as indexes into ubi->lookuptbl; patch 4 checks every PEB number taken from the fastmap with one helper and falls back to a full scan when one is outside the device. Patch 5 checks that each volume's EBA table header fits in the fastmap and that its reserved_pebs is not above the PEB count before fm_pos is advanced by it, as on 32-bit builds the advance can wrap around and pass the end-of-buffer check. The SPL loader parses the EBA tables the same way, so patch 5 changes both.

Patch 6: check_av() does not check the size of a static volume's last LEB against the volume's usable LEB size, which is smaller than the LEB size when the volume has data padding, and a fastmap's value is not checked at all. The size goes into used_bytes, which bounds what 'ubi read' and ubi_volume_read() map to LEBs and look up in the EBA table. A second sandbox test (dm ubi_static_last_leb_size) writes a static volume with data padding and one full LEB, checks that it attaches and reads back, then sets the LEB's data_size one byte over the usable LEB
size: 'ubi part' attaches it without the fix and refuses it with it.

Both tests fail on current main and pass with the series, and patch 6's test also fails with only patches 1 to 5 applied; with the series applied, 'ut dm' on sandbox shows no new failures. The fastmap paths (patches 3 to 5) have no sandbox test: sandbox_defconfig does not enable fastmap. They were checked by building sandbox with CONFIG_MTD_UBI_FASTMAP=y, where both tests also pass, and igep00x0_defconfig (32-bit ARM, UBI fastmap and SPL_UBI): both build without new warnings.

Linux and barebox share the code of patches 4 to 6: the checks of patches 4 and 6 have been proposed for Linux, and all three for barebox.

Patch 6's test builds on the test file that patch 1 adds; otherwise the patches do not depend on each other.

CI: Azure build 13722 passed, all jobs, with this series on
https://github.com/u-boot/u-boot/pull/1064, a CI-only pull request, merged with main ee9fc27f2a2:
https://dev.azure.com/u-boot/u-boot/_build/results?buildId=13722

Ana Bobillo (6):
mtd: ubi: validate data_size in the VID header
mtd: ubispl: check data_size before loading a LEB
mtd: ubispl: check the PEB numbers read from the fastmap
mtd: ubi: fastmap: check PEB numbers read from the fastmap
mtd: ubi: fastmap: bound the size of a volume's EBA table
mtd: ubi: vtbl: check the size of a static volume's last LEB

 MAINTAINERS                 |   1 +
 drivers/mtd/ubi/fastmap.c   |  87 ++++++++++++---
 drivers/mtd/ubi/io.c        |   5 +
 drivers/mtd/ubi/vtbl.c      |   6 ++
 drivers/mtd/ubispl/ubispl.c |  44 +++++++-
 test/dm/Makefile            |   3 +
 test/dm/ubi.c               | 207 ++++++++++++++++++++++++++++++++++++
 7 files changed, 337 insertions(+), 16 deletions(-)
 create mode 100644 test/dm/ubi.c

base-commit: 3973f3c4d24df75ca90d7c0a9f03e5e5c9b48f32

#1 lore raw

PATCH 1/6 mtd: ubi: validate data_size in the VID header

From: Ana Bobillo <[email protected]>

validate_vid_hdr() never checks that a VID header's data_size fits in a LEB. Only the LEBs of a static volume other than its last one have their data_size pinned to the usable LEB size; for the last LEB of a static volume and for a copied LEB of a dynamic one any positive value passes. The attach code then trusts it: when two PEBs hold the same LEB and the newer one is a copy, ubi_compare_lebs() reads data_size bytes of that PEB into ubi->peb_buf, which holds one PEB, and computes the data CRC over them. A handcrafted UBI image can therefore make 'ubi part' overrun peb_buf. The ubi_assert() in ubi_io_read() that would catch the length is compiled out unless DEBUG is defined.

Linux fixed this in commit 281fda27673f ("UBI: Validate data_size") by Richard Weinberger, after the v4.2 code that U-Boot's UBI was last synced with. Apply the same check.

Add a test which writes a static volume of one full LEB on the sandbox NAND, so that its VID header carries the largest valid data_size, checks that it attaches and reads back, then sets data_size one byte larger and checks that attaching fails.

---
 MAINTAINERS          |   1 +
 drivers/mtd/ubi/io.c |   5 ++
 test/dm/Makefile     |   3 +
 test/dm/ubi.c        | 137 +++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 146 insertions(+)
 create mode 100644 test/dm/ubi.c
MAINTAINERS +1 -0
index 5052671740d..b2ced485702 100644
@@ -1801,6 +1801,7 @@ M:	Heiko Schocher <[email protected]>
 S:	Maintained
 T:	git https://git.u-boot-project.org/u-boot/custodians/u-boot-ubi.git
 F:	drivers/mtd/ubi/
+F:	test/dm/ubi.c
 
 UFETCH
 M:	Casey Connolly <[email protected]>
drivers/mtd/ubi/io.c +5 -0
index 2ec968c85ff..ee92a2be13c 100644
@@ -916,6 +916,11 @@ static int validate_vid_hdr(const struct ubi_device *ubi,
 		goto bad;
 	}
 
+	if (data_size > ubi->leb_size) {
+		ubi_err(ubi, "bad data_size");
+		goto bad;
+	}
+
 	if (vol_type == UBI_VID_STATIC) {
 		/*
 		 * Although from high-level point of view static volumes may
test/dm/Makefile +3 -0
index 1b3a20aa932..29e3db05a48 100644
@@ -149,6 +149,9 @@ obj-$(CONFIG_UT_DM) += tag.o
 obj-$(CONFIG_TEE) += tee.o
 obj-$(CONFIG_TIMER) += timer.o
 obj-$(CONFIG_TPM_V2) += tpm.o
+ifeq ($(CONFIG_CMD_UBI)$(CONFIG_NAND_SANDBOX),yy)
+obj-y += ubi.o
+endif
 obj-$(CONFIG_DM_USB) += usb.o
 obj-$(CONFIG_VIDEO_SANDBOX_SDL) += video.o
 ifeq ($(CONFIG_VIRTIO_SANDBOX),y)
test/dm/ubi.c new file +137 -0

137 lines not on this page · raw message

Reviewed-by on v1 1/6
#2 lore raw

Re: [PATCH 1/6] mtd: ubi: validate data_size in the VID header

Hello Ana,

Quoted 22 lines · Ana Bobillo

From: Ana Bobillo <[email protected]>

validate_vid_hdr() never checks that a VID header's data_size fits in a LEB. Only the LEBs of a static volume other than its last one have their data_size pinned to the usable LEB size; for the last LEB of a static volume and for a copied LEB of a dynamic one any positive value passes. The attach code then trusts it: when two PEBs hold the same LEB and the newer one is a copy, ubi_compare_lebs() reads data_size bytes of that PEB into ubi->peb_buf, which holds one PEB, and computes the data CRC over them. A handcrafted UBI image can therefore make 'ubi part' overrun peb_buf. The ubi_assert() in ubi_io_read() that would catch the length is compiled out unless DEBUG is defined.

Linux fixed this in commit 281fda27673f ("UBI: Validate data_size") by Richard Weinberger, after the v4.2 code that U-Boot's UBI was last synced with. Apply the same check.

Add a test which writes a static volume of one full LEB on the sandbox NAND, so that its VID header carries the largest valid data_size, checks that it attaches and reads back, then sets data_size one byte larger and checks that attaching fails.

Quoted 8 lines
---
  MAINTAINERS          |   1 +
  drivers/mtd/ubi/io.c |   5 ++
  test/dm/Makefile     |   3 +
  test/dm/ubi.c        | 137 +++++++++++++++++++++++++++++++++++++++++++
  4 files changed, 146 insertions(+)

create mode 100644 test/dm/ubi.c

Thanks!

bye,
Heiko

Quoted 187 lines
MAINTAINERS +1 -0
index 5052671740d..b2ced485702 100644
@@ -1801,6 +1801,7 @@ M:	Heiko Schocher <[email protected]>
  S:	Maintained
  T:	git https://git.u-boot-project.org/u-boot/custodians/u-boot-ubi.git
  F:	drivers/mtd/ubi/
+F:	test/dm/ubi.c
 
  UFETCH
  M:	Casey Connolly <[email protected]>
drivers/mtd/ubi/io.c +5 -0
index 2ec968c85ff..ee92a2be13c 100644
@@ -916,6 +916,11 @@ static int validate_vid_hdr(const struct ubi_device *ubi,
  		goto bad;
  	}
 
+	if (data_size > ubi->leb_size) {
+		ubi_err(ubi, "bad data_size");
+		goto bad;
+	}
+
  	if (vol_type == UBI_VID_STATIC) {
  		/*
  		 * Although from high-level point of view static volumes may
test/dm/Makefile +3 -0
index 1b3a20aa932..29e3db05a48 100644
@@ -149,6 +149,9 @@ obj-$(CONFIG_UT_DM) += tag.o
  obj-$(CONFIG_TEE) += tee.o
  obj-$(CONFIG_TIMER) += timer.o
  obj-$(CONFIG_TPM_V2) += tpm.o
+ifeq ($(CONFIG_CMD_UBI)$(CONFIG_NAND_SANDBOX),yy)
+obj-y += ubi.o
+endif
  obj-$(CONFIG_DM_USB) += usb.o
  obj-$(CONFIG_VIDEO_SANDBOX_SDL) += video.o
  ifeq ($(CONFIG_VIRTIO_SANDBOX),y)
test/dm/ubi.c new file +137 -0
new file mode 100644
index 00000000000..81654b33f1e
@@ -0,0 +1,137 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Tests for attaching UBI to the sandbox NAND
+ */
+
+#include <malloc.h>
+#include <mtd.h>
+#include <ubi_uboot.h>
+#include <dm/test.h>
+#include <linux/err.h>
+#include <linux/mtd/mtd.h>
+#include <linux/string.h>
+#include <test/test.h>
+#include <test/ut.h>
+
+#define UBI_TEST_MTD	"nand2"
+
+static int ubi_test_erase_peb(struct unit_test_state *uts,
+			      struct mtd_info *mtd, u64 off)
+{
+	struct erase_info ei;
+
+	memset(&ei, 0, sizeof(ei));
+	ei.mtd = mtd;
+	ei.addr = off;
+	ei.len = mtd->erasesize;
+	ut_assertok(mtd_erase(mtd, &ei));
+
+	return 0;
+}
+
+/*
+ * Set data_size in the VID header of LEB 0 of volume 0, with a valid header
+ * CRC, by rewriting the PEB that holds it. @peb holds one eraseblock.
+ */
+static int ubi_test_set_data_size(struct unit_test_state *uts,
+				  struct mtd_info *mtd, u8 *peb, u32 data_size)
+{
+	struct ubi_ec_hdr *ec_hdr = (struct ubi_ec_hdr *)peb;
+	struct ubi_vid_hdr *vid_hdr;
+	size_t retlen;
+	u64 off;
+
+	for (off = 0; off < mtd->size; off += mtd->erasesize) {
+		if (mtd_block_isbad(mtd, off))
+			continue;
+		ut_assertok(mtd_read(mtd, off, mtd->erasesize, &retlen, peb));
+		if (be32_to_cpu(ec_hdr->magic) != UBI_EC_HDR_MAGIC)
+			continue;
+		vid_hdr = (struct ubi_vid_hdr *)
+			(peb + be32_to_cpu(ec_hdr->vid_hdr_offset));
+		if (be32_to_cpu(vid_hdr->magic) == UBI_VID_HDR_MAGIC &&
+		    be32_to_cpu(vid_hdr->vol_id) == 0 &&
+		    be32_to_cpu(vid_hdr->lnum) == 0)
+			break;
+	}
+	ut_assert(off < mtd->size);
+
+	vid_hdr->data_size = cpu_to_be32(data_size);
+	vid_hdr->hdr_crc = cpu_to_be32(crc32(UBI_CRC32_INIT, vid_hdr,
+					     UBI_VID_HDR_SIZE_CRC));
+
+	ut_assertok(ubi_test_erase_peb(uts, mtd, off));
+	ut_assertok(mtd_write(mtd, off, mtd->erasesize, &retlen, peb));
+
+	return 0;
+}
+
+/* Find the test MTD device and erase it all */
+static int ubi_test_erase_mtd(struct unit_test_state *uts,
+			      struct mtd_info **mtdp)
+{
+	struct mtd_info *mtd;
+	u64 off;
+
+	mtd_probe_devices();
+	mtd = get_mtd_device_nm(UBI_TEST_MTD);
+	ut_assert(!IS_ERR_OR_NULL(mtd));
+	put_mtd_device(mtd);
+
+	for (off = 0; off < mtd->size; off += mtd->erasesize) {
+		if (mtd_block_isbad(mtd, off))
+			continue;
+		ut_assertok(ubi_test_erase_peb(uts, mtd, off));
+	}
+	*mtdp = mtd;
+
+	return 0;
+}
+
+static int ubi_test_vid_hdr_data_size(struct unit_test_state *uts)
+{
+	struct mtd_info *mtd;
+	int leb_size;
+	u8 *buf;
+
+	ut_assertok(ubi_test_erase_mtd(uts, &mtd));
+
+	buf = malloc(mtd->erasesize);
+	ut_assertnonnull(buf);
+
+	/* A static volume whose only LEB is full: data_size is the LEB size */
+	ut_assertok(ubi_part(UBI_TEST_MTD, NULL));
+	leb_size = ubi_devices[0]->leb_size;
+	ut_assertok(ubi_create_vol("vol0", leb_size, false, 0, false));
+	memset(buf, 0xa5, leb_size);
+	ut_assertok(ubi_volume_write("vol0", buf, 0, leb_size));
+	ubi_detach();
+
+	/* It attaches again and reads back */
+	ut_assertok(ubi_part(UBI_TEST_MTD, NULL));
+	memset(buf, 0, leb_size);
+	ut_assertok(ubi_volume_read("vol0", buf, 0, leb_size));
+	ut_assertnull(memchr_inv(buf, 0xa5, leb_size));
+	ubi_detach();
+
+	/* One byte more than the LEB holds is a corrupt header */
+	ut_assertok(ubi_test_set_data_size(uts, mtd, buf, leb_size + 1));
+	ut_asserteq(-EINVAL, ubi_part(UBI_TEST_MTD, NULL));
+
+	free(buf);
+
+	return 0;
+}
+
+static int dm_test_ubi_vid_hdr_data_size(struct unit_test_state *uts)
+{
+	int ret;
+
+	/* UBI holds the MTD device: release it before and after the test */
+	ubi_detach();
+	ret = ubi_test_vid_hdr_data_size(uts);
+	ubi_detach();
+
+	return ret;
+}
+DM_TEST(dm_test_ubi_vid_hdr_data_size, UTF_SCAN_FDT | UTF_LIVE_TREE);
Signature · 5 lines
Nabla Software Engineering
HRB 40522 Augsburg
Phone: +49 821 45592596
E-Mail: [email protected]
Geschäftsführer : Stefano Babic
#3 lore raw

PATCH 2/6 mtd: ubispl: check data_size before loading a LEB

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

ubi_load_block() reads data_size bytes of a PEB to the load address and computes the data CRC over them, with data_size taken from the block's VID header. The SPL loader checks the header's magic, CRC and used_ebs but not data_size, so a header claiming more data than a LEB holds makes the loader read past the end of the PEB and write beyond the part of the load buffer that LEB is meant to fill.

Treat a block whose data_size exceeds the LEB size as corrupt, as is done when the data CRC does not match: the loader then looks for another copy of the LEB and, if none is found and fastmap was used, retries with a full scan. Each LEB now adds at most one LEB to the loaded image.

Fixes 6f4e7d3c75a8 ("spl: Lightweight UBI and UBI fastmap support")
---
 drivers/mtd/ubispl/ubispl.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)
drivers/mtd/ubispl/ubispl.c +12 -0
index 0143caa051d..0466cc72c9e 100644
@@ -964,6 +964,18 @@ retry:
 	 */
 	dlen = be32_to_cpu(vh->data_size);
 
+	/*
+	 * A data_size beyond the LEB is never valid: reading it would run
+	 * past the PEB and past this LEB's part of the load buffer. Treat
+	 * the block as corrupt and look for another copy.
+	 */
+	if (dlen > ubi->leb_size) {
+		ubi_warn("Vol: %u LEB %u PEB %u bad data_size %u", vol_id,
+			 lnum, pnum, dlen);
+		generic_set_bit(pnum, ubi->corrupt);
+		goto find_other;
+	}
+
 	/*
 	 * Read the data into RAM. We ignore the return value
 	 * here as the only thing which might go wrong are
Reviewed-by on v1 2/6
#4 lore raw

Re: [PATCH 2/6] mtd: ubispl: check data_size before loading a LEB

Hello Ana,

Quoted 14 lines · Ana Bobillo

From: Ana Bobillo <[email protected]>

ubi_load_block() reads data_size bytes of a PEB to the load address and computes the data CRC over them, with data_size taken from the block's VID header. The SPL loader checks the header's magic, CRC and used_ebs but not data_size, so a header claiming more data than a LEB holds makes the loader read past the end of the PEB and write beyond the part of the load buffer that LEB is meant to fill.

Treat a block whose data_size exceeds the LEB size as corrupt, as is done when the data CRC does not match: the loader then looks for another copy of the LEB and, if none is found and fastmap was used, retries with a full scan. Each LEB now adds at most one LEB to the loaded image.

Quoted 5 lines
Fixes 6f4e7d3c75a8 ("spl: Lightweight UBI and UBI fastmap support")
---
  drivers/mtd/ubispl/ubispl.c | 12 ++++++++++++
  1 file changed, 12 insertions(+)

Thanks!

bye,
Heiko

Signature · 5 lines
Nabla Software Engineering
HRB 40522 Augsburg
Phone: +49 821 45592596
E-Mail: [email protected]
Geschäftsführer : Stefano Babic
#5 lore raw

PATCH 3/6 mtd: ubispl: check the PEB numbers read from the fastmap

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

ubi_attach_fastmap() sets a bit in the fm_used bitmap for each PEB of the fastmap's used list and tests and clears one for each PEB of a volume's EBA table, using the PEB numbers as read from the fastmap. fm_used has room for CONFIG_SPL_UBI_MAX_PEBS bits: a larger PEB number in either list reaches past its end, and a used-list entry of 2^31 or more becomes a negative index before its start.

Check both against the PEB count with ubi_io_is_bad(), as scan_pool(), assign_aeb_to_av() and ubi_scan_fastmap() already do for the PEBs they take from the fastmap, and reject the fastmap if one is out of range:
the loader then falls back to a full scan.

Fixes 6f4e7d3c75a8 ("spl: Lightweight UBI and UBI fastmap support")
---
 drivers/mtd/ubispl/ubispl.c | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)
drivers/mtd/ubispl/ubispl.c +14 -1
index 0466cc72c9e..c3b964b64dd 100644
@@ -558,12 +558,20 @@ static int ubi_attach_fastmap(struct ubi_scan_info *ubi,
 
 	/* read EC values from used list */
 	for (i = 0; i < be32_to_cpu(fmhdr->used_peb_count); i++) {
+		int pnum;
+
 		fmec = (struct ubi_fm_ec *)(fm_raw + fm_pos);
 		fm_pos += sizeof(*fmec);
 		if (fm_pos >= fm_size)
 			goto fail_bad;
 
-		generic_set_bit(be32_to_cpu(fmec->pnum), ubi->fm_used);
+		pnum = be32_to_cpu(fmec->pnum);
+		if (ubi_io_is_bad(ubi, pnum)) {
+			ubi_err("FM: Bad PEB in fastmap used list! %d", pnum);
+			goto fail_bad;
+		}
+
+		generic_set_bit(pnum, ubi->fm_used);
 	}
 
 	/* read EC values from scrub list */
@@ -623,6 +631,11 @@ static int ubi_attach_fastmap(struct ubi_scan_info *ubi,
 			if ((int)be32_to_cpu(fm_eba->pnum[j]) < 0)
 				continue;
 
+			if (ubi_io_is_bad(ubi, pnum)) {
+				ubi_err("FM: Bad PEB in fastmap EBA! %d", pnum);
+				goto fail_bad;
+			}
+
 			if (!__test_and_clear_bit(pnum, ubi->fm_used))
 				continue;
 
Reviewed-by on v1 3/6
#6 lore raw

Re: [PATCH 3/6] mtd: ubispl: check the PEB numbers read from the fastmap

Hello Ana,

Quoted 14 lines · Ana Bobillo

From: Ana Bobillo <[email protected]>

ubi_attach_fastmap() sets a bit in the fm_used bitmap for each PEB of the fastmap's used list and tests and clears one for each PEB of a volume's EBA table, using the PEB numbers as read from the fastmap. fm_used has room for CONFIG_SPL_UBI_MAX_PEBS bits: a larger PEB number in either list reaches past its end, and a used-list entry of 2^31 or more becomes a negative index before its start.

Check both against the PEB count with ubi_io_is_bad(), as scan_pool(), assign_aeb_to_av() and ubi_scan_fastmap() already do for the PEBs they take from the fastmap, and reject the fastmap if one is out of range:
the loader then falls back to a full scan.

Quoted 5 lines
Fixes 6f4e7d3c75a8 ("spl: Lightweight UBI and UBI fastmap support")
---
  drivers/mtd/ubispl/ubispl.c | 15 ++++++++++++++-
  1 file changed, 14 insertions(+), 1 deletion(-)

Thanks!

bye,
Heiko

Signature · 5 lines
Nabla Software Engineering
HRB 40522 Augsburg
Phone: +49 821 45592596
E-Mail: [email protected]
Geschäftsführer : Stefano Babic
#7 lore raw

PATCH 4/6 mtd: ubi: fastmap: check PEB numbers read from the fastmap

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

The fastmap lists the PEBs of the device with their erase counters, and ubi_attach_fastmap() passes the numbers in its free, used, scrub and erase lists to add_aeb() as they are on flash. ubi_wl_init() then uses each of them as an index into ubi->lookuptbl, which has room for ubi->peb_count entries, and stores a pointer there. So a fastmap with a PEB number outside the device makes UBI write past the end of the table, or before its start for a negative number. The CRC over the fastmap doesn't protect against a fastmap that was written that way.

Check every PEB number taken from the fastmap with one helper that accepts only 0 to peb_count - 1, and treat the fastmap as bad otherwise, so UBI falls back to a full scan. Besides the four lists, this covers the pools and the locations of the fastmap blocks. An out-of-range number there is otherwise first passed to ubi_io_is_bad(), whose range assert is compiled out unless DEBUG is defined: on NAND it reaches the driver's bad block check through mtd_block_isbad(), which lets an offset equal to the device size through, and on flash without bad blocks, such as NOR, it returns 0 without looking at it. Where that lets it through, the read that follows fails the attach instead of falling back to a scan. Also, ubi_scan_fastmap() takes the block locations it keeps for wear leveling from the copy of the fastmap superblock at the start of the fastmap data, not from the anchor's copy checked first, and ubi_wl_init() indexes ubi->lookuptbl with them too, so check that copy as well. The EBA table needs no check of its own, as its PEB numbers are only looked up in the used list.

Linux has the same code, and the same check of the four lists has been proposed there.

Fixes ff94bc40af34 ("mtd, ubi, ubifs: resync with Linux-3.14")
---
 drivers/mtd/ubi/fastmap.c | 73 ++++++++++++++++++++++++++++++++-------
 1 file changed, 60 insertions(+), 13 deletions(-)
drivers/mtd/ubi/fastmap.c +60 -13
index 9c6b15b8cb5..bbf4247d1f4 100644
@@ -105,6 +105,31 @@ size_t ubi_calc_fm_size(struct ubi_device *ubi)
 	return roundup(size, ubi->leb_size);
 }
 
+/**
+ * read_pnum - read a PEB number from the fastmap and check it.
+ * @ubi: UBI device description object
+ * @pnum_be: the PEB number as stored on flash
+ * @out_pnum: the PEB number is stored here if it is valid
+ *
+ * The fastmap is read from flash, so a PEB number in it may be outside the
+ * device, and such a number must not be used as an index into UBI's tables.
+ *
+ * Returns %true and stores the PEB number in @out_pnum if it is valid,
+ * %false otherwise.
+ */
+static bool read_pnum(struct ubi_device *ubi, __be32 pnum_be, int *out_pnum)
+{
+	int pnum = be32_to_cpu(pnum_be);
+
+	if (pnum < 0 || pnum >= ubi->peb_count) {
+		ubi_err(ubi, "fastmap references PEB out of range: %i", pnum);
+		return false;
+	}
+
+	*out_pnum = pnum;
+	return true;
+}
+
 /**
  * new_fm_vhdr - allocate a new volume header for fastmap usage.
  * @ubi: UBI device description object
@@ -489,7 +514,10 @@ static int scan_pool(struct ubi_device *ubi, struct ubi_attach_info *ai,
 		int scrub = 0;
 		int image_seq;
 
-		pnum = be32_to_cpu(pebs[i]);
+		if (!read_pnum(ubi, pebs[i], &pnum)) {
+			ret = UBI_BAD_FASTMAP;
+			goto out;
+		}
 
 		if (ubi_io_is_bad(ubi, pnum)) {
 			ubi_err(ubi, "bad PEB in fastmap pool!");
@@ -616,7 +644,7 @@ static int ubi_attach_fastmap(struct ubi_device *ubi,
 	struct ubi_fm_ec *fmec;
 	struct ubi_fm_volhdr *fmvhdr;
 	struct ubi_fm_eba *fm_eba;
-	int ret, i, j, pool_size, wl_pool_size;
+	int ret, i, j, pool_size, wl_pool_size, pnum;
 	size_t fm_pos = 0, fm_size = ubi->fm_size;
 	unsigned long long max_sqnum = 0;
 	void *fm_raw = ubi->fm_buf;
@@ -697,8 +725,10 @@ static int ubi_attach_fastmap(struct ubi_device *ubi,
 		if (fm_pos >= fm_size)
 			goto fail_bad;
 
-		add_aeb(ai, &ai->free, be32_to_cpu(fmec->pnum),
-			be32_to_cpu(fmec->ec), 0);
+		if (!read_pnum(ubi, fmec->pnum, &pnum))
+			goto fail_bad;
+
+		add_aeb(ai, &ai->free, pnum, be32_to_cpu(fmec->ec), 0);
 	}
 
 	/* read EC values from used list */
@@ -708,8 +738,10 @@ static int ubi_attach_fastmap(struct ubi_device *ubi,
 		if (fm_pos >= fm_size)
 			goto fail_bad;
 
-		add_aeb(ai, &used, be32_to_cpu(fmec->pnum),
-			be32_to_cpu(fmec->ec), 0);
+		if (!read_pnum(ubi, fmec->pnum, &pnum))
+			goto fail_bad;
+
+		add_aeb(ai, &used, pnum, be32_to_cpu(fmec->ec), 0);
 	}
 
 	/* read EC values from scrub list */
@@ -719,8 +751,10 @@ static int ubi_attach_fastmap(struct ubi_device *ubi,
 		if (fm_pos >= fm_size)
 			goto fail_bad;
 
-		add_aeb(ai, &used, be32_to_cpu(fmec->pnum),
-			be32_to_cpu(fmec->ec), 1);
+		if (!read_pnum(ubi, fmec->pnum, &pnum))
+			goto fail_bad;
+
+		add_aeb(ai, &used, pnum, be32_to_cpu(fmec->ec), 1);
 	}
 
 	/* read EC values from erase list */
@@ -730,8 +764,10 @@ static int ubi_attach_fastmap(struct ubi_device *ubi,
 		if (fm_pos >= fm_size)
 			goto fail_bad;
 
-		add_aeb(ai, &ai->erase, be32_to_cpu(fmec->pnum),
-			be32_to_cpu(fmec->ec), 1);
+		if (!read_pnum(ubi, fmec->pnum, &pnum))
+			goto fail_bad;
+
+		add_aeb(ai, &ai->erase, pnum, be32_to_cpu(fmec->ec), 1);
 	}
 
 	ai->mean_ec = div_u64(ai->ec_sum, ai->ec_count);
@@ -781,7 +817,7 @@ static int ubi_attach_fastmap(struct ubi_device *ubi,
 		}
 
 		for (j = 0; j < be32_to_cpu(fm_eba->reserved_pebs); j++) {
-			int pnum = be32_to_cpu(fm_eba->pnum[j]);
+			pnum = be32_to_cpu(fm_eba->pnum[j]);
 
 			if ((int)be32_to_cpu(fm_eba->pnum[j]) < 0)
 				continue;
@@ -954,7 +990,10 @@ int ubi_scan_fastmap(struct ubi_device *ubi, struct ubi_attach_info *ai,
 	for (i = 0; i < used_blocks; i++) {
 		int image_seq;
 
-		pnum = be32_to_cpu(fmsb->block_loc[i]);
+		if (!read_pnum(ubi, fmsb->block_loc[i], &pnum)) {
+			ret = UBI_BAD_FASTMAP;
+			goto free_hdr;
+		}
 
 		if (ubi_io_is_bad(ubi, pnum)) {
 			ret = UBI_BAD_FASTMAP;
@@ -1052,6 +1091,14 @@ int ubi_scan_fastmap(struct ubi_device *ubi, struct ubi_attach_info *ai,
 	for (i = 0; i < used_blocks; i++) {
 		struct ubi_wl_entry *e;
 
+		if (!read_pnum(ubi, fmsb2->block_loc[i], &pnum)) {
+			while (i--)
+				kfree(fm->e[i]);
+
+			ret = UBI_BAD_FASTMAP;
+			goto free_hdr;
+		}
+
 		e = kmem_cache_alloc(ubi_wl_entry_slab, GFP_KERNEL);
 		if (!e) {
 			while (i--)
@@ -1061,7 +1108,7 @@ int ubi_scan_fastmap(struct ubi_device *ubi, struct ubi_attach_info *ai,
 			goto free_hdr;
 		}
 
-		e->pnum = be32_to_cpu(fmsb2->block_loc[i]);
+		e->pnum = pnum;
 		e->ec = be32_to_cpu(fmsb2->block_ec[i]);
 		fm->e[i] = e;
 	}
Reviewed-by on v1 4/6
#8 lore raw

Re: [PATCH 4/6] mtd: ubi: fastmap: check PEB numbers read from the fastmap

Hello Ana,

Quoted 28 lines · Ana Bobillo

From: Ana Bobillo <[email protected]>

The fastmap lists the PEBs of the device with their erase counters, and ubi_attach_fastmap() passes the numbers in its free, used, scrub and erase lists to add_aeb() as they are on flash. ubi_wl_init() then uses each of them as an index into ubi->lookuptbl, which has room for ubi->peb_count entries, and stores a pointer there. So a fastmap with a PEB number outside the device makes UBI write past the end of the table, or before its start for a negative number. The CRC over the fastmap doesn't protect against a fastmap that was written that way.

Check every PEB number taken from the fastmap with one helper that accepts only 0 to peb_count - 1, and treat the fastmap as bad otherwise, so UBI falls back to a full scan. Besides the four lists, this covers the pools and the locations of the fastmap blocks. An out-of-range number there is otherwise first passed to ubi_io_is_bad(), whose range assert is compiled out unless DEBUG is defined: on NAND it reaches the driver's bad block check through mtd_block_isbad(), which lets an offset equal to the device size through, and on flash without bad blocks, such as NOR, it returns 0 without looking at it. Where that lets it through, the read that follows fails the attach instead of falling back to a scan. Also, ubi_scan_fastmap() takes the block locations it keeps for wear leveling from the copy of the fastmap superblock at the start of the fastmap data, not from the anchor's copy checked first, and ubi_wl_init() indexes ubi->lookuptbl with them too, so check that copy as well. The EBA table needs no check of its own, as its PEB numbers are only looked up in the used list.

Quoted 8 lines

Linux has the same code, and the same check of the four lists has been proposed there.

Fixes ff94bc40af34 ("mtd, ubi, ubifs: resync with Linux-3.14")
---
  drivers/mtd/ubi/fastmap.c | 73 ++++++++++++++++++++++++++++++++-------
  1 file changed, 60 insertions(+), 13 deletions(-)

Thanks!

bye,
Heiko

Signature · 5 lines
Nabla Software Engineering
HRB 40522 Augsburg
Phone: +49 821 45592596
E-Mail: [email protected]
Geschäftsführer : Stefano Babic
#9 lore raw

PATCH 5/6 mtd: ubi: fastmap: bound the size of a volume's EBA table

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

ubi_attach_fastmap() reads each volume's EBA table header, then advances fm_pos by four bytes for each of its reserved_pebs entries and checks that the result is still within the fastmap. Two things are missing:

- The header itself is read without checking that it fits into the fastmap first.
- On 32-bit builds, fm_pos is 32 bits wide, so a large enough reserved_pebs makes the multiplication wrap around and the check pass. The loop that follows then reads up to reserved_pebs entries past the end of the fastmap buffer.

Check fm_pos after the header, and reject a volume that reserves more PEBs than the device has before using the count, which also keeps the multiplication from wrapping.

The SPL loader's ubi_attach_fastmap() in drivers/mtd/ubispl parses the EBA tables the same way, and most boards that use it are 32-bit, so make the same change there.

Fixes ff94bc40af34 ("mtd, ubi, ubifs: resync with Linux-3.14")
Fixes 6f4e7d3c75a8 ("spl: Lightweight UBI and UBI fastmap support")
---
 drivers/mtd/ubi/fastmap.c   | 14 ++++++++++++++
 drivers/mtd/ubispl/ubispl.c | 17 +++++++++++++++--
 2 files changed, 29 insertions(+), 2 deletions(-)
drivers/mtd/ubi/fastmap.c +14 -0
index bbf4247d1f4..ed9adfa5209 100644
@@ -806,6 +806,20 @@ static int ubi_attach_fastmap(struct ubi_device *ubi,
 
 		fm_eba = (struct ubi_fm_eba *)(fm_raw + fm_pos);
 		fm_pos += sizeof(*fm_eba);
+		if (fm_pos >= fm_size)
+			goto fail_bad;
+
+		/*
+		 * A volume cannot reserve more PEBs than the device has, and
+		 * bounding the count first keeps the multiplication below
+		 * from wrapping around on 32-bit builds.
+		 */
+		if (be32_to_cpu(fm_eba->reserved_pebs) > ubi->peb_count) {
+			ubi_err(ubi, "bad fastmap EBA reserved PEBs: %u",
+				be32_to_cpu(fm_eba->reserved_pebs));
+			goto fail_bad;
+		}
+
 		fm_pos += (sizeof(__be32) * be32_to_cpu(fm_eba->reserved_pebs));
 		if (fm_pos >= fm_size)
 			goto fail_bad;
drivers/mtd/ubispl/ubispl.c +15 -2
index c3b964b64dd..9293dd489a5 100644
@@ -612,7 +612,21 @@ static int ubi_attach_fastmap(struct ubi_scan_info *ubi,
 
 		fm_eba = (struct ubi_fm_eba *)(fm_raw + fm_pos);
 		fm_pos += sizeof(*fm_eba);
-		fm_pos += (sizeof(__be32) * be32_to_cpu(fm_eba->reserved_pebs));
+		if (fm_pos >= fm_size)
+			goto fail_bad;
+
+		/*
+		 * A volume cannot reserve more PEBs than the device has, and
+		 * bounding the count first keeps the multiplication below
+		 * from wrapping around on 32-bit builds.
+		 */
+		reserved = be32_to_cpu(fm_eba->reserved_pebs);
+		if (reserved > ubi->peb_count) {
+			ubi_err("bad fastmap EBA reserved PEBs: %u", reserved);
+			goto fail_bad;
+		}
+
+		fm_pos += sizeof(__be32) * reserved;
 		if (fm_pos >= fm_size)
 			goto fail_bad;
 
@@ -623,7 +637,6 @@ static int ubi_attach_fastmap(struct ubi_scan_info *ubi,
 			goto fail_bad;
 		}
 
-		reserved = be32_to_cpu(fm_eba->reserved_pebs);
 		ubi_dbg("FA: vol %u used %u res: %u", vol_id, used, reserved);
 		for (j = 0; j < reserved; j++) {
 			int pnum = be32_to_cpu(fm_eba->pnum[j]);
Reviewed-by on v1 5/6
#10 lore raw

Re: [PATCH 5/6] mtd: ubi: fastmap: bound the size of a volume's EBA table

Hello Ana,

Quoted 21 lines · Ana Bobillo

From: Ana Bobillo <[email protected]>

ubi_attach_fastmap() reads each volume's EBA table header, then advances fm_pos by four bytes for each of its reserved_pebs entries and checks that the result is still within the fastmap. Two things are missing:

- The header itself is read without checking that it fits into the fastmap first.
- On 32-bit builds, fm_pos is 32 bits wide, so a large enough reserved_pebs makes the multiplication wrap around and the check pass. The loop that follows then reads up to reserved_pebs entries past the end of the fastmap buffer.

Check fm_pos after the header, and reject a volume that reserves more PEBs than the device has before using the count, which also keeps the multiplication from wrapping.

The SPL loader's ubi_attach_fastmap() in drivers/mtd/ubispl parses the EBA tables the same way, and most boards that use it are 32-bit, so make the same change there.

Quoted 7 lines
Fixes ff94bc40af34 ("mtd, ubi, ubifs: resync with Linux-3.14")
Fixes 6f4e7d3c75a8 ("spl: Lightweight UBI and UBI fastmap support")
---
  drivers/mtd/ubi/fastmap.c   | 14 ++++++++++++++
  drivers/mtd/ubispl/ubispl.c | 17 +++++++++++++++--
  2 files changed, 29 insertions(+), 2 deletions(-)

Thanks!

bye,
Heiko

Signature · 5 lines
Nabla Software Engineering
HRB 40522 Augsburg
Phone: +49 821 45592596
E-Mail: [email protected]
Geschäftsführer : Stefano Babic
#11 lore raw

PATCH 6/6 mtd: ubi: vtbl: check the size of a static volume's last LEB

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

check_av() checks what attaching found out about a volume against its volume table record, but not how much data the last LEB of a static volume holds. That size comes from the VID header of the last LEB when UBI scans the device, where it is only checked against the LEB size, not against the smaller usable LEB size of a volume with data padding. When UBI attaches by fastmap, the size taken from the fastmap's volume header is not checked at all.

init_volumes() adds this size to the volume's used_bytes. 'ubi read' and ubi_volume_read(), which the UBI block device also uses, read up to used_bytes, map each offset to a LEB and pass it to ubi_eba_read_leb(), which looks it up in the volume's EBA table without a bounds check. So, for a volume that uses all its reserved LEBs, a last LEB larger than the usable LEB size makes the end of the volume map to an entry past the end of the table, and a larger size from a fastmap moves that entry further out.

Reject a static volume whose last LEB holds a negative amount of data or more than the usable LEB size, the bounds self_check_volume() expects. UBI writers, U-Boot's and Linux's as well as ubinize, stay within them.

Add a test which writes a static volume with data padding, filling its one LEB to the usable LEB size, checks that it attaches and reads back, then sets the data_size of that LEB one byte larger, which still fits in the LEB, and checks that attaching fails.

Fixes c91a719daa33 ("UBI: Add basic UBI support to U-Boot (Part 5/8)")
---
 drivers/mtd/ubi/vtbl.c |  6 ++++
 test/dm/ubi.c          | 70 ++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 76 insertions(+)
drivers/mtd/ubi/vtbl.c +6 -0
index a2b5352cb2d..4a2b6e7fa6f 100644
@@ -693,6 +693,12 @@ static int check_av(const struct ubi_volume *vol,
 		err = 5;
 		goto bad;
 	}
+	if (vol->vol_type == UBI_STATIC_VOLUME &&
+	    (av->last_data_size < 0 ||
+	     av->last_data_size > vol->usable_leb_size)) {
+		err = 6;
+		goto bad;
+	}
 	return 0;
 
 bad:
test/dm/ubi.c +70 -0

73 lines not on this page · raw message

Reviewed-by on v1 6/6
#12 lore raw

Re: [PATCH 6/6] mtd: ubi: vtbl: check the size of a static volume's last LEB

Hello Ana,

Quoted 28 lines · Ana Bobillo

From: Ana Bobillo <[email protected]>

check_av() checks what attaching found out about a volume against its volume table record, but not how much data the last LEB of a static volume holds. That size comes from the VID header of the last LEB when UBI scans the device, where it is only checked against the LEB size, not against the smaller usable LEB size of a volume with data padding. When UBI attaches by fastmap, the size taken from the fastmap's volume header is not checked at all.

init_volumes() adds this size to the volume's used_bytes. 'ubi read' and ubi_volume_read(), which the UBI block device also uses, read up to used_bytes, map each offset to a LEB and pass it to ubi_eba_read_leb(), which looks it up in the volume's EBA table without a bounds check. So, for a volume that uses all its reserved LEBs, a last LEB larger than the usable LEB size makes the end of the volume map to an entry past the end of the table, and a larger size from a fastmap moves that entry further out.

Reject a static volume whose last LEB holds a negative amount of data or more than the usable LEB size, the bounds self_check_volume() expects. UBI writers, U-Boot's and Linux's as well as ubinize, stay within them.

Add a test which writes a static volume with data padding, filling its one LEB to the usable LEB size, checks that it attaches and reads back, then sets the data_size of that LEB one byte larger, which still fits in the LEB, and checks that attaching fails.

Quoted 6 lines
Fixes c91a719daa33 ("UBI: Add basic UBI support to U-Boot (Part 5/8)")
---
  drivers/mtd/ubi/vtbl.c |  6 ++++
  test/dm/ubi.c          | 70 ++++++++++++++++++++++++++++++++++++++++++
  2 files changed, 76 insertions(+)

Thanks (for your whole patchset, nice findings)!

checkpatch is clean on all six, they apply and build fine, and I ran the sandbox tests, both new ones pass, started a CI run...

bye,
Heiko

Signature · 5 lines
Nabla Software Engineering
HRB 40522 Augsburg
Phone: +49 821 45592596
E-Mail: [email protected]
Geschäftsführer : Stefano Babic