efi_loader: sections with zero VirtualSize
authorHeinrich Schuchardt <heinrich.schuchardt@canonical.com>
Sun, 29 Aug 2021 09:52:44 +0000 (11:52 +0200)
committerHeinrich Schuchardt <xypron.glpk@gmx.de>
Sat, 4 Sep 2021 10:03:57 +0000 (12:03 +0200)
In a section header VirtualSize may be zero. This is for instance seen in
the .sbat section of shim. In this case use SizeOfRawData as section size.

Fixes: 9d30a941cce5 ("efi_loader: don't load beyond VirtualSize")
Signed-off-by: Heinrich Schuchardt <heinrich.schuchardt@canonical.com>
Reviewed-by: Asherah Connor <ashe@kivikakk.ee>
lib/efi_loader/efi_image_loader.c

index a0eb63f..838e3a7 100644 (file)
@@ -801,6 +801,23 @@ efi_status_t efi_check_pe(void *buffer, size_t size, void **nt_header)
 }
 
 /**
+ * section_size() - determine size of section
+ *
+ * The size of a section in memory if normally given by VirtualSize.
+ * If VirtualSize is not provided, use SizeOfRawData.
+ *
+ * @sec:       section header
+ * Return:     size of section in memory
+ */
+static u32 section_size(IMAGE_SECTION_HEADER *sec)
+{
+       if (sec->Misc.VirtualSize)
+               return sec->Misc.VirtualSize;
+       else
+               return sec->SizeOfRawData;
+}
+
+/**
  * efi_load_pe() - relocate EFI binary
  *
  * This function loads all sections from a PE binary into a newly reserved
@@ -869,8 +886,9 @@ 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];
+
                virt_size = max_t(unsigned long, virt_size,
-                                 sec->VirtualAddress + sec->Misc.VirtualSize);
+                                 sec->VirtualAddress + section_size(sec));
        }
 
        /* Read 32/64bit specific header bits */
@@ -931,11 +949,16 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
        /* Load sections into RAM */
        for (i = num_sections - 1; i >= 0; i--) {
                IMAGE_SECTION_HEADER *sec = &sections[i];
-               memset(efi_reloc + sec->VirtualAddress, 0,
-                      sec->Misc.VirtualSize);
+               u32 copy_size = section_size(sec);
+
+               if (copy_size > sec->SizeOfRawData) {
+                       copy_size = sec->SizeOfRawData;
+                       memset(efi_reloc + sec->VirtualAddress, 0,
+                              sec->Misc.VirtualSize);
+               }
                memcpy(efi_reloc + sec->VirtualAddress,
                       efi + sec->PointerToRawData,
-                      min(sec->Misc.VirtualSize, sec->SizeOfRawData));
+                      copy_size);
        }
 
        /* Run through relocations */