Skip to contentSkip to conversation

efi_loader: capsule: check sizes against the capsule

PATCH In review Ana Bobillo 2 participants 9 messages Oct 28 – Oct 30

lore
Share & tools
lore
#0 lore raw

v2 cover efi_loader: capsule: check sizes against the capsule

The capsule update code takes several lengths and offsets from a capsule and uses them without checking them against the size of the capsule. On the capsule on disk path this happens before the image is authenticated, so a capsule file in \EFI\UpdateCapsule on the ESP makes U-Boot read outside the capsule buffer the next time capsule on disk runs, even where CONFIG_EFI_CAPSULE_AUTHENTICATE rejects the capsule afterwards.

Patches 1-4 check the capsule file size, the capsule header size, the FMP capsule layout (header, item offset list, item offsets, image and vendor code sizes) and the certificate length of an image, each against the size of the capsule. Patch 5 checks the FMP payload header size; with CONFIG_EFI_CAPSULE_AUTHENTICATE that header is part of the signed image, so there it is hardening.

Patch 6 adds unit tests for patches 2-4, and patch 7 capsule on disk tests for patches 1 and 5. Each test fails without the patch it covers, except the one for patch 1: a capsule file shorter than its header is usually rejected anyway, because the read past the end of its buffer picks up heap data. Valgrind (CONFIG_VALGRIND) reports that read without patch 1 and nothing with it. The FWU accept capsule check of patch 2 has no test, as no sandbox configuration enables FWU_MULTI_BANK_UPDATE.

On an MbedTLS build a malformed certificate of valid length still crashes sandbox in efi_signature_verify(), with or without this series:
pkcs7_parse_message() returns ERR_PTR() of an MbedTLS error code, which IS_ERR() does not catch. Vsevolod Kozlov's "lib/mbedtls: Do not use ERR_PTR with mbedTLS error values" fixes that.

CI: Azure build 13698 passed, all 91 jobs, with this series on
https://github.com/u-boot/u-boot/pull/1064, a CI-only pull request that also carries my USB Ethernet rx, ext4 v2 and block size v2 series, merged with main c267fa81d42:
https://dev.azure.com/u-boot/u-boot/_build/results?buildId=13698

Changes in v2:
- Use size_t for item and item_count in patch 3 (Heinrich)
- Test a capsule header running past the end of the capsule in patch 6
- Add patch 7, capsule on disk tests for patches 1 and 5 (Heinrich)
- Add Ilias's Reviewed-by to patch 1
- Rebase on main

Ana Bobillo (7):
efi_loader: capsule: check the size of a capsule file
efi_loader: capsule: check the capsule header size
efi_loader: capsule: check the FMP capsule against its size
efi_loader: capsule: check the certificate length of an image
efi_loader: firmware: check the FMP payload header size
test: lib: add tests for the capsule size checks
test: py: efi_capsule: test truncated capsules and FMP payload headers

 arch/sandbox/dts/sandbox_capsule.dtsi         |  52 +++++
 lib/efi_loader/efi_capsule.c                  |  64 ++++--
 lib/efi_loader/efi_firmware.c                 |  20 +-
 test/lib/Makefile                             |   1 +
 test/lib/efi_capsule.c                        | 212 ++++++++++++++++++
 .../test_capsule_firmware_raw.py              |  34 +++
 .../test_capsule_firmware_signed_raw.py       |  56 +++++
 7 files changed, 420 insertions(+), 19 deletions(-)
 create mode 100644 test/lib/efi_capsule.c

base-commit: 8649a54d301a4d0ac526324c7a7ad2574939ff27

#1 lore raw

PATCH v2 1/7 efi_loader: capsule: check the size of a capsule file

From: Ana Bobillo <[email protected]>

efi_capsule_read_file() compares the size of the capsule file with the capsule_image_size field of its header, but does not check that the file holds a whole header first. A capsule file shorter than struct efi_capsule_header makes it read past the end of the buffer it allocated for the file.

Reject a capsule file shorter than its header.

Fixes c74cd8bd08d1 ("efi_loader: capsule: add capsule_on_disk support")
---
 lib/efi_loader/efi_capsule.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/efi_loader/efi_capsule.c +1 -1
index a77810fa15c..54c118736cf 100644
@@ -1190,7 +1190,7 @@ static efi_status_t efi_capsule_read_file(const u16 *filename,
 	/* fetch data */
 	ret = EFI_CALL((*fh->read)(fh, &size, buf));
 	if (ret == EFI_SUCCESS) {
-		if (size >= buf->capsule_image_size) {
+		if (size >= sizeof(*buf) && size >= buf->capsule_image_size) {
 			*capsule = buf;
 		} else {
 			free(buf);
#2 lore raw

PATCH v2 2/7 efi_loader: capsule: check the capsule header size

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

On the capsule on disk path, efi_capsule_update_firmware() is called without the header checks of efi_update_capsule(). It only checks header_size against the size of the FMP capsule header, so a header_size smaller than struct efi_capsule_header is accepted, and the empty capsules of the FWU multi bank update are handled before any check at all: fwu_empty_capsule_process() reads the image GUID of an accept capsule at header_size, which may lie anywhere after the capsule.

Check that header_size covers the capsule header and lies within the capsule before handling any capsule, and that an accept capsule holds the image GUID.

Fixes 8d99026f0697 ("efi_loader: capsule: support firmware update")
Fixes 86794052418b ("FWU: Add support for the FWU Multi Bank Update feature")
---
 lib/efi_loader/efi_capsule.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)
lib/efi_loader/efi_capsule.c +12 -0
index 54c118736cf..e8835315e86 100644
@@ -445,7 +445,14 @@ static __maybe_unused efi_status_t fwu_empty_capsule_process(
 		/*
 		 * Image accepted by the OS. Set the acceptance
 		 * status for the image.
+		 *
+		 * The caller has checked that header_size does not exceed
+		 * capsule_image_size.
 		 */
+		if (capsule->capsule_image_size - capsule->header_size <
+		    sizeof(*image_guid))
+			return EFI_INVALID_PARAMETER;
+
 		image_guid = (void *)(char *)capsule +
 			capsule->header_size;
 
@@ -544,6 +551,11 @@ static efi_status_t efi_capsule_update_firmware(
 	uint update_index;
 	bool fw_accept_os;
 
+	/* sanity check */
+	if (capsule_data->header_size < sizeof(*capsule_data) ||
+	    capsule_data->header_size > capsule_data->capsule_image_size)
+		return EFI_INVALID_PARAMETER;
+
 	if (IS_ENABLED(CONFIG_FWU_MULTI_BANK_UPDATE)) {
 		if (fwu_empty_capsule(capsule_data)) {
 			if (fwu_empty_capsule_checks_pass()) {
Reviewed-by on v2 2/7
#3 lore raw

Re: [PATCH v2 2/7] efi_loader: capsule: check the capsule header size

Quoted 12 lines · Ana Bobillo

From: Ana Bobillo <[email protected]>

On the capsule on disk path, efi_capsule_update_firmware() is called without the header checks of efi_update_capsule(). It only checks header_size against the size of the FMP capsule header, so a header_size smaller than struct efi_capsule_header is accepted, and the empty capsules of the FWU multi bank update are handled before any check at all: fwu_empty_capsule_process() reads the image GUID of an accept capsule at header_size, which may lie anywhere after the capsule.

Quoted 8 lines

Check that header_size covers the capsule header and lies within the capsule before handling any capsule, and that an accept capsule holds the image GUID.

Fixes 8d99026f0697 ("efi_loader: capsule: support firmware update")
Fixes 86794052418b ("FWU: Add support for the FWU Multi Bank Update feature")

---

Quoted 34 lines
 lib/efi_loader/efi_capsule.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)
lib/efi_loader/efi_capsule.c +12 -0
index 54c118736cf..e8835315e86 100644
@@ -445,7 +445,14 @@ static __maybe_unused efi_status_t fwu_empty_capsule_process(
                /*
                 * Image accepted by the OS. Set the acceptance
                 * status for the image.
+                *
+                * The caller has checked that header_size does not exceed
+                * capsule_image_size.
                 */
+               if (capsule->capsule_image_size - capsule->header_size <
+                   sizeof(*image_guid))
+                       return EFI_INVALID_PARAMETER;
+
                image_guid = (void *)(char *)capsule +
                        capsule->header_size;
 
@@ -544,6 +551,11 @@ static efi_status_t efi_capsule_update_firmware(
        uint update_index;
        bool fw_accept_os;
 
+       /* sanity check */
+       if (capsule_data->header_size < sizeof(*capsule_data) ||
+           capsule_data->header_size > capsule_data->capsule_image_size)
+               return EFI_INVALID_PARAMETER;
+
        if (IS_ENABLED(CONFIG_FWU_MULTI_BANK_UPDATE)) {
                if (fwu_empty_capsule(capsule_data)) {
                        if (fwu_empty_capsule_checks_pass()) {
#4 lore raw

PATCH v2 3/7 efi_loader: capsule: check the FMP capsule against its size

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

efi_capsule_update_firmware() reads the FMP capsule header, its item offset list and each image header without checking them against the size of the capsule:

- the capsule may end before the end of the FMP capsule header;
- the item offset list is indexed up to embedded_driver_count + payload_item_count - 1, which may run past the end of the capsule;
- the check of an item offset adds the image header size to a 64-bit offset and can wrap around, letting an offset close to U64_MAX through;
- update_image_size is passed on to the FMP driver without checking that the image fits in the capsule.

On the capsule on disk path all of this happens before the FMP driver authenticates the image: a capsule file in \EFI\UpdateCapsule on the ESP makes U-Boot read outside the capsule buffer the next time capsule on disk runs.

Check each of them against the capsule size, and check that the vendor code fits after the image too, along the lines of EDK2's ValidateFmpCapsule().

Fixes 8d99026f0697 ("efi_loader: capsule: support firmware update")

---
Changes in v2:
- Use size_t for item and item_count (Heinrich)

 lib/efi_loader/efi_capsule.c | 46 ++++++++++++++++++++++++++----------
 1 file changed, 33 insertions(+), 13 deletions(-)
lib/efi_loader/efi_capsule.c +33 -13
index e8835315e86..f57a7e60a5d 100644
@@ -538,11 +538,12 @@ static efi_status_t efi_capsule_update_firmware(
 {
 	struct efi_firmware_management_capsule_header *capsule;
 	struct efi_firmware_management_capsule_image_header *image;
-	size_t capsule_size, image_binary_size;
+	size_t capsule_size, image_binary_size, remaining;
 	void *image_binary, *vendor_code;
 	efi_handle_t *handles;
 	efi_uintn_t no_handles;
-	int item;
+	size_t item, item_count;
+	u64 item_offset;
 	struct efi_firmware_management_protocol *fmp;
 	u16 *abort_reason;
 	efi_guid_t *image_type_id;
@@ -588,18 +589,27 @@ static efi_status_t efi_capsule_update_firmware(
 		return EFI_UNSUPPORTED;
 	}
 
-	/* sanity check */
-	if (capsule_data->header_size < sizeof(*capsule) ||
-	    capsule_data->header_size >= capsule_data->capsule_image_size)
-		return EFI_INVALID_PARAMETER;
-
 	capsule = (void *)capsule_data + capsule_data->header_size;
 	capsule_size = capsule_data->capsule_image_size
 			- capsule_data->header_size;
 
+	/* sanity check */
+	if (capsule_size < sizeof(*capsule)) {
+		log_err("Capsule does not have enough data\n");
+		return EFI_INVALID_PARAMETER;
+	}
+
 	if (capsule->version != 0x00000001)
 		return EFI_UNSUPPORTED;
 
+	item_count = capsule->embedded_driver_count +
+		     capsule->payload_item_count;
+	if (item_count > (capsule_size - sizeof(*capsule)) /
+			 sizeof(*capsule->item_offset_list)) {
+		log_err("Capsule does not have enough data\n");
+		return EFI_INVALID_PARAMETER;
+	}
+
 	handles = NULL;
 	ret = EFI_CALL(efi_locate_handle_buffer(
 			BY_PROTOCOL,
@@ -609,24 +619,34 @@ static efi_status_t efi_capsule_update_firmware(
 		return EFI_UNSUPPORTED;
 
 	/* Payload */
-	for (item = capsule->embedded_driver_count;
-	     item < capsule->embedded_driver_count
-		    + capsule->payload_item_count; item++) {
+	for (item = capsule->embedded_driver_count; item < item_count;
+	     item++) {
 		/* sanity check */
-		if ((capsule->item_offset_list[item] + sizeof(*image)
-				 >= capsule_size)) {
+		item_offset = capsule->item_offset_list[item];
+		if (item_offset >= capsule_size ||
+		    capsule_size - item_offset <= sizeof(*image)) {
 			log_err("Capsule does not have enough data\n");
 			ret = EFI_INVALID_PARAMETER;
 			goto out;
 		}
 
-		image = (void *)capsule + capsule->item_offset_list[item];
+		image = (void *)capsule + item_offset;
 
 		if (image->version != 0x00000003) {
 			ret = EFI_UNSUPPORTED;
 			goto out;
 		}
 
+		/* the image and the vendor code must fit in the capsule */
+		remaining = capsule_size - item_offset - sizeof(*image);
+		if (image->update_image_size > remaining ||
+		    image->update_vendor_code_size >
+				remaining - image->update_image_size) {
+			log_err("Capsule does not have enough data\n");
+			ret = EFI_INVALID_PARAMETER;
+			goto out;
+		}
+
 		/* find a device for update firmware */
 		fmp = efi_fmp_find(&image->update_image_type_id,
 				   image->update_image_index,
#5 lore raw

PATCH v2 4/7 efi_loader: capsule: check the certificate length of an image

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

efi_remove_auth_hdr() skips the authentication header of an image by the dwLength of its certificate without checking it against the image size. A dwLength larger than the image makes the image size wrap around:

- with CONFIG_EFI_CAPSULE_AUTHENTICATE, efi_capsule_authenticate() then parses dwLength bytes of certificate past the end of the image before the signature is checked;
- without it, efi_capsule_update_firmware() passes the wrapped image size on to the FMP driver.

Reject a certificate that does not fit in the image.

Fixes 04be98bd6bcf ("efi: capsule: Add support for uefi capsule authentication")
Fixes c2cc60c1f93b ("efi_loader: capsule: remove authentication data")
---
 lib/efi_loader/efi_capsule.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
lib/efi_loader/efi_capsule.c +3 -1
index f57a7e60a5d..646428c7d8f 100644
@@ -270,7 +270,9 @@ static efi_status_t efi_remove_auth_hdr(void **image, efi_uintn_t *image_size)
 		goto out;
 
 	if (auth_hdr->auth_info.hdr.dwLength <=
-	    offsetof(struct win_certificate_uefi_guid, cert_data))
+	    offsetof(struct win_certificate_uefi_guid, cert_data) ||
+	    auth_hdr->auth_info.hdr.dwLength >
+	    *image_size - sizeof(auth_hdr->monotonic_count))
 		goto out;
 
 	*image = (uint8_t *)*image + sizeof(auth_hdr->monotonic_count) +
#6 lore raw

PATCH v2 5/7 efi_loader: firmware: check the FMP payload header size

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

efi_firmware_get_fw_version() reads an FMP payload header at the start of an image without checking that the image holds one, and skips it by its header_size without checking that against the image size. A header_size larger than the image makes the image size wrap around before the image is written.

Only look for the header in an image large enough to hold it, and reject a header_size smaller than the header or larger than the image.

With CONFIG_EFI_CAPSULE_AUTHENTICATE the header is part of the signed image, so there this is hardening.

Fixes 675b62e12f9d ("efi_loader: Add logic to parse EDKII specific fmp payload header")
---
 lib/efi_loader/efi_firmware.c | 20 ++++++++++++++++----
 1 file changed, 16 insertions(+), 4 deletions(-)
lib/efi_loader/efi_firmware.c +16 -4
index 84de95f5c23..4a5249e5d4a 100644
@@ -499,22 +499,32 @@ efi_status_t efi_firmware_set_fmp_state_var(struct fmp_state *state, u8 image_in
  * Parse the FMP payload header and fill the fmp_state structure.
  * If no FMP payload header is found, fmp_state structure is not updated.
  *
+ * Return:		EFI_SUCCESS, or EFI_INVALID_PARAMETER for a bad header_size
  */
-static void efi_firmware_get_fw_version(const void **p_image,
-					efi_uintn_t *p_image_size,
-					struct fmp_state *state)
+static efi_status_t efi_firmware_get_fw_version(const void **p_image,
+						efi_uintn_t *p_image_size,
+						struct fmp_state *state)
 {
 	const struct fmp_payload_header *header;
 	u32 fmp_hdr_signature = FMP_PAYLOAD_HDR_SIGNATURE;
 
+	if (*p_image_size < sizeof(*header))
+		return EFI_SUCCESS;
+
 	header = *p_image;
 	if (header->signature == fmp_hdr_signature) {
+		if (header->header_size < sizeof(*header) ||
+		    header->header_size > *p_image_size)
+			return EFI_INVALID_PARAMETER;
+
 		/* FMP header is inserted above the capsule payload */
 		state->fw_version = header->fw_version;
 
 		*p_image += header->header_size;
 		*p_image_size -= header->header_size;
 	}
+
+	return EFI_SUCCESS;
 }
 
 /**
@@ -543,7 +553,9 @@ efi_status_t efi_firmware_verify_image(const void **p_image,
 	if (ret != EFI_SUCCESS)
 		return ret;
 
-	efi_firmware_get_fw_version(p_image, p_image_size, state);
+	ret = efi_firmware_get_fw_version(p_image, p_image_size, state);
+	if (ret != EFI_SUCCESS)
+		return ret;
 
 	image_type_id = efi_firmware_get_image_type_id(image_index);
 	if (!image_type_id)
#7 lore raw

PATCH v2 6/7 test: lib: add tests for the capsule size checks

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

Add unit tests that pass malformed FMP capsules to efi_update_capsule() and an image with a certificate longer than itself to efi_capsule_authenticate(), and check that they are rejected:

- a capsule header running past the end of the capsule;
- a capsule ending inside the FMP capsule header;
- an item offset list running past the end of the capsule;
- an item offset that wraps around when the image header size is added;
- an image or vendor code larger than the rest of the capsule;
- a certificate longer than the image.

Each capsule is built inside a larger zeroed buffer, so that without the checks the code reads the bytes around it and returns another status (for the certificate, a wrapped image size) instead of faulting.

---
Changes in v2:
- Test a capsule header running past the end of the capsule

 test/lib/Makefile      |   1 +
 test/lib/efi_capsule.c | 212 +++++++++++++++++++++++++++++++++++++++++
 2 files changed, 213 insertions(+)
 create mode 100644 test/lib/efi_capsule.c
test/lib/Makefile +1 -0
index 9fc4a1a9b5d..0fb6c6eabde 100644
@@ -10,6 +10,7 @@ obj-y += abuf.o
 obj-y += alist.o
 obj-$(CONFIG_ECDSA_VERIFY_MBEDTLS) += ecdsa.o
 obj-$(CONFIG_EFI_LOADER) += efi_device_path.o efi_memory.o
+obj-$(CONFIG_EFI_CAPSULE_FIRMWARE) += efi_capsule.o
 obj-$(CONFIG_EFI_SECURE_BOOT) += efi_image_region.o
 ifdef CONFIG_RISCV
 obj-$(CONFIG_USE_PRIVATE_LIBGCC) += test_clz.o
test/lib/efi_capsule.c new file +212 -0

212 lines not on this page · raw message

#8 lore raw

PATCH v2 7/7 test: py: efi_capsule: test truncated capsules and FMP payload headers

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

Add capsule on disk tests for the checks that need a capsule file or a signed capsule:

- a capsule file shorter than the capsule header;
- signed capsules whose FMP payload header has a header_size smaller than the header or larger than the image.

None of them may update the firmware, and each file is removed.

---
Changes in v2:
- New patch: capsule on disk tests for patches 1 and 5 (Heinrich)

 arch/sandbox/dts/sandbox_capsule.dtsi         | 52 +++++++++++++++++
 .../test_capsule_firmware_raw.py              | 34 +++++++++++
 .../test_capsule_firmware_signed_raw.py       | 56 +++++++++++++++++++
 3 files changed, 142 insertions(+)
arch/sandbox/dts/sandbox_capsule.dtsi +52 -0
index 34d29916b30..f7418f9794a 100644
@@ -166,4 +166,56 @@
 			};
 		};
 	};
+
+	capsule12 {
+		filename = "Test116";
+		efi-capsule {
+			image-index = <0x1>;
+			image-guid = SANDBOX_UBOOT_IMAGE_GUID;
+			private-key = CAPSULE_PRIV_KEY;
+			public-key-cert = CAPSULE_PUB_KEY;
+			monotonic-count = <0x1>;
+
+			/* FMP payload header, header_size 0: smaller than the header */
+			payload-header {
+				type = "text";
+				text = "MSS1";
+			};
+
+			payload-header-rest {
+				type = "fill";
+				size = <12>;
+			};
+
+			text {
+				text = "u-boot:New";
+			};
+		};
+	};
+
+	capsule13 {
+		filename = "Test117";
+		efi-capsule {
+			image-index = <0x1>;
+			image-guid = SANDBOX_UBOOT_IMAGE_GUID;
+			private-key = CAPSULE_PRIV_KEY;
+			public-key-cert = CAPSULE_PUB_KEY;
+			monotonic-count = <0x1>;
+
+			/* FMP payload header, header_size 64: larger than the image */
+			payload-header {
+				type = "text";
+				text = "MSS1\x40";
+			};
+
+			payload-header-rest {
+				type = "fill";
+				size = <11>;
+			};
+
+			text {
+				text = "u-boot:New";
+			};
+		};
+	};
 };
test/py/tests/test_efi_capsule/test_capsule_firmware_raw.py +34 -0
index b8cb483b380..a79a975c67e 100644
@@ -7,6 +7,7 @@ This test verifies capsule-on-disk firmware update for raw images
 """
 
 import pytest
+from capsule_defs import CAPSULE_DATA_DIR, CAPSULE_INSTALL_DIR
 from capsule_common import (
     capsule_setup,
     init_content,
@@ -238,3 +239,36 @@ class TestEfiCapsuleFirmwareRaw:
             check_file_removed(ubman, disk_img, capsule_files)
 
             verify_content(ubman, '100000', 'u-boot:Old')
+
+    def test_efi_capsule_fw6(
+            self, u_boot_config, ubman, efi_capsule_data):
+        """ Test Case 6
+        Update U-Boot on SPI Flash with a capsule file shorter than
+        the capsule header
+        No update should happen
+        0x100000-0x150000: U-Boot binary (but dummy)
+        """
+        disk_img = efi_capsule_data
+        capsule_files = ['Test01']
+        with ubman.log.section('Test Case 6-a, before reboot'):
+            capsule_setup(ubman, disk_img, '0x0000000000000004')
+            init_content(ubman, '100000', 'u-boot.bin.old', 'Old')
+            # place only the first 16 bytes of the capsule file
+            ubman.run_command_list([
+                f'fatload host 0:1 4000000 {CAPSULE_DATA_DIR}/Test01',
+                f'fatwrite host 0:1 4000000 {CAPSULE_INSTALL_DIR}/Test01 10'])
+
+        capsule_early = u_boot_config.buildconfig.get(
+            'config_efi_capsule_on_disk_early')
+
+        # reboot
+        ubman.restart_uboot(expect_reset = capsule_early)
+
+        with ubman.log.section('Test Case 6-b, after reboot'):
+            if not capsule_early:
+                exec_manual_update(ubman, disk_img, capsule_files)
+
+            # deleted anyway
+            check_file_removed(ubman, disk_img, capsule_files)
+
+            verify_content(ubman, '100000', 'u-boot:Old')
test/py/tests/test_efi_capsule/test_capsule_firmware_signed_raw.py +56 -0

59 lines not on this page · raw message