Skip to contentSkip to conversation

block, disk: Check block sizes and partition tables of devices

PATCH RESEND Superseded Ana Bobillo 3 participants 22 messages Oct 24 – Oct 27

Subsystems (4)

v1 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

cover block, disk: Check block sizes and partition tables of devices

This is a resend of the series posted earlier today, now with the patches inline: the first posting carried them as attachments, which b4 and Patchwork cannot use, as Heinrich pointed out. The patches are unchanged and still apply to master.

U-Boot scans the partitions of a block device as soon as it probes it, and takes several sizes from the device and from its partition tables as they are. A USB stick or SD card that U-Boot merely probes can therefore make it read or write outside its buffers. This series checks those sizes where they are read.

Block size. A block driver sets the block size of a device from what the device reports, and only the virtio block driver and the host command check it. The partition and filesystem code sizes buffers by the block size, expects a block to hold a 512-byte boot sector and converts between bytes and blocks with log2(blksz). So a USB stick, SCSI disk, ATAPI drive or NVMe namespace reporting a block size below 512 bytes, one that is not a power of two or a huge one makes U-Boot read or write outside its buffers, in the partition scan run when the device is probed and in the filesystem code after it.

Patch 1 adds blk_valid_blksz() and has blk_post_probe() refuse a block device whose block size it rejects, which covers every block driver. Patches 2-5 check the block size where the USB storage, SCSI, IDE (ATAPI) and NVMe drivers read it, so that each refuses such a device
cleanly: the USB LUN is skipped instead of failing the whole stick, no SCSI block device is created, the ATAPI drive is treated as one without a medium and the NVMe namespace is skipped like an inactive one.

The upper bound is 64KiB, the largest logical block size Linux accepts; the GPT code is already tested with block sizes up to 32KiB.

Partition tables. Patch 6 checks the header size and the size of the partition entry array of a GPT, as Linux does, before they size the CRC of the header and the entry buffer. It leaves alloc_read_gpt_entries() alone, so it applies with or without Benoît Monin's "disk: efi: Reuse the GPT entries buffer with simple malloc". Patch 7 walks the chain of DOS extended partition tables in a loop, bounded by the number of tables read: a table linking back to itself adds no partition, so the limit added for CVE-2019-13103 did not stop the recursion. Patch 8 makes room for partition number 256 in the UUID made up for a DOS partition. Patch 9 has the TCG2 measurement of the GPT check the primary header it reads itself with validate_gpt_header(), now exported: the partition driver falls back to the backup header when the primary one is not valid, so the measurement could still take its sizes from a primary header that the driver refused.

Patches 1-3 and 6-9 add tests: DM tests on sandbox, for the GPT a test in test/lib on a blkmap device, and for the TCG2 measurement a test in test/py that starts an EFI application from a GPT disk on sandbox and checks PCR 5. Without the series the new tests fail; with it they pass, as do the rest of "ut dm" and "ut lib" on sandbox_defconfig with CONFIG_ASAN (but for lib_crypt, which ASan flags without the series too), and every patch builds on its own. The test/py test is skipped with CONFIG_ASAN, under which sandbox cannot run an EFI application; on sandbox_defconfig it passes, as do the other EFI, TPM and GPT tests in test/py. The IDE and NVMe changes are build tested only, as sandbox has no emulator for them.

Ana Bobillo (9):
block: Refuse a device with an unsupported block size
usb: storage: Refuse a block size the block layer cannot use
scsi: Refuse a block size the block layer cannot use
ide: Refuse an ATAPI block size atapi_read() cannot read
nvme: Skip a namespace with an unsupported LBA data size
disk: part_efi: Check the header and entry sizes of a GPT
disk: part_dos: Walk the extended partition tables in a bounded loop
disk: part_dos: Make room for a three-digit partition number in the
UUID
efi_loader: Check the GPT header before measuring it

 arch/sandbox/include/asm/test.h  |  20 ++++
 cmd/host.c                       |   6 +-
 common/usb_storage.c             |   8 +-
 disk/part_dos.c                  |  47 ++++++---
 disk/part_efi.c                  |  48 +++++++--
 drivers/block/blk-uclass.c       |  15 ++-
 drivers/block/ide.c              |  11 +-
 drivers/nvme/nvme.c              |  33 +++++-
 drivers/scsi/sandbox_scsi.c      |   8 ++
 drivers/scsi/scsi.c              |   4 +
 drivers/usb/emul/sandbox_flash.c |   8 ++
 drivers/virtio/virtio_blk.c      |   3 +-
 include/blk.h                    |  20 ++++
 include/part.h                   |  23 +++++
 lib/efi_loader/efi_tcg2.c        |  16 +++
 test/dm/blk.c                    |  41 ++++++++
 test/dm/part.c                   | 146 ++++++++++++++++++++++++++
 test/dm/scsi.c                   |  37 +++++++
 test/dm/usb.c                    |  45 ++++++++
 test/lib/part_efi.c              | 161 +++++++++++++++++++++++++++++
 test/py/tests/test_efi_tcg2.py   | 170 +++++++++++++++++++++++++++++++
 21 files changed, 839 insertions(+), 31 deletions(-)
 create mode 100644 test/py/tests/test_efi_tcg2.py

base-commit: acc808479730e13e74199119eb9b2b9113999244

#1 lore raw

PATCH RESEND 1/9 block: Refuse a device with an unsupported block size

From: Ana Bobillo <[email protected]>

A block driver sets blksz and log2blksz from what the device reports: the READ CAPACITY reply of a USB stick or a SCSI disk, the LBA format of an NVMe namespace, the sector size of a Xen backend. Apart from the virtio block driver and the host command, nothing checks the value before blk_post_probe() scans the device for partitions, yet the partition and filesystem code relies on it:

- part_get_info_extended() and print_partition_extended() read one block into a buffer of blksz bytes and parse the partition table at offset 0x1be, past the end of a block smaller than 512 bytes
- fs_devread() converts bytes to blocks with shifts by log2blksz, masks by blksz - 1 and divisions by blksz, which only agree when blksz is a power of two; with any other value it reads more bytes into the caller's buffer than the caller asked for
- buffers of blksz bytes go on the stack, so a block size in the gigabytes overruns it

Add blk_valid_blksz(), which accepts a power of two from 512 bytes up to BLK_MAX_BLKSZ (64KiB, the largest logical block size Linux accepts), and refuse to probe a block device whose block size it rejects, or whose log2blksz does not match its blksz, before its partitions are scanned. This covers every block driver in one place.

A device with neither a size nor a block size, which is how the SCSI code leaves a removable drive without a medium, is still probed, but its partitions are no longer scanned: part_test_dos() would otherwise parse 512 bytes of a zero-sized buffer.

Use the helper in the virtio block driver and the host command too, so that they also refuse a block size above 64KiB.

---
 cmd/host.c                  |  6 +++---
 drivers/block/blk-uclass.c  | 15 ++++++++++++--
 drivers/virtio/virtio_blk.c |  3 +--
 include/blk.h               | 20 ++++++++++++++++++
 test/dm/blk.c               | 41 +++++++++++++++++++++++++++++++++++++
 5 files changed, 78 insertions(+), 7 deletions(-)
cmd/host.c +3 -3
index 51f2b1e3f6e..6a715bed39d 100644
@@ -13,7 +13,6 @@
 #include <dm/device-internal.h>
 #include <dm/uclass-internal.h>
 #include <linux/errno.h>
-#include <linux/log2.h>
 
 static int do_host_load(struct cmd_tbl *cmdtp, int flag, int argc,
 			char *const argv[])
@@ -67,8 +66,9 @@ static int do_host_bind(struct cmd_tbl *cmdtp, int flag, int argc,
 	file = argv[1];
 	if (argc > 2) {
 		blksz = dectoul(argv[2], NULL);
-		if (blksz < DEFAULT_BLKSZ || !is_power_of_2(blksz)) {
-			printf("blksz must be >= 512 and power of 2\n");
+		if (!blk_valid_blksz(blksz)) {
+			printf("blksz must be a power of 2 from %d to %d\n",
+			       DEFAULT_BLKSZ, BLK_MAX_BLKSZ);
 			return CMD_RET_FAILURE;
 		}
 	}
drivers/block/blk-uclass.c +13 -2
index 6d2161cfc7b..d7b946f2dbc 100644
@@ -828,9 +828,20 @@ static int part_create_block_devices(struct udevice *blk_dev)
 
 static int blk_post_probe(struct udevice *dev)
 {
-	if (CONFIG_IS_ENABLED(PARTITIONS) && blk_enabled()) {
-		struct blk_desc *desc = dev_get_uclass_plat(dev);
+	struct blk_desc *desc = dev_get_uclass_plat(dev);
+
+	/* A removable device without a medium has no size yet */
+	if (!desc->blksz && !desc->lba)
+		return 0;
+
+	if (!blk_valid_blksz(desc->blksz) ||
+	    desc->log2blksz != LOG2(desc->blksz)) {
+		log_err("%s: unsupported block size %lu (log2 %d)\n",
+			dev->name, desc->blksz, desc->log2blksz);
+		return -EINVAL;
+	}
 
+	if (CONFIG_IS_ENABLED(PARTITIONS) && blk_enabled()) {
 		part_init(desc);
 
 		if (desc->part_type != PART_TYPE_UNKNOWN &&
drivers/virtio/virtio_blk.c +1 -2
index 404d9140cb2..98bfc8369cc 100644
@@ -12,7 +12,6 @@
 #include <virtio_types.h>
 #include <virtio.h>
 #include <virtio_ring.h>
-#include <linux/log2.h>
 #include <linux/err.h>
 #include "virtio_blk.h"
 #include <malloc.h>
@@ -263,7 +262,7 @@ static int virtio_blk_probe(struct udevice *dev)
 	if (virtio_has_feature(dev, VIRTIO_BLK_F_BLK_SIZE)) {
 		virtio_cread(dev, struct virtio_blk_config, blk_size, &blk_size);
 		desc->blksz = blk_size;
-		if (!is_power_of_2(blk_size) || desc->blksz < 512)
+		if (!blk_valid_blksz(blk_size))
 			return -EIO;
 	} else {
 		desc->blksz = 512;
include/blk.h +20 -0
index 2cb9cb31ac2..d7efb6012ee 100644
@@ -10,6 +10,7 @@
 #include <bouncebuf.h>
 #include <dm/uclass-id.h>
 #include <efi.h>
+#include <linux/sizes.h>
 
 #ifdef CONFIG_SYS_64BIT_LBA
 typedef uint64_t lbaint_t;
@@ -22,9 +23,28 @@ typedef ulong lbaint_t;
 #define LBAFU "%" LBAFlength "u"
 
 #define DEFAULT_BLKSZ		512
+/* Largest block size supported, as in Linux */
+#define BLK_MAX_BLKSZ		SZ_64K
 
 struct udevice;
 
+/**
+ * blk_valid_blksz() - Check that a block size is supported
+ *
+ * The block, partition and filesystem code size buffers by the block size,
+ * expect a block to hold at least a 512-byte boot sector and convert between
+ * bytes and blocks with log2(block size), so a device is only usable with a
+ * block size that is a power of two from DEFAULT_BLKSZ to BLK_MAX_BLKSZ.
+ *
+ * @blksz: Block size in bytes
+ * Return: true if @blksz is supported, false if not
+ */
+static inline bool blk_valid_blksz(unsigned long blksz)
+{
+	return blksz >= DEFAULT_BLKSZ && blksz <= BLK_MAX_BLKSZ &&
+	       !(blksz & (blksz - 1));
+}
+
 static inline bool blk_enabled(void)
 {
 	return CONFIG_IS_ENABLED(BLK) || IS_ENABLED(CONFIG_SPL_LEGACY_BLOCK);
test/dm/blk.c +41 -0

53 lines not on this page · raw message

#2 lore raw

Re: [PATCH RESEND 1/9] block: Refuse a device with an unsupported block size

Hi Ana,

Quoted 31 lines · Ana Bobillo

block: Refuse a device with an unsupported block size

A block driver sets blksz and log2blksz from what the device reports: the READ CAPACITY reply of a USB stick or a SCSI disk, the LBA format of an NVMe namespace, the sector size of a Xen backend. Apart from the virtio block driver and the host command, nothing checks the value before blk_post_probe() scans the device for partitions, yet the partition and filesystem code relies on it:

- part_get_info_extended() and print_partition_extended() read one block into a buffer of blksz bytes and parse the partition table at offset 0x1be, past the end of a block smaller than 512 bytes
- fs_devread() converts bytes to blocks with shifts by log2blksz, masks by blksz - 1 and divisions by blksz, which only agree when blksz is a power of two; with any other value it reads more bytes into the caller's buffer than the caller asked for
- buffers of blksz bytes go on the stack, so a block size in the gigabytes overruns it

Add blk_valid_blksz(), which accepts a power of two from 512 bytes up to [...]

 cmd/host.c                  |  6 +++---
 drivers/block/blk-uclass.c  | 15 +++++++++++++--
 drivers/virtio/virtio_blk.c |  3 +--
 include/blk.h               | 20 ++++++++++++++++++++
 test/dm/blk.c               | 41 +++++++++++++++++++++++++++++++++++++++++
 5 files changed, 78 insertions(+), 7 deletions(-)

include/blk.h typedef ulong lbaint_t; · line 27

Quoted 5 lines
include/blk.h +5 -0
@@ -22,9 +23,28 @@ typedef ulong lbaint_t;
+static inline bool blk_valid_blksz(unsigned long blksz)
+{
+	return blksz >= DEFAULT_BLKSZ && blksz <= BLK_MAX_BLKSZ &&
+	       !(blksz & (blksz - 1));
+}

Please can you use is_power_of_2() from linux/log2.h here? The two callers you convert already use it, so this keeps the same check rather than adding a second copy, and you can leave the linux/log2.h includes in cmd/host.c and virtio_blk.c alone.

drivers/block/blk-uclass.c static int part_create_block_devices(struct udevice *blk_dev) · line 833

Quoted 8 lines
drivers/block/blk-uclass.c +6 -0
@@ -828,9 +828,20 @@ static int part_create_block_devices(struct udevice *blk_dev)
+	if (!blk_valid_blksz(desc->blksz) ||
+	    desc->log2blksz != LOG2(desc->blksz)) {
+		log_err("%s: unsupported block size %lu (log2 %d)\n",
+			dev->name, desc->blksz, desc->log2blksz);
+		return -EINVAL;
+	}

Just to check, have you looked at the code-size impact? The check now sits outside the PARTITIONS condition, so every SPL with BLK picks it up, along with the message, even when SPL_PARTITIONS is off. I think that is right, since the SPL FAT/ext4 code relies on blksz too, but it would be worth saying so in the commit message so that nobody moves it back inside the condition.

Regards,
Simon

#3 lore raw

PATCH RESEND 2/9 usb: storage: Refuse a block size the block layer cannot use

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

usb_stor_get_info() takes the block size from the READ CAPACITY reply of the device as it is. With the block layer now refusing an unsupported block size, such a device would fail to probe in blk_post_probe(), and usb_stor_probe_device() would stop there, skipping the other LUNs of the device.

Check the block size where it is read, and treat a LUN reporting one that blk_valid_blksz() rejects as unusable, as for a LUN that is not ready. This also covers the legacy (non-BLK) path, which calls part_init() itself.

The fallback used when READ CAPACITY fails sets the reply in host byte order, while it is read back as big endian, so on a little-endian host the device got a block size of 128KiB rather than 512 bytes. Set it in big endian like the reply it stands in for.

Add a test where the sandbox flash stick reports an unsupported block size.

---
 arch/sandbox/include/asm/test.h  | 10 +++++++
 common/usb_storage.c             |  8 ++++--
 drivers/usb/emul/sandbox_flash.c |  8 ++++++
 test/dm/usb.c                    | 45 ++++++++++++++++++++++++++++++++
 4 files changed, 69 insertions(+), 2 deletions(-)
arch/sandbox/include/asm/test.h +10 -0
index 0438790028b..e5590d01a92 100644
@@ -123,6 +123,16 @@ long sandbox_i2c_rtc_get_set_base_time(struct udevice *dev, long base_time);
 
 int sandbox_usb_keyb_add_string(struct udevice *dev, const char *str);
 
+/**
+ * sandbox_flash_set_block_size() - Set the block size a flash stick reports
+ *
+ * @dev:	USB flash-stick emulator
+ * @block_size:	Block size in bytes
+ *
+ * The host reads it when it next probes the stick's mass-storage device.
+ */
+void sandbox_flash_set_block_size(struct udevice *dev, int block_size);
+
 /**
  * sandbox_osd_get_mem() - get the internal memory of a sandbox OSD
  *
common/usb_storage.c +6 -2
index ac331f1c1b0..49acae26724 100644
@@ -1496,8 +1496,8 @@ int usb_stor_get_info(struct usb_device *dev, struct us_data *ss,
 	if (usb_read_capacity(pccb, ss) != 0) {
 		printf("READ_CAP ERROR\n");
 		ss->flags &= ~USB_READY;
-		cap[0] = 2880;
-		cap[1] = 0x200;
+		cap[0] = cpu_to_be32(2880);
+		cap[1] = cpu_to_be32(0x200);
 	}
 	debug("Read Capacity returns: 0x%08x, 0x%08x\n", cap[0], cap[1]);
 #if 0
@@ -1512,6 +1512,10 @@ int usb_stor_get_info(struct usb_device *dev, struct us_data *ss,
 	blksz = be32_to_cpu(cap[1]);
 
 	debug("Capacity = 0x%08x, blocksz = 0x%08x\n", capacity, blksz);
+	if (!blk_valid_blksz(blksz)) {
+		printf("Unsupported block size %u\n", blksz);
+		return 0;
+	}
 	dev_desc->lba = capacity;
 	dev_desc->blksz = blksz;
 	dev_desc->log2blksz = LOG2(dev_desc->blksz);
drivers/usb/emul/sandbox_flash.c +8 -0
index b5176bb30ce..02e0901050f 100644
@@ -13,6 +13,7 @@
 #include <scsi.h>
 #include <scsi_emul.h>
 #include <usb.h>
+#include <asm/test.h>
 
 /*
  * This driver emulates a flash stick using the UFI command specification and
@@ -357,6 +358,13 @@ static int sandbox_flash_probe(struct udevice *dev)
 	return 0;
 }
 
+void sandbox_flash_set_block_size(struct udevice *dev, int block_size)
+{
+	struct sandbox_flash_priv *priv = dev_get_priv(dev);
+
+	priv->eminfo.block_size = block_size;
+}
+
 static int sandbox_flash_remove(struct udevice *dev)
 {
 	struct sandbox_flash_priv *priv = dev_get_priv(dev);
test/dm/usb.c +45 -0

51 lines not on this page · raw message

#4 lore raw

Re: [PATCH RESEND 2/9] usb: storage: Refuse a block size the block layer cannot use

Hi Ana,

Quoted 13 lines · Ana Bobillo

usb: storage: Refuse a block size the block layer cannot use

usb_stor_get_info() takes the block size from the READ CAPACITY reply of the device as it is. With the block layer now refusing an unsupported block size, such a device would fail to probe in blk_post_probe(), and usb_stor_probe_device() would stop there, skipping the other LUNs of the device.

Check the block size where it is read, and treat a LUN reporting one that blk_valid_blksz() rejects as unusable, as for a LUN that is not ready. This also covers the legacy (non-BLK) path, which calls part_init() itself.

Quoted 4 lines

The fallback used when READ CAPACITY fails sets the reply in host byte order, while it is read back as big endian, so on a little-endian host the device got a block size of 128KiB rather than 512 bytes. Set it in big endian like the reply it stands in for.

This is a separate bug that predates the series, so please can you put it in its own patch before this one, with a Fixes: tag. The capacity changes too: before, be32_to_cpu(2880) + 1 gives about 1G blocks on a little-endian host and now it gives 2881, which the commit message should mention. Also, 2880 goes where READ CAPACITY returns the last LBA, so this fakes 2881 blocks, not the 2880 of a 1.44MB floppy. That may be worth fixing in the same patch.

common/usb_storage.c int usb_stor_get_info(struct usb_device *dev, struct us_data *ss, · line 1515

Quoted 6 lines
common/usb_storage.c +4 -0
@@ -1512,6 +1512,10 @@ int usb_stor_get_info(struct usb_device *dev, struct us_data *ss,
+	if (!blk_valid_blksz(blksz)) {
+		printf("Unsupported block size %u\n", blksz);
+		return 0;
+	}

Since the point is to skip one LUN and keep the others, it would be worth including the LUN (dev_desc->lun) in the message so the user can tell which one was dropped.

test/dm/usb.c static int dm_test_usb_flash(struct unit_test_state *uts) · line 88

Quoted 7 lines
test/dm/usb.c +5 -0
@@ -84,6 +84,51 @@ static int dm_test_usb_flash(struct unit_test_state *uts)
+		ret = device_find_first_child_by_uclass(dev, UCLASS_BLK, &blk);
+		if (!cases[i].ok) {
+			ut_asserteq(-ENODEV, ret);
+			continue;
+		}

You could add UTF_CONSOLE and check for the 'Unsupported block size' line here, to show that usb_stor_get_info() refuses the LUN and not something further along. This is not blocking.

Quoted 10 lines

Add a test where the sandbox flash stick reports an unsupported block size.
[...]

 arch/sandbox/include/asm/test.h  | 10 +++++++++
 common/usb_storage.c             |  8 +++++--
 drivers/usb/emul/sandbox_flash.c |  8 +++++++
 test/dm/usb.c                    | 45 ++++++++++++++++++++++++++++++++++++++++
 4 files changed, 69 insertions(+), 2 deletions(-)

Regards,
Simon

#5 lore raw

PATCH RESEND 3/9 scsi: Refuse a block size the block layer cannot use

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

scsi_detect_dev() takes the block size from the READ CAPACITY reply of the device as it is. do_scsi_scan_one() then hands it to blk_create_devicef() as an int, which drops the upper bits of the unsigned long, so the block layer may not even see the value the device reported.

Check the block size where it is read, so that no block device is created for a disk reporting one that blk_valid_blksz() rejects.

Add a test where the sandbox SCSI disk reports an unsupported block size.

---
 arch/sandbox/include/asm/test.h | 10 +++++++++
 drivers/scsi/sandbox_scsi.c     |  8 +++++++
 drivers/scsi/scsi.c             |  4 ++++
 test/dm/scsi.c                  | 37 +++++++++++++++++++++++++++++++++
 4 files changed, 59 insertions(+)
arch/sandbox/include/asm/test.h +10 -0
index e5590d01a92..76e2f11b059 100644
@@ -133,6 +133,16 @@ int sandbox_usb_keyb_add_string(struct udevice *dev, const char *str);
  */
 void sandbox_flash_set_block_size(struct udevice *dev, int block_size);
 
+/**
+ * sandbox_scsi_set_block_size() - Set the block size a SCSI disk reports
+ *
+ * @dev:	Sandbox SCSI controller
+ * @block_size:	Block size in bytes
+ *
+ * The host reads it when it next scans the bus.
+ */
+void sandbox_scsi_set_block_size(struct udevice *dev, int block_size);
+
 /**
  * sandbox_osd_get_mem() - get the internal memory of a sandbox OSD
  *
drivers/scsi/sandbox_scsi.c +8 -0
index 5f0b01d86d5..34fc7cda915 100644
@@ -14,6 +14,7 @@
 #include <malloc.h>
 #include <scsi.h>
 #include <scsi_emul.h>
+#include <asm/test.h>
 
 enum {
 	SANDBOX_SCSI_BLOCK_LEN		= 512,
@@ -118,6 +119,13 @@ static int sandbox_scsi_probe(struct udevice *dev)
 	return 0;
 }
 
+void sandbox_scsi_set_block_size(struct udevice *dev, int block_size)
+{
+	struct sandbox_scsi_priv *priv = dev_get_priv(dev);
+
+	priv->eminfo.block_size = block_size;
+}
+
 static int sandbox_scsi_remove(struct udevice *dev)
 {
 	struct sandbox_scsi_priv *priv = dev_get_priv(dev);
drivers/scsi/scsi.c +4 -0
index 50e7d749921..a732db726ac 100644
@@ -543,6 +543,10 @@ static int scsi_detect_dev(struct udevice *dev, int target, int lun,
 		scsi_print_error(pccb);
 		return -EINVAL;
 	}
+	if (!blk_valid_blksz(blksz)) {
+		printf("Unsupported block size %lu\n", blksz);
+		return -EINVAL;
+	}
 	dev_desc->lba = capacity;
 	dev_desc->blksz = blksz;
 	dev_desc->log2blksz = LOG2(dev_desc->blksz);
test/dm/scsi.c +37 -0
index 66859c991df..7617ee54893 100644
@@ -6,6 +6,7 @@
 #include <dm.h>
 #include <part.h>
 #include <scsi.h>
+#include <asm/test.h>
 #include <dm/test.h>
 #include <test/test.h>
 #include <test/ut.h>
@@ -36,3 +37,39 @@ static int dm_test_scsi_base(struct unit_test_state *uts)
 	return 0;
 }
 DM_TEST(dm_test_scsi_base, UTF_SCAN_PDATA | UTF_SCAN_FDT);
+
+/* Test that a disk reporting an unsupported block size is refused */
+static int dm_test_scsi_blksz(struct unit_test_state *uts)
+{
+	static const struct {
+		int blksz;
+		bool ok;
+	} cases[] = {
+		{ 256, false },
+		{ 520, false },
+		{ 2 * BLK_MAX_BLKSZ, false },
+		{ SZ_4K, true },
+	};
+	struct udevice *dev, *blk;
+	struct blk_desc *desc;
+	int i, ret;
+
+	ut_assertok(uclass_first_device_err(UCLASS_SCSI, &dev));
+
+	for (i = 0; i < ARRAY_SIZE(cases); i++) {
+		sandbox_scsi_set_block_size(dev, cases[i].blksz);
+		ut_assertok(scsi_scan(false));
+
+		ret = device_find_first_child_by_uclass(dev, UCLASS_BLK, &blk);
+		if (!cases[i].ok) {
+			ut_asserteq(-ENODEV, ret);
+			continue;
+		}
+		ut_assertok(ret);
+		desc = dev_get_uclass_plat(blk);
+		ut_asserteq(cases[i].blksz, desc->blksz);
+	}
+
+	return 0;
+}
+DM_TEST(dm_test_scsi_blksz, UTF_SCAN_PDATA | UTF_SCAN_FDT);
Reviewed-by on v1 3/9
#6 lore raw

Re: [PATCH RESEND 3/9] scsi: Refuse a block size the block layer cannot use

Quoted 14 lines · Ana Bobillo

scsi: Refuse a block size the block layer cannot use

scsi_detect_dev() takes the block size from the READ CAPACITY reply of the device as it is. do_scsi_scan_one() then hands it to blk_create_devicef() as an int, which drops the upper bits of the unsigned long, so the block layer may not even see the value the device reported.

Check the block size where it is read, so that no block device is created for a disk reporting one that blk_valid_blksz() rejects.

Add a test where the sandbox SCSI disk reports an unsupported block size.

Quoted 7 lines
 arch/sandbox/include/asm/test.h | 10 ++++++++++
 drivers/scsi/sandbox_scsi.c     |  8 ++++++++
 drivers/scsi/scsi.c             |  4 ++++
 test/dm/scsi.c                  | 37 +++++++++++++++++++++++++++++++++++++
 4 files changed, 59 insertions(+)
#7 lore raw

PATCH RESEND 4/9 ide: Refuse an ATAPI block size atapi_read() cannot read

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

atapi_inquiry() takes the block size from the READ CAPACITY reply of an ATAPI device as it is, while atapi_read() asks the device for, and moves the buffer on by, ATAPI_READ_BLOCK_SIZE (2048) bytes for every block. With any other block size the callers' buffers, which are sized by blksz, do not match what atapi_read() writes into them: a 512-byte block size makes a read of several blocks write past the end of the buffer.

Only accept ATAPI_READ_BLOCK_SIZE. A device reporting anything else is left with a zero block size, which ide_probe() already skips, as for a drive without a medium. This refuses drives with 512-byte blocks, such as ZIP drives, whose reads of more than one block already overran the buffer; supporting them needs atapi_read() to use the block size of the device.

---
 drivers/block/ide.c | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
drivers/block/ide.c +9 -2
index 44ce054bdf5..035bbf2ed84 100644
@@ -450,6 +450,7 @@ static void atapi_inquiry(struct blk_desc *desc)
 {
 	u8 ccb[12];	/* Command descriptor block */
 	u8 iobuf[64];	/* temp buf */
+	ulong blksz;
 	u8 c;
 	int device;
 
@@ -514,10 +515,16 @@ static void atapi_inquiry(struct blk_desc *desc)
 		  iobuf[0], iobuf[1], iobuf[2], iobuf[3],
 		  iobuf[4], iobuf[5], iobuf[6], iobuf[7]);
 
+	blksz = (ulong)iobuf[4] << 24 | (ulong)iobuf[5] << 16 |
+		(ulong)iobuf[6] << 8 | (ulong)iobuf[7];
+	/* atapi_read() transfers ATAPI_READ_BLOCK_SIZE bytes per block */
+	if (blksz != ATAPI_READ_BLOCK_SIZE) {
+		printf("Unsupported block size %lu\n", blksz);
+		return;
+	}
 	desc->lba = (ulong)iobuf[0] << 24 | (ulong)iobuf[1] << 16 |
 		(ulong)iobuf[2] << 8 | (ulong)iobuf[3];
-	desc->blksz = (ulong)iobuf[4] << 24 | (ulong)iobuf[5] << 16 |
-		(ulong)iobuf[6] << 8 | (ulong)iobuf[7];
+	desc->blksz = blksz;
 	desc->log2blksz = LOG2(desc->blksz);
 
 	/* ATAPI devices cannot use 48bit addressing (ATA/ATAPI v7) */
#8 lore raw

Re: [PATCH RESEND 4/9] ide: Refuse an ATAPI block size atapi_read() cannot read

Hi Ana,

Quoted 23 lines · Ana Bobillo

ide: Refuse an ATAPI block size atapi_read() cannot read

atapi_inquiry() takes the block size from the READ CAPACITY reply of an ATAPI device as it is, while atapi_read() asks the device for, and moves the buffer on by, ATAPI_READ_BLOCK_SIZE (2048) bytes for every block. With any other block size the callers' buffers, which are sized by blksz, do not match what atapi_read() writes into them: a 512-byte block size makes a read of several blocks write past the end of the buffer.

Only accept ATAPI_READ_BLOCK_SIZE. A device reporting anything else is left with a zero block size, which ide_probe() already skips, as for a drive without a medium. This refuses drives with 512-byte blocks, such as ZIP drives, whose reads of more than one block already overran the buffer; supporting them needs atapi_read() to use the block size of the device.

 drivers/block/ide.c | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)

drivers/block/ide.c static void atapi_inquiry(struct blk_desc *desc) · line 519

Quoted 5 lines
drivers/block/ide.c +5 -0
@@ -514,10 +515,16 @@ static void atapi_inquiry(struct blk_desc *desc)
+	/* atapi_read() transfers ATAPI_READ_BLOCK_SIZE bytes per block */
+	if (blksz != ATAPI_READ_BLOCK_SIZE) {
+		printf("Unsupported block size %lu\n", blksz);
+		return;
+	}

Some CD drives report a block size other than 2048 in READ CAPACITY even though READ(12) sends them 2048-byte blocks: HP CD recorders report 2340, Philips writers 2352 and some drives 0. Linux maps all of these to 2048 in get_sectorsize() in drivers/scsi/sr.c, but with this patch (and patch 1) these drives are refused. They didn't really work before either, since part_iso refuses anything other than 2048 or 512. I'm not sure how much we should care about these drives, but it might be worth mapping these values to ATAPI_READ_BLOCK_SIZE here, as Linux does, and only refusing what is left. What do you think?

BTW this message comes out on the same line as the ' Device %d: ' prefix from ide_ident(), and dev_print() then prints the model on the next line. It might read better if it said what is being skipped, e.g. 'ATAPI block size %lu not supported, skipping'.

Regards,
Simon

#9 lore raw

PATCH RESEND 5/9 nvme: Skip a namespace with an unsupported LBA data size

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

nvme_blk_probe() takes the LBA data size (log2 of the block size) of the namespace's current LBA format as the device reports it, and shifts by
it: 1 << ns->lba_shift is undefined for a value of 31 or more, and nvme_blk_rw() sizes each transfer with
1 << (dev->max_transfer_shift - ns->lba_shift), a negative shift for a block larger than the maximum transfer size of the controller.

Check it, through a new nvme_lba_shift(), against the block sizes blk_valid_blksz() accepts and the maximum transfer size. nvme_init() skips a namespace with an unsupported LBA data size, as it skips an inactive one, rather than create a block device for it that then fails to probe, failing nvme_init() and leaving the namespaces it has already probed on a controller that failed to probe. nvme_blk_probe() checks the value it uses again.

---
 drivers/nvme/nvme.c | 33 ++++++++++++++++++++++++++++++++-
 1 file changed, 32 insertions(+), 1 deletion(-)
drivers/nvme/nvme.c +32 -1
index c815a967137..3df9b531bfd 100644
@@ -15,6 +15,7 @@
 #include <time.h>
 #include <dm/device-internal.h>
 #include <linux/compat.h>
+#include <linux/log2.h>
 #include "nvme.h"
 
 #define NVME_Q_DEPTH		2
@@ -701,6 +702,26 @@ int nvme_scan_namespace(void)
 	return 0;
 }
 
+/**
+ * nvme_lba_shift() - Get the LBA data size of a namespace
+ *
+ * @dev: NVMe controller
+ * @id: Identify Namespace data of the namespace
+ * Return: log2 of its block size, or -EINVAL if that size is not supported
+ */
+static int nvme_lba_shift(struct nvme_dev *dev, struct nvme_id_ns *id)
+{
+	u8 ds = id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ds;
+
+	if (ds < ilog2(DEFAULT_BLKSZ) || ds > ilog2(BLK_MAX_BLKSZ) ||
+	    ds > dev->max_transfer_shift) {
+		log_err("Unsupported LBA data size 2^%d\n", ds);
+		return -EINVAL;
+	}
+
+	return ds;
+}
+
 static int nvme_blk_probe(struct udevice *udev)
 {
 	struct nvme_dev *ndev = dev_get_priv(udev->parent);
@@ -708,6 +729,7 @@ static int nvme_blk_probe(struct udevice *udev)
 	struct nvme_ns *ns = dev_get_priv(udev);
 	u8 flbas;
 	struct nvme_id_ns *id;
+	int ret;
 
 	id = memalign(ndev->page_size, sizeof(struct nvme_id_ns));
 	if (!id)
@@ -724,7 +746,12 @@ static int nvme_blk_probe(struct udevice *udev)
 	memcpy(&ns->eui64, &id->eui64, sizeof(id->eui64));
 	flbas = id->flbas & NVME_NS_FLBAS_LBA_MASK;
 	ns->flbas = flbas;
-	ns->lba_shift = id->lbaf[flbas].ds;
+	ret = nvme_lba_shift(ndev, id);
+	if (ret < 0) {
+		free(id);
+		return ret;
+	}
+	ns->lba_shift = ret;
 	list_add(&ns->list, &ndev->namespaces);
 
 	desc->lba = le64_to_cpu(id->nsze);
@@ -899,6 +926,10 @@ int nvme_init(struct udevice *udev)
 		if (!id->nsze)
 			continue;
 
+		/* skip a namespace whose block size is not supported */
+		if (nvme_lba_shift(ndev, id) < 0)
+			continue;
+
 		/*
 		 * Encode the namespace id to the device name so that
 		 * we can extract it when doing the probe.
Reviewed-by on v1 5/9
#10 lore raw

Re: [PATCH RESEND 5/9] nvme: Skip a namespace with an unsupported LBA data size

Quoted 17 lines · Ana Bobillo

nvme: Skip a namespace with an unsupported LBA data size

nvme_blk_probe() takes the LBA data size (log2 of the block size) of the namespace's current LBA format as the device reports it, and shifts by
it: 1 << ns->lba_shift is undefined for a value of 31 or more, and nvme_blk_rw() sizes each transfer with
1 << (dev->max_transfer_shift - ns->lba_shift), a negative shift for a block larger than the maximum transfer size of the controller.

Check it, through a new nvme_lba_shift(), against the block sizes blk_valid_blksz() accepts and the maximum transfer size. nvme_init() skips a namespace with an unsupported LBA data size, as it skips an inactive one, rather than create a block device for it that then fails to probe, failing nvme_init() and leaving the namespaces it has already probed on a controller that failed to probe. nvme_blk_probe() checks the value it uses again.

Quoted 4 lines
 drivers/nvme/nvme.c | 33 ++++++++++++++++++++++++++++++++-
 1 file changed, 32 insertions(+), 1 deletion(-)
#11 lore raw

PATCH RESEND 6/9 disk: part_efi: Check the header and entry sizes of a GPT

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

validate_gpt_header() computes the CRC of a GPT header over header_size bytes, as the header gives it, and nothing checks the size of the partition entries before they are used:

- the header is read into a buffer of one block, on the stack behind part_get_info(), part_print_efi(), gpt_repair_headers() and the gpt command, so a header_size larger than the block size makes the CRC read past the end of that buffer
- alloc_read_gpt_entries() allocates and reads num_partition_entries * sizeof_partition_entry bytes, computed in 32 bits, but the entries are then used as an array of num_partition_entries gpt_entry structures: with a smaller entry size, or a product that wraps, part_get_gpt_pte() and part_print_efi() read past the end of the allocation. On a 32-bit board, rounding a product close to 4GiB up to whole blocks also wraps, to a tiny allocation that the entries are then read into.

As Linux does in is_gpt_valid(), refuse a header whose header_size is smaller than the header or larger than the block it is read from, one whose sizeof_partition_entry is not sizeof(gpt_entry), and one whose entry array is larger than 4MiB (KMALLOC_MAX_SIZE in Linux with 4KiB pages, 32768 entries). Larger entries are allowed by the UEFI specification, but U-Boot has never read them correctly, and Linux does not accept them either.

The header size is checked before the CRC is computed over it. All the checks are in validate_gpt_header(), so they also apply to is_valid_gpt_buf(), which fastboot uses on a GPT it is sent.

Add a test that gives the primary header of a GPT on a blkmap device each of these sizes, with CRCs to match, and checks that it is refused and that the backup header is used instead.

---
 disk/part_efi.c     |  46 +++++++++++--
 test/lib/part_efi.c | 155 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 196 insertions(+), 5 deletions(-)
disk/part_efi.c +41 -5
index d8751297fbe..efb6756cf2c 100644
@@ -30,6 +30,12 @@
 #include <linux/printk.h>
 #include <u-boot/crc.h>
 
+/*
+ * Largest partition entry array accepted, as in Linux (KMALLOC_MAX_SIZE with
+ * 4KiB pages): 32768 entries, far more than any tool writes
+ */
+#define GPT_ENTRIES_MAX_SIZE	SZ_4M
+
 /* GUID for basic data partitons */
 #if CONFIG_IS_ENABLED(EFI_PARTITION)
 static const efi_guid_t partition_basic_data_guid = PARTITION_BASIC_DATA_GUID;
@@ -89,10 +95,11 @@ static int get_bootable(gpt_entry *p)
 }
 
 static int validate_gpt_header(gpt_header *gpt_h, lbaint_t lba,
-		lbaint_t lastlba)
+		lbaint_t lastlba, unsigned long blksz)
 {
 	uint32_t crc32_backup = 0;
 	uint32_t calc_crc32;
+	u32 header_size, entry_size, num_entries;
 
 	/* Check the GPT header signature */
 	if (le64_to_cpu(gpt_h->signature) != GPT_HEADER_SIGNATURE_UBOOT) {
@@ -103,12 +110,22 @@ static int validate_gpt_header(gpt_header *gpt_h, lbaint_t lba,
 		return -1;
 	}
 
+	/*
+	 * The CRC covers header_size bytes, so the header has to fit in the
+	 * one block that was read into gpt_h
+	 */
+	header_size = le32_to_cpu(gpt_h->header_size);
+	if (header_size < sizeof(gpt_header) || header_size > blksz) {
+		log_debug("GPT: header_size incorrect: %u not in %zu..%lu\n",
+			  header_size, sizeof(gpt_header), blksz);
+		return -1;
+	}
+
 	/* Check the GUID Partition Table CRC */
 	memcpy(&crc32_backup, &gpt_h->header_crc32, sizeof(crc32_backup));
 	memset(&gpt_h->header_crc32, 0, sizeof(gpt_h->header_crc32));
 
-	calc_crc32 = efi_crc32((const unsigned char *)gpt_h,
-		le32_to_cpu(gpt_h->header_size));
+	calc_crc32 = efi_crc32((const unsigned char *)gpt_h, header_size);
 
 	memcpy(&gpt_h->header_crc32, &crc32_backup, sizeof(crc32_backup));
 
@@ -143,6 +160,24 @@ static int validate_gpt_header(gpt_header *gpt_h, lbaint_t lba,
 		return -1;
 	}
 
+	/*
+	 * The partition entries are used as an array of gpt_entry, read into
+	 * a buffer whose size is the product of these two fields, worked out
+	 * in 32 bits and then rounded up to whole blocks
+	 */
+	entry_size = le32_to_cpu(gpt_h->sizeof_partition_entry);
+	if (entry_size != sizeof(gpt_entry)) {
+		log_debug("GPT: sizeof_partition_entry incorrect: %u != %zu\n",
+			  entry_size, sizeof(gpt_entry));
+		return -1;
+	}
+	num_entries = le32_to_cpu(gpt_h->num_partition_entries);
+	if (num_entries > GPT_ENTRIES_MAX_SIZE / entry_size) {
+		log_debug("GPT: num_partition_entries too large: %u\n",
+			  num_entries);
+		return -1;
+	}
+
 	debug("GPT: first_usable_lba: %llX last_usable_lba: %llX last lba: "
 	      LBAF "\n", le64_to_cpu(gpt_h->first_usable_lba),
 	      le64_to_cpu(gpt_h->last_usable_lba), lastlba);
@@ -925,7 +960,7 @@ int is_valid_gpt_buf(struct blk_desc *desc, void *buf)
 	/* determine start of GPT Header in the buffer */
 	gpt_h = buf + (GPT_PRIMARY_PARTITION_TABLE_LBA * desc->blksz);
 	if (validate_gpt_header(gpt_h, GPT_PRIMARY_PARTITION_TABLE_LBA,
-				desc->lba))
+				desc->lba, desc->blksz))
 		return -1;
 
 	/* determine start of GPT Entries in the buffer */
@@ -1095,7 +1130,8 @@ static int is_gpt_valid(struct blk_desc *desc, u64 lba, gpt_header *pgpt_head,
 		return 2;
 	}
 
-	if (validate_gpt_header(pgpt_head, (lbaint_t)lba, desc->lba))
+	if (validate_gpt_header(pgpt_head, (lbaint_t)lba, desc->lba,
+				desc->blksz))
 		return 0;
 
 	if (desc->sig_type == SIG_TYPE_NONE) {
test/lib/part_efi.c +155 -0

165 lines not on this page · raw message

#12 lore raw

Re: [PATCH RESEND 6/9] disk: part_efi: Check the header and entry sizes of a GPT

Hi Ana,

Quoted 28 lines · Ana Bobillo

disk: part_efi: Check the header and entry sizes of a GPT

validate_gpt_header() computes the CRC of a GPT header over header_size bytes, as the header gives it, and nothing checks the size of the partition entries before they are used:

- the header is read into a buffer of one block, on the stack behind part_get_info(), part_print_efi(), gpt_repair_headers() and the gpt command, so a header_size larger than the block size makes the CRC read past the end of that buffer
- alloc_read_gpt_entries() allocates and reads num_partition_entries * sizeof_partition_entry bytes, computed in 32 bits, but the entries are then used as an array of num_partition_entries gpt_entry structures: with a smaller entry size, or a product that wraps, part_get_gpt_pte() and part_print_efi() read past the end of the allocation. On a 32-bit board, rounding a product close to 4GiB up to whole blocks also wraps, to a tiny allocation that the entries are then read into.

As Linux does in is_gpt_valid(), refuse a header whose header_size is [...]

 disk/part_efi.c     |  46 ++++++++++++++--
 test/lib/part_efi.c | 155 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 196 insertions(+), 5 deletions(-)

disk/part_efi.c line 34

Quoted 5 lines
disk/part_efi.c +5 -0
@@ -30,6 +30,12 @@
+/*
+ * Largest partition entry array accepted, as in Linux (KMALLOC_MAX_SIZE with
+ * 4KiB pages): 32768 entries, far more than any tool writes
+ */
+#define GPT_ENTRIES_MAX_SIZE	SZ_4M

SZ_4M only resolves here because patch 1 adds linux/sizes.h to blk.h. Please can you include <linux/sizes.h> directly in part_efi.c, so that this patch does not quietly depend on the block-size patches? That matters if the partition-table patches are picked up separately.

disk/part_efi.c int is_valid_gpt_buf(struct blk_desc *desc, void *buf) · line 963

Quoted 7 lines
disk/part_efi.c +1 -1
@@ -925,7 +960,7 @@ int is_valid_gpt_buf(struct blk_desc *desc, void *buf)
 	gpt_h = buf + (GPT_PRIMARY_PARTITION_TABLE_LBA * desc->blksz);
 	if (validate_gpt_header(gpt_h, GPT_PRIMARY_PARTITION_TABLE_LBA,
-				desc->lba))
+				desc->lba, desc->blksz))
 		return -1;

BTW the fastboot path still takes partition_entry_lba from the header without checking it, so the entry CRC can be computed at an offset past the end of the download buffer. That predates this patch so is not blocking, but the commit message reads as if fastboot is now fully covered. It could be a follow-up.

Regards,
Simon

#13 lore raw

PATCH RESEND 7/9 disk: part_dos: Walk the extended partition tables in a bounded loop

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

part_get_info_extended() and print_partition_extended() follow the links from one extended partition table to the next by recursing, and stop at MAX_EXT_PARTS partitions, the limit added for CVE-2019-13103. But a link adds no partition: an extended partition table holding only a link back to itself does not advance part_num, so the recursion goes on until the stack runs out, whenever a logical partition of the device is looked up. Even within the limit, every level keeps a buffer of one block on the stack, so a long chain of tables on a device with large blocks needs megabytes of stack.

Follow the links in a loop instead, reusing the one buffer, and stop after MAX_EXT_TABLES tables, as many as MAX_EXT_PARTS partitions need, so that a disk with as many partitions as before still reads. Linux bounds the same walk in parse_extended(), by the number of links followed without finding a partition.

print_partition_extended() followed every link of a table, where part_get_info_extended() follows only the first, so it could list partitions that cannot be looked up, under numbers that clash, and its walk was not a chain but a tree. Follow only the first link there too.

Add a test with a table that links only to itself, after two logical partitions.

---
 disk/part_dos.c |  41 ++++++++++++++------
 test/dm/part.c  | 100 ++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 130 insertions(+), 11 deletions(-)
disk/part_dos.c +30 -11
index 4b560fde1fb..f451aef76a8 100644
@@ -28,6 +28,13 @@
  * to use large numbers of partitions */
 #define MAX_EXT_PARTS 256
 
+/*
+ * A link to the next extended partition table adds no partition, so tables
+ * linking back to each other do not advance part_num. Bound the number of
+ * tables read along a chain as well, allowing as many as MAX_EXT_PARTS needs.
+ */
+#define MAX_EXT_TABLES MAX_EXT_PARTS
+
 static inline int is_extended(int part_type)
 {
     return (part_type == DOS_PART_TYPE_EXTENDED ||
@@ -135,10 +142,13 @@ static void print_partition_extended(struct blk_desc *desc,
 {
 	ALLOC_CACHE_ALIGN_BUFFER(unsigned char, buffer, desc->blksz);
 	dos_partition_t *pt;
+	int tables = 0;
 	int i;
 
-	/* set a maximum recursion level */
-	if (part_num > MAX_EXT_PARTS)
+next_table:
+	/* bound the walk */
+	tables++;
+	if (part_num > MAX_EXT_PARTS || tables > MAX_EXT_TABLES)
 	{
 		printf("** Nested DOS partitions detected, stopping **\n");
 		return;
@@ -187,9 +197,14 @@ static void print_partition_extended(struct blk_desc *desc,
 			lbaint_t lba_start
 				= get_unaligned_le32 (&pt->start_sect) + relative;
 
-			print_partition_extended(desc, lba_start,
-						 !ext_part_sector ? lba_start :
-						 relative, part_num, disksig);
+			/*
+			 * Follow only the first link, as
+			 * part_get_info_extended() does, reusing the buffer
+			 */
+			if (ext_part_sector == 0)
+				relative = lba_start;
+			ext_part_sector = lba_start;
+			goto next_table;
 		}
 	}
 
@@ -220,11 +235,14 @@ static int part_get_info_extended(struct blk_desc *desc,
 	ALLOC_CACHE_ALIGN_BUFFER(unsigned char, buffer, desc->blksz);
 	struct disk_partition wdinfo = { 0 };
 	dos_partition_t *pt;
+	int tables = 0;
 	int i, ret;
 	int dos_type;
 
-	/* set a maximum recursion level */
-	if (part_num > MAX_EXT_PARTS)
+next_table:
+	/* bound the walk */
+	tables++;
+	if (part_num > MAX_EXT_PARTS || tables > MAX_EXT_TABLES)
 	{
 		printf("** Nested DOS partitions detected, stopping **\n");
 		return -1;
@@ -302,10 +320,11 @@ static int part_get_info_extended(struct blk_desc *desc,
 			lbaint_t lba_start
 				= get_unaligned_le32 (&pt->start_sect) + relative;
 
-			return part_get_info_extended(desc, lba_start,
-				 ext_part_sector == 0 ? lba_start : relative,
-						      part_num, which_part, info,
-						      mbr, disksig);
+			/* follow the link, reusing the buffer */
+			if (ext_part_sector == 0)
+				relative = lba_start;
+			ext_part_sector = lba_start;
+			goto next_table;
 		}
 	}
 
test/dm/part.c +100 -0

113 lines not on this page · raw message

#14 lore raw

Re: [PATCH RESEND 7/9] disk: part_dos: Walk the extended partition tables in a bounded loop

Hi Ana,

Quoted 18 lines · Ana Bobillo

disk: part_dos: Walk the extended partition tables in a bounded loop

part_get_info_extended() and print_partition_extended() follow the links from one extended partition table to the next by recursing, and stop at MAX_EXT_PARTS partitions, the limit added for CVE-2019-13103. But a link adds no partition: an extended partition table holding only a link back to itself does not advance part_num, so the recursion goes on until the stack runs out, whenever a logical partition of the device is looked up. Even within the limit, every level keeps a buffer of one block on the stack, so a long chain of tables on a device with large blocks needs megabytes of stack.

Follow the links in a loop instead, reusing the one buffer, and stop after MAX_EXT_TABLES tables, as many as MAX_EXT_PARTS partitions need, so that a disk with as many partitions as before still reads. Linux bounds the same walk in parse_extended(), by the number of links followed without finding a partition.

Quoted 4 lines

print_partition_extended() followed every link of a table, where part_get_info_extended() follows only the first, so it could list partitions that cannot be looked up, under numbers that clash, and its walk was not a chain but a tree. Follow only the first link there too.

Since you are likely to send a new version, please can you use the present tense here ('follows every link', 'so it can list', 'its walk is not a chain'), since the code still behaves like this before this patch.

Quoted 8 lines

[...]

 disk/part_dos.c |  41 ++++++++++++++++-------
 test/dm/part.c  | 100 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 130 insertions(+), 11 deletions(-)

disk/part_dos.c static void print_partition_extended(struct blk_desc *desc, · line 145

Quoted 6 lines
disk/part_dos.c +4 -2
@@ -135,10 +142,13 @@ static void print_partition_extended(struct blk_desc *desc,
-	/* set a maximum recursion level */
-	if (part_num > MAX_EXT_PARTS)
+next_table:
+	/* bound the walk */
+	tables++;
+	if (part_num > MAX_EXT_PARTS || tables > MAX_EXT_TABLES)

The subject says 'bounded loop', but in both functions this is a backward goto out of an inner for() loop. It works, but it is hard to follow, and kernel style keeps goto for error unwinding. Please can you write it as a real loop, e.g. for (tables = 0; tables < MAX_EXT_TABLES; tables++) { ... }, with the 'follow the link' part setting ext_part_sector and doing a 'continue' (or a 'break' when there is no link)? The code that finds the next link is now the same in both functions, so should be in a helper.

disk/part_dos.c line 33

Quoted 8 lines
disk/part_dos.c +6 -0
@@ -28,6 +28,13 @@
+/*
+ * A link to the next extended partition table adds no partition, so tables
+ * linking back to each other do not advance part_num. Bound the number of
+ * tables read along a chain as well, allowing as many as MAX_EXT_PARTS needs.
+ */
+#define MAX_EXT_TABLES MAX_EXT_PARTS

One thing I'd like to check is what happens at probe time. part_create_block_devices() calls part_get_info() for every partition up to MAX_SEARCH_PARTITIONS, so with the table in your test each of partitions 7..128 reads 256 blocks and prints '** Nested DOS partitions detected, stopping **'. That is about 31k single-block reads and 122 identical lines when a USB stick is plugged in. It is much better than running out of stack, but it would be worth bounding the number of links followed without finding a partition, as Linux does (it resets 'loopct' when it finds one). Then the limit can be much smaller than 256 while still allowing a long, valid chain. What do you think?

test/dm/part.c static int dm_test_part_get_info_by_uuid(struct unit_test_state *uts) · line 253

Quoted 5 lines
test/dm/part.c +3 -0
@@ -248,3 +251,100 @@ static int dm_test_part_get_info_by_uuid(struct unit_test_state *uts)
+	/* and so does listing them */
+	desc->part_type = PART_TYPE_DOS;
+	part_print(desc);

It would be better to call part_init(desc) here than to set part_type directly, so the test also checks that the table is detected as DOS.

Regards,
Simon

#15 lore raw

PATCH RESEND 8/9 disk: part_dos: Make room for a three-digit partition number in the UUID

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

part_get_info_extended() makes up the UUID of a DOS partition as "%08x-%02x" from the disk signature and the partition number, into a buffer of 12 bytes. That is enough up to partition 255, but MAX_EXT_PARTS lets the number reach 256, whose three digits make sprintf() write the terminating NUL past the end of the buffer.

Size the buffer like the UUID it is copied into, and use snprintf().

Add a test with 256 partitions, which catches the overflow on sandbox with CONFIG_ASAN.

---
 disk/part_dos.c |  6 ++++--
 test/dm/part.c  | 46 ++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 50 insertions(+), 2 deletions(-)
disk/part_dos.c +4 -2
index f451aef76a8..04a68ca6478 100644
@@ -294,9 +294,11 @@ next_table:
 				snprintf(info->type, sizeof(info->type), "0x%x", pt->sys_ind);
 				info->bootable = get_bootable(pt);
 				if (CONFIG_IS_ENABLED(PARTITION_UUIDS)) {
-					char str[12];
+					/* part_num may take three digits */
+					char str[UUID_STR_LEN + 1];
 
-					sprintf(str, "%08x-%02x", disksig, part_num);
+					snprintf(str, sizeof(str), "%08x-%02x",
+						 disksig, part_num);
 					disk_partition_set_uuid(info, str);
 				}
 				info->sys_ind = pt->sys_ind;
test/dm/part.c +46 -0

49 lines not on this page · raw message

Reviewed-by on v1 8/9
#16 lore raw

Re: [PATCH RESEND 8/9] disk: part_dos: Make room for a three-digit partition number in the UUID

Quoted 10 lines · Ana Bobillo

disk: part_dos: Make room for a three-digit partition number in the UUID

part_get_info_extended() makes up the UUID of a DOS partition as "%08x-%02x" from the disk signature and the partition number, into a buffer of 12 bytes. That is enough up to partition 255, but MAX_EXT_PARTS lets the number reach 256, whose three digits make sprintf() write the terminating NUL past the end of the buffer.

Size the buffer like the UUID it is copied into, and use snprintf().

Quoted 8 lines

Add a test with 256 partitions, which catches the overflow on sandbox with CONFIG_ASAN.

 disk/part_dos.c |  6 ++++--
 test/dm/part.c  | 46 ++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 50 insertions(+), 2 deletions(-)
#17 lore raw

PATCH RESEND 9/9 efi_loader: Check the GPT header before measuring it

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

tcg2_measure_gpt_data() reads the primary GPT header of the disk an EFI application is started from, and uses num_partition_entries and sizeof_partition_entry as the header gives them: the entries are read into a buffer whose size is their product, worked out in 32 bits, and then walked num_partition_entries times with sizeof_partition_entry as the stride. Nothing checks the header first, not even its signature or CRC, so a product that wraps, or an entry size smaller than the GUID read from each entry, makes the walks read past the end of the buffer.

The partition driver does check the header, in validate_gpt_header(), but when the primary header is not valid it uses the backup one. The partitions of a disk whose primary header it refuses can then still be found, and an application started from one of them gets that refused header used here.

Export validate_gpt_header() and check the header with it before using its sizes. When the header is not valid, measure no GPT event but return success, as an error would make efi_tcg2_measure_efi_app_invocation() skip the separators. EDK2 likewise measures no GPT event when it finds no valid header (the checks added for CVE-2022-36763) and still measures the image. Its partition driver restores a primary header that is not valid from the backup, so that the restored header is measured; U-Boot leaves the disk alone, so no GPT event is measured for such a disk.

Add a test that starts an EFI application from a GPT disk on sandbox and checks PCR 5: with a valid GPT it holds the GPT event and the separator, and with a primary header whose entry array comes to one block in 32 bits, only the separator. Without this change sandbox crashes in the second case. Call validate_gpt_header() directly in lib_test_gpt_sizes too.

Fixes ce3dbc5d080d ("efi_loader: add UEFI GPT measurement")
---
 disk/part_efi.c                |   4 +-
 include/part.h                 |  23 +++++
 lib/efi_loader/efi_tcg2.c      |  16 ++++
 test/lib/part_efi.c            |   6 ++
 test/py/tests/test_efi_tcg2.py | 170 +++++++++++++++++++++++++++++++++
 5 files changed, 217 insertions(+), 2 deletions(-)
 create mode 100644 test/py/tests/test_efi_tcg2.py
disk/part_efi.c +2 -2
index efb6756cf2c..dc379559b4c 100644
@@ -94,8 +94,8 @@ static int get_bootable(gpt_entry *p)
 	return ret;
 }
 
-static int validate_gpt_header(gpt_header *gpt_h, lbaint_t lba,
-		lbaint_t lastlba, unsigned long blksz)
+int validate_gpt_header(gpt_header *gpt_h, lbaint_t lba,
+			lbaint_t lastlba, unsigned long blksz)
 {
 	uint32_t crc32_backup = 0;
 	uint32_t calc_crc32;
include/part.h +23 -0
index 1dc510cb6b1..a886a46ae18 100644
@@ -680,6 +680,29 @@ int get_disk_guid(struct blk_desc *desc, char *guid);
  */
 int part_get_gpt_pte(struct blk_desc *desc, int part, gpt_entry *gpt_e);
 
+/**
+ * validate_gpt_header() - Check a GPT header read from a disk
+ *
+ * Check the signature, size and CRC of the header, its own LBA, its usable
+ * LBAs and the size of its partition entries. The CRC field is zeroed while
+ * the CRC is computed, and then put back.
+ *
+ * @gpt_h:	GPT header, at the start of a buffer of @blksz bytes
+ * @lba:	LBA the header was read from
+ * @lastlba:	number of blocks of the disk, which no usable LBA may be past
+ * @blksz:	block size of the disk
+ *
+ * Return:	0 if the header is valid, -1 if not
+ */
+int validate_gpt_header(gpt_header *gpt_h, lbaint_t lba, lbaint_t lastlba,
+			unsigned long blksz);
+
+#else
+static inline int validate_gpt_header(gpt_header *gpt_h, lbaint_t lba,
+				      lbaint_t lastlba, unsigned long blksz)
+{
+	return -1;
+}
 #endif
 
 #if CONFIG_IS_ENABLED(DOS_PARTITION)
lib/efi_loader/efi_tcg2.c +16 -0
index 5f9bbe97455..c858e8df6d7 100644
@@ -16,6 +16,7 @@
 #include <efi_tcg2.h>
 #include <log.h>
 #include <malloc.h>
+#include <part.h>
 #include <smbios.h>
 #include <version_string.h>
 #include <tpm_api.h>
@@ -1220,6 +1221,21 @@ tcg2_measure_gpt_data(struct udevice *dev,
 	if (ret != EFI_SUCCESS)
 		goto out2;
 
+	/*
+	 * The header gives the number and the size of the entries read and
+	 * walked below, so check it with the partition driver's header check,
+	 * which takes the number of blocks of the disk. If it is not valid, the
+	 * partitions may have been found through the backup header: measure no
+	 * GPT then, but return success, as an error would skip the separators.
+	 */
+	if (validate_gpt_header(gpt_h, GPT_PRIMARY_PARTITION_TABLE_LBA,
+				block_io->media->last_block + 1,
+				block_io->media->block_size)) {
+		log_warning("Primary GPT header is not valid, not measured\n");
+		ret = EFI_SUCCESS;
+		goto out2;
+	}
+
 	/* read GPT entry */
 	total_gpt_entry_size = gpt_h->num_partition_entries *
 			       gpt_h->sizeof_partition_entry;
test/lib/part_efi.c +6 -0
index c8fdfe2f41c..e2990bdb0b5 100644
@@ -366,6 +366,12 @@ static int gpt_sizes_check(struct unit_test_state *uts, struct udevice *dev,
 		ut_asserteq(1, blk_dwrite(desc, GPT_PRIMARY_PARTITION_TABLE_LBA,
 					  1, hdr));
 
+		/* efi_tcg2 reads the header itself and checks it with this */
+		ret = validate_gpt_header(hdr, GPT_PRIMARY_PARTITION_TABLE_LBA,
+					  desc->lba, blksz);
+		ut_assertf(ret == cases[i].ret, "case %d: header check %d\n", i,
+			   ret);
+
 		/*
 		 * Read it back into a buffer as large as the one above, so
 		 * that a header longer than its block is refused by the size
test/py/tests/test_efi_tcg2.py new file +170 -0

170 lines not on this page · raw message

#18 lore raw

Re: [PATCH RESEND 9/9] efi_loader: Check the GPT header before measuring it

Hi Ana,

Quoted 31 lines · Ana Bobillo

efi_loader: Check the GPT header before measuring it

tcg2_measure_gpt_data() reads the primary GPT header of the disk an EFI application is started from, and uses num_partition_entries and sizeof_partition_entry as the header gives them: the entries are read into a buffer whose size is their product, worked out in 32 bits, and then walked num_partition_entries times with sizeof_partition_entry as the stride. Nothing checks the header first, not even its signature or CRC, so a product that wraps, or an entry size smaller than the GUID read from each entry, makes the walks read past the end of the buffer.

The partition driver does check the header, in validate_gpt_header(), but when the primary header is not valid it uses the backup one. The partitions of a disk whose primary header it refuses can then still be found, and an application started from one of them gets that refused header used here.

Export validate_gpt_header() and check the header with it before using its sizes. When the header is not valid, measure no GPT event but return success, as an error would make efi_tcg2_measure_efi_app_invocation() [...]

 disk/part_efi.c                |   4 +-
 include/part.h                 |  23 ++++++
 lib/efi_loader/efi_tcg2.c      |  16 ++++
 test/lib/part_efi.c            |   6 ++
 test/py/tests/test_efi_tcg2.py | 170 +++++++++++++++++++++++++++++++++++++++++
 5 files changed, 217 insertions(+), 2 deletions(-)

lib/efi_loader/efi_tcg2.c tcg2_measure_gpt_data(struct udevice *dev, · line 1227

Quoted 7 lines
lib/efi_loader/efi_tcg2.c +7 -0
@@ -1220,6 +1221,21 @@ tcg2_measure_gpt_data(struct udevice *dev,
+	if (validate_gpt_header(gpt_h, GPT_PRIMARY_PARTITION_TABLE_LBA,
+				block_io->media->last_block + 1,
+				block_io->media->block_size)) {
+		log_warning("Primary GPT header is not valid, not measured\n");
+		ret = EFI_SUCCESS;
+		goto out2;
+	}

This fixes the overrun, since the entry size is now fixed at sizeof(gpt_entry) and the array is limited to 4MiB. One thing I'd like to check, though. Your argument also applies to the entries. is_gpt_valid() runs validate_gpt_entries() too, so if the primary header is fine but its entry-array CRC is wrong, the partition driver uses the backup. This code still measures the primary header and the entries that the driver refused. EDK2 checks the entry-array CRC before measuring (PartitionCheckGptEntryArrayCRC() in PartitionValidGptTable()). It would be worth checking the CRC of the entries here too, once they are read, perhaps by exporting validate_gpt_entries() (or a helper that does both checks) instead of only the header check. What do you think?

Regards,
Simon

#19 lore raw

Re: [PATCH RESEND 9/9] efi_loader: Check the GPT header before measuring it

In reply to Ana Bobillo

Hi Ana,

Quoted 12 lines · Ana Bobillo

From: Ana Bobillo <[email protected]>

tcg2_measure_gpt_data() reads the primary GPT header of the disk an EFI application is started from, and uses num_partition_entries and sizeof_partition_entry as the header gives them: the entries are read into a buffer whose size is their product, worked out in 32 bits, and then walked num_partition_entries times with sizeof_partition_entry as the stride. Nothing checks the header first, not even its signature or CRC, so a product that wraps, or an entry size smaller than the GUID read from each entry, makes the walks read past the end of the buffer.

Is this an actual security issue though? IOW the measurements on PCR5 will be invalid wrt to what remote attestation or secret unsealing expects, right?
I still think we should fix it, but a more accurate commit message would help

Quoted 5 lines

The partition driver does check the header, in validate_gpt_header(), but when the primary header is not valid it uses the backup one. The partitions of a disk whose primary header it refuses can then still be found, and an application started from one of them gets that refused header used here.

Same as above.

Quoted 9 lines

Export validate_gpt_header() and check the header with it before using its sizes. When the header is not valid, measure no GPT event but return success, as an error would make efi_tcg2_measure_efi_app_invocation() skip the separators. EDK2 likewise measures no GPT event when it finds no valid header (the checks added for CVE-2022-36763) and still measures the image. Its partition driver restores a primary header that is not valid from the backup, so that the restored header is measured; U-Boot leaves the disk alone, so no GPT event is measured for such a disk.

Shouldn't we do the same thing here before measuring?

Thanks
/Ilias

Quoted 295 lines

Add a test that starts an EFI application from a GPT disk on sandbox and checks PCR 5: with a valid GPT it holds the GPT event and the separator, and with a primary header whose entry array comes to one block in 32 bits, only the separator. Without this change sandbox crashes in the second case. Call validate_gpt_header() directly in lib_test_gpt_sizes too.

Fixes ce3dbc5d080d ("efi_loader: add UEFI GPT measurement")
---
 disk/part_efi.c                |   4 +-
 include/part.h                 |  23 +++++
 lib/efi_loader/efi_tcg2.c      |  16 ++++
 test/lib/part_efi.c            |   6 ++
 test/py/tests/test_efi_tcg2.py | 170 +++++++++++++++++++++++++++++++++
 5 files changed, 217 insertions(+), 2 deletions(-)
 create mode 100644 test/py/tests/test_efi_tcg2.py
disk/part_efi.c +2 -2
index efb6756cf2c..dc379559b4c 100644
@@ -94,8 +94,8 @@ static int get_bootable(gpt_entry *p)
        return ret;
 }
 
-static int validate_gpt_header(gpt_header *gpt_h, lbaint_t lba,
-               lbaint_t lastlba, unsigned long blksz)
+int validate_gpt_header(gpt_header *gpt_h, lbaint_t lba,
+                       lbaint_t lastlba, unsigned long blksz)
 {
        uint32_t crc32_backup = 0;
        uint32_t calc_crc32;
include/part.h +23 -0
index 1dc510cb6b1..a886a46ae18 100644
@@ -680,6 +680,29 @@ int get_disk_guid(struct blk_desc *desc, char *guid);
  */
 int part_get_gpt_pte(struct blk_desc *desc, int part, gpt_entry *gpt_e);
 
+/**
+ * validate_gpt_header() - Check a GPT header read from a disk
+ *
+ * Check the signature, size and CRC of the header, its own LBA, its usable
+ * LBAs and the size of its partition entries. The CRC field is zeroed while
+ * the CRC is computed, and then put back.
+ *
+ * @gpt_h:     GPT header, at the start of a buffer of @blksz bytes
+ * @lba:       LBA the header was read from
+ * @lastlba:   number of blocks of the disk, which no usable LBA may be past
+ * @blksz:     block size of the disk
+ *
+ * Return:     0 if the header is valid, -1 if not
+ */
+int validate_gpt_header(gpt_header *gpt_h, lbaint_t lba, lbaint_t lastlba,
+                       unsigned long blksz);
+
+#else
+static inline int validate_gpt_header(gpt_header *gpt_h, lbaint_t lba,
+                                     lbaint_t lastlba, unsigned long blksz)
+{
+       return -1;
+}
 #endif
 
 #if CONFIG_IS_ENABLED(DOS_PARTITION)
lib/efi_loader/efi_tcg2.c +16 -0
index 5f9bbe97455..c858e8df6d7 100644
@@ -16,6 +16,7 @@
 #include <efi_tcg2.h>
 #include <log.h>
 #include <malloc.h>
+#include <part.h>
 #include <smbios.h>
 #include <version_string.h>
 #include <tpm_api.h>
@@ -1220,6 +1221,21 @@ tcg2_measure_gpt_data(struct udevice *dev,
        if (ret != EFI_SUCCESS)
                goto out2;
 
+       /*
+        * The header gives the number and the size of the entries read and
+        * walked below, so check it with the partition driver's header check,
+        * which takes the number of blocks of the disk. If it is not valid, the
+        * partitions may have been found through the backup header: measure no
+        * GPT then, but return success, as an error would skip the separators.
+        */
+       if (validate_gpt_header(gpt_h, GPT_PRIMARY_PARTITION_TABLE_LBA,
+                               block_io->media->last_block + 1,
+                               block_io->media->block_size)) {
+               log_warning("Primary GPT header is not valid, not measured\n");
+               ret = EFI_SUCCESS;
+               goto out2;
+       }
+
        /* read GPT entry */
        total_gpt_entry_size = gpt_h->num_partition_entries *
                               gpt_h->sizeof_partition_entry;
test/lib/part_efi.c +6 -0
index c8fdfe2f41c..e2990bdb0b5 100644
@@ -366,6 +366,12 @@ static int gpt_sizes_check(struct unit_test_state *uts, struct udevice *dev,
                ut_asserteq(1, blk_dwrite(desc, GPT_PRIMARY_PARTITION_TABLE_LBA,
                                          1, hdr));
 
+               /* efi_tcg2 reads the header itself and checks it with this */
+               ret = validate_gpt_header(hdr, GPT_PRIMARY_PARTITION_TABLE_LBA,
+                                         desc->lba, blksz);
+               ut_assertf(ret == cases[i].ret, "case %d: header check %d\n", i,
+                          ret);
+
                /*
                 * Read it back into a buffer as large as the one above, so
                 * that a header longer than its block is refused by the size
test/py/tests/test_efi_tcg2.py new file +170 -0
new file mode 100644
index 00000000000..ae21ff76da8
@@ -0,0 +1,170 @@
+# SPDX-License-Identifier: GPL-2.0+
+
+"""Test the measurements made by the EFI_TCG2_PROTOCOL on sandbox
+
+The sandbox TPM starts with every PCR clear, and the events measured when an
+EFI application is started (boot variables, GPT, separators) are only measured
+the first time one is. So each case restarts U-Boot, starts one application
+and checks PCR 5 against the events it should then hold.
+"""
+
+import hashlib
+import os
+import re
+import shutil
+import struct
+import zlib
+
+import pytest
+
+import utils
+from tests.fs_helper import FsHelper
+
+# EFI System Partition
+ESP_TYPE = 'C12A7328-F81F-11D2-BA4B-00A0C93EC93B'
+SECTOR = 512
+
+# Fields of the GPT header, by offset
+GPT_HEADER_SIZE = 92
+GPT_HDR_SIZE_OFF = 12
+GPT_HDR_CRC_OFF = 16
+GPT_ENTRIES_OFF = 72    # partition_entry_lba, num_partition_entries, ...
+GPT_NUM_ENTRIES_OFF = 80
+GPT_ENTRY_SIZE = 128
+
+
+def extend(pcr, data):
+    """Extend a SHA256 PCR value with the digest of some data
+
+    Args:
+        pcr (bytes): PCR value before
+        data (bytes): Event data
+
+    Returns:
+        bytes: PCR value after
+    """
+    return hashlib.sha256(pcr + hashlib.sha256(data).digest()).digest()
+
+
+def make_gpt_disk(ubman, fname):
+    """Write a GPT disk image with helloworld.efi on its only partition
+
+    Args:
+        ubman (ConsoleBase): U-Boot console
+        fname (str): Filename of the disk image
+    """
+    with FsHelper(ubman.config, 'vfat', 1, 'tcg2') as fsh:
+        shutil.copy(os.path.join(ubman.config.build_dir,
+                                 'lib/efi_loader/helloworld.efi'),
+                    fsh.srcdir)
+        fsh.mk_fs()
+        with open(fsh.fs_img, 'rb') as inf:
+            fs_data = inf.read()
+
+    # 1MiB for the primary GPT, the partition, 1MiB for the backup GPT
+    with open(fname, 'wb') as outf:
+        outf.truncate((2 << 20) + len(fs_data))
+    utils.run_and_log(ubman, f'sfdisk {fname}',
+                      stdin=(f'label: gpt\nstart=2048, '
+                             f'size={len(fs_data) // SECTOR}, '
+                             f'type={ESP_TYPE}\n').encode())
+    with open(fname, 'r+b') as outf:
+        outf.seek(1 << 20)
+        outf.write(fs_data)
+
+
+def gpt_event(fname):
+    """Get the EV_EFI_GPT_EVENT data for the primary GPT of a disk image
+
+    Args:
+        fname (str): Filename of the disk image
+
+    Returns:
+        bytes: The header, the number of partitions, then their entries
+    """
+    with open(fname, 'rb') as inf:
+        disk = inf.read()
+    hdr = disk[SECTOR:SECTOR + GPT_HEADER_SIZE]
+    entry_lba, num, size = struct.unpack_from('<QII', hdr, GPT_ENTRIES_OFF)
+    entries = []
+    for i in range(num):
+        start = entry_lba * SECTOR + i * size
+        entry = disk[start:start + size]
+        if any(entry[:16]):
+            entries.append(entry)
+    return hdr + struct.pack('<Q', len(entries)) + b''.join(entries)
+
+
+def set_num_entries(fname, num):
+    """Set num_partition_entries in the primary GPT header and fix its CRC
+
+    Args:
+        fname (str): Filename of the disk image
+        num (int): Number of partition entries
+    """
+    with open(fname, 'r+b') as outf:
+        outf.seek(SECTOR)
+        hdr = bytearray(outf.read(SECTOR))
+        struct.pack_into('<I', hdr, GPT_NUM_ENTRIES_OFF, num)
+        struct.pack_into('<I', hdr, GPT_HDR_CRC_OFF, 0)
+        hdr_size = struct.unpack_from('<I', hdr, GPT_HDR_SIZE_OFF)[0]
+        struct.pack_into('<I', hdr, GPT_HDR_CRC_OFF,
+                         zlib.crc32(hdr[:hdr_size]))
+        outf.seek(SECTOR)
+        outf.write(hdr)
+
+
+def boot_and_read_pcr5(ubman, fname):
+    """Start helloworld.efi from a disk image on a fresh U-Boot
+
+    Args:
+        ubman (ConsoleBase): U-Boot console
+        fname (str): Filename of the disk image
+
+    Returns:
+        bytes: PCR 5 after the application has run
+    """
+    addr = utils.find_ram_base(ubman) + (4 << 20)
+    ubman.restart_uboot()
+    ubman.run_command(f'host bind 0 {fname}')
+    output = ubman.run_command(f'load host 0:1 {addr:x} helloworld.efi')
+    assert 'bytes read' in output
+    output = ubman.run_command(f'bootefi {addr:x}')
+    assert 'Hello, world!' in output
+    output = ubman.run_command(f'tpm2 pcr_read 5 {addr:x}')
+    assert 'PCR #5 sha256 32 byte content' in output
+    digest = output.split('content', 1)[1].split('\n', 1)[1]
+    return bytes.fromhex(''.join(re.findall(r'\b[0-9a-f]{2}\b', digest)))
+
+
[email protected]('sandbox')
+# EFI applications are built with the sanitizer but cannot run with it
[email protected]('asan')
[email protected]('efi_tcg2_protocol')
[email protected]('efi_partition')
[email protected]('cmd_tpm_v2')
[email protected]('bootefi_hello_compile')
+def test_efi_tcg2_gpt_header(ubman):
+    """Check that the GPT is measured only when its header is valid
+
+    PCR 5 holds the GPT event and then the separator. A primary header that
+    the partition driver refuses gives no GPT event, though the partitions
+    are still found through the backup header, and the separator is still
+    measured.
+    """
+    fname = os.path.join(ubman.config.persistent_data_dir, 'tcg2_gpt.img')
+    separator = struct.pack('<I', 0)
+    try:
+        make_gpt_disk(ubman, fname)
+        expect = extend(extend(bytes(32), gpt_event(fname)), separator)
+        assert boot_and_read_pcr5(ubman, fname) == expect
+
+        # an entry array whose size comes to one block in 32 bits
+        set_num_entries(fname, (1 << 32) // GPT_ENTRY_SIZE +
+                        SECTOR // GPT_ENTRY_SIZE)
+        expect = extend(bytes(32), separator)
+        assert boot_and_read_pcr5(ubman, fname) == expect
+    finally:
+        if os.path.exists(fname):
+            os.remove(fname)
+        ubman.restart_uboot()
#20 lore raw

Re: [PATCH RESEND 9/9] efi_loader: Check the GPT header before measuring it

Hi Ilias,

Quoted 5 lines · Ilias Apalodimas

Is this an actual security issue though? IOW the measurements on PCR5 will be invalid wrt to what remote attestation or secret unsealing expects, right?
I still think we should fix it, but a more accurate commit message would help

Yes, the PCR 5 side is the one that matters, and the message should have led with it. tcg2_measure_gpt_data() measures the primary GPT without any check, while the partition driver uses the backup GPT whenever the primary header or entries are not valid. Unused entries are not measured but are covered by the entry array CRC, so a byte changed in an unused primary entry leaves PCR 5 at its expected value while the partitions come from the backup GPT, whatever that holds. I checked it on sandbox with master: with a backup GPT whose partition has another GUID and such a primary GPT, PCR 5 is the same as for the untouched disk. So a disk whose partitions were changed that way still attests, and unseals, as the original one.

The unchecked sizes are a separate bug: a header whose entry array size wraps in 32 bits makes the walks read far past the entry buffer, and sandbox dies in bootefi.

Quoted 5 lines
Quoted 3 lines

Its partition driver restores a primary header that is not valid from the backup, so that the restored header is measured; U-Boot leaves the disk alone, so no GPT event is measured for such a disk.

Shouldn't we do the same thing here before measuring?

Yes. EDK2 also changed its side this summer: since 7c12d4359abd ("SecurityPkg/DxeTpm2MeasureBootLib: Use GptLib parser") it measures the GPT its partition driver uses, read with the driver's own parser, after the driver has restored the primary GPT on the disk.

So v2 does the same: a new part_get_gpt_primary() in part_efi.c returns the GPT as find_valid_gpt() finds it, and when that is the backup, gives its header as the primary header gpt_repair_headers() makes from it. efi_tcg2 measures that and no longer reads the disk itself. I did not want the measurement to write to the disk, so the header is only rebuilt in memory: a disk whose primary GPT was lost gives the PCR 5 it has once repaired with "gpt repair". Only when no valid GPT can be read is no GPT event measured.

The test in v2 checks PCR 5 for a valid GPT, for a primary header whose sizes wrap (the same PCR 5, through the backup), and for a backup GPT that differs from a primary one with a changed unused entry (PCR 5 holds the backup GPT).

v2 of the series follows once its CI run is done.

Thanks,
Ana

#21 lore raw
In reply to Ana Bobillo

Hi Ana,

Quoted 7 lines · Ana Bobillo

Patch 1 adds blk_valid_blksz() and has blk_post_probe() refuse a block device whose block size it rejects, which covers every block driver. Patches 2-5 check the block size where the USB storage, SCSI, IDE (ATAPI) and NVMe drivers read it, so that each refuses such a device
cleanly: the USB LUN is skipped instead of failing the whole stick, no SCSI block device is created, the ATAPI drive is treated as one without a medium and the NVMe namespace is skipped like an inactive one.

One thing I'd like to check is the order of these patches. With only patch 1 applied, the uclass refuses these devices but the drivers don't yet handle that cleanly. A bad LUN then fails the whole USB stick and nvme_init() fails part-way, which is the behaviour patches 2 and 5 describe as the problem. Also, on a little-endian host the USB fallback after READ CAPACITY fails gives a 128KiB block size, so a stick that probes today would fail to probe until patch 2 lands. Please can you add the helper first, then the driver patches, and put the blk_post_probe() check last, so each step stays bisectable?

Regards,
Simon