Skip to contentSkip to conversation

efi_loader: check PE images before using them

PATCH Superseded Ana Bobillo 2 participants 17 messages Nov 3 – Nov 6

v2 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

v2 cover efi_loader: check PE images before using them

U-Boot takes the offsets and sizes of a PE/COFF image from its headers and uses them before it knows whether the image may run. With Secure Boot on, efi_load_pe() authenticates the image first but goes on copying and relocating it when authentication fails, and only then returns EFI_SECURITY_VIOLATION; efi_image_parse(), which collects the regions to hash, runs before the signature is checked, and so does the walk of the certificate table. TCG2 measured boot parses every image as well. So an image that will be refused, or one that is only measured, can make U-Boot read or write outside its buffers, or hang.

This series checks those fields against the image where they are read, along the lines of EDK2's PeCoffLoaderLib and DxeImageVerificationLib:

- patch 1 has efi_check_pe() check for a 64bit NT header again, as its comment says;
- patch 2 checks the headers, the sections and the certificate table in efi_image_parse(), and fails on errors of efi_image_region_add();
- patches 3 and 4 have efi_load_pe() reject, before allocating the image, a section whose end wraps around and section data past the end of the file; patch 5 makes room in the loaded image for all of the headers;
- patch 6 checks the relocation table against the image;
- patch 7 rejects a certificate table holding a certificate shorter than its header, which made the walk loop forever, or longer than the rest of the table;
- patch 8 refuses to load an image whose subsystem is not one of the UEFI image types, as EDK2 does;
- patch 9 marks an image whose TCG2 measurement failed as not authenticated, so that it is not started unmeasured;
- patches 10 and 11 add unit tests and a Secure Boot test.

Patch 9 applies on top of Heinrich's "efi_loader: handling of missing TPM in efi_load_pe()" [1], which does the same for a missing TPM. The other patches apply to main without it.

barebox, whose EFI loader is based on this file, made several of the same changes this year; patches 2, 3 and 4 follow them and say so.

Valid images are unaffected: the unit tests check PE32 and PE32+ images with 16, 6 or 5 data directories, an unpadded last section and a file alignment of 0, the EFI selftests and the Secure Boot tests pass, and each patch builds on its own. Tested on sandbox.

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

[1] https://patchwork.ozlabs.org/patch/2335140/

Changes in v2:
- rebase on current main
- patch 1: declare the NT header pointer in efi_check_pe() as IMAGE_NT_HEADERS64 *, the type its size is checked against (Heinrich)
- patch 2: require SizeOfOptionalHeader to hold exactly NumberOfRvaAndSizes data directories, at most 16, as EDK2 and shim do; check FileAlignment once, taking 0 as the PECOFF default of 512; drop pe_align_size() for ALIGN() on a u64; start num_regions at 4; say why sorted is freed on the error path; drop the wrong remark on barebox (Heinrich)
- patch 3: say in the comment why the sum wraps on 64bit systems too (Heinrich)
- patch 4: check all of a section's raw data against the image, also when VirtualSize is smaller (Heinrich)
- patch 5: allocate room for the headers instead of refusing an image whose headers are longer than its sections (Heinrich); retitled from "check that the PE headers fit into the loaded image"
- new patch 8: refuse an image of an unknown subsystem in efi_load_pe() (suggested by Ilias)
- patch 9 (was 8): mark an image whose measurement failed as not authenticated, as [1] does for a missing TPM, so that LoadImage() returns EFI_SECURITY_VIOLATION and StartImage() refuses it, instead of refusing to load it; say why an image that is not measured goes unnoticed; retitled from "do not load an image that cannot be measured"
- patch 10 (was 9): test the subsystem check, a file alignment of 0, more than 16 data directories and raw data past the image beyond a smaller VirtualSize; the headers test checks that the loaded image holds all of the headers; the measurement test expects EFI_SECURITY_VIOLATION
- add Ilias's Reviewed-by to patches 1 and 3, Heinrich's to patch 1

Ana Bobillo (11):
efi_loader: check the NT header size in efi_check_pe()
efi_loader: check the PE image ranges in efi_image_parse()
efi_loader: reject a PE section whose end wraps around
efi_loader: check PE section raw data against the image size
efi_loader: make room for the PE headers in the loaded image
efi_loader: check the relocation table against the image size
efi_loader: check certificate lengths in efi_image_authenticate()
efi_loader: refuse a PE image of an unknown subsystem
efi_loader: do not start an image that cannot be measured
test: lib: add tests for the PE image checks
test: py: test invalid certificate lengths in signed images

 lib/efi_loader/efi_image_loader.c             | 364 +++++++++----
 test/lib/Makefile                             |   2 +-
 test/lib/efi_image_loader.c                   | 501 ++++++++++++++++++
 test/py/tests/test_efi_secboot/conftest.py    |  31 ++
 test/py/tests/test_efi_secboot/test_signed.py |  36 ++
 5 files changed, 832 insertions(+), 102 deletions(-)
 create mode 100644 test/lib/efi_image_loader.c

base-commit: ab4dc5aacf957835c295b59ef2dd28281839cb20
prerequisite-patch-id: 1a9ac95eb73ee7e45e338735a4b05df5dc7060ac

#1 lore raw

PATCH v2 1/11 efi_loader: check the NT header size in efi_check_pe()

From: Ana Bobillo <[email protected]>

efi_check_pe() is meant to check that the image holds a 64bit NT header, which is longer than a 32bit one, as its comment says. Since commit 5dad05a0e61d ("efi_loader: carve out efi_check_pe()") it checks for a 32bit one only, so the callers read the optional header fields and data directories of a PE32+ image past the end of a truncated image. The addition of e_lfanew can also wrap around on 32bit systems.

Check for the size of the 64bit NT header again, without wrapping, and declare the header pointer with that type too.

Fixes 5dad05a0e61d ("efi_loader: carve out efi_check_pe()")
---
 lib/efi_loader/efi_image_loader.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
lib/efi_loader/efi_image_loader.c +4 -3
index a03866c2907..c2c3109ad1d 100644
@@ -835,7 +835,7 @@ static bool efi_image_authenticate(void *efi, size_t efi_size)
 efi_status_t efi_check_pe(void *buffer, size_t size, void **nt_header)
 {
 	IMAGE_DOS_HEADER *dos = buffer;
-	IMAGE_NT_HEADERS32 *nt;
+	IMAGE_NT_HEADERS64 *nt;
 
 	if (size < sizeof(*dos))
 		return EFI_INVALID_PARAMETER;
@@ -849,9 +849,10 @@ efi_status_t efi_check_pe(void *buffer, size_t size, void **nt_header)
 	 * least one section header follows we only need to check for the length
 	 * of the 64bit header which is longer than the 32bit header.
 	 */
-	if (size < dos->e_lfanew + sizeof(IMAGE_NT_HEADERS32))
+	if (dos->e_lfanew > size ||
+	    size - dos->e_lfanew < sizeof(*nt))
 		return EFI_INVALID_PARAMETER;
-	nt = (IMAGE_NT_HEADERS32 *)((u8 *)buffer + dos->e_lfanew);
+	nt = (IMAGE_NT_HEADERS64 *)((u8 *)buffer + dos->e_lfanew);
 
 	/* Check for PE-COFF magic */
 	if (nt->Signature != IMAGE_NT_SIGNATURE)
#2 lore raw

PATCH v2 2/11 efi_loader: check the PE image ranges in efi_image_parse()

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

efi_image_parse() collects the regions of an image to be hashed for Secure Boot and for TCG2 measurements. It takes the header size, the section table, each section's raw data and the certificate table from the image without checking them against the image size:

- SizeOfHeaders and each section's PointerToRawData and SizeOfRawData are added as regions even when they run past the end of the image, which is then read out of bounds when the regions are hashed;
- the section table is read wherever SizeOfOptionalHeader and NumberOfSections put it;
- the end of the certificate table is computed in 32 bits, so a large offset wraps around and passes the check;
- errors of efi_image_region_add() are ignored.

All of this happens before the signature is verified.

Call efi_check_pe() first, check each offset and size against the image size without wrapping, add regions only through a checked helper and fail on its errors. Require the optional header to hold exactly the data directories it declares, at most 16, as EDK2 and shim do. Take a file alignment of 0 as the PECOFF default of 512 and require any other to be a power of two. The padding of a section to the file alignment is hashed only as far as the image goes, so an image whose last section is not padded is still accepted. Check the certificate table against the size of WIN_CERTIFICATE, not of a pointer to it. The sorted section table is now freed on the error path too, which the new error exits from the section loop need.

barebox, whose EFI loader is based on this file, added similar checks in 4ec1f7166778 ("efi: validate PE parser input ranges").

Fixes 4540dabdcaca ("efi_loader: image_loader: support image authentication")
---
 lib/efi_loader/efi_image_loader.c | 254 +++++++++++++++++++++---------
 1 file changed, 176 insertions(+), 78 deletions(-)
lib/efi_loader/efi_image_loader.c +176 -78
index c2c3109ad1d..7be5b6f2a9b 100644
@@ -393,6 +393,45 @@ void *efi_prepare_aligned_image(void *efi, u64 *efi_size)
 	}
 }
 
+/**
+ * pe_range_ok() - check that a range lies within the image
+ * @len:	size of the image
+ * @off:	offset of the range from the start of the image
+ * @size:	size of the range
+ *
+ * Return:	true if [@off, @off + @size) lies within [0, @len)
+ */
+static bool pe_range_ok(size_t len, size_t off, size_t size)
+{
+	return off <= len && size <= len - off;
+}
+
+/**
+ * efi_image_region_add_checked() - add a region of an image
+ * @regs:	pointer to array of regions
+ * @efi:	pointer to the image
+ * @len:	size of the image
+ * @start:	offset of the region in the image
+ * @size:	size of the region
+ * @nocheck:	flag against overlapped regions
+ *
+ * Add the region [@start, @start + @size[ of the image to @regs if it lies
+ * within the image.
+ *
+ * Return:	status code
+ */
+static efi_status_t efi_image_region_add_checked(struct efi_image_regions *regs,
+						 const void *efi, size_t len,
+						 size_t start, size_t size,
+						 int nocheck)
+{
+	if (!pe_range_ok(len, start, size))
+		return EFI_INVALID_PARAMETER;
+
+	return efi_image_region_add(regs, efi + start, efi + start + size,
+				    nocheck);
+}
+
 /**
  * efi_image_parse() - parse a PE image
  * @efi:	Pointer to image
@@ -401,8 +440,8 @@ void *efi_prepare_aligned_image(void *efi, u64 *efi_size)
  * @auth:	Pointer to a pointer to authentication data in PE
  * @auth_len:	Size of @auth
  *
- * Parse image binary in PE32(+) format, assuming that sanity of PE image
- * has been checked by a caller.
+ * Parse image binary in PE32(+) format. Each offset and size taken from the
+ * image is checked against @len before it is used.
  * On success, an address of authentication data in @efi and its size will
  * be returned in @auth and @auth_len, respectively.
  *
@@ -411,97 +450,142 @@ void *efi_prepare_aligned_image(void *efi, u64 *efi_size)
 bool efi_image_parse(void *efi, size_t len, struct efi_image_regions **regp,
 		     WIN_CERTIFICATE **auth, size_t *auth_len)
 {
-	struct efi_image_regions *regs;
-	IMAGE_DOS_HEADER *dos;
+	struct efi_image_regions *regs = NULL;
 	IMAGE_NT_HEADERS32 *nt;
-	IMAGE_SECTION_HEADER *sections, **sorted;
+	IMAGE_SECTION_HEADER *sections, **sorted = NULL;
 	int num_regions, num_sections, i;
 	int ctidx = IMAGE_DIRECTORY_ENTRY_SECURITY;
-	u32 align, size, authsz, authoff;
-	size_t bytes_hashed;
+	u32 align, authsz, authoff, header_size, num_dirs;
+	size_t bytes_hashed, opt_off, opt_size, dirs_start;
+	size_t csum_off, subsys_off, dir_off, dir_end;
+	size_t sections_off, sections_size;
 
-	dos = (void *)efi;
-	nt = (void *)(efi + dos->e_lfanew);
 	authoff = 0;
 	authsz = 0;
 
 	/*
-	 * Count maximum number of regions to be digested.
-	 * We don't have to have an exact number here.
-	 * See efi_image_region_add()'s in parsing below.
+	 * efi_check_pe() checks the DOS and PE signatures and that the image
+	 * is large enough to hold a 64bit NT header, which is longer than a
+	 * 32bit one. Every optional header field and data directory entry
+	 * read below therefore lies within the image.
 	 */
-	num_regions = 3; /* for header */
-	num_regions += nt->FileHeader.NumberOfSections;
-	num_regions++; /* for extra */
-
-	regs = calloc(sizeof(*regs) + sizeof(struct image_region) * num_regions,
-		      1);
-	if (!regs)
-		goto err;
-	regs->max = num_regions;
+	if (efi_check_pe(efi, len, (void **)&nt) != EFI_SUCCESS)
+		return false;
+	opt_off = (u8 *)&nt->OptionalHeader - (u8 *)efi;
+	opt_size = nt->FileHeader.SizeOfOptionalHeader;
 
-	/*
-	 * Collect data regions for hash calculation
-	 * 1. File headers
-	 */
 	if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
 		IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
 		IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
 
-		/* Skip CheckSum */
-		efi_image_region_add(regs, efi, &opt->CheckSum, 0);
-		if (nt64->OptionalHeader.NumberOfRvaAndSizes <= ctidx) {
-			efi_image_region_add(regs,
-					     &opt->Subsystem,
-					     efi + opt->SizeOfHeaders, 0);
-		} else {
-			/* Skip Certificates Table */
-			efi_image_region_add(regs,
-					     &opt->Subsystem,
-					     &opt->DataDirectory[ctidx], 0);
-			efi_image_region_add(regs,
-					     &opt->DataDirectory[ctidx] + 1,
-					     efi + opt->SizeOfHeaders, 0);
-
+		dirs_start = offsetof(IMAGE_OPTIONAL_HEADER64, DataDirectory);
+		csum_off = opt_off + offsetof(IMAGE_OPTIONAL_HEADER64,
+					      CheckSum);
+		subsys_off = opt_off + offsetof(IMAGE_OPTIONAL_HEADER64,
+						Subsystem);
+		dir_off = opt_off + offsetof(IMAGE_OPTIONAL_HEADER64,
+					     DataDirectory[ctidx]);
+		header_size = opt->SizeOfHeaders;
+		align = opt->FileAlignment;
+		num_dirs = opt->NumberOfRvaAndSizes;
+		if (num_dirs > ctidx) {
 			authoff = opt->DataDirectory[ctidx].VirtualAddress;
 			authsz = opt->DataDirectory[ctidx].Size;
 		}
-
-		bytes_hashed = opt->SizeOfHeaders;
-		align = opt->FileAlignment;
 	} else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
 		IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
 
-		/* Skip CheckSum */
-		efi_image_region_add(regs, efi, &opt->CheckSum, 0);
-		if (nt->OptionalHeader.NumberOfRvaAndSizes <= ctidx) {
-			efi_image_region_add(regs,
-					     &opt->Subsystem,
-					     efi + opt->SizeOfHeaders, 0);
-		} else {
-			/* Skip Certificates Table */
-			efi_image_region_add(regs, &opt->Subsystem,
-					     &opt->DataDirectory[ctidx], 0);
-			efi_image_region_add(regs,
-					     &opt->DataDirectory[ctidx] + 1,
-					     efi + opt->SizeOfHeaders, 0);
-
+		dirs_start = offsetof(IMAGE_OPTIONAL_HEADER32, DataDirectory);
+		csum_off = opt_off + offsetof(IMAGE_OPTIONAL_HEADER32,
+					      CheckSum);
+		subsys_off = opt_off + offsetof(IMAGE_OPTIONAL_HEADER32,
+						Subsystem);
+		dir_off = opt_off + offsetof(IMAGE_OPTIONAL_HEADER32,
+					     DataDirectory[ctidx]);
+		header_size = opt->SizeOfHeaders;
+		align = opt->FileAlignment;
+		num_dirs = opt->NumberOfRvaAndSizes;
+		if (num_dirs > ctidx) {
 			authoff = opt->DataDirectory[ctidx].VirtualAddress;
 			authsz = opt->DataDirectory[ctidx].Size;
 		}
-
-		bytes_hashed = opt->SizeOfHeaders;
-		align = opt->FileAlignment;
 	} else {
 		log_err("%s: Invalid optional header magic %x\n", __func__,
 			nt->OptionalHeader.Magic);
+		return false;
+	}
+	dir_end = dir_off + sizeof(IMAGE_DATA_DIRECTORY);
+
+	/*
+	 * The optional header must hold exactly the data directories it
+	 * declares, at most 16, as EDK2 and shim require. The section table
+	 * follows the optional header; it and the whole header area
+	 * (SizeOfHeaders) must lie within the image, as must the certificate
+	 * table.
+	 */
+	num_sections = nt->FileHeader.NumberOfSections;
+	sections_off = opt_off + opt_size;
+	sections_size = (size_t)num_sections * sizeof(IMAGE_SECTION_HEADER);
+	if (num_dirs > IMAGE_NUMBEROF_DIRECTORY_ENTRIES ||
+	    opt_size != dirs_start + num_dirs * sizeof(IMAGE_DATA_DIRECTORY) ||
+	    !pe_range_ok(len, sections_off, sections_size) ||
+	    !pe_range_ok(len, 0, header_size) ||
+	    header_size < sections_off + sections_size) {
+		log_err("%s: Invalid PE headers\n", __func__);
+		return false;
+	}
+	if (authsz && !pe_range_ok(len, authoff, authsz)) {
+		log_err("%s: Size for auth too large: %u\n", __func__, authsz);
+		return false;
+	}
+
+	/* The file alignment is a power of two, by default 512 (PECOFF) */
+	if (!align)
+		align = 512;
+	if (align & (align - 1)) {
+		log_err("%s: Invalid file alignment %u\n", __func__, align);
+		return false;
+	}
+
+	/*
+	 * Count maximum number of regions to be digested: three for the
+	 * header, one for each section and one for extra data.
+	 * We don't have to have an exact number here.
+	 * See efi_image_region_add()'s in parsing below.
+	 */
+	num_regions = 4 + num_sections;
+
+	regs = calloc(sizeof(*regs) + sizeof(struct image_region) * num_regions,
+		      1);
+	if (!regs)
 		goto err;
+	regs->max = num_regions;
+
+	/*
+	 * Collect data regions for hash calculation
+	 * 1. File headers
+	 */
+	/* Skip CheckSum */
+	if (efi_image_region_add_checked(regs, efi, len, 0, csum_off, 0))
+		goto err;
+	if (num_dirs <= ctidx) {
+		if (efi_image_region_add_checked(regs, efi, len, subsys_off,
+						 header_size - subsys_off, 0))
+			goto err;
+	} else {
+		/* Skip Certificates Table */
+		if (efi_image_region_add_checked(regs, efi, len, subsys_off,
+						 dir_off - subsys_off, 0))
+			goto err;
+		if (efi_image_region_add_checked(regs, efi, len, dir_end,
+						 header_size - dir_end, 0))
+			goto err;
 	}
 
+	bytes_hashed = header_size;
+
 	/* 2. Sections */
-	num_sections = nt->FileHeader.NumberOfSections;
-	sections = (void *)((uint8_t *)&nt->OptionalHeader +
-			    nt->FileHeader.SizeOfOptionalHeader);
+	sections = (void *)((uint8_t *)efi + sections_off);
 	sorted = calloc(sizeof(IMAGE_SECTION_HEADER *), num_sections);
 	if (!sorted) {
 		log_err("%s: Out of memory\n", __func__);
@@ -516,14 +600,29 @@ bool efi_image_parse(void *efi, size_t len, struct efi_image_regions **regp,
 	qsort(sorted, num_sections, sizeof(sorted[0]), cmp_pe_section);
 
 	for (i = 0; i < num_sections; i++) {
+		size_t size;
+
 		if (!sorted[i]->SizeOfRawData)
 			continue;
 
-		size = (sorted[i]->SizeOfRawData + align - 1) & ~(align - 1);
-		efi_image_region_add(regs, efi + sorted[i]->PointerToRawData,
-				     efi + sorted[i]->PointerToRawData + size,
-				     0);
-		log_debug("section[%d](%s): raw: 0x%x-0x%x, virt: %x-%x\n",
+		if (!pe_range_ok(len, sorted[i]->PointerToRawData,
+				 sorted[i]->SizeOfRawData)) {
+			log_err("%s: Invalid section %d\n", __func__, i);
+			goto err;
+		}
+		/*
+		 * The padding to the file alignment ends with the image. Round
+		 * up in 64 bits, where the sum of two u32 cannot wrap around.
+		 */
+		size = min_t(u64, ALIGN((u64)sorted[i]->SizeOfRawData, align),
+			     len - sorted[i]->PointerToRawData);
+		if (efi_image_region_add_checked(regs, efi, len,
+						 sorted[i]->PointerToRawData,
+						 size, 0)) {
+			log_err("%s: Invalid section %d\n", __func__, i);
+			goto err;
+		}
+		log_debug("section[%d](%s): raw: 0x%x-0x%zx, virt: %x-%x\n",
 			  i, sorted[i]->Name,
 			  sorted[i]->PointerToRawData,
 			  sorted[i]->PointerToRawData + size,
@@ -534,25 +633,23 @@ bool efi_image_parse(void *efi, size_t len, struct efi_image_regions **regp,
 		bytes_hashed += size;
 	}
 	free(sorted);
+	sorted = NULL;
 
 	/* 3. Extra data excluding Certificates Table */
-	if (bytes_hashed + authsz < len) {
+	if (bytes_hashed < len && authsz < len - bytes_hashed) {
 		log_debug("extra data for hash: %zu\n",
 			  len - (bytes_hashed + authsz));
-		efi_image_region_add(regs, efi + bytes_hashed,
-				     efi + len - authsz, 0);
+		if (efi_image_region_add_checked(regs, efi, len, bytes_hashed,
+						 len - bytes_hashed - authsz,
+						 0))
+			goto err;
 	}
 
 	/* Return Certificates Table */
 	if (authsz) {
-		if (len < authoff + authsz) {
-			log_err("%s: Size for auth too large: %u >= %zu\n",
-				__func__, authsz, len - authoff);
-			goto err;
-		}
-		if (authsz < sizeof(*auth)) {
+		if (authsz < sizeof(**auth)) {
 			log_err("%s: Size for auth too small: %u < %zu\n",
-				__func__, authsz, sizeof(*auth));
+				__func__, authsz, sizeof(**auth));
 			goto err;
 		}
 		*auth = efi + authoff;
@@ -569,6 +666,7 @@ bool efi_image_parse(void *efi, size_t len, struct efi_image_regions **regp,
 	return true;
 
 err:
+	free(sorted);
 	free(regs);
 
 	return false;
#3 lore raw

PATCH v2 3/11 efi_loader: reject a PE section whose end wraps around

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

efi_load_pe() computes the end of each section as the sum of its VirtualAddress and its size, both u32, so the sum wraps around before it is widened to unsigned long. A section near 4 GiB then yields a small virt_size, and the memset() and memcpy() of the section write far past the allocated image.

Relative virtual addresses are 32 bit, so reject a section whose end does not fit into 32 bits. barebox, whose EFI loader is based on this file, fixed the same in b6598389d46d ("efi: loader: fix integer overflow in PE virt_size calculation").

This runs before the image is rejected when Secure Boot fails to verify it.

Fixes cb149c66342c ("efi_loader: Add PE image loader")
---
 lib/efi_loader/efi_image_loader.c | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)
lib/efi_loader/efi_image_loader.c +14 -2
index 7be5b6f2a9b..f81ccd62ab1 100644
@@ -1048,9 +1048,21 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
 	/* Calculate upper virtual address boundary */
 	for (i = num_sections - 1; i >= 0; i--) {
 		IMAGE_SECTION_HEADER *sec = &sections[i];
+		u32 end;
 
-		virt_size = max_t(unsigned long, virt_size,
-				  sec->VirtualAddress + section_size(sec));
+		/*
+		 * VirtualAddress and section_size() are both u32, so their sum
+		 * wraps around at 4 GiB, on 64bit systems too. A wrapped end
+		 * would make virt_size too small for the memset() and memcpy()
+		 * below.
+		 */
+		if (__builtin_add_overflow(sec->VirtualAddress,
+					   section_size(sec), &end)) {
+			log_err("Section %d virtual address overflow\n", i);
+			return EFI_LOAD_ERROR;
+		}
+
+		virt_size = max_t(unsigned long, virt_size, end);
 	}
 
 	/* Read 32/64bit specific header bits */
#4 lore raw

PATCH v2 4/11 efi_loader: check PE section raw data against the image size

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

efi_load_pe() copies each section from PointerToRawData in the image without checking that the copied bytes lie within the image, so a section pointing near or past the end of the image is read out of bounds.

Reject a section whose raw data does not lie within the image before the image is allocated, also when VirtualSize is smaller and only part of the raw data is copied. barebox, whose EFI loader is based on this file, checks the copied part since 552a54e4d357 ("efi: loader: validate section raw data bounds against image size").

This runs before the image is rejected when Secure Boot fails to verify it.

Fixes cb149c66342c ("efi_loader: Add PE image loader")
---
 lib/efi_loader/efi_image_loader.c | 7 +++++++
 1 file changed, 7 insertions(+)
lib/efi_loader/efi_image_loader.c +7 -0
index f81ccd62ab1..f9594189bef 100644
@@ -1062,6 +1062,13 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
 			return EFI_LOAD_ERROR;
 		}
 
+		/* The raw data of the section must lie within the image */
+		if (!pe_range_ok(efi_size, sec->PointerToRawData,
+				 sec->SizeOfRawData)) {
+			log_err("Section %d exceeds image size\n", i);
+			return EFI_LOAD_ERROR;
+		}
+
 		virt_size = max_t(unsigned long, virt_size, end);
 	}
 
#5 lore raw

PATCH v2 5/11 efi_loader: make room for the PE headers in the loaded image

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

efi_load_pe() copies the PE headers to the start of the allocated image. The size it copies is not the size of the headers: it adds the size of a whole 32bit NT header, which already holds an optional header, to SizeOfOptionalHeader, and assumes that the NT header follows the DOS header directly. Nor is it checked against the size of the allocation, which only covers the sections. An image with many empty section headers but little section data makes the copy write past the allocation, and the copy reads past the end of a small image.

Copy the headers up to the end of the section table, which is already checked to lie within the image, and allocate at least that much.

This runs before the image is rejected when Secure Boot fails to verify it.

Fixes 8458bf648fd7 ("efi_loader: set image_base and image_size to correct values")
---
 lib/efi_loader/efi_image_loader.c | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)
lib/efi_loader/efi_image_loader.c +9 -6
index f9594189bef..1877c164944 100644
@@ -996,7 +996,6 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
 			 struct efi_loaded_image *loaded_image_info)
 {
 	IMAGE_NT_HEADERS32 *nt;
-	IMAGE_DOS_HEADER *dos;
 	IMAGE_SECTION_HEADER *sections;
 	int num_sections;
 	void *efi_reloc;
@@ -1006,6 +1005,7 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
 	int rel_idx = IMAGE_DIRECTORY_ENTRY_BASERELOC;
 	uint64_t image_base;
 	unsigned long virt_size = 0;
+	size_t hdr_size;
 	int supported = 0;
 	efi_status_t ret;
 
@@ -1072,6 +1072,13 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
 		virt_size = max_t(unsigned long, virt_size, end);
 	}
 
+	/*
+	 * The PE headers, up to the end of the section table, are copied to
+	 * the start of the loaded image: make room for them.
+	 */
+	hdr_size = (void *)(sections + num_sections) - efi;
+	virt_size = max_t(unsigned long, virt_size, hdr_size);
+
 	/* Read 32/64bit specific header bits */
 	if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
 		IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
@@ -1127,11 +1134,7 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
 #endif
 
 	/* Copy PE headers */
-	memcpy(efi_reloc, efi,
-	       sizeof(*dos)
-		 + sizeof(*nt)
-		 + nt->FileHeader.SizeOfOptionalHeader
-		 + num_sections * sizeof(IMAGE_SECTION_HEADER));
+	memcpy(efi_reloc, efi, hdr_size);
 
 	/* Load sections into RAM */
 	for (i = num_sections - 1; i >= 0; i--) {
#6 lore raw

PATCH v2 6/11 efi_loader: check the relocation table against the image size

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

efi_loader_relocate() checks each relocation block and entry against the end of the relocation table and each target against the image size, but the table itself is taken from the base relocation data directory as it
is: its address and size are not checked against the image, so the blocks are read from wherever they point, up to 4 GiB past the image. The directory is also read when NumberOfRvaAndSizes says the image has none, in which case its bytes belong to the section table.

Use the base relocation directory only if the image has one, and reject a relocation table that does not lie within the image, as EDK2's PeCoffLoaderRelocateImage() does.

This runs before the image is rejected when Secure Boot fails to verify it.

Fixes cb149c66342c ("efi_loader: Add PE image loader")
---
 lib/efi_loader/efi_image_loader.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)
lib/efi_loader/efi_image_loader.c +12 -2
index 1877c164944..73e96b63671 100644
@@ -117,9 +117,17 @@ static efi_status_t efi_loader_relocate(const IMAGE_BASE_RELOCATION *rel,
 					unsigned long virt_size)
 {
 	unsigned long delta = (unsigned long)efi_reloc - pref_address;
+	unsigned long rel_off = (const char *)rel - (const char *)efi_reloc;
 	const IMAGE_BASE_RELOCATION *end;
 	int i;
 
+	/* The relocation table must lie within the image */
+	if (rel_size &&
+	    (rel_off > virt_size || rel_size > virt_size - rel_off)) {
+		log_debug("Relocation table exceeds image size\n");
+		return EFI_LOAD_ERROR;
+	}
+
 	if (delta == 0)
 		return EFI_SUCCESS;
 
@@ -1095,7 +1103,8 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
 			goto err;
 		}
 		handle->entry = efi_reloc + opt->AddressOfEntryPoint;
-		rel_size = opt->DataDirectory[rel_idx].Size;
+		rel_size = opt->NumberOfRvaAndSizes > rel_idx ?
+			   opt->DataDirectory[rel_idx].Size : 0;
 		rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
 	} else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
 		IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
@@ -1111,7 +1120,8 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
 			goto err;
 		}
 		handle->entry = efi_reloc + opt->AddressOfEntryPoint;
-		rel_size = opt->DataDirectory[rel_idx].Size;
+		rel_size = opt->NumberOfRvaAndSizes > rel_idx ?
+			   opt->DataDirectory[rel_idx].Size : 0;
 		rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
 	} else {
 		log_err("Invalid optional header magic %x\n",
#7 lore raw

PATCH v2 7/11 efi_loader: check certificate lengths in efi_image_authenticate()

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

efi_image_authenticate() walks the certificate table of an image by dwLength, rounded up to a multiple of 8, without checking it:

- a dwLength of 0, or one that wraps around to 0 when rounded up, does not advance the walk, so U-Boot hangs on such an image;
- a dwLength larger than the rest of the table makes pkcs7_parse_message() read past the end of the table and of the image.

As EDK2's DxeImageVerificationLib does, reject an image whose certificate table holds a certificate shorter than its header or longer than the rest of the table.

Fixes 4540dabdcaca ("efi_loader: image_loader: support image authentication")
Fixes 1a44b7059c18 ("efi_loader: image_loader: add a check against certificate type of authenticode")
---
 lib/efi_loader/efi_image_loader.c | 21 +++++++++++++++++++--
 1 file changed, 19 insertions(+), 2 deletions(-)
lib/efi_loader/efi_image_loader.c +19 -2
index 73e96b63671..5a784bfb43a 100644
@@ -808,10 +808,27 @@ static bool efi_image_authenticate(void *efi, size_t efi_size)
 	for (wincert = wincerts, wincerts_end = (u8 *)wincerts + wincerts_len;
 	     (u8 *)wincert < wincerts_end;
 	     wincert = (WIN_CERTIFICATE *)
-			((u8 *)wincert + ALIGN(wincert->dwLength, 8))) {
-		if ((u8 *)wincert + sizeof(*wincert) >= wincerts_end)
+			((u8 *)wincert + ALIGN((size_t)wincert->dwLength, 8))) {
+		size_t remaining = wincerts_end - (u8 *)wincert;
+
+		if (sizeof(*wincert) >= remaining)
 			break;
 
+		/*
+		 * dwLength includes the WIN_CERTIFICATE header. A shorter one
+		 * would not advance the walk, and one longer than the rest of
+		 * the certificate table would make the signature run past its
+		 * end. Like EDK2, reject an image with such a corrupted
+		 * certificate table.
+		 */
+		if (wincert->dwLength < sizeof(*wincert) ||
+		    wincert->dwLength > remaining) {
+			log_err("Invalid certificate length: %u\n",
+				wincert->dwLength);
+			ret = false;
+			goto out;
+		}
+
 		if (wincert->dwLength <= sizeof(*wincert)) {
 			log_debug("dwLength too small: %u < %zu\n",
 				  wincert->dwLength, sizeof(*wincert));
#8 lore raw

Re: [PATCH v2 07/11] efi_loader: check certificate lengths in efi_image_authenticate()

Quoted 47 lines · Ana Bobillo

From: Ana Bobillo <[email protected]>

efi_image_authenticate() walks the certificate table of an image by dwLength, rounded up to a multiple of 8, without checking it:

- a dwLength of 0, or one that wraps around to 0 when rounded up, does not advance the walk, so U-Boot hangs on such an image;
- a dwLength larger than the rest of the table makes pkcs7_parse_message() read past the end of the table and of the image.

As EDK2's DxeImageVerificationLib does, reject an image whose certificate table holds a certificate shorter than its header or longer than the rest of the table.

Fixes 4540dabdcaca ("efi_loader: image_loader: support image authentication")
Fixes 1a44b7059c18 ("efi_loader: image_loader: add a check against certificate type of authenticode")
---
 lib/efi_loader/efi_image_loader.c | 21 +++++++++++++++++++--
 1 file changed, 19 insertions(+), 2 deletions(-)
lib/efi_loader/efi_image_loader.c +12 -2
index 73e96b63671..5a784bfb43a 100644
@@ -808,10 +808,27 @@ static bool efi_image_authenticate(void *efi, size_t efi_size)
        for (wincert = wincerts, wincerts_end = (u8 *)wincerts + wincerts_len;
             (u8 *)wincert < wincerts_end;
             wincert = (WIN_CERTIFICATE *)
-                       ((u8 *)wincert + ALIGN(wincert->dwLength, 8))) {
-               if ((u8 *)wincert + sizeof(*wincert) >= wincerts_end)
+                       ((u8 *)wincert + ALIGN((size_t)wincert->dwLength, 8))) {
+               size_t remaining = wincerts_end - (u8 *)wincert;
+
+               if (sizeof(*wincert) >= remaining)
                        break;
 
+               /*
+                * dwLength includes the WIN_CERTIFICATE header. A shorter one
+                * would not advance the walk, and one longer than the rest of
+                * the certificate table would make the signature run past its
+                * end. Like EDK2, reject an image with such a corrupted
+                * certificate table.
+                */
+               if (wincert->dwLength < sizeof(*wincert) ||

lib/efi_loader/efi_image_loader.c static bool efi_image_authenticate(void *efi, size_t efi_size) · line 834

Quoted 10 lines
lib/efi_loader/efi_image_loader.c +7 -0
+                   wincert->dwLength > remaining) {
+                       log_err("Invalid certificate length: %u\n",
+                               wincert->dwLength);
+                       ret = false;
+                       goto out;
+               }
+
                if (wincert->dwLength <= sizeof(*wincert)) {
                        log_debug("dwLength too small: %u < %zu\n",
                                  wincert->dwLength, sizeof(*wincert));

The code you just added above rejects the < case no ? So with this we'll print something like "dwLength too small: 8 < 8".

Also the new check is similar to the old one. Combine them to a single check that makes sense.

Thanks
/Ilias

#9 lore raw

Re: [PATCH v2 07/11] efi_loader: check certificate lengths in efi_image_authenticate()

Hi Ilias,

Quoted 5 lines · Ilias Apalodimas

The code you just added above rejects the < case no ? So with this we'll print something like "dwLength too small: 8 < 8".

Also the new check is similar to the old one. Combine them to a single check that makes sense.

Yes, only a dwLength of 8 still reached the old branch. In v3 the two are a single check: a certificate no longer than its header, or longer than the rest of the table, rejects the image, so an empty certificate is no longer skipped either.

Thanks,
Ana

#10 lore raw

PATCH v2 8/11 efi_loader: refuse a PE image of an unknown subsystem

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

efi_load_pe() loads an image whose Subsystem field is none of the UEFI image types as an application: efi_set_code_and_data_type() only logs "invalid image type". Such an image is then not measured by tcg2_measure_pe_image(), and efi_start_image() does not measure its invocation either, so with measured boot it runs without a trace in PCR 4.

The UEFI specification defines subsystems 10, 11 and 12 for UEFI images, and LoadImage() returns EFI_UNSUPPORTED for an image type that is not supported. EDK2 does so in CoreLoadPeImage(). Do the same here, also for IMAGE_SUBSYSTEM_EFI_ROM, which was given a runtime driver's memory types but could not be measured either.

Fixes 36b41a3cedd6 ("efi_loader: allocate correct memory type for EFI image")
---
 lib/efi_loader/efi_image_loader.c | 22 ++++++++++++++--------
 1 file changed, 14 insertions(+), 8 deletions(-)
lib/efi_loader/efi_image_loader.c +14 -8
index 5a784bfb43a..a0879f18621 100644
@@ -252,8 +252,10 @@ static efi_status_t efi_loader_relocate(const IMAGE_BASE_RELOCATION *rel,
  * @loaded_image_info:	image descriptor
  * @image_type:		field Subsystem of the optional header for
  *			Windows specific field
+ * Return:		status code, EFI_UNSUPPORTED if @image_type is not
+ *			one of the UEFI image types
  */
-static void efi_set_code_and_data_type(
+static efi_status_t efi_set_code_and_data_type(
 			struct efi_loaded_image *loaded_image_info,
 			uint16_t image_type)
 {
@@ -267,17 +269,15 @@ static void efi_set_code_and_data_type(
 		loaded_image_info->image_data_type = EFI_BOOT_SERVICES_DATA;
 		break;
 	case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
-	case IMAGE_SUBSYSTEM_EFI_ROM:
 		loaded_image_info->image_code_type = EFI_RUNTIME_SERVICES_CODE;
 		loaded_image_info->image_data_type = EFI_RUNTIME_SERVICES_DATA;
 		break;
 	default:
 		log_err("invalid image type: %u\n", image_type);
-		/* Let's assume it is an application */
-		loaded_image_info->image_code_type = EFI_LOADER_CODE;
-		loaded_image_info->image_data_type = EFI_LOADER_DATA;
-		break;
+		return EFI_UNSUPPORTED;
 	}
+
+	return EFI_SUCCESS;
 }
 
 /**
@@ -1109,7 +1109,10 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
 		IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
 		IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
 		image_base = opt->ImageBase;
-		efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
+		ret = efi_set_code_and_data_type(loaded_image_info,
+						 opt->Subsystem);
+		if (ret != EFI_SUCCESS)
+			goto err;
 		handle->image_type = opt->Subsystem;
 		efi_reloc = efi_alloc_aligned_pages(virt_size,
 						    loaded_image_info->image_code_type,
@@ -1126,7 +1129,10 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
 	} else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
 		IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
 		image_base = opt->ImageBase;
-		efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
+		ret = efi_set_code_and_data_type(loaded_image_info,
+						 opt->Subsystem);
+		if (ret != EFI_SUCCESS)
+			goto err;
 		handle->image_type = opt->Subsystem;
 		efi_reloc = efi_alloc_aligned_pages(virt_size,
 						    loaded_image_info->image_code_type,
Reviewed-by on v2 8/11
#11 lore raw

Re: [PATCH v2 08/11] efi_loader: refuse a PE image of an unknown subsystem

Quoted 16 lines · Ana Bobillo

From: Ana Bobillo <[email protected]>

efi_load_pe() loads an image whose Subsystem field is none of the UEFI image types as an application: efi_set_code_and_data_type() only logs "invalid image type". Such an image is then not measured by tcg2_measure_pe_image(), and efi_start_image() does not measure its invocation either, so with measured boot it runs without a trace in PCR 4.

The UEFI specification defines subsystems 10, 11 and 12 for UEFI images, and LoadImage() returns EFI_UNSUPPORTED for an image type that is not supported. EDK2 does so in CoreLoadPeImage(). Do the same here, also for IMAGE_SUBSYSTEM_EFI_ROM, which was given a runtime driver's memory types but could not be measured either.

Quoted 4 lines
Fixes 36b41a3cedd6 ("efi_loader: allocate correct memory type for EFI image")

---

Quoted 64 lines
 lib/efi_loader/efi_image_loader.c | 22 ++++++++++++++--------
 1 file changed, 14 insertions(+), 8 deletions(-)
lib/efi_loader/efi_image_loader.c +14 -8
index 5a784bfb43a..a0879f18621 100644
@@ -252,8 +252,10 @@ static efi_status_t efi_loader_relocate(const IMAGE_BASE_RELOCATION *rel,
  * @loaded_image_info: image descriptor
  * @image_type:                field Subsystem of the optional header for
  *                     Windows specific field
+ * Return:             status code, EFI_UNSUPPORTED if @image_type is not
+ *                     one of the UEFI image types
  */
-static void efi_set_code_and_data_type(
+static efi_status_t efi_set_code_and_data_type(
                        struct efi_loaded_image *loaded_image_info,
                        uint16_t image_type)
 {
@@ -267,17 +269,15 @@ static void efi_set_code_and_data_type(
                loaded_image_info->image_data_type = EFI_BOOT_SERVICES_DATA;
                break;
        case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
-       case IMAGE_SUBSYSTEM_EFI_ROM:
                loaded_image_info->image_code_type = EFI_RUNTIME_SERVICES_CODE;
                loaded_image_info->image_data_type = EFI_RUNTIME_SERVICES_DATA;
                break;
        default:
                log_err("invalid image type: %u\n", image_type);
-               /* Let's assume it is an application */
-               loaded_image_info->image_code_type = EFI_LOADER_CODE;
-               loaded_image_info->image_data_type = EFI_LOADER_DATA;
-               break;
+               return EFI_UNSUPPORTED;
        }
+
+       return EFI_SUCCESS;
 }
 
 /**
@@ -1109,7 +1109,10 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
                IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
                IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
                image_base = opt->ImageBase;
-               efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
+               ret = efi_set_code_and_data_type(loaded_image_info,
+                                                opt->Subsystem);
+               if (ret != EFI_SUCCESS)
+                       goto err;
                handle->image_type = opt->Subsystem;
                efi_reloc = efi_alloc_aligned_pages(virt_size,
                                                    loaded_image_info->image_code_type,
@@ -1126,7 +1129,10 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
        } else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
                IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
                image_base = opt->ImageBase;
-               efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
+               ret = efi_set_code_and_data_type(loaded_image_info,
+                                                opt->Subsystem);
+               if (ret != EFI_SUCCESS)
+                       goto err;
                handle->image_type = opt->Subsystem;
                efi_reloc = efi_alloc_aligned_pages(virt_size,
                                                    loaded_image_info->image_code_type,
#12 lore raw

PATCH v2 9/11 efi_loader: do not start an image that cannot be measured

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

With TCG2 measured boot, efi_load_pe() measures each image into PCR 4 or 2. When the measurement finds no TPM, it marks the image as not authenticated, so that it cannot be started. Any other error is ignored, so an image whose hash cannot be computed, because efi_image_parse() rejects it, or whose PCR could not be extended is loaded and can be started without being measured. With the range checks added to efi_image_parse() earlier in this series, more malformed images take this path. Such an image runs with boot services and can start the expected boot loader itself, which is measured as usual, so the PCRs end up as for a good boot.

Handle every failed measurement like the missing TPM: mark the image as not authenticated, so that LoadImage() returns EFI_SECURITY_VIOLATION and StartImage() refuses to start it. A full event log is no error, as in EDK2's DxeTpm2MeasureBootLib: the PCR has been extended all the same.

Fixes 163a0d7e2cbd ("efi_loader: add PE/COFF image measurement")

---
This applies on top of Heinrich's "efi_loader: handling of missing TPM in efi_load_pe()": https://patchwork.ozlabs.org/patch/2335140/

 lib/efi_loader/efi_image_loader.c | 8 ++++++++
 1 file changed, 8 insertions(+)
lib/efi_loader/efi_image_loader.c +8 -0
index a0879f18621..ef6ff055c63 100644
@@ -1163,6 +1163,14 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
 		 */
 		log_err("PE image measurement failed, no tpm device found\n");
 		handle->auth_status = EFI_IMAGE_AUTH_FAILED;
+	} else if (ret != EFI_SUCCESS && ret != EFI_VOLUME_FULL) {
+		/*
+		 * The image cannot be hashed or the PCR cannot be extended.
+		 * Do not start an image that has not been measured. A full
+		 * event log is no error: the PCR has been extended all the same.
+		 */
+		log_err("PE image measurement failed\n");
+		handle->auth_status = EFI_IMAGE_AUTH_FAILED;
 	}
 #endif
 
#13 lore raw

Re: [PATCH v2 09/11] efi_loader: do not start an image that cannot be measured

Hi Ana,

Applying this seems to fail. Can you rebase and respin the series?

Thanks
/Ilias

Quoted 47 lines · Ana Bobillo

From: Ana Bobillo <[email protected]>

With TCG2 measured boot, efi_load_pe() measures each image into PCR 4 or 2. When the measurement finds no TPM, it marks the image as not authenticated, so that it cannot be started. Any other error is ignored, so an image whose hash cannot be computed, because efi_image_parse() rejects it, or whose PCR could not be extended is loaded and can be started without being measured. With the range checks added to efi_image_parse() earlier in this series, more malformed images take this path. Such an image runs with boot services and can start the expected boot loader itself, which is measured as usual, so the PCRs end up as for a good boot.

Handle every failed measurement like the missing TPM: mark the image as not authenticated, so that LoadImage() returns EFI_SECURITY_VIOLATION and StartImage() refuses to start it. A full event log is no error, as in EDK2's DxeTpm2MeasureBootLib: the PCR has been extended all the same.

Fixes 163a0d7e2cbd ("efi_loader: add PE/COFF image measurement")

---
This applies on top of Heinrich's "efi_loader: handling of missing TPM in efi_load_pe()": https://patchwork.ozlabs.org/patch/2335140/

 lib/efi_loader/efi_image_loader.c | 8 ++++++++
 1 file changed, 8 insertions(+)
lib/efi_loader/efi_image_loader.c +8 -0
index a0879f18621..ef6ff055c63 100644
@@ -1163,6 +1163,14 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
                 */
                log_err("PE image measurement failed, no tpm device found\n");
                handle->auth_status = EFI_IMAGE_AUTH_FAILED;
+       } else if (ret != EFI_SUCCESS && ret != EFI_VOLUME_FULL) {
+               /*
+                * The image cannot be hashed or the PCR cannot be extended.
+                * Do not start an image that has not been measured. A full
+                * event log is no error: the PCR has been extended all the same.
+                */
+               log_err("PE image measurement failed\n");
+               handle->auth_status = EFI_IMAGE_AUTH_FAILED;
        }
 #endif
 
#14 lore raw

Re: [PATCH v2 09/11] efi_loader: do not start an image that cannot be measured

Hi Ilias,

Quoted 1 line · Ilias Apalodimas

Applying this seems to fail. Can you rebase and respin the series?

Sorry about that: v2 09 was written on top of Heinrich's "efi_loader:
handling of missing TPM in efi_load_pe()", which is not in main yet. I've sent v3, rebased on main. Its patch 9 no longer needs Heinrich's:
the series applies to main with or without it, and his applies on top of the series.

Thanks,
Ana

#15 lore raw

PATCH v2 10/11 test: lib: add tests for the PE image checks

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

Add unit tests that pass malformed PE images to efi_check_pe(), LoadImage() and efi_image_parse() and check that they are rejected:

- an image ending after a 32bit NT header;
- a section whose end wraps around 4 GiB;
- a section whose raw data runs past the end of the image, also when its VirtualSize is smaller;
- a relocation table past the end of the image;
- an image whose subsystem is not a UEFI image type;
- an image that cannot be measured, when TCG2 is installed, which may be loaded but must not be started;
- headers, an optional header, a section or a certificate table that do not fit, an optional header that holds fewer data directories than it declares or more than 16, a file alignment that is not a power of two, and sections sharing their raw data.

Check that PE32 and PE32+ images with 16, 6 or 5 data directories, an empty section, a last section that is not padded, a file alignment of 0 and trailing data of an odd size still load and parse, and that the loaded image holds all of the headers when they are longer than the sections.

Each image is built at the start of a larger zeroed buffer, so that without the checks most tests read the bytes after it and get a wrong status instead of faulting. Without the checks the tests of the wrapped section and of the relocation table far past the image crash, and the test of the headers writes past the loaded image.

---
 test/lib/Makefile           |   2 +-
 test/lib/efi_image_loader.c | 501 ++++++++++++++++++++++++++++++++++++
 2 files changed, 502 insertions(+), 1 deletion(-)
test/lib/Makefile +1 -1
index 9fc4a1a9b5d..a67e53ca9c5 100644
@@ -9,7 +9,7 @@ ifeq ($(CONFIG_XPL_BUILD),)
 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_LOADER) += efi_device_path.o efi_image_loader.o efi_memory.o
 obj-$(CONFIG_EFI_SECURE_BOOT) += efi_image_region.o
 ifdef CONFIG_RISCV
 obj-$(CONFIG_USE_PRIVATE_LIBGCC) += test_clz.o
test/lib/efi_image_loader.c new file +501 -0

501 lines not on this page · raw message

#16 lore raw

PATCH v2 11/11 test: py: test invalid certificate lengths in signed images

In reply to Ana Bobillo

From: Ana Bobillo <[email protected]>

Add a Secure Boot test with two signed images whose first certificate has an invalid length: zero, which made efi_image_authenticate() loop forever, and one larger than the certificate table. Both images must be rejected.

---
 test/py/tests/test_efi_secboot/conftest.py    | 31 ++++++++++++++++
 test/py/tests/test_efi_secboot/test_signed.py | 36 +++++++++++++++++++
 2 files changed, 67 insertions(+)
test/py/tests/test_efi_secboot/conftest.py +31 -0
index 0755497d46d..9858dd36f17 100644
@@ -4,11 +4,36 @@
 
 """Fixture for UEFI secure boot test."""
 
+import struct
 from subprocess import call, check_call, CalledProcessError
 from tests import fs_helper
 import pytest
 from defs import *
 
+
+def set_cert_length(src, dst, length):
+    """Copy a signed image, setting the length of its first certificate.
+
+    Args:
+        src: Path of the signed image.
+        dst: Path of the image to write.
+        length: dwLength to set, or None for one past the certificate table.
+    """
+    with open(src, 'rb') as inf:
+        data = bytearray(inf.read())
+    pe_off = struct.unpack_from('<I', data, 0x3c)[0]
+    opt_off = pe_off + 24
+    magic = struct.unpack_from('<H', data, opt_off)[0]
+    # The data directories follow the PE32+ or the PE32 optional header
+    dirs_off = opt_off + (112 if magic == 0x20b else 96)
+    # The certificate table is data directory 4
+    cert_off, cert_size = struct.unpack_from('<II', data, dirs_off + 4 * 8)
+    if length is None:
+        length = cert_size + 8
+    struct.pack_into('<I', data, cert_off, length)
+    with open(dst, 'wb') as outf:
+        outf.write(data)
+
 @pytest.fixture(scope='function')
 def efi_boot_env(request, ubman):
     """Set up a file system to be used in UEFI secure boot test.
@@ -118,6 +143,12 @@ def efi_boot_env(request, ubman):
         # Create a corrupted signed image
         check_call('cd %s; sh %s/test/py/tests/test_efi_secboot/forge_image.sh helloworld.efi.signed helloworld_forged.efi.signed'
                    % (mnt_point, ubman.config.source_dir), shell=True)
+        # Create signed images with an invalid certificate length
+        set_cert_length('%s/helloworld.efi.signed' % mnt_point,
+                        '%s/helloworld_certlen0.efi.signed' % mnt_point, 0)
+        set_cert_length('%s/helloworld.efi.signed' % mnt_point,
+                        '%s/helloworld_certlen_long.efi.signed' % mnt_point,
+                        None)
         # Digest image
         check_call('cd %s; %shash-to-efi-sig-list helloworld.efi db_hello.hash; %ssign-efi-sig-list -t "2020-04-07" -c KEK.crt -k KEK.key db db_hello.hash db_hello.auth'
                    % (mnt_point, EFITOOLS_PATH, EFITOOLS_PATH),
test/py/tests/test_efi_secboot/test_signed.py +36 -0
index 9e6d3fdf8d8..d14f9b795d5 100644
@@ -378,3 +378,39 @@ class TestEfiSignedImage(object):
                 'printenv -e -n PK'])
             assert 'Failed to set EFI variable' not in ''.join(output)
             assert '\"PK\" not defined' in ''.join(output)
+
+    def test_efi_signed_image_auth9(self, ubman, efi_boot_env):
+        """
+        Test Case 9 - Secure boot is in force,
+                      the length of the certificate in the signed image
+                      is invalid.
+                      Must be rejected.
+        """
+        ubman.restart_uboot()
+        disk_img = efi_boot_env
+        with ubman.log.section('Test Case 9a'):
+            # Test Case 9a, certificate length of zero
+            output = ubman.run_command_list([
+                'host bind 0 %s' % disk_img,
+                'fatload host 0:1 4000000 db.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000:$filesize db',
+                'fatload host 0:1 4000000 KEK.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000:$filesize KEK',
+                'fatload host 0:1 4000000 PK.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000:$filesize PK'])
+            assert 'Failed to set EFI variable' not in ''.join(output)
+            output = ubman.run_command_list([
+                'efidebug boot add -b 1 HELLO1 host 0:1 /helloworld_certlen0.efi.signed -s ""',
+                'efidebug boot order 1',
+                'efidebug test bootmgr'])
+            assert '\'HELLO1\' failed' in ''.join(output)
+            assert 'efi_bootmgr_load() returned: 26' in ''.join(output)
+
+        with ubman.log.section('Test Case 9b'):
+            # Test Case 9b, certificate longer than the certificate table
+            output = ubman.run_command_list([
+                'efidebug boot add -b 2 HELLO2 host 0:1 /helloworld_certlen_long.efi.signed -s ""',
+                'efidebug boot order 2',
+                'efidebug test bootmgr'])
+            assert '\'HELLO2\' failed' in ''.join(output)
+            assert 'efi_bootmgr_load() returned: 26' in ''.join(output)