Skip to contentSkip to conversation

UEFI NX support and NX Linux loader using shim loader protocol

PATCH Superseded Mate Kukri 2 participants 29 messages May 24, 2024 RISC-V

v1 of 8 Superseded Latest is v8 →

lore
Share & tools
lore

Mate Kukri

author
#0 lore raw

cover UEFI NX support and NX Linux loader using shim loader protocol

Current state of the patchset:
- Cherry-picked Fedora NX patches to make GRUB itself work under NX. This required some fixups to build on non-64 bit arches (operation on 32-bit is currently untested)
- Cherry-picked Julian Andres Klode's loader framework patch (used in Debian and Ubuntu for the downstream loader).
- Implemented shim loader protocol support using the above loader framework.
- Added patch to disallow using the legacy Linux loader when NX is required.

Future work:
- Completely disable non-NX compatible loaders when heap allocation are marked NX. This should be independent from the NX-enforcement flag and Secure Boot status. (Note that this is non-crtitical for security, as non-UEFI/Linux loaders are disabled by SB lockdown, but would be nice to avoid crashes for unsuspecting users on future hardware).
- Implement NX in non-Linux loaders where applicable.

Julian Andres Klode (1):
efi: Provide wrappers for load_image, start_image, unload_image

Laszlo Ersek (3):
grub_dl_load_segments(): page-align the tramp/GOT areas too grub_dl_set_mem_attrs(): add self-check for the tramp/GOT sizes grub_dl_set_mem_attrs(): fix format string

Mate Kukri (3):
mm: Fixup bogus assumptions about types sizes in format strings
efi: Use shim's loader protocol for EFI image verification and loading
efi: Disallow fallback to legacy Linux loader when shim says NX is
required.

Peter Jones (8):
modules: make .module_license read-only
modules: strip .llvm_addrsig sections and similar.
modules: Don't allocate space for non-allocable sections.
pe: add the DOS header struct and fix some bad naming.
modules: load module sections at page-aligned addresses
nx: add memory attribute get/set API
nx: set page permissions for loaded modules.
nx: set the nx compatible flag in EFI grub images

 docs/grub-dev.texi                 |   6 +-
 grub-core/genmod.sh.in             |   5 +-
 grub-core/kern/arm/dl.c            |  13 +++
 grub-core/kern/arm64/dl.c          |  13 +++
 grub-core/kern/dl.c                | 168 ++++++++++++++++++++++++-----
 grub-core/kern/efi/efi.c           |  93 ++++++++++++++++
 grub-core/kern/efi/mm.c            | 128 ++++++++++++++++++++++
 grub-core/kern/efi/sb.c            |  39 +++----
 grub-core/kern/emu/full.c          |  13 +++
 grub-core/kern/i386/dl.c           |  13 +++
 grub-core/kern/ia64/dl.c           |   9 ++
 grub-core/kern/mips/dl.c           |   8 ++
 grub-core/kern/powerpc/dl.c        |   9 ++
 grub-core/kern/riscv/dl.c          |  13 +++
 grub-core/kern/sparc64/dl.c        |   9 ++
 grub-core/kern/x86_64/dl.c         |  13 +++
 grub-core/loader/efi/chainloader.c |  13 +--
 grub-core/loader/efi/linux.c       |  69 +++++++-----
 include/grub/dl.h                  |  48 ++++++++-
 include/grub/efi/api.h             |  30 ++++++
 include/grub/efi/efi.h             |  44 ++++++++
 include/grub/efi/pe32.h            |  98 +++++++++++++++--
 include/grub/efi/sb.h              |   3 -
 include/grub/mm.h                  |  32 ++++++
 util/mkimage.c                     |   1 +
 25 files changed, 786 insertions(+), 104 deletions(-)
Signature · 7 lines
2.39.2


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
author
#1 lore raw

PATCH 1/15 modules: make .module_license read-only

From: Peter Jones <[email protected]>

Currently .module_license is set writable (that is, the section has the SHF_WRITE flag set) in the module's ELF headers. This probably never actually matters, but it can't possibly be correct.

This patch sets that data as "const", which causes that flag not to be set.

(cherry picked from commit f6563e15bb490bb76a1a95cd3648fe03d1134d14)
---
 include/grub/dl.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
include/grub/dl.h +1 -1
index cd1f46c8b..750fc8d3d 100644
@@ -119,7 +119,7 @@ grub_mod_fini (void)
 #define ATTRIBUTE_USED __unused__
 #endif
 #define GRUB_MOD_LICENSE(license)	\
-  static char grub_module_license[] __attribute__ ((section (GRUB_MOD_SECTION (module_license)), ATTRIBUTE_USED)) = "LICENSE=" license;
+  static const char grub_module_license[] __attribute__ ((section (GRUB_MOD_SECTION (module_license)), ATTRIBUTE_USED)) = "LICENSE=" license;
 #define GRUB_MOD_DEP(name)	\
 static const char grub_module_depend_##name[] \
  __attribute__((section(GRUB_MOD_SECTION(moddeps)), ATTRIBUTE_USED)) = #name
Signature · 7 lines
2.39.2


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
Reviewed-by Vladimir Serbinenko on v1 1/15
#2 lore raw

Re: [PATCH 01/15] modules: make .module_license read-only

Reviewed-by Vladimir Serbinenko
Quoted 39 lines · Mate Kukri

From: Peter Jones <[email protected]>

Currently .module_license is set writable (that is, the section has the SHF_WRITE flag set) in the module's ELF headers. This probably never actually matters, but it can't possibly be correct.

This patch sets that data as "const", which causes that flag not to be set.

(cherry picked from commit f6563e15bb490bb76a1a95cd3648fe03d1134d14)
---
 include/grub/dl.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
include/grub/dl.h +1 -2
index cd1f46c8b..750fc8d3d 100644
@@ -119,7 +119,7 @@ grub_mod_fini (void)
 #define ATTRIBUTE_USED __unused__
 #endif
 #define GRUB_MOD_LICENSE(license)      \
-  static char grub_module_license[] __attribute__ ((section (GRUB_MOD_SECTION (module_license)), ATTRIBUTE_USED)) = "LICENSE=" license;
+  static const char grub_module_license[] __attribute__ ((section (GRUB_MOD_SECTION (module_license)), ATTRIBUTE_USED)) = "LICENSE=" license;
 #define GRUB_MOD_DEP(name)     \
 static const char grub_module_depend_##name[] \
  __attribute__((section(GRUB_MOD_SECTION(moddeps)), ATTRIBUTE_USED)) = #name
--

2.39.2

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel

Signature · 7 lines
Regards
Vladimir 'phcoder' Serbinenko

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
author
#3 lore raw

PATCH 2/15 modules: strip .llvm_addrsig sections and similar.

In reply to Mate Kukri

From: Peter Jones <[email protected]>

Currently grub modules built with clang or gcc have several sections which we don't actually need or support.

We already have a list of section to skip in genmod.sh, and this patch adds the following sections to that list (as well as a few newlines):

.note.gnu.property
.llvm*

Note that the glob there won't work without a new enough linker, but the failure is just reversion to the status quo, so that's not a big problem.

(cherry picked from commit 0f66524e94d3c4f4d669d75c2122b0f1036776ea)
---
 grub-core/genmod.sh.in | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
grub-core/genmod.sh.in +4 -1
index e57c4d920..337753c57 100644
@@ -57,8 +57,11 @@ if test x@TARGET_APPLE_LINKER@ != x1; then
 	    @TARGET_STRIP@ --strip-unneeded \
 		-K grub_mod_init -K grub_mod_fini \
 		-K _grub_mod_init -K _grub_mod_fini \
-		-R .note.gnu.gold-version -R .note.GNU-stack \
+		-R .note.GNU-stack \
+		-R .note.gnu.gold-version \
+		-R .note.gnu.property \
 		-R .gnu.build.attributes \
+		-R '.llvm*' \
 		-R .rel.gnu.build.attributes \
 		-R .rela.gnu.build.attributes \
 		-R .eh_frame -R .rela.eh_frame -R .rel.eh_frame \
Signature · 7 lines
2.39.2


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
Reviewed-by Vladimir Serbinenko on v1 2/15
#4 lore raw

Re: [PATCH 02/15] modules: strip .llvm_addrsig sections and similar.

Reviewed-by Vladimir Serbinenko
Quoted 48 lines · Mate Kukri

From: Peter Jones <[email protected]>

Currently grub modules built with clang or gcc have several sections which we don't actually need or support.

We already have a list of section to skip in genmod.sh, and this patch adds the following sections to that list (as well as a few newlines):

.note.gnu.property
.llvm*

Note that the glob there won't work without a new enough linker, but the failure is just reversion to the status quo, so that's not a big problem.

(cherry picked from commit 0f66524e94d3c4f4d669d75c2122b0f1036776ea)
---
 grub-core/genmod.sh.in | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
grub-core/genmod.sh.in +4 -2
index e57c4d920..337753c57 100644
@@ -57,8 +57,11 @@ if test x@TARGET_APPLE_LINKER@ != x1; then
            @TARGET_STRIP@ --strip-unneeded \
                -K grub_mod_init -K grub_mod_fini \
                -K _grub_mod_init -K _grub_mod_fini \
-               -R .note.gnu.gold-version -R .note.GNU-stack \
+               -R .note.GNU-stack \
+               -R .note.gnu.gold-version \
+               -R .note.gnu.property \
                -R .gnu.build.attributes \
+               -R '.llvm*' \
                -R .rel.gnu.build.attributes \
                -R .rela.gnu.build.attributes \
                -R .eh_frame -R .rela.eh_frame -R .rel.eh_frame \
--

2.39.2

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel

Signature · 7 lines
Regards
Vladimir 'phcoder' Serbinenko

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
author
#5 lore raw

PATCH 3/15 modules: Don't allocate space for non-allocable sections.

In reply to Mate Kukri

From: Peter Jones <[email protected]>

Currently when loading grub modules, we allocate space for all sections, including those without SHF_ALLOC set. We then copy the sections that /do/ have SHF_ALLOC set into the allocated memory, leaving some of our allocation untouched forever. Additionally, on platforms with GOT fixups and trampolines, we currently compute alignment round-ups for the sections and sections with sh_size = 0.

This patch removes the extra space from the allocation computation, and makes the allocation computation loop skip empty sections as the loading loop does.

(cherry picked from commit 0f76b53f2fe86542123c7aa1ae39c90852972a99)
---
 grub-core/kern/dl.c | 3 +++
 1 file changed, 3 insertions(+)
grub-core/kern/dl.c +3 -0
index 0bf40caa6..37db9fab0 100644
@@ -237,6 +237,9 @@ grub_dl_load_segments (grub_dl_t mod, const Elf_Ehdr *e)
        i < e->e_shnum;
        i++, s = (const Elf_Shdr *)((const char *) s + e->e_shentsize))
     {
+      if (s->sh_size == 0 || !(s->sh_flags & SHF_ALLOC))
+	continue;
+
       tsize = ALIGN_UP (tsize, s->sh_addralign) + s->sh_size;
       if (talign < s->sh_addralign)
 	talign = s->sh_addralign;
Signature · 7 lines
2.39.2


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
Reviewed-by Vladimir Serbinenko on v1 3/15
#6 lore raw

Re: [PATCH 03/15] modules: Don't allocate space for non-allocable sections.

Reviewed-by Vladimir Serbinenko
Quoted 44 lines · Mate Kukri

From: Peter Jones <[email protected]>

Currently when loading grub modules, we allocate space for all sections, including those without SHF_ALLOC set. We then copy the sections that /do/ have SHF_ALLOC set into the allocated memory, leaving some of our allocation untouched forever. Additionally, on platforms with GOT fixups and trampolines, we currently compute alignment round-ups for the sections and sections with sh_size = 0.

This patch removes the extra space from the allocation computation, and makes the allocation computation loop skip empty sections as the loading loop does.

(cherry picked from commit 0f76b53f2fe86542123c7aa1ae39c90852972a99)
---
 grub-core/kern/dl.c | 3 +++
 1 file changed, 3 insertions(+)
grub-core/kern/dl.c +3 -1
index 0bf40caa6..37db9fab0 100644
@@ -237,6 +237,9 @@ grub_dl_load_segments (grub_dl_t mod, const Elf_Ehdr *e)
        i < e->e_shnum;
        i++, s = (const Elf_Shdr *)((const char *) s + e->e_shentsize))
     {
+      if (s->sh_size == 0 || !(s->sh_flags & SHF_ALLOC))
+       continue;
+
       tsize = ALIGN_UP (tsize, s->sh_addralign) + s->sh_size;
       if (talign < s->sh_addralign)
        talign = s->sh_addralign;
--

2.39.2

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel

Signature · 7 lines
Regards
Vladimir 'phcoder' Serbinenko

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
author
#7 lore raw

PATCH 4/15 pe: add the DOS header struct and fix some bad naming.

In reply to Mate Kukri

From: Peter Jones <[email protected]>

In order to properly validate a loaded kernel's support for being loaded without a writable stack or executable, we need to be able to properly parse arbitrary PE headers.

Currently, pe32.h is written in such a way that the MS-DOS header that tells us where to find the PE header in the binary can't be accessed. Further, for some reason it calls the DOS MZ magic "GRUB_PE32_MAGIC".

This patch adds the structure for the DOS header, renames the DOS magic define, and adds defines for the actual PE magic.

(cherry picked from commit c850db5c0478c8328ebdd48ee8cce02995d4ead0)

Conflicts:

	grub-core/loader/arm64/linux.c	(deleted)
	include/grub/efi/pe32.h		(fixup)
---
 include/grub/efi/pe32.h | 98 ++++++++++++++++++++++++++++++++++++++---
 1 file changed, 92 insertions(+), 6 deletions(-)
include/grub/efi/pe32.h +92 -6
index 4e6e9d254..20db6be19 100644
@@ -48,6 +48,29 @@
 
 #define GRUB_PE32_MAGIC			0x5a4d
 
+struct grub_dos_header
+{
+  grub_uint16_t magic;
+  grub_uint16_t cblp;
+  grub_uint16_t cp;
+  grub_uint16_t crlc;
+  grub_uint16_t cparhdr;
+  grub_uint16_t minalloc;
+  grub_uint16_t maxalloc;
+  grub_uint16_t ss;
+  grub_uint16_t sp;
+  grub_uint16_t csum;
+  grub_uint16_t ip;
+  grub_uint16_t cs;
+  grub_uint16_t lfarlc;
+  grub_uint16_t ovno;
+  grub_uint16_t res0[4];
+  grub_uint16_t oemid;
+  grub_uint16_t oeminfo;
+  grub_uint16_t res1[10];
+  grub_uint32_t lfanew;
+};
+
 struct grub_msdos_image_header
 {
   /* This is always 'MZ'. (GRUB_PE32_MAGIC)  */
@@ -171,6 +194,8 @@ struct grub_pe32_optional_header
   struct grub_pe32_data_directory reserved_entry;
 };
 
+#define GRUB_PE32_NX_COMPAT 0x0100
+
 struct grub_pe64_optional_header
 {
   grub_uint16_t magic;
@@ -236,7 +261,11 @@ struct grub_pe64_optional_header
 struct grub_pe32_section_table
 {
   char name[8];
-  grub_uint32_t virtual_size;
+  union
+    {
+      grub_uint32_t physical_address;
+      grub_uint32_t virtual_size;
+    };
   grub_uint32_t virtual_address;
   grub_uint32_t raw_data_size;
   grub_uint32_t raw_data_offset;
@@ -247,12 +276,18 @@ struct grub_pe32_section_table
   grub_uint32_t characteristics;
 };
 
+#define GRUB_PE32_SCN_TYPE_NO_PAD		0x00000008
 #define GRUB_PE32_SCN_CNT_CODE			0x00000020
 #define GRUB_PE32_SCN_CNT_INITIALIZED_DATA	0x00000040
-#define GRUB_PE32_SCN_MEM_DISCARDABLE		0x02000000
-#define GRUB_PE32_SCN_MEM_EXECUTE		0x20000000
-#define GRUB_PE32_SCN_MEM_READ			0x40000000
-#define GRUB_PE32_SCN_MEM_WRITE			0x80000000
+#define GRUB_PE32_SCN_CNT_UNINITIALIZED_DATA	0x00000080
+#define GRUB_PE32_SCN_LNK_OTHER			0x00000100
+#define GRUB_PE32_SCN_LNK_INFO			0x00000200
+#define GRUB_PE32_SCN_LNK_REMOVE		0x00000800
+#define GRUB_PE32_SCN_LNK_COMDAT		0x00001000
+#define GRUB_PE32_SCN_GPREL			0x00008000
+#define GRUB_PE32_SCN_MEM_16BIT			0x00020000
+#define GRUB_PE32_SCN_MEM_LOCKED		0x00040000
+#define GRUB_PE32_SCN_MEM_PRELOAD		0x00080000
 
 #define GRUB_PE32_SCN_ALIGN_1BYTES		0x00100000
 #define GRUB_PE32_SCN_ALIGN_2BYTES		0x00200000
@@ -261,11 +296,28 @@ struct grub_pe32_section_table
 #define GRUB_PE32_SCN_ALIGN_16BYTES		0x00500000
 #define GRUB_PE32_SCN_ALIGN_32BYTES		0x00600000
 #define GRUB_PE32_SCN_ALIGN_64BYTES		0x00700000
+#define GRUB_PE32_SCN_ALIGN_128BYTES		0x00800000
+#define GRUB_PE32_SCN_ALIGN_256BYTES		0x00900000
+#define GRUB_PE32_SCN_ALIGN_512BYTES		0x00A00000
+#define GRUB_PE32_SCN_ALIGN_1024BYTES		0x00B00000
+#define GRUB_PE32_SCN_ALIGN_2048BYTES		0x00C00000
+#define GRUB_PE32_SCN_ALIGN_4096BYTES		0x00D00000
+#define GRUB_PE32_SCN_ALIGN_8192BYTES		0x00E00000
 
 #define GRUB_PE32_SCN_ALIGN_SHIFT		20
 #define GRUB_PE32_SCN_ALIGN_MASK		7
 
-#define GRUB_PE32_SIGNATURE_SIZE 4
+#define GRUB_PE32_SCN_LNK_NRELOC_OVFL		0x01000000
+#define GRUB_PE32_SCN_MEM_DISCARDABLE		0x02000000
+#define GRUB_PE32_SCN_MEM_NOT_CACHED		0x04000000
+#define GRUB_PE32_SCN_MEM_NOT_PAGED		0x08000000
+#define GRUB_PE32_SCN_MEM_SHARED		0x10000000
+#define GRUB_PE32_SCN_MEM_EXECUTE		0x20000000
+#define GRUB_PE32_SCN_MEM_READ			0x40000000
+#define GRUB_PE32_SCN_MEM_WRITE			0x80000000
+
+#define GRUB_PE32_SIGNATURE_SIZE		4
+#define GRUB_PE32_SIGNATURE			"PE\0\0"
 
 #if GRUB_TARGET_SIZEOF_VOID_P == 8
 #define GRUB_PE32_NATIVE_MAGIC			GRUB_PE32_PE64_MAGIC
@@ -290,6 +342,40 @@ struct grub_pe_image_header
 #endif
 };
 
+struct grub_pe32_header
+{
+  /* This should be filled in with GRUB_PE32_MSDOS_STUB.  */
+  grub_uint8_t msdos_stub[GRUB_PE32_MSDOS_STUB_SIZE];
+
+  /* This is always PE\0\0.  */
+  char signature[GRUB_PE32_SIGNATURE_SIZE];
+
+  /* The COFF file header.  */
+  struct grub_pe32_coff_header coff_header;
+
+#if GRUB_TARGET_SIZEOF_VOID_P == 8
+  /* The Optional header.  */
+  struct grub_pe64_optional_header optional_header;
+#else
+  /* The Optional header.  */
+  struct grub_pe32_optional_header optional_header;
+#endif
+};
+
+struct grub_pe32_header_32
+{
+  char signature[GRUB_PE32_SIGNATURE_SIZE];
+  struct grub_pe32_coff_header coff_header;
+  struct grub_pe32_optional_header optional_header;
+};
+
+struct grub_pe32_header_64
+{
+  char signature[GRUB_PE32_SIGNATURE_SIZE];
+  struct grub_pe32_coff_header coff_header;
+  struct grub_pe64_optional_header optional_header;
+};
+
 struct grub_pe32_fixup_block
 {
   grub_uint32_t page_rva;
Signature · 7 lines
2.39.2


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
#8 lore raw

Re: [PATCH 04/15] pe: add the DOS header struct and fix some bad naming.

Quoted 3 lines

struct grub_msdos_image_header

 {
   /* This is always 'MZ'. (GRUB_PE32_MAGIC)  */

Please adjust this

include/grub/efi/pe32.h struct grub_pe32_optional_header · line 198

Quoted 6 lines
include/grub/efi/pe32.h +2 -0
@@ -171,6 +194,8 @@ struct grub_pe32_optional_header
   struct grub_pe32_data_directory reserved_entry;
 };
 
+#define GRUB_PE32_NX_COMPAT 0x0100
+

This was not mentioned in the description. Looks like 2 patches are conflated.

Quoted 27 lines
include/grub/efi/pe32.h +6 -5
 struct grub_pe64_optional_header
 {
   grub_uint16_t magic;
@@ -236,7 +261,11 @@ struct grub_pe64_optional_header
 struct grub_pe32_section_table
 {
   char name[8];
-  grub_uint32_t virtual_size;
+  union
+    {
+      grub_uint32_t physical_address;
+      grub_uint32_t virtual_size;
+    };
   grub_uint32_t virtual_address;
   grub_uint32_t raw_data_size;
   grub_uint32_t raw_data_offset;
@@ -247,12 +276,18 @@ struct grub_pe32_section_table
   grub_uint32_t characteristics;
 };
 
+#define GRUB_PE32_SCN_TYPE_NO_PAD              0x00000008
 #define GRUB_PE32_SCN_CNT_CODE                 0x00000020
 #define GRUB_PE32_SCN_CNT_INITIALIZED_DATA     0x00000040
-#define GRUB_PE32_SCN_MEM_DISCARDABLE          0x02000000
-#define GRUB_PE32_SCN_MEM_EXECUTE              0x20000000
-#define GRUB_PE32_SCN_MEM_READ                 0x40000000
-#define GRUB_PE32_SCN_MEM_WRITE                        0x80000000

include/grub/efi/pe32.h struct grub_pe32_section_table · line 291

Quoted 10 lines
include/grub/efi/pe32.h +9 -0
+#define GRUB_PE32_SCN_CNT_UNINITIALIZED_DATA   0x00000080
+#define GRUB_PE32_SCN_LNK_OTHER                        0x00000100
+#define GRUB_PE32_SCN_LNK_INFO                 0x00000200
+#define GRUB_PE32_SCN_LNK_REMOVE               0x00000800
+#define GRUB_PE32_SCN_LNK_COMDAT               0x00001000
+#define GRUB_PE32_SCN_GPREL                    0x00008000
+#define GRUB_PE32_SCN_MEM_16BIT                        0x00020000
+#define GRUB_PE32_SCN_MEM_LOCKED               0x00040000
+#define GRUB_PE32_SCN_MEM_PRELOAD              0x00080000
 

Again, not mentioned

Quoted 81 lines
include/grub/efi/pe32.h +52 -2
 #define GRUB_PE32_SCN_ALIGN_1BYTES             0x00100000
 #define GRUB_PE32_SCN_ALIGN_2BYTES             0x00200000
@@ -261,11 +296,28 @@ struct grub_pe32_section_table
 #define GRUB_PE32_SCN_ALIGN_16BYTES            0x00500000
 #define GRUB_PE32_SCN_ALIGN_32BYTES            0x00600000
 #define GRUB_PE32_SCN_ALIGN_64BYTES            0x00700000
+#define GRUB_PE32_SCN_ALIGN_128BYTES           0x00800000
+#define GRUB_PE32_SCN_ALIGN_256BYTES           0x00900000
+#define GRUB_PE32_SCN_ALIGN_512BYTES           0x00A00000
+#define GRUB_PE32_SCN_ALIGN_1024BYTES          0x00B00000
+#define GRUB_PE32_SCN_ALIGN_2048BYTES          0x00C00000
+#define GRUB_PE32_SCN_ALIGN_4096BYTES          0x00D00000
+#define GRUB_PE32_SCN_ALIGN_8192BYTES          0x00E00000
 
 #define GRUB_PE32_SCN_ALIGN_SHIFT              20
 #define GRUB_PE32_SCN_ALIGN_MASK               7
 
-#define GRUB_PE32_SIGNATURE_SIZE 4
+#define GRUB_PE32_SCN_LNK_NRELOC_OVFL          0x01000000
+#define GRUB_PE32_SCN_MEM_DISCARDABLE          0x02000000
+#define GRUB_PE32_SCN_MEM_NOT_CACHED           0x04000000
+#define GRUB_PE32_SCN_MEM_NOT_PAGED            0x08000000
+#define GRUB_PE32_SCN_MEM_SHARED               0x10000000
+#define GRUB_PE32_SCN_MEM_EXECUTE              0x20000000
+#define GRUB_PE32_SCN_MEM_READ                 0x40000000
+#define GRUB_PE32_SCN_MEM_WRITE                        0x80000000
+
+#define GRUB_PE32_SIGNATURE_SIZE               4
+#define GRUB_PE32_SIGNATURE                    "PE\0\0"
 
 #if GRUB_TARGET_SIZEOF_VOID_P == 8
 #define GRUB_PE32_NATIVE_MAGIC                 GRUB_PE32_PE64_MAGIC
@@ -290,6 +342,40 @@ struct grub_pe_image_header
 #endif
 };
 
+struct grub_pe32_header
+{
+  /* This should be filled in with GRUB_PE32_MSDOS_STUB.  */
+  grub_uint8_t msdos_stub[GRUB_PE32_MSDOS_STUB_SIZE];
+
+  /* This is always PE\0\0.  */
+  char signature[GRUB_PE32_SIGNATURE_SIZE];
+
+  /* The COFF file header.  */
+  struct grub_pe32_coff_header coff_header;
+
+#if GRUB_TARGET_SIZEOF_VOID_P == 8
+  /* The Optional header.  */
+  struct grub_pe64_optional_header optional_header;
+#else
+  /* The Optional header.  */
+  struct grub_pe32_optional_header optional_header;
+#endif
+};
+
+struct grub_pe32_header_32
+{
+  char signature[GRUB_PE32_SIGNATURE_SIZE];
+  struct grub_pe32_coff_header coff_header;
+  struct grub_pe32_optional_header optional_header;
+};
+
+struct grub_pe32_header_64
+{
+  char signature[GRUB_PE32_SIGNATURE_SIZE];
+  struct grub_pe32_coff_header coff_header;
+  struct grub_pe64_optional_header optional_header;
+};
+
 struct grub_pe32_fixup_block
 {
   grub_uint32_t page_rva;
--

2.39.2

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel

Signature · 7 lines
Regards
Vladimir 'phcoder' Serbinenko

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
author
#9 lore raw

PATCH 5/15 modules: load module sections at page-aligned addresses

In reply to Mate Kukri

From: Peter Jones <[email protected]>

Currently we load module sections at whatever alignment gcc+ld happened to dump into the ELF section header, which is often pretty useless. For example, by default time.mod has these sections on a current x86_64 build:

$ eu-readelf -a grub-core/time.mod |& grep ^Section -A13
Section Headers:
[Nr] Name            Type         Addr  Off      Size     ES Flags Lk Inf Al
[ 0]                 NULL         0     00000000 00000000  0        0   0  0
[ 1] .text           PROGBITS     0     00000040 0000015e  0 AX     0   0  1
[ 2] .rela.text      RELA         0     00000458 000001e0 24 I      8   1  8
[ 3] .rodata.str1.1  PROGBITS     0     0000019e 000000a1  1 AMS    0   0  1
[ 4] .module_license PROGBITS     0     00000240 0000000f  0 A      0   0  8
[ 5] .data           PROGBITS     0     0000024f 00000000  0 WA     0   0  1
[ 6] .bss            NOBITS       0     00000250 00000008  0 WA     0   0  8
[ 7] .modname        PROGBITS     0     00000250 00000005  0        0   0  1
[ 8] .symtab         SYMTAB       0     00000258 00000150 24        9   6  8
[ 9] .strtab         STRTAB       0     000003a8 000000ab  0        0   0  1
[10] .shstrtab       STRTAB       0     00000638 00000059  0        0   0  1

With NX protections being page based, loading sections with either a 1 or 8 *byte* alignment does absolutely nothing to help us out.

This patch switches most EFI platforms to load module sections at 4kB page-aligned addresses. To do so, it adds an new per-arch function, grub_arch_dl_min_alignment(), which returns the alignment needed for dynamically loaded sections (in bytes). Currently it sets it to 4096 when GRUB_MACHINE_EFI is true on x86_64, i386, arm, arm64, and emu, and 1-byte alignment on everything else.

It then changes the allocation size computation and the loader code in grub_dl_load_segments() to align the locations and sizes up to these boundaries, and fills any added padding with zeros.

All of this happens before relocations are applied, so the relocations factor that in with no change.

As an aside, initially Daniel Kiper and I thought that it might be a better idea to split the modules up into top-level sections as .text.modules, .rodata.modules, .data.modules, etc., so that their page permissions would get set by the loader that's loading grub itself. This turns out to have two significant downsides: 1) either in mkimage or in grub_dl_relocate_symbols(), you wind up having to dynamically process the relocations to accommodate the moved module sections, and 2) you then need to change the permissions on the modules and change them back while relocating them in grub_dl_relocate_symbols(), which means that any loader that /does/ honor the section flags but does /not/ generally support NX with the memory attributes API will cause grub to fail.

(cherry picked from commit 887f1d8fa976bb7ac4e283e896c3be9d70f8b150)

Conflicts:
grub-core/kern/dl.c (obvious)

---
 docs/grub-dev.texi          |  6 +++---
 grub-core/kern/arm/dl.c     | 13 +++++++++++++
 grub-core/kern/arm64/dl.c   | 13 +++++++++++++
 grub-core/kern/dl.c         | 29 +++++++++++++++++++++--------
 grub-core/kern/emu/full.c   | 13 +++++++++++++
 grub-core/kern/i386/dl.c    | 13 +++++++++++++
 grub-core/kern/ia64/dl.c    |  9 +++++++++
 grub-core/kern/mips/dl.c    |  8 ++++++++
 grub-core/kern/powerpc/dl.c |  9 +++++++++
 grub-core/kern/riscv/dl.c   | 13 +++++++++++++
 grub-core/kern/sparc64/dl.c |  9 +++++++++
 grub-core/kern/x86_64/dl.c  | 13 +++++++++++++
 include/grub/dl.h           |  2 ++
 13 files changed, 139 insertions(+), 11 deletions(-)
docs/grub-dev.texi +3 -3
index 1276c5930..2f782cda5 100644
@@ -996,9 +996,9 @@ declare startup asm file ($cpu_$platform_startup) as well as any other files
 (e.g. init.c and callwrap.S) (e.g. $cpu_$platform = kern/$cpu/$platform/init.c).
 At this stage you will also need to add dummy dl.c and cache.S with functions
 grub_err_t grub_arch_dl_check_header (void *ehdr), grub_err_t
-grub_arch_dl_relocate_symbols (grub_dl_t mod, void *ehdr) (dl.c) and
-void grub_arch_sync_caches (void *address, grub_size_t len) (cache.S). They
-won't be used for now.
+grub_arch_dl_relocate_symbols (grub_dl_t mod, void *ehdr) (dl.c), grub_uint32_t
+grub_arch_dl_min_alignment (void), and void grub_arch_sync_caches (void
+*address, grub_size_t len) (cache.S). They won't be used for now.
 
 You will need to create directory include/$cpu/$platform and a file
 include/$cpu/types.h. The latter following this template:
grub-core/kern/arm/dl.c +13 -0
index eab9d17ff..926073793 100644
@@ -278,3 +278,16 @@ grub_arch_dl_check_header (void *ehdr)
 
   return GRUB_ERR_NONE;
 }
+
+/*
+ * Tell the loader what our minimum section alignment is.
+ */
+grub_size_t
+grub_arch_dl_min_alignment (void)
+{
+#ifdef GRUB_MACHINE_EFI
+  return 4096;
+#else
+  return 1;
+#endif
+}
grub-core/kern/arm64/dl.c +13 -0
index a2b5789a9..95c6d5bf4 100644
@@ -196,3 +196,16 @@ grub_arch_dl_relocate_symbols (grub_dl_t mod, void *ehdr,
 
   return GRUB_ERR_NONE;
 }
+
+/*
+ * Tell the loader what our minimum section alignment is.
+ */
+grub_size_t
+grub_arch_dl_min_alignment (void)
+{
+#ifdef GRUB_MACHINE_EFI
+  return 4096;
+#else
+  return 1;
+#endif
+}
grub-core/kern/dl.c +21 -8
index 37db9fab0..fb06fd8c6 100644
@@ -224,7 +224,7 @@ grub_dl_load_segments (grub_dl_t mod, const Elf_Ehdr *e)
 {
   unsigned i;
   const Elf_Shdr *s;
-  grub_size_t tsize = 0, talign = 1;
+  grub_size_t tsize = 0, talign = 1, arch_addralign = 1;
 #if !defined (__i386__) && !defined (__x86_64__) && !defined(__riscv) && \
   !defined (__loongarch__)
   grub_size_t tramp;
@@ -233,16 +233,24 @@ grub_dl_load_segments (grub_dl_t mod, const Elf_Ehdr *e)
 #endif
   char *ptr;
 
+  arch_addralign = grub_arch_dl_min_alignment ();
+
   for (i = 0, s = (const Elf_Shdr *)((const char *) e + e->e_shoff);
        i < e->e_shnum;
        i++, s = (const Elf_Shdr *)((const char *) s + e->e_shentsize))
     {
+      grub_size_t sh_addralign;
+      grub_size_t sh_size;
+
       if (s->sh_size == 0 || !(s->sh_flags & SHF_ALLOC))
 	continue;
 
-      tsize = ALIGN_UP (tsize, s->sh_addralign) + s->sh_size;
-      if (talign < s->sh_addralign)
-	talign = s->sh_addralign;
+      sh_addralign = ALIGN_UP(s->sh_addralign, arch_addralign);
+      sh_size = ALIGN_UP(s->sh_size, sh_addralign);
+
+      tsize = ALIGN_UP (tsize, sh_addralign) + sh_size;
+      if (talign < sh_addralign)
+	talign = sh_addralign;
     }
 
 #if !defined (__i386__) && !defined (__x86_64__) && !defined(__riscv) && \
@@ -272,6 +280,9 @@ grub_dl_load_segments (grub_dl_t mod, const Elf_Ehdr *e)
        i < e->e_shnum;
        i++, s = (Elf_Shdr *)((char *) s + e->e_shentsize))
     {
+      grub_size_t sh_addralign = ALIGN_UP(s->sh_addralign, arch_addralign);
+      grub_size_t sh_size = ALIGN_UP(s->sh_size, sh_addralign);
+
       if (s->sh_flags & SHF_ALLOC)
 	{
 	  grub_dl_segment_t seg;
@@ -284,17 +295,19 @@ grub_dl_load_segments (grub_dl_t mod, const Elf_Ehdr *e)
 	    {
 	      void *addr;
 
-	      ptr = (char *) ALIGN_UP ((grub_addr_t) ptr, s->sh_addralign);
+	      ptr = (char *) ALIGN_UP ((grub_addr_t) ptr, sh_addralign);
 	      addr = ptr;
-	      ptr += s->sh_size;
+	      ptr += sh_size;
 
 	      switch (s->sh_type)
 		{
 		case SHT_PROGBITS:
 		  grub_memcpy (addr, (char *) e + s->sh_offset, s->sh_size);
+		  grub_memset ((char *)addr + s->sh_size, 0,
+			       sh_size - s->sh_size);
 		  break;
 		case SHT_NOBITS:
-		  grub_memset (addr, 0, s->sh_size);
+		  grub_memset (addr, 0, sh_size);
 		  break;
 		}
 
@@ -303,7 +316,7 @@ grub_dl_load_segments (grub_dl_t mod, const Elf_Ehdr *e)
 	  else
 	    seg->addr = 0;
 
-	  seg->size = s->sh_size;
+	  seg->size = sh_size;
 	  seg->section = i;
 	  seg->next = mod->segment;
 	  mod->segment = seg;
grub-core/kern/emu/full.c +13 -0
index e8d63b1f5..1de1c28eb 100644
@@ -67,3 +67,16 @@ grub_arch_dl_init_linker (void)
 }
 #endif
 
+
+/*
+ * Tell the loader what our minimum section alignment is.
+ */
+grub_size_t
+grub_arch_dl_min_alignment (void)
+{
+#ifdef GRUB_MACHINE_EFI
+  return 4096;
+#else
+  return 1;
+#endif
+}
grub-core/kern/i386/dl.c +13 -0
index 1346da5cc..d6b4681fc 100644
@@ -79,3 +79,16 @@ grub_arch_dl_relocate_symbols (grub_dl_t mod, void *ehdr,
 
   return GRUB_ERR_NONE;
 }
+
+/*
+ * Tell the loader what our minimum section alignment is.
+ */
+grub_size_t
+grub_arch_dl_min_alignment (void)
+{
+#ifdef GRUB_MACHINE_EFI
+  return 4096;
+#else
+  return 1;
+#endif
+}
grub-core/kern/ia64/dl.c +9 -0
index db59300fe..92d82c575 100644
@@ -148,3 +148,12 @@ grub_arch_dl_relocate_symbols (grub_dl_t mod, void *ehdr,
     }
   return GRUB_ERR_NONE;
 }
+
+/*
+ * Tell the loader what our minimum section alignment is.
+ */
+grub_size_t
+grub_arch_dl_min_alignment (void)
+{
+  return 1;
+}
grub-core/kern/mips/dl.c +8 -0
index 5b02f97fc..db411899d 100644
@@ -272,3 +272,11 @@ grub_arch_dl_init_linker (void)
   grub_dl_register_symbol ("_gp_disp", &_gp_disp_dummy, 0, 0);
 }
 
+/*
+ * Tell the loader what our minimum section alignment is.
+ */
+grub_size_t
+grub_arch_dl_min_alignment (void)
+{
+  return 1;
+}
grub-core/kern/powerpc/dl.c +9 -0
index 7b6418eab..0eb8bc5bd 100644
@@ -167,3 +167,12 @@ grub_arch_dl_relocate_symbols (grub_dl_t mod, void *ehdr,
 
   return GRUB_ERR_NONE;
 }
+
+/*
+ * Tell the loader what our minimum section alignment is.
+ */
+grub_size_t
+grub_arch_dl_min_alignment (void)
+{
+  return 1;
+}
grub-core/kern/riscv/dl.c +13 -0
index 896653bb4..1fa085b4a 100644
@@ -344,3 +344,16 @@ grub_arch_dl_relocate_symbols (grub_dl_t mod, void *ehdr,
 
   return GRUB_ERR_NONE;
 }
+
+/*
+ * Tell the loader what our minimum section alignment is.
+ */
+grub_size_t
+grub_arch_dl_min_alignment (void)
+{
+#ifdef GRUB_MACHINE_EFI
+  return 4096;
+#else
+  return 1;
+#endif
+}
grub-core/kern/sparc64/dl.c +9 -0
index f3d960186..f054f0824 100644
@@ -189,3 +189,12 @@ grub_arch_dl_relocate_symbols (grub_dl_t mod, void *ehdr,
 
   return GRUB_ERR_NONE;
 }
+
+/*
+ * Tell the loader what our minimum section alignment is.
+ */
+grub_size_t
+grub_arch_dl_min_alignment (void)
+{
+  return 1;
+}
grub-core/kern/x86_64/dl.c +13 -0
index e5a8bdcf4..a105dc50c 100644
@@ -119,3 +119,16 @@ grub_arch_dl_relocate_symbols (grub_dl_t mod, void *ehdr,
 
   return GRUB_ERR_NONE;
 }
+
+/*
+ * Tell the loader what our minimum section alignment is.
+ */
+grub_size_t
+grub_arch_dl_min_alignment (void)
+{
+#ifdef GRUB_MACHINE_EFI
+  return 4096;
+#else
+  return 1;
+#endif
+}
include/grub/dl.h +2 -0
index 750fc8d3d..8a37cc16f 100644
@@ -264,6 +264,8 @@ grub_err_t grub_arch_dl_check_header (void *ehdr);
 grub_err_t
 grub_arch_dl_relocate_symbols (grub_dl_t mod, void *ehdr,
 			       Elf_Shdr *s, grub_dl_segment_t seg);
+grub_size_t
+grub_arch_dl_min_alignment (void);
 #endif
 
 #if defined (_mips)
Signature · 7 lines
2.39.2


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
#10 lore raw

Re: [PATCH 05/15] modules: load module sections at page-aligned addresses

What happens when 2 sections with the same NX and WR attributes follow each other? Do we need to split them per page? How often do we needlessly split in the current codebase?

Quoted 1 line

to dump into the ELF section header, which is often pretty useless.

I think this is not true. It's not useless, just doesn't take the NX requirement into account. I think it would be a better formulation

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel

author
#11 lore raw

PATCH 6/15 nx: add memory attribute get/set API

In reply to Mate Kukri

From: Peter Jones <[email protected]>

For NX, we need to set the page access permission attributes for write and execute permissions.

This patch adds two new primitives, grub_set_mem_attrs() and grub_clear_mem_attrs(), and associated constant definitions, to be used for that purpose.

For most platforms, it adds a dummy implementation that returns GRUB_ERR_NONE. On EFI platforms, it adds a common helper function, grub_efi_status_to_err(), which translates EFI error codes to grub error codes, adds headers for the EFI Memory Attribute Protocol (still pending standardization), and an implementation of the grub nx primitives using it.

[rharwood: add pjones's none/nyi fixup]
(cherry picked from commit 45bfb1cc8316096a5ce1e58850ce5f8a6e0e100c)

Conflicts:
grub-core/kern/efi/mm.c (fixup)
include/grub/efi/api.h (fixup)

---
 grub-core/kern/efi/efi.c |  36 +++++++++++
 grub-core/kern/efi/mm.c  | 128 +++++++++++++++++++++++++++++++++++++++
 include/grub/efi/api.h   |  25 ++++++++
 include/grub/efi/efi.h   |   2 +
 include/grub/mm.h        |  32 ++++++++++
 5 files changed, 223 insertions(+)
grub-core/kern/efi/efi.c +36 -0
index b93ae3aba..f34c1ef54 100644
@@ -1049,3 +1049,39 @@ grub_efi_find_configuration_table (const grub_guid_t *target_guid)
 
   return 0;
 }
+
+grub_err_t
+grub_efi_status_to_err (grub_efi_status_t status)
+{
+  grub_err_t err;
+  switch (status)
+    {
+    case GRUB_EFI_SUCCESS:
+      err = GRUB_ERR_NONE;
+      break;
+    case GRUB_EFI_INVALID_PARAMETER:
+    default:
+      err = GRUB_ERR_BAD_ARGUMENT;
+      break;
+    case GRUB_EFI_OUT_OF_RESOURCES:
+      err = GRUB_ERR_OUT_OF_MEMORY;
+      break;
+    case GRUB_EFI_DEVICE_ERROR:
+      err = GRUB_ERR_IO;
+      break;
+    case GRUB_EFI_WRITE_PROTECTED:
+      err = GRUB_ERR_WRITE_ERROR;
+      break;
+    case GRUB_EFI_SECURITY_VIOLATION:
+      err = GRUB_ERR_ACCESS_DENIED;
+      break;
+    case GRUB_EFI_NOT_FOUND:
+      err = GRUB_ERR_FILE_NOT_FOUND;
+      break;
+    case GRUB_EFI_ABORTED:
+      err = GRUB_ERR_WAIT;
+      break;
+    }
+
+  return err;
+}
grub-core/kern/efi/mm.c +128 -0

131 lines not on this page · raw message

include/grub/efi/api.h +25 -0
index d44d00ad7..b686e8afe 100644
@@ -379,6 +379,11 @@
     {0xb6, 0xc7, 0x44, 0x0b, 0x29, 0xbb, 0x8c, 0x4f } \
   }
 
+#define GRUB_EFI_MEMORY_ATTRIBUTE_PROTOCOL_GUID \
+  { 0xf4560cf6, 0x40ec, 0x4b4a, \
+    { 0xa1, 0x92, 0xbf, 0x1d, 0x57, 0xd0, 0xb1, 0x89 } \
+  }
+
 struct grub_efi_sal_system_table
 {
   grub_uint32_t signature;
@@ -1815,4 +1820,24 @@ struct initrd_media_device_path {
 } GRUB_PACKED;
 typedef struct initrd_media_device_path initrd_media_device_path_t;
 
+struct grub_efi_memory_attribute_protocol
+{
+  grub_efi_status_t (__grub_efi_api *get_memory_attributes) (
+			    struct grub_efi_memory_attribute_protocol *this,
+			    grub_efi_physical_address_t base_address,
+			    grub_efi_uint64_t length,
+			    grub_efi_uint64_t *attributes);
+  grub_efi_status_t (__grub_efi_api *set_memory_attributes) (
+			    struct grub_efi_memory_attribute_protocol *this,
+			    grub_efi_physical_address_t base_address,
+			    grub_efi_uint64_t length,
+			    grub_efi_uint64_t attributes);
+  grub_efi_status_t (__grub_efi_api *clear_memory_attributes) (
+			    struct grub_efi_memory_attribute_protocol *this,
+			    grub_efi_physical_address_t base_address,
+			    grub_efi_uint64_t length,
+			    grub_efi_uint64_t attributes);
+};
+typedef struct grub_efi_memory_attribute_protocol grub_efi_memory_attribute_protocol_t;
+
 #endif /* ! GRUB_EFI_API_HEADER */
include/grub/efi/efi.h +2 -0
index a5cd99e5a..194adc1f7 100644
@@ -151,4 +151,6 @@ struct grub_net_card;
 grub_efi_handle_t
 grub_efinet_get_device_handle (struct grub_net_card *card);
 
+grub_err_t EXPORT_FUNC(grub_efi_status_to_err) (grub_efi_status_t status);
+
 #endif /* ! GRUB_EFI_EFI_HEADER */
include/grub/mm.h +32 -0
index f3bf87fa0..8ee1fc717 100644
@@ -23,6 +23,7 @@
 #include <grub/err.h>
 #include <grub/types.h>
 #include <grub/symbol.h>
+#include <grub/err.h>
 #include <config.h>
 
 #ifndef NULL
@@ -56,6 +57,37 @@ void *EXPORT_FUNC(grub_realloc) (void *ptr, grub_size_t size);
 void *EXPORT_FUNC(grub_memalign) (grub_size_t align, grub_size_t size);
 #endif
 
+#define GRUB_MEM_ATTR_R	0x0000000000000004LLU
+#define GRUB_MEM_ATTR_W	0x0000000000000002LLU
+#define GRUB_MEM_ATTR_X	0x0000000000000001LLU
+
+#ifdef GRUB_MACHINE_EFI
+grub_err_t EXPORT_FUNC(grub_get_mem_attrs) (grub_addr_t addr,
+					    grub_size_t size,
+					    grub_uint64_t *attrs);
+grub_err_t EXPORT_FUNC(grub_update_mem_attrs) (grub_addr_t addr,
+					       grub_size_t size,
+					       grub_uint64_t set_attrs,
+					       grub_uint64_t clear_attrs);
+#else /* !GRUB_MACHINE_EFI */
+static inline grub_err_t
+grub_get_mem_attrs (grub_addr_t addr __attribute__((__unused__)),
+		    grub_size_t size __attribute__((__unused__)),
+		    grub_uint64_t *attrs __attribute__((__unused__)))
+{
+  return GRUB_ERR_NONE;
+}
+
+static inline grub_err_t
+grub_update_mem_attrs (grub_addr_t addr __attribute__((__unused__)),
+		       grub_size_t size __attribute__((__unused__)),
+		       grub_uint64_t set_attrs __attribute__((__unused__)),
+		       grub_uint64_t clear_attrs __attribute__((__unused__)))
+{
+  return GRUB_ERR_NONE;
+}
+#endif /* GRUB_MACHINE_EFI */
+
 void grub_mm_check_real (const char *file, int line);
 #define grub_mm_check() grub_mm_check_real (GRUB_FILE, __LINE__);
 
Signature · 7 lines
2.39.2


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
#12 lore raw

Re: [PATCH 06/15] nx: add memory attribute get/set API

grub-core/kern/efi/mm.c grub_efi_get_ram_base(grub_addr_t *base_addr) · line 740

Quoted 3 lines
grub-core/kern/efi/mm.c +3 -0
+  if (!proto)
+    return GRUB_ERR_NOT_IMPLEMENTED_YET;
+

Here and in other places you return an error without using grub_error. Also NOT_IMPLEMENTED_YET means that *GRUB* doesn't implement it yet, not firmware. Also given that you ignore the return here anyway a single bool or even void return might be more appropriate

Quoted 1 line

+ if (physaddr & 0xfff || size & 0xfff || size == 0 || attrs == NULL)

Can we not put 0xfff/0x1000 everywhere and instead use defines?

Quoted 186 lines
grub-core/kern/efi/mm.c +76 -0
+    {
+      grub_dprintf ("nx", "%s called on 0x%"PRIxGRUB_ADDR"-0x%"PRIxGRUB_ADDR" and attrs %p\n",
+                   __func__, physaddr, physaddr+size-1, attrs);
+      return 0;
+    }
+
+  efi_status = proto->get_memory_attributes(proto, physaddr, size, attrs);
+  *attrs = uefi_mem_attrs_to_grub_mem_attrs (*attrs);
+
+  return grub_efi_status_to_err (efi_status);
+}
+
+grub_err_t
+grub_update_mem_attrs (grub_addr_t addr, grub_size_t size,
+                      grub_uint64_t set_attrs, grub_uint64_t clear_attrs)
+{
+  grub_efi_memory_attribute_protocol_t *proto;
+  grub_efi_physical_address_t physaddr = addr;
+  grub_guid_t protocol_guid = GRUB_EFI_MEMORY_ATTRIBUTE_PROTOCOL_GUID;
+  grub_efi_status_t efi_status = GRUB_EFI_SUCCESS;
+  grub_uint64_t before = 0, after = 0, uefi_set_attrs, uefi_clear_attrs;
+  grub_err_t err;
+
+  proto = grub_efi_locate_protocol (&protocol_guid, 0);
+  if (!proto)
+    return GRUB_ERR_NONE;
+
+  err = grub_get_mem_attrs (addr, size, &before);
+  if (err)
+    grub_dprintf ("nx", "grub_get_mem_attrs(0x%"PRIxGRUB_ADDR", %"PRIuGRUB_SIZE", %p) -> 0x%x\n",
+                 addr, size, &before, err);
+
+  if (physaddr & 0xfff || size & 0xfff || size == 0)
+    {
+      grub_dprintf ("nx", "%s called on 0x%"PRIxGRUB_ADDR"-0x%"PRIxGRUB_ADDR" +%s%s%s -%s%s%s\n",
+                   __func__, physaddr, physaddr + size - 1,
+                   (set_attrs & GRUB_MEM_ATTR_R) ? "r" : "",
+                   (set_attrs & GRUB_MEM_ATTR_W) ? "w" : "",
+                   (set_attrs & GRUB_MEM_ATTR_X) ? "x" : "",
+                   (clear_attrs & GRUB_MEM_ATTR_R) ? "r" : "",
+                   (clear_attrs & GRUB_MEM_ATTR_W) ? "w" : "",
+                   (clear_attrs & GRUB_MEM_ATTR_X) ? "x" : "");
+      return 0;
+    }
+
+  uefi_set_attrs = grub_mem_attrs_to_uefi_mem_attrs (set_attrs);
+  grub_dprintf ("nx", "translating set_attrs from 0x%lx to 0x%lx\n", set_attrs, uefi_set_attrs);
+  uefi_clear_attrs = grub_mem_attrs_to_uefi_mem_attrs (clear_attrs);
+  grub_dprintf ("nx", "translating clear_attrs from 0x%lx to 0x%lx\n", clear_attrs, uefi_clear_attrs);
+  if (uefi_set_attrs)
+    efi_status = proto->set_memory_attributes(proto, physaddr, size, uefi_set_attrs);
+  if (efi_status == GRUB_EFI_SUCCESS && uefi_clear_attrs)
+    efi_status = proto->clear_memory_attributes(proto, physaddr, size, uefi_clear_attrs);
+
+  err = grub_get_mem_attrs (addr, size, &after);
+  if (err)
+    grub_dprintf ("nx", "grub_get_mem_attrs(0x%"PRIxGRUB_ADDR", %"PRIuGRUB_SIZE", %p) -> 0x%x\n",
+                 addr, size, &after, err);
+
+  grub_dprintf ("nx", "set +%s%s%s -%s%s%s on 0x%"PRIxGRUB_ADDR"-0x%"PRIxGRUB_ADDR" before:%c%c%c after:%c%c%c\n",
+               (set_attrs & GRUB_MEM_ATTR_R) ? "r" : "",
+               (set_attrs & GRUB_MEM_ATTR_W) ? "w" : "",
+               (set_attrs & GRUB_MEM_ATTR_X) ? "x" : "",
+               (clear_attrs & GRUB_MEM_ATTR_R) ? "r" : "",
+               (clear_attrs & GRUB_MEM_ATTR_W) ? "w" : "",
+               (clear_attrs & GRUB_MEM_ATTR_X) ? "x" : "",
+               addr, addr + size - 1,
+               (before & GRUB_MEM_ATTR_R) ? 'r' : '-',
+               (before & GRUB_MEM_ATTR_W) ? 'w' : '-',
+               (before & GRUB_MEM_ATTR_X) ? 'x' : '-',
+               (after & GRUB_MEM_ATTR_R) ? 'r' : '-',
+               (after & GRUB_MEM_ATTR_W) ? 'w' : '-',
+               (after & GRUB_MEM_ATTR_X) ? 'x' : '-');
+
+  return grub_efi_status_to_err (efi_status);
+}
include/grub/efi/api.h +25 -0
index d44d00ad7..b686e8afe 100644
@@ -379,6 +379,11 @@
     {0xb6, 0xc7, 0x44, 0x0b, 0x29, 0xbb, 0x8c, 0x4f } \
   }
 
+#define GRUB_EFI_MEMORY_ATTRIBUTE_PROTOCOL_GUID \
+  { 0xf4560cf6, 0x40ec, 0x4b4a, \
+    { 0xa1, 0x92, 0xbf, 0x1d, 0x57, 0xd0, 0xb1, 0x89 } \
+  }
+
 struct grub_efi_sal_system_table
 {
   grub_uint32_t signature;
@@ -1815,4 +1820,24 @@ struct initrd_media_device_path {
 } GRUB_PACKED;
 typedef struct initrd_media_device_path initrd_media_device_path_t;
 
+struct grub_efi_memory_attribute_protocol
+{
+  grub_efi_status_t (__grub_efi_api *get_memory_attributes) (
+                           struct grub_efi_memory_attribute_protocol *this,
+                           grub_efi_physical_address_t base_address,
+                           grub_efi_uint64_t length,
+                           grub_efi_uint64_t *attributes);
+  grub_efi_status_t (__grub_efi_api *set_memory_attributes) (
+                           struct grub_efi_memory_attribute_protocol *this,
+                           grub_efi_physical_address_t base_address,
+                           grub_efi_uint64_t length,
+                           grub_efi_uint64_t attributes);
+  grub_efi_status_t (__grub_efi_api *clear_memory_attributes) (
+                           struct grub_efi_memory_attribute_protocol *this,
+                           grub_efi_physical_address_t base_address,
+                           grub_efi_uint64_t length,
+                           grub_efi_uint64_t attributes);
+};
+typedef struct grub_efi_memory_attribute_protocol grub_efi_memory_attribute_protocol_t;
+
 #endif /* ! GRUB_EFI_API_HEADER */
include/grub/efi/efi.h +2 -0
index a5cd99e5a..194adc1f7 100644
@@ -151,4 +151,6 @@ struct grub_net_card;
 grub_efi_handle_t
 grub_efinet_get_device_handle (struct grub_net_card *card);
 
+grub_err_t EXPORT_FUNC(grub_efi_status_to_err) (grub_efi_status_t status);
+
 #endif /* ! GRUB_EFI_EFI_HEADER */
include/grub/mm.h +32 -1
index f3bf87fa0..8ee1fc717 100644
@@ -23,6 +23,7 @@
 #include <grub/err.h>
 #include <grub/types.h>
 #include <grub/symbol.h>
+#include <grub/err.h>
 #include <config.h>
 
 #ifndef NULL
@@ -56,6 +57,37 @@ void *EXPORT_FUNC(grub_realloc) (void *ptr, grub_size_t size);
 void *EXPORT_FUNC(grub_memalign) (grub_size_t align, grub_size_t size);
 #endif
 
+#define GRUB_MEM_ATTR_R        0x0000000000000004LLU
+#define GRUB_MEM_ATTR_W        0x0000000000000002LLU
+#define GRUB_MEM_ATTR_X        0x0000000000000001LLU
+
+#ifdef GRUB_MACHINE_EFI
+grub_err_t EXPORT_FUNC(grub_get_mem_attrs) (grub_addr_t addr,
+                                           grub_size_t size,
+                                           grub_uint64_t *attrs);
+grub_err_t EXPORT_FUNC(grub_update_mem_attrs) (grub_addr_t addr,
+                                              grub_size_t size,
+                                              grub_uint64_t set_attrs,
+                                              grub_uint64_t clear_attrs);
+#else /* !GRUB_MACHINE_EFI */
+static inline grub_err_t
+grub_get_mem_attrs (grub_addr_t addr __attribute__((__unused__)),
+                   grub_size_t size __attribute__((__unused__)),
+                   grub_uint64_t *attrs __attribute__((__unused__)))
+{
+  return GRUB_ERR_NONE;
+}
+
+static inline grub_err_t
+grub_update_mem_attrs (grub_addr_t addr __attribute__((__unused__)),
+                      grub_size_t size __attribute__((__unused__)),
+                      grub_uint64_t set_attrs __attribute__((__unused__)),
+                      grub_uint64_t clear_attrs __attribute__((__unused__)))
+{
+  return GRUB_ERR_NONE;
+}
+#endif /* GRUB_MACHINE_EFI */
+
 void grub_mm_check_real (const char *file, int line);
 #define grub_mm_check() grub_mm_check_real (GRUB_FILE, __LINE__);
 
--

2.39.2

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel

Signature · 7 lines
Regards
Vladimir 'phcoder' Serbinenko

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
author
#13 lore raw

PATCH 7/15 nx: set page permissions for loaded modules.

In reply to Mate Kukri

From: Peter Jones <[email protected]>

For NX, we need to set write and executable permissions on the sections of grub modules when we load them.

On sections with SHF_ALLOC set, which is typically everything except .modname and the symbol and string tables, this patch clears the Read Only flag on sections that have the ELF flag SHF_WRITE set, and clears the No eXecute flag on sections with SHF_EXECINSTR set. In all other cases it sets both flags.

[rharwood: arm tgptr -> tgaddr]
(cherry picked from commit ad1b904d325b7edb651111577e065a20e6b77c74)

Conflicts:
grub-core/kern/dl.c (obvious)

---
 grub-core/kern/dl.c | 102 ++++++++++++++++++++++++++++++++++++++------
 include/grub/dl.h   |  44 +++++++++++++++++++
 2 files changed, 133 insertions(+), 13 deletions(-)
grub-core/kern/dl.c +89 -13
index fb06fd8c6..2784fae7a 100644
@@ -233,6 +233,8 @@ grub_dl_load_segments (grub_dl_t mod, const Elf_Ehdr *e)
 #endif
   char *ptr;
 
+  grub_dprintf ("modules", "loading segments for \"%s\"\n", mod->name);
+
   arch_addralign = grub_arch_dl_min_alignment ();
 
   for (i = 0, s = (const Elf_Shdr *)((const char *) e + e->e_shoff);
@@ -334,6 +336,7 @@ grub_dl_load_segments (grub_dl_t mod, const Elf_Ehdr *e)
   ptr += got;
 #endif
 
+  grub_dprintf ("modules", "done loading segments for \"%s\"\n", mod->name);
   return GRUB_ERR_NONE;
 }
 
@@ -600,6 +603,7 @@ grub_dl_relocate_symbols (grub_dl_t mod, void *ehdr)
   Elf_Shdr *s;
   unsigned i;
 
+  grub_dprintf ("modules", "relocating symbols for \"%s\"\n", mod->name);
   for (i = 0, s = (Elf_Shdr *) ((char *) e + e->e_shoff);
        i < e->e_shnum;
        i++, s = (Elf_Shdr *) ((char *) s + e->e_shentsize))
@@ -608,22 +612,92 @@ grub_dl_relocate_symbols (grub_dl_t mod, void *ehdr)
 	grub_dl_segment_t seg;
 	grub_err_t err;
 
-	/* Find the target segment.  */
-	for (seg = mod->segment; seg; seg = seg->next)
-	  if (seg->section == s->sh_info)
-	    break;
+	seg = grub_dl_find_segment(mod, s->sh_info);
+        if (!seg)
+	  continue;
 
-	if (seg)
-	  {
-	    if (!mod->symtab)
-	      return grub_error (GRUB_ERR_BAD_MODULE, "relocation without symbol table");
+	if (!mod->symtab)
+	  return grub_error (GRUB_ERR_BAD_MODULE, "relocation without symbol table");
 
-	    err = grub_arch_dl_relocate_symbols (mod, ehdr, s, seg);
-	    if (err)
-	      return err;
-	  }
+	err = grub_arch_dl_relocate_symbols (mod, ehdr, s, seg);
+	if (err)
+	  return err;
       }
 
+  grub_dprintf ("modules", "done relocating symbols for \"%s\"\n", mod->name);
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_dl_set_mem_attrs (grub_dl_t mod, void *ehdr)
+{
+  unsigned i;
+  const Elf_Shdr *s;
+  const Elf_Ehdr *e = ehdr;
+#if !defined (__i386__) && !defined (__x86_64__) && !defined(__riscv)
+  grub_size_t arch_addralign = grub_arch_dl_min_alignment ();
+  grub_addr_t tgaddr;
+  grub_uint64_t tgsz;
+#endif
+
+  grub_dprintf ("modules", "updating memory attributes for \"%s\"\n",
+		mod->name);
+  for (i = 0, s = (const Elf_Shdr *)((const char *) e + e->e_shoff);
+       i < e->e_shnum;
+       i++, s = (const Elf_Shdr *)((const char *) s + e->e_shentsize))
+    {
+      grub_dl_segment_t seg;
+      grub_uint64_t set_attrs = GRUB_MEM_ATTR_R;
+      grub_uint64_t clear_attrs = GRUB_MEM_ATTR_W|GRUB_MEM_ATTR_X;
+
+      seg = grub_dl_find_segment(mod, i);
+      if (!seg)
+	continue;
+
+      if (seg->size == 0 || !(s->sh_flags & SHF_ALLOC))
+	continue;
+
+      if (s->sh_flags & SHF_WRITE)
+	{
+	  set_attrs |= GRUB_MEM_ATTR_W;
+	  clear_attrs &= ~GRUB_MEM_ATTR_W;
+	}
+
+      if (s->sh_flags & SHF_EXECINSTR)
+	{
+	  set_attrs |= GRUB_MEM_ATTR_X;
+	  clear_attrs &= ~GRUB_MEM_ATTR_X;
+	}
+
+      grub_dprintf ("modules", "setting memory attrs for section \"%s\" to -%s%s%s+%s%s%s\n",
+		    grub_dl_get_section_name(e, s),
+		    (clear_attrs & GRUB_MEM_ATTR_R) ? "r" : "",
+		    (clear_attrs & GRUB_MEM_ATTR_W) ? "w" : "",
+		    (clear_attrs & GRUB_MEM_ATTR_X) ? "x" : "",
+		    (set_attrs & GRUB_MEM_ATTR_R) ? "r" : "",
+		    (set_attrs & GRUB_MEM_ATTR_W) ? "w" : "",
+		    (set_attrs & GRUB_MEM_ATTR_X) ? "x" : "");
+      grub_update_mem_attrs ((grub_addr_t)(seg->addr), seg->size, set_attrs, clear_attrs);
+    }
+
+#if !defined (__i386__) && !defined (__x86_64__) && !defined(__riscv)
+  tgaddr = grub_min((grub_addr_t)mod->tramp, (grub_addr_t)mod->got);
+  tgsz = grub_max((grub_addr_t)mod->trampptr, (grub_addr_t)mod->gotptr) - tgaddr;
+
+  if (tgsz)
+    {
+      tgsz = ALIGN_UP(tgsz, arch_addralign);
+
+      grub_dprintf ("modules", "updating attributes for GOT and trampolines\n",
+		    mod->name);
+      grub_update_mem_attrs (tgaddr, tgsz, GRUB_MEM_ATTR_R|GRUB_MEM_ATTR_X,
+			     GRUB_MEM_ATTR_W);
+    }
+#endif
+
+  grub_dprintf ("modules", "done updating module memory attributes for \"%s\"\n",
+		mod->name);
+
   return GRUB_ERR_NONE;
 }
 
@@ -660,6 +734,7 @@ grub_dl_load_core_noinit (void *addr, grub_size_t size)
   mod->ref_count = 1;
 
   grub_dprintf ("modules", "relocating to %p\n", mod);
+
   /* Me, Vladimir Serbinenko, hereby I add this module check as per new
      GNU module policy. Note that this license check is informative only.
      Modules have to be licensed under GPLv3 or GPLv3+ (optionally
@@ -673,7 +748,8 @@ grub_dl_load_core_noinit (void *addr, grub_size_t size)
       || grub_dl_resolve_dependencies (mod, e)
       || grub_dl_load_segments (mod, e)
       || grub_dl_resolve_symbols (mod, e)
-      || grub_dl_relocate_symbols (mod, e))
+      || grub_dl_relocate_symbols (mod, e)
+      || grub_dl_set_mem_attrs (mod, e))
     {
       mod->fini = 0;
       grub_dl_unload (mod);
include/grub/dl.h +44 -0

56 lines not on this page · raw message

Signature · 7 lines
2.39.2


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
#14 lore raw

Re: [PATCH 07/15] nx: set page permissions for loaded modules.

Can you not add needless dprintf's ? This part is size-constrained on i386-pc and part of the patch just adds dprintf's unrelated to the topic at hand.
Can we skip all this on non-efi and have it ifdef-ed out for the sake of size?

Quoted 162 lines · Mate Kukri

From: Peter Jones <[email protected]>

For NX, we need to set write and executable permissions on the sections of grub modules when we load them.

On sections with SHF_ALLOC set, which is typically everything except .modname and the symbol and string tables, this patch clears the Read Only flag on sections that have the ELF flag SHF_WRITE set, and clears the No eXecute flag on sections with SHF_EXECINSTR set. In all other cases it sets both flags.

[rharwood: arm tgptr -> tgaddr]
(cherry picked from commit ad1b904d325b7edb651111577e065a20e6b77c74)

Conflicts:
grub-core/kern/dl.c (obvious)

---
 grub-core/kern/dl.c | 102 ++++++++++++++++++++++++++++++++++++++------
 include/grub/dl.h   |  44 +++++++++++++++++++
 2 files changed, 133 insertions(+), 13 deletions(-)
grub-core/kern/dl.c +86 -12
index fb06fd8c6..2784fae7a 100644
@@ -233,6 +233,8 @@ grub_dl_load_segments (grub_dl_t mod, const Elf_Ehdr *e)
 #endif
   char *ptr;
 
+  grub_dprintf ("modules", "loading segments for \"%s\"\n", mod->name);
+
   arch_addralign = grub_arch_dl_min_alignment ();
 
   for (i = 0, s = (const Elf_Shdr *)((const char *) e + e->e_shoff);
@@ -334,6 +336,7 @@ grub_dl_load_segments (grub_dl_t mod, const Elf_Ehdr *e)
   ptr += got;
 #endif
 
+  grub_dprintf ("modules", "done loading segments for \"%s\"\n", mod->name);
   return GRUB_ERR_NONE;
 }
 
@@ -600,6 +603,7 @@ grub_dl_relocate_symbols (grub_dl_t mod, void *ehdr)
   Elf_Shdr *s;
   unsigned i;
 
+  grub_dprintf ("modules", "relocating symbols for \"%s\"\n", mod->name);
   for (i = 0, s = (Elf_Shdr *) ((char *) e + e->e_shoff);
        i < e->e_shnum;
        i++, s = (Elf_Shdr *) ((char *) s + e->e_shentsize))
@@ -608,22 +612,92 @@ grub_dl_relocate_symbols (grub_dl_t mod, void *ehdr)
        grub_dl_segment_t seg;
        grub_err_t err;
 
-       /* Find the target segment.  */
-       for (seg = mod->segment; seg; seg = seg->next)
-         if (seg->section == s->sh_info)
-           break;
+       seg = grub_dl_find_segment(mod, s->sh_info);
+        if (!seg)
+         continue;
 
-       if (seg)
-         {
-           if (!mod->symtab)
-             return grub_error (GRUB_ERR_BAD_MODULE, "relocation without symbol table");
+       if (!mod->symtab)
+         return grub_error (GRUB_ERR_BAD_MODULE, "relocation without symbol table");
 
-           err = grub_arch_dl_relocate_symbols (mod, ehdr, s, seg);
-           if (err)
-             return err;
-         }
+       err = grub_arch_dl_relocate_symbols (mod, ehdr, s, seg);
+       if (err)
+         return err;
       }
 
+  grub_dprintf ("modules", "done relocating symbols for \"%s\"\n", mod->name);
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_dl_set_mem_attrs (grub_dl_t mod, void *ehdr)
+{
 
+  unsigned i;
+  const Elf_Shdr *s;
+  const Elf_Ehdr *e = ehdr;
+#if !defined (__i386__) && !defined (__x86_64__) && !defined(__riscv)
+  grub_size_t arch_addralign = grub_arch_dl_min_alignment ();
+  grub_addr_t tgaddr;
+  grub_uint64_t tgsz;
+#endif
+
+  grub_dprintf ("modules", "updating memory attributes for \"%s\"\n",
+               mod->name);
+  for (i = 0, s = (const Elf_Shdr *)((const char *) e + e->e_shoff);
+       i < e->e_shnum;
+       i++, s = (const Elf_Shdr *)((const char *) s + e->e_shentsize))
+    {
+      grub_dl_segment_t seg;
+      grub_uint64_t set_attrs = GRUB_MEM_ATTR_R;
+      grub_uint64_t clear_attrs = GRUB_MEM_ATTR_W|GRUB_MEM_ATTR_X;
+
+      seg = grub_dl_find_segment(mod, i);
+      if (!seg)
+       continue;
+
+      if (seg->size == 0 || !(s->sh_flags & SHF_ALLOC))
+       continue;
+
+      if (s->sh_flags & SHF_WRITE)
+       {
+         set_attrs |= GRUB_MEM_ATTR_W;
+         clear_attrs &= ~GRUB_MEM_ATTR_W;
+       }
+
+      if (s->sh_flags & SHF_EXECINSTR)
+       {
+         set_attrs |= GRUB_MEM_ATTR_X;
+         clear_attrs &= ~GRUB_MEM_ATTR_X;
+       }
+
+      grub_dprintf ("modules", "setting memory attrs for section \"%s\" to -%s%s%s+%s%s%s\n",
+                   grub_dl_get_section_name(e, s),
+                   (clear_attrs & GRUB_MEM_ATTR_R) ? "r" : "",
+                   (clear_attrs & GRUB_MEM_ATTR_W) ? "w" : "",
+                   (clear_attrs & GRUB_MEM_ATTR_X) ? "x" : "",
+                   (set_attrs & GRUB_MEM_ATTR_R) ? "r" : "",
+                   (set_attrs & GRUB_MEM_ATTR_W) ? "w" : "",
+                   (set_attrs & GRUB_MEM_ATTR_X) ? "x" : "");
+      grub_update_mem_attrs ((grub_addr_t)(seg->addr), seg->size, set_attrs, clear_attrs);
+    }
+
+#if !defined (__i386__) && !defined (__x86_64__) && !defined(__riscv)
+  tgaddr = grub_min((grub_addr_t)mod->tramp, (grub_addr_t)mod->got);
+  tgsz = grub_max((grub_addr_t)mod->trampptr, (grub_addr_t)mod->gotptr) - tgaddr;
+
+  if (tgsz)
+    {
+      tgsz = ALIGN_UP(tgsz, arch_addralign);
+
+      grub_dprintf ("modules", "updating attributes for GOT and trampolines\n",
+                   mod->name);
+      grub_update_mem_attrs (tgaddr, tgsz, GRUB_MEM_ATTR_R|GRUB_MEM_ATTR_X,
+                            GRUB_MEM_ATTR_W);
+    }
+#endif
+
+  grub_dprintf ("modules", "done updating module memory attributes for \"%s\"\n",
+               mod->name);
+
   return GRUB_ERR_NONE;
 }

grub-core/kern/dl.c grub_dl_load_core_noinit (void *addr, grub_size_t size) · line 737

Quoted 4 lines
grub-core/kern/dl.c +1 -0
@@ -660,6 +734,7 @@ grub_dl_load_core_noinit (void *addr, grub_size_t size)
   mod->ref_count = 1;
 
   grub_dprintf ("modules", "relocating to %p\n", mod);
+

Needless hunk

Quoted 62 lines
grub-core/kern/dl.c +2 -1
   /* Me, Vladimir Serbinenko, hereby I add this module check as per new
      GNU module policy. Note that this license check is informative only.
      Modules have to be licensed under GPLv3 or GPLv3+ (optionally
@@ -673,7 +748,8 @@ grub_dl_load_core_noinit (void *addr, grub_size_t size)
       || grub_dl_resolve_dependencies (mod, e)
       || grub_dl_load_segments (mod, e)
       || grub_dl_resolve_symbols (mod, e)
-      || grub_dl_relocate_symbols (mod, e))
+      || grub_dl_relocate_symbols (mod, e)
+      || grub_dl_set_mem_attrs (mod, e))
     {
       mod->fini = 0;
       grub_dl_unload (mod);
include/grub/dl.h +34 -0
index 8a37cc16f..4c8a9b4ee 100644
@@ -27,6 +27,7 @@
 #include <grub/elf.h>
 #include <grub/list.h>
 #include <grub/misc.h>
+#include <grub/mm.h>
 #endif
 
 /*
@@ -254,6 +255,49 @@ grub_dl_is_persistent (grub_dl_t mod)
   return mod->persistent;
 }
 
+static inline const char *
+grub_dl_get_section_name (const Elf_Ehdr *e, const Elf_Shdr *s)
+{
+  Elf_Shdr *str_s;
+  const char *str;
+
+  str_s = (Elf_Shdr *) ((char *) e + e->e_shoff + e->e_shstrndx * e->e_shentsize);
+  str = (char *) e + str_s->sh_offset;
+
+  return str + s->sh_name;
+}
+
+static inline long
+grub_dl_find_section_index (Elf_Ehdr *e, const char *name)
+{
+  Elf_Shdr *s;
+  const char *str;
+  unsigned i;
+
+  s = (Elf_Shdr *) ((char *) e + e->e_shoff + e->e_shstrndx * e->e_shentsize);
+  str = (char *) e + s->sh_offset;
+
+  for (i = 0, s = (Elf_Shdr *) ((char *) e + e->e_shoff);
+       i < e->e_shnum;
+       i++, s = (Elf_Shdr *) ((char *) s + e->e_shentsize))
+    if (grub_strcmp (str + s->sh_name, name) == 0)
+      return (long)i;
+  return -1;
+}
+
+/* Return the segment for a section of index N */
+static inline grub_dl_segment_t
+grub_dl_find_segment (grub_dl_t mod, unsigned n)

include/grub/dl.h grub_dl_is_persistent (grub_dl_t mod) · line 300

Quoted 10 lines
include/grub/dl.h +10 -0
+{
+  grub_dl_segment_t seg;
+
+  for (seg = mod->segment; seg; seg = seg->next)
+    if (seg->section == n)
+      return seg;
+
+  return NULL;
+}
+

I like those inlines

Quoted 11 lines
include/grub/dl.h +0 -1
 #endif
 
 grub_err_t grub_dl_register_symbol (const char *name, void *addr,
--

2.39.2

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel

Signature · 7 lines
Regards
Vladimir 'phcoder' Serbinenko

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
author
#15 lore raw

PATCH 8/15 nx: set the nx compatible flag in EFI grub images

In reply to Mate Kukri

From: Peter Jones <[email protected]>

For NX, we need the grub binary to announce that it is compatible with the NX feature. This implies that when loading the executable grub image, several attributes are true:

- the binary doesn't need an executable stack
- the binary doesn't need sections to be both executable and writable
- the binary knows how to use the EFI Memory Attributes protocol on code it is loading.

This patch adds a definition for the PE DLL Characteristics flag GRUB_PE32_NX_COMPAT, and changes grub-mkimage to set that flag.

(cherry picked from commit a9ec858bd62b004c331cad9b5b00071d3081b626)

Conflicts:
util/mkimage.c

---
 util/mkimage.c | 1 +
 1 file changed, 1 insertion(+)
util/mkimage.c +1 -0
index 4237383ac..9b4720e21 100644
@@ -1403,6 +1403,7 @@ grub_install_generate_image (const char *dir, const char *prefix,
 #pragma GCC diagnostic push
 #pragma GCC diagnostic ignored "-Wdangling-pointer"
 #endif
+	PE_OHDR (o32, o64, dll_characteristics) = grub_host_to_target16 (GRUB_PE32_NX_COMPAT);
 	PE_OHDR (o32, o64, header_size) = grub_host_to_target32 (header_size);
 	PE_OHDR (o32, o64, entry_addr) = grub_host_to_target32 (layout.start_address);
 	PE_OHDR (o32, o64, image_base) = 0;
Signature · 7 lines
2.39.2


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
#16 lore raw

Re: [PATCH 08/15] nx: set the nx compatible flag in EFI grub images

Reviewed By: Vladimir Serbinenko

Quoted 47 lines · Mate Kukri

From: Peter Jones <[email protected]>

For NX, we need the grub binary to announce that it is compatible with the NX feature. This implies that when loading the executable grub image, several attributes are true:

- the binary doesn't need an executable stack
- the binary doesn't need sections to be both executable and writable
- the binary knows how to use the EFI Memory Attributes protocol on code it is loading.

This patch adds a definition for the PE DLL Characteristics flag GRUB_PE32_NX_COMPAT, and changes grub-mkimage to set that flag.

(cherry picked from commit a9ec858bd62b004c331cad9b5b00071d3081b626)

Conflicts:
util/mkimage.c

---
 util/mkimage.c | 1 +
 1 file changed, 1 insertion(+)
util/mkimage.c +1 -1
index 4237383ac..9b4720e21 100644
@@ -1403,6 +1403,7 @@ grub_install_generate_image (const char *dir, const char *prefix,
 #pragma GCC diagnostic push
 #pragma GCC diagnostic ignored "-Wdangling-pointer"
 #endif
+       PE_OHDR (o32, o64, dll_characteristics) = grub_host_to_target16 (GRUB_PE32_NX_COMPAT);
        PE_OHDR (o32, o64, header_size) = grub_host_to_target32 (header_size);
        PE_OHDR (o32, o64, entry_addr) = grub_host_to_target32 (layout.start_address);
        PE_OHDR (o32, o64, image_base) = 0;
--

2.39.2

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel

Signature · 7 lines
Regards
Vladimir 'phcoder' Serbinenko

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
author
#17 lore raw

PATCH 9/15 grub_dl_load_segments(): page-align the tramp/GOT areas too

In reply to Mate Kukri

From: Laszlo Ersek <[email protected]>

The tramp/GOT write-protection in grub_dl_set_mem_attrs() requires that the tramp/GOT areas of the module image *not* share a page with any other memory allocations. Page-align the tramp/GOT areas, while satisfying their intrinsic alignment requirements too.

Fixes 887f1d8fa976 (modules: load module sections at page-aligned addresses)
Fixes ad1b904d325b (nx: set page permissions for loaded modules.)
(cherry picked from commit c3569e4a245c21a3806ca122ee88da7c91d3d454)

Conflicts:
grub-core/kern/dl.c (obvious)

---
 grub-core/kern/dl.c | 24 ++++++++++++++++--------
 1 file changed, 16 insertions(+), 8 deletions(-)
grub-core/kern/dl.c +16 -8
index 2784fae7a..9f31ad3b9 100644
@@ -228,7 +228,9 @@ grub_dl_load_segments (grub_dl_t mod, const Elf_Ehdr *e)
 #if !defined (__i386__) && !defined (__x86_64__) && !defined(__riscv) && \
   !defined (__loongarch__)
   grub_size_t tramp;
+  grub_size_t tramp_align;
   grub_size_t got;
+  grub_size_t got_align;
   grub_err_t err;
 #endif
   char *ptr;
@@ -260,12 +262,18 @@ grub_dl_load_segments (grub_dl_t mod, const Elf_Ehdr *e)
   err = grub_arch_dl_get_tramp_got_size (e, &tramp, &got);
   if (err)
     return err;
-  tsize += ALIGN_UP (tramp, GRUB_ARCH_DL_TRAMP_ALIGN);
-  if (talign < GRUB_ARCH_DL_TRAMP_ALIGN)
-    talign = GRUB_ARCH_DL_TRAMP_ALIGN;
-  tsize += ALIGN_UP (got, GRUB_ARCH_DL_GOT_ALIGN);
-  if (talign < GRUB_ARCH_DL_GOT_ALIGN)
-    talign = GRUB_ARCH_DL_GOT_ALIGN;
+  tramp_align = GRUB_ARCH_DL_TRAMP_ALIGN;
+  if (tramp_align < arch_addralign)
+    tramp_align = arch_addralign;
+  tsize += ALIGN_UP (tramp, tramp_align);
+  if (talign < tramp_align)
+    talign = tramp_align;
+  got_align = GRUB_ARCH_DL_GOT_ALIGN;
+  if (got_align < arch_addralign)
+    got_align = arch_addralign;
+  tsize += ALIGN_UP (got, got_align);
+  if (talign < got_align)
+    talign = got_align;
 #endif
 
 #ifdef GRUB_MACHINE_EMU
@@ -326,11 +334,11 @@ grub_dl_load_segments (grub_dl_t mod, const Elf_Ehdr *e)
     }
 #if !defined (__i386__) && !defined (__x86_64__) && !defined(__riscv) && \
   !defined (__loongarch__)
-  ptr = (char *) ALIGN_UP ((grub_addr_t) ptr, GRUB_ARCH_DL_TRAMP_ALIGN);
+  ptr = (char *) ALIGN_UP ((grub_addr_t) ptr, tramp_align);
   mod->tramp = ptr;
   mod->trampptr = ptr;
   ptr += tramp;
-  ptr = (char *) ALIGN_UP ((grub_addr_t) ptr, GRUB_ARCH_DL_GOT_ALIGN);
+  ptr = (char *) ALIGN_UP ((grub_addr_t) ptr, got_align);
   mod->got = ptr;
   mod->gotptr = ptr;
   ptr += got;
Signature · 7 lines
2.39.2


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
#18 lore raw

Re: [PATCH 09/15] grub_dl_load_segments(): page-align the tramp/GOT areas too

Quoted 8 lines
grub-core/kern/dl.c +2 -6
-  tsize += ALIGN_UP (tramp, GRUB_ARCH_DL_TRAMP_ALIGN);
-  if (talign < GRUB_ARCH_DL_TRAMP_ALIGN)
-    talign = GRUB_ARCH_DL_TRAMP_ALIGN;
-  tsize += ALIGN_UP (got, GRUB_ARCH_DL_GOT_ALIGN);
-  if (talign < GRUB_ARCH_DL_GOT_ALIGN)
-    talign = GRUB_ARCH_DL_GOT_ALIGN;
+  tramp_align = GRUB_ARCH_DL_TRAMP_ALIGN;
+  if (tramp_align < arch_addralign)

grub-core/kern/dl.c grub_dl_load_segments (grub_dl_t mod, const Elf_Ehdr *e) · line 276

Quoted 10 lines
grub-core/kern/dl.c +10 -0
+    tramp_align = arch_addralign;
+  tsize += ALIGN_UP (tramp, tramp_align);
+  if (talign < tramp_align)
+    talign = tramp_align;
+  got_align = GRUB_ARCH_DL_GOT_ALIGN;
+  if (got_align < arch_addralign)
+    got_align = arch_addralign;
+  tsize += ALIGN_UP (got, got_align);
+  if (talign < got_align)
+    talign = got_align;

Why not use grub_max for better readability?

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel

author
#19 lore raw

PATCH 10/15 grub_dl_set_mem_attrs(): add self-check for the tramp/GOT sizes

In reply to Mate Kukri

From: Laszlo Ersek <[email protected]>

On aarch64 UEFI, we currently have a crasher:

grub_dl_load_core()

    grub_dl_load_core_noinit()

      /* independent allocation: must remain writable */
      mod = grub_zalloc();

      /* allocates module image with incorrect tail alignment */
      grub_dl_load_segments()

      /* write-protecting the module image makes "mod" read-only! */
      grub_dl_set_mem_attrs()
        grub_update_mem_attrs()

    grub_dl_init()
      /* page fault, crash */
      mod->next = ...;

- Commit 887f1d8fa976 ("modules: load module sections at page-aligned addresses", 2023-02-08) forgot to page-align the allocation of the trampolines and GOT areas of grub2 modules, in grub_dl_load_segments().

- Commit ad1b904d325b ("nx: set page permissions for loaded modules.", 2023-02-08) calculated a common bounding box for the trampolines and GOT areas in grub_dl_set_mem_attrs(), rounded the box size up to a whole multiple of EFI page size ("arch_addralign"), and write-protected the resultant page range.

Consequently, grub_dl_load_segments() places the module image in memory such that its tail -- the end of the trampolines and GOT areas -- lands at the head of a page whose tail in turn contains independent memory allocations, such as "mod". grub_dl_set_mem_attrs() will then unwittingly write-protect these other allocations too.

But "mod" must remain writable: we assign "mod->next" in grub_dl_init() subsequently. Currently we crash there with a page fault / permission fault.

(The crash is not trivial to hit: the tramp/GOT areas are irrelevant on x86_64, plus the page protection depends on the UEFI platform firmware providing EFI_MEMORY_ATTRIBUTE_PROTOCOL. In practice, the crash is restricted to aarch64 edk2 (ArmVirtQemu) builds containing commit 1c4dfadb4611, "ArmPkg/CpuDxe: Implement EFI memory attributes protocol", 2023-03-16.)

Example log before the patch:

Quoted 13 lines

kern/dl.c:736: updating attributes for GOT and trampolines ("video_fb") kern/efi/mm.c:927: set +rx -w on 0x13b88b000-0x13b88bfff before:rwx after:r-x kern/dl.c:744: done updating module memory attributes for "video_fb" kern/dl.c:639: flushing 0xe4f0 bytes at 0x13b87d000 kern/arm64/cache.c:42: D$ line size: 64
kern/arm64/cache.c:43: I$ line size: 64
kern/dl.c:839: module name: video_fb
kern/dl.c:840: init function: 0x0
kern/dl.c:865: Initing module video_fb

Synchronous Exception at 0x000000013B8A76EC
PC 0x00013B8A76EC

Quoted 8 lines

X0 0x000000013B88B960 X1 0x0000000000000000 X2 0x000000013F93587C X3 0x0000000000000075

SP 0x00000000470745C0 ELR 0x000000013B8A76EC SPSR 0x60000205 FPSR 0x00000000
ESR 0x9600004F FAR 0x000000013B88B9D0

ESR : EC 0x25 IL 0x1 ISS 0x0000004F

Data abort: Permission fault, third level

Note the following:

- The whole 4K page at 0x1_3B88_B000 is write-protected.

- The "video_fb" module actually lives at [0x1_3B87_D000, 0x1_3B88_B4F0) -- left-inclusive, right-exclusive --; that is, in the last page (at 0x1_3B88_B000), it only occupies the first 0x4F0 bytes.

- The instruction at 0x1_3B8A_76EC faults. Not shown here, but it is a store instruction, which writes to the field at offset 0x70 of the structure pointed-to by the X0 register. This is the "mod->next" assignment from grub_dl_init().

- The faulting address is therefore (X0 + 0x70), i.e., 0x1_3B88_B9D0. This is indeed the value held in the FAR register.

- The faulting address 0x1_3B88_B9D0 falls in the above-noted page (at 0x1_3B88_B000), namely at offset 0x9D0. This is *beyond* the first 0x4F0 bytes that the very tail of the "video_fb" module occupies at the front of that page.

For now, add a self-check that reports this bug (and prevents the crash by skipping the write protection).

Example log after the patch:

Quoted 3 lines

kern/dl.c:742:BUG: trying to protect pages outside of module allocation ("video_fb"): module base 0x13b87d000, size 0xe4f0; tramp/GOT base 0x13b88b000, size 0x1000

(cherry picked from commit deb4c03d7658f0695db8217896c2830009b7469d)
---
 grub-core/kern/dl.c | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
grub-core/kern/dl.c +10 -1
index 9f31ad3b9..042033a90 100644
@@ -645,7 +645,7 @@ grub_dl_set_mem_attrs (grub_dl_t mod, void *ehdr)
 #if !defined (__i386__) && !defined (__x86_64__) && !defined(__riscv)
   grub_size_t arch_addralign = grub_arch_dl_min_alignment ();
   grub_addr_t tgaddr;
-  grub_uint64_t tgsz;
+  grub_size_t tgsz;
 #endif
 
   grub_dprintf ("modules", "updating memory attributes for \"%s\"\n",
@@ -698,6 +698,15 @@ grub_dl_set_mem_attrs (grub_dl_t mod, void *ehdr)
 
       grub_dprintf ("modules", "updating attributes for GOT and trampolines\n",
 		    mod->name);
+      if (tgaddr < (grub_addr_t)mod->base ||
+          tgsz > (grub_addr_t)-1 - tgaddr ||
+	  tgaddr + tgsz > (grub_addr_t)mod->base + mod->sz)
+	return grub_error (GRUB_ERR_BUG,
+			   "BUG: trying to protect pages outside of module "
+			   "allocation (\"%s\"): module base %p, size 0x%"
+			   PRIxGRUB_SIZE "; tramp/GOT base 0x%" PRIxGRUB_ADDR
+			   ", size 0x%" PRIxGRUB_SIZE,
+			   mod->name, mod->base, mod->sz, tgaddr, tgsz);
       grub_update_mem_attrs (tgaddr, tgsz, GRUB_MEM_ATTR_R|GRUB_MEM_ATTR_X,
 			     GRUB_MEM_ATTR_W);
     }
Signature · 7 lines
2.39.2


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
#20 lore raw

Re: [PATCH 10/15] grub_dl_set_mem_attrs(): add self-check for the tramp/GOT sizes

Do you mean that this crash is introduced and not fixed in this patch series? Can't we fix it by bumping total allocation size to multiple of page size?

Quoted 148 lines · Mate Kukri

From: Laszlo Ersek <[email protected]>

On aarch64 UEFI, we currently have a crasher:

grub_dl_load_core()

    grub_dl_load_core_noinit()

      /* independent allocation: must remain writable */
      mod = grub_zalloc();

      /* allocates module image with incorrect tail alignment */
      grub_dl_load_segments()

      /* write-protecting the module image makes "mod" read-only! */
      grub_dl_set_mem_attrs()
        grub_update_mem_attrs()

    grub_dl_init()
      /* page fault, crash */
      mod->next = ...;

- Commit 887f1d8fa976 ("modules: load module sections at page-aligned addresses", 2023-02-08) forgot to page-align the allocation of the trampolines and GOT areas of grub2 modules, in grub_dl_load_segments().

- Commit ad1b904d325b ("nx: set page permissions for loaded modules.", 2023-02-08) calculated a common bounding box for the trampolines and GOT areas in grub_dl_set_mem_attrs(), rounded the box size up to a whole multiple of EFI page size ("arch_addralign"), and write-protected the resultant page range.

Consequently, grub_dl_load_segments() places the module image in memory such that its tail -- the end of the trampolines and GOT areas -- lands at the head of a page whose tail in turn contains independent memory allocations, such as "mod". grub_dl_set_mem_attrs() will then unwittingly write-protect these other allocations too.

But "mod" must remain writable: we assign "mod->next" in grub_dl_init() subsequently. Currently we crash there with a page fault / permission fault.

(The crash is not trivial to hit: the tramp/GOT areas are irrelevant on x86_64, plus the page protection depends on the UEFI platform firmware providing EFI_MEMORY_ATTRIBUTE_PROTOCOL. In practice, the crash is restricted to aarch64 edk2 (ArmVirtQemu) builds containing commit 1c4dfadb4611, "ArmPkg/CpuDxe: Implement EFI memory attributes protocol", 2023-03-16.)

Example log before the patch:

Quoted 13 lines

kern/dl.c:736: updating attributes for GOT and trampolines ("video_fb") kern/efi/mm.c:927: set +rx -w on 0x13b88b000-0x13b88bfff before:rwx after:r-x kern/dl.c:744: done updating module memory attributes for "video_fb" kern/dl.c:639: flushing 0xe4f0 bytes at 0x13b87d000 kern/arm64/cache.c:42: D$ line size: 64
kern/arm64/cache.c:43: I$ line size: 64
kern/dl.c:839: module name: video_fb
kern/dl.c:840: init function: 0x0
kern/dl.c:865: Initing module video_fb

Synchronous Exception at 0x000000013B8A76EC
PC 0x00013B8A76EC

Quoted 8 lines

X0 0x000000013B88B960 X1 0x0000000000000000 X2 0x000000013F93587C X3 0x0000000000000075

SP 0x00000000470745C0 ELR 0x000000013B8A76EC SPSR 0x60000205 FPSR 0x00000000
ESR 0x9600004F FAR 0x000000013B88B9D0

ESR : EC 0x25 IL 0x1 ISS 0x0000004F

Data abort: Permission fault, third level

Note the following:

- The whole 4K page at 0x1_3B88_B000 is write-protected.

- The "video_fb" module actually lives at [0x1_3B87_D000, 0x1_3B88_B4F0) -- left-inclusive, right-exclusive --; that is, in the last page (at 0x1_3B88_B000), it only occupies the first 0x4F0 bytes.

- The instruction at 0x1_3B8A_76EC faults. Not shown here, but it is a store instruction, which writes to the field at offset 0x70 of the structure pointed-to by the X0 register. This is the "mod->next" assignment from grub_dl_init().

- The faulting address is therefore (X0 + 0x70), i.e., 0x1_3B88_B9D0. This is indeed the value held in the FAR register.

- The faulting address 0x1_3B88_B9D0 falls in the above-noted page (at 0x1_3B88_B000), namely at offset 0x9D0. This is *beyond* the first 0x4F0 bytes that the very tail of the "video_fb" module occupies at the front of that page.

For now, add a self-check that reports this bug (and prevents the crash by skipping the write protection).

Example log after the patch:

Quoted 3 lines

kern/dl.c:742:BUG: trying to protect pages outside of module allocation ("video_fb"): module base 0x13b87d000, size 0xe4f0; tramp/GOT base 0x13b88b000, size 0x1000

(cherry picked from commit deb4c03d7658f0695db8217896c2830009b7469d)
---
 grub-core/kern/dl.c | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
grub-core/kern/dl.c +10 -2
index 9f31ad3b9..042033a90 100644
@@ -645,7 +645,7 @@ grub_dl_set_mem_attrs (grub_dl_t mod, void *ehdr)
 #if !defined (__i386__) && !defined (__x86_64__) && !defined(__riscv)
   grub_size_t arch_addralign = grub_arch_dl_min_alignment ();
   grub_addr_t tgaddr;
-  grub_uint64_t tgsz;
+  grub_size_t tgsz;
 #endif
 
   grub_dprintf ("modules", "updating memory attributes for \"%s\"\n",
@@ -698,6 +698,15 @@ grub_dl_set_mem_attrs (grub_dl_t mod, void *ehdr)
 
       grub_dprintf ("modules", "updating attributes for GOT and trampolines\n",
                    mod->name);
+      if (tgaddr < (grub_addr_t)mod->base ||
+          tgsz > (grub_addr_t)-1 - tgaddr ||
+         tgaddr + tgsz > (grub_addr_t)mod->base + mod->sz)
+       return grub_error (GRUB_ERR_BUG,
+                          "BUG: trying to protect pages outside of module "
+                          "allocation (\"%s\"): module base %p, size 0x%"
+                          PRIxGRUB_SIZE "; tramp/GOT base 0x%" PRIxGRUB_ADDR
+                          ", size 0x%" PRIxGRUB_SIZE,
+                          mod->name, mod->base, mod->sz, tgaddr, tgsz);
       grub_update_mem_attrs (tgaddr, tgsz, GRUB_MEM_ATTR_R|GRUB_MEM_ATTR_X,
                             GRUB_MEM_ATTR_W);
     }
--

2.39.2

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel

Signature · 7 lines
Regards
Vladimir 'phcoder' Serbinenko

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
author
#21 lore raw

PATCH 11/15 grub_dl_set_mem_attrs(): fix format string

In reply to Mate Kukri

From: Laszlo Ersek <[email protected]>

The grub_dprintf() call for printing the message

updating attributes for GOT and trampolines

passes the argument "mod->name", but the format string doesn't accept that argument.

Print the module name too.

Example output:

Quoted 1 line

kern/dl.c:736: updating attributes for GOT and trampolines ("video_fb")

Fixes ad1b904d325b (nx: set page permissions for loaded modules.)
(cherry picked from commit ee58dd70d627df54b806e94409673a11caab5a5d)
---
 grub-core/kern/dl.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
grub-core/kern/dl.c +2 -1
index 042033a90..78e53b078 100644
@@ -696,7 +696,8 @@ grub_dl_set_mem_attrs (grub_dl_t mod, void *ehdr)
     {
       tgsz = ALIGN_UP(tgsz, arch_addralign);
 
-      grub_dprintf ("modules", "updating attributes for GOT and trampolines\n",
+      grub_dprintf ("modules",
+		    "updating attributes for GOT and trampolines (\"%s\")\n",
 		    mod->name);
       if (tgaddr < (grub_addr_t)mod->base ||
           tgsz > (grub_addr_t)-1 - tgaddr ||
Signature · 7 lines
2.39.2


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
author
#22 lore raw

PATCH 12/15 mm: Fixup bogus assumptions about types sizes in format strings

In reply to Mate Kukri
---
 grub-core/kern/efi/mm.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
grub-core/kern/efi/mm.c +4 -4
index 46f2266e1..1064036f4 100644
@@ -741,7 +741,7 @@ grub_get_mem_attrs (grub_addr_t addr, grub_size_t size, grub_uint64_t *attrs)
   if (physaddr & 0xfff || size & 0xfff || size == 0 || attrs == NULL)
     {
       grub_dprintf ("nx", "%s called on 0x%"PRIxGRUB_ADDR"-0x%"PRIxGRUB_ADDR" and attrs %p\n",
-		    __func__, physaddr, physaddr+size-1, attrs);
+		    __func__, (grub_addr_t)physaddr, (grub_addr_t)(physaddr+size-1), attrs);
       return 0;
     }
 
@@ -774,7 +774,7 @@ grub_update_mem_attrs (grub_addr_t addr, grub_size_t size,
   if (physaddr & 0xfff || size & 0xfff || size == 0)
     {
       grub_dprintf ("nx", "%s called on 0x%"PRIxGRUB_ADDR"-0x%"PRIxGRUB_ADDR" +%s%s%s -%s%s%s\n",
-		    __func__, physaddr, physaddr + size - 1,
+		    __func__, (grub_addr_t)physaddr, (grub_addr_t)(physaddr + size - 1),
 		    (set_attrs & GRUB_MEM_ATTR_R) ? "r" : "",
 		    (set_attrs & GRUB_MEM_ATTR_W) ? "w" : "",
 		    (set_attrs & GRUB_MEM_ATTR_X) ? "x" : "",
@@ -785,9 +785,9 @@ grub_update_mem_attrs (grub_addr_t addr, grub_size_t size,
     }
 
   uefi_set_attrs = grub_mem_attrs_to_uefi_mem_attrs (set_attrs);
-  grub_dprintf ("nx", "translating set_attrs from 0x%lx to 0x%lx\n", set_attrs, uefi_set_attrs);
+  grub_dprintf ("nx", "translating set_attrs from 0x%"PRIxGRUB_UINT64_T" to 0x%"PRIxGRUB_UINT64_T"\n", set_attrs, uefi_set_attrs);
   uefi_clear_attrs = grub_mem_attrs_to_uefi_mem_attrs (clear_attrs);
-  grub_dprintf ("nx", "translating clear_attrs from 0x%lx to 0x%lx\n", clear_attrs, uefi_clear_attrs);
+  grub_dprintf ("nx", "translating clear_attrs from 0x%"PRIxGRUB_UINT64_T" to 0x%"PRIxGRUB_UINT64_T"\n", clear_attrs, uefi_clear_attrs);
   if (uefi_set_attrs)
     efi_status = proto->set_memory_attributes(proto, physaddr, size, uefi_set_attrs);
   if (efi_status == GRUB_EFI_SUCCESS && uefi_clear_attrs)
Signature · 7 lines
2.39.2


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
author
#23 lore raw

PATCH 13/15 efi: Provide wrappers for load_image, start_image, unload_image

In reply to Mate Kukri

From: Julian Andres Klode <[email protected]>

These can be used to register a different implementation later, for example, when shim provides a protocol with those functions.

---
 grub-core/kern/efi/efi.c           | 57 ++++++++++++++++++++++++++++++
 grub-core/loader/efi/chainloader.c | 13 +++----
 grub-core/loader/efi/linux.c       | 12 +++----
 include/grub/efi/efi.h             | 37 +++++++++++++++++++
 4 files changed, 104 insertions(+), 15 deletions(-)
grub-core/kern/efi/efi.c +57 -0
index f34c1ef54..3d3b884bb 100644
@@ -1085,3 +1085,60 @@ grub_efi_status_to_err (grub_efi_status_t status)
 
   return err;
 }
+
+static const grub_efi_loader_t *override_loader = NULL;
+
+grub_err_t
+grub_efi_register_loader (const grub_efi_loader_t *loader)
+{
+  if (override_loader != NULL)
+    return grub_error (GRUB_ERR_BUG, "trying to register different loader");
+  override_loader = loader;
+  return GRUB_ERR_NONE;
+}
+
+grub_err_t
+grub_efi_unregister_loader (const grub_efi_loader_t *loader)
+{
+  if (loader != override_loader)
+    return grub_error (GRUB_ERR_BUG, "trying to unregister different loader");
+
+  override_loader = NULL;
+  return GRUB_ERR_NONE;
+}
+
+grub_efi_status_t
+grub_efi_load_image (grub_efi_boolean_t boot_policy,
+		     grub_efi_handle_t parent_image_handle,
+		     grub_efi_device_path_t *file_path, void *source_buffer,
+		     grub_efi_uintn_t source_size,
+		     grub_efi_handle_t *image_handle)
+{
+  if (override_loader != NULL)
+    return override_loader->load_image (boot_policy, parent_image_handle,
+					file_path, source_buffer, source_size,
+					image_handle);
+  return grub_efi_system_table->boot_services->load_image (
+      boot_policy, parent_image_handle, file_path, source_buffer, source_size,
+      image_handle);
+}
+
+grub_efi_status_t
+grub_efi_start_image (grub_efi_handle_t image_handle,
+		      grub_efi_uintn_t *exit_data_size,
+		      grub_efi_char16_t **exit_data)
+{
+  if (override_loader != NULL)
+    return override_loader->start_image (image_handle, exit_data_size,
+					 exit_data);
+  return grub_efi_system_table->boot_services->start_image (
+      image_handle, exit_data_size, exit_data);
+}
+
+grub_efi_status_t
+grub_efi_unload_image (grub_efi_handle_t image_handle)
+{
+  if (override_loader != NULL)
+    return override_loader->unload_image (image_handle);
+  return grub_efi_system_table->boot_services->unload_image (image_handle);
+}
grub-core/loader/efi/chainloader.c +5 -8
index 1de98f783..eb833b678 100644
@@ -50,14 +50,12 @@ grub_chainloader_unload (void *context)
 {
   grub_efi_handle_t image_handle = (grub_efi_handle_t) context;
   grub_efi_loaded_image_t *loaded_image;
-  grub_efi_boot_services_t *b;
 
   loaded_image = grub_efi_get_loaded_image (image_handle);
   if (loaded_image != NULL)
     grub_free (loaded_image->load_options);
 
-  b = grub_efi_system_table->boot_services;
-  b->unload_image (image_handle);
+  grub_efi_unload_image (image_handle);
 
   grub_dl_unref (my_mod);
   return GRUB_ERR_NONE;
@@ -73,7 +71,7 @@ grub_chainloader_boot (void *context)
   grub_efi_char16_t *exit_data = NULL;
 
   b = grub_efi_system_table->boot_services;
-  status = b->start_image (image_handle, &exit_data_size, &exit_data);
+  status = grub_efi_start_image (image_handle, &exit_data_size, &exit_data);
   if (status != GRUB_EFI_SUCCESS)
     {
       if (exit_data)
@@ -343,9 +341,8 @@ grub_cmd_chainloader (grub_command_t cmd __attribute__ ((unused)),
     }
 #endif
 
-  status = b->load_image (0, grub_efi_image_handle, file_path,
-			  boot_image, size,
-			  &image_handle);
+  status = grub_efi_load_image (0, grub_efi_image_handle, file_path,
+				boot_image, size, &image_handle);
   if (status != GRUB_EFI_SUCCESS)
     {
       if (status == GRUB_EFI_OUT_OF_RESOURCES)
@@ -422,7 +419,7 @@ grub_cmd_chainloader (grub_command_t cmd __attribute__ ((unused)),
     b->free_pages (address, pages);
 
   if (image_handle != NULL)
-    b->unload_image (image_handle);
+    grub_efi_unload_image (image_handle);
 
   grub_dl_unref (my_mod);
 
grub-core/loader/efi/linux.c +5 -7
index bfbd95aee..58be3c9f8 100644
@@ -187,7 +187,6 @@ grub_arch_efi_linux_boot_image (grub_addr_t addr, grub_size_t size, char *args)
 {
   grub_efi_memory_mapped_device_path_t *mempath;
   grub_efi_handle_t image_handle;
-  grub_efi_boot_services_t *b;
   grub_efi_status_t status;
   grub_efi_loaded_image_t *loaded_image;
   int len;
@@ -207,10 +206,9 @@ grub_arch_efi_linux_boot_image (grub_addr_t addr, grub_size_t size, char *args)
   mempath[1].header.subtype = GRUB_EFI_END_ENTIRE_DEVICE_PATH_SUBTYPE;
   mempath[1].header.length = sizeof (grub_efi_device_path_t);
 
-  b = grub_efi_system_table->boot_services;
-  status = b->load_image (0, grub_efi_image_handle,
-			  (grub_efi_device_path_t *) mempath,
-			  (void *) addr, size, &image_handle);
+  status = grub_efi_load_image (0, grub_efi_image_handle,
+				(grub_efi_device_path_t *)mempath,
+				(void *)addr, size, &image_handle);
   if (status != GRUB_EFI_SUCCESS)
     return grub_error (GRUB_ERR_BAD_OS, "cannot load image");
 
@@ -235,14 +233,14 @@ grub_arch_efi_linux_boot_image (grub_addr_t addr, grub_size_t size, char *args)
 			    (grub_uint8_t *) args, len, NULL);
 
   grub_dprintf ("linux", "starting image %p\n", image_handle);
-  status = b->start_image (image_handle, 0, NULL);
+  status = grub_efi_start_image (image_handle, 0, NULL);
 
   /* When successful, not reached */
   grub_error (GRUB_ERR_BAD_OS, "start_image() returned 0x%" PRIxGRUB_EFI_UINTN_T, status);
   grub_efi_free_pages ((grub_addr_t) loaded_image->load_options,
 		       GRUB_EFI_BYTES_TO_PAGES (loaded_image->load_options_size));
 unload:
-  b->unload_image (image_handle);
+  grub_efi_unload_image (image_handle);
 
   return grub_errno;
 }
include/grub/efi/efi.h +37 -0
index 194adc1f7..6b517a1ea 100644
@@ -132,6 +132,43 @@ grub_err_t grub_arch_efi_linux_load_image_header(grub_file_t file,
 grub_err_t grub_arch_efi_linux_boot_image(grub_addr_t addr, grub_size_t size,
                                            char *args);
 
+grub_efi_status_t 
+EXPORT_FUNC (grub_efi_load_image) (grub_efi_boolean_t boot_policy,
+				   grub_efi_handle_t parent_image_handle,
+				   grub_efi_device_path_t *file_path,
+				   void *source_buffer, grub_efi_uintn_t source_size,
+				   grub_efi_handle_t *image_handle);
+
+grub_efi_status_t
+EXPORT_FUNC (grub_efi_start_image) (grub_efi_handle_t image_handle,
+				    grub_efi_uintn_t *exit_data_size,
+				    grub_efi_char16_t **exit_data);
+
+grub_efi_status_t
+EXPORT_FUNC (grub_efi_unload_image) (grub_efi_handle_t image_handle);
+
+typedef struct grub_efi_loader
+{
+  grub_efi_status_t (__grub_efi_api *load_image) (grub_efi_boolean_t boot_policy,
+				   grub_efi_handle_t parent_image_handle,
+				   grub_efi_device_path_t *file_path,
+				   void *source_buffer,
+				   grub_efi_uintn_t source_size,
+				   grub_efi_handle_t *image_handle);
+
+  grub_efi_status_t (__grub_efi_api *start_image) (grub_efi_handle_t image_handle,
+				    grub_efi_uintn_t *exit_data_size,
+				    grub_efi_char16_t **exit_data);
+
+  grub_efi_status_t (__grub_efi_api *unload_image) (grub_efi_handle_t image_handle);
+} grub_efi_loader_t;
+
+grub_err_t
+EXPORT_FUNC (grub_efi_register_loader) (const grub_efi_loader_t *loader);
+
+grub_err_t
+EXPORT_FUNC (grub_efi_unregister_loader) (const grub_efi_loader_t *loader);
+
 grub_addr_t grub_efi_section_addr (const char *section);
 
 void grub_efi_mm_init (void);
Signature · 7 lines
2.39.2


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
#24 lore raw

Re: [PATCH 13/15] efi: Provide wrappers for load_image, start_image, unload_image

WDYT of moving this logic to chainloader? Yes, it will make linux depend on chainloader but I think given its current logic it's a honest dependency

Quoted 224 lines · Mate Kukri

From: Julian Andres Klode <[email protected]>

These can be used to register a different implementation later, for example, when shim provides a protocol with those functions.

---
 grub-core/kern/efi/efi.c           | 57 ++++++++++++++++++++++++++++++
 grub-core/loader/efi/chainloader.c | 13 +++----
 grub-core/loader/efi/linux.c       | 12 +++----
 include/grub/efi/efi.h             | 37 +++++++++++++++++++
 4 files changed, 104 insertions(+), 15 deletions(-)
grub-core/kern/efi/efi.c +57 -0
index f34c1ef54..3d3b884bb 100644
@@ -1085,3 +1085,60 @@ grub_efi_status_to_err (grub_efi_status_t status)
 
   return err;
 }
+
+static const grub_efi_loader_t *override_loader = NULL;
+
+grub_err_t
+grub_efi_register_loader (const grub_efi_loader_t *loader)
+{
+  if (override_loader != NULL)
+    return grub_error (GRUB_ERR_BUG, "trying to register different loader");
+  override_loader = loader;
+  return GRUB_ERR_NONE;
+}
+
+grub_err_t
+grub_efi_unregister_loader (const grub_efi_loader_t *loader)
+{
+  if (loader != override_loader)
+    return grub_error (GRUB_ERR_BUG, "trying to unregister different loader");
+
+  override_loader = NULL;
+  return GRUB_ERR_NONE;
+}
+
+grub_efi_status_t
+grub_efi_load_image (grub_efi_boolean_t boot_policy,
+                    grub_efi_handle_t parent_image_handle,
+                    grub_efi_device_path_t *file_path, void *source_buffer,
+                    grub_efi_uintn_t source_size,
+                    grub_efi_handle_t *image_handle)
+{
+  if (override_loader != NULL)
+    return override_loader->load_image (boot_policy, parent_image_handle,
+                                       file_path, source_buffer, source_size,
+                                       image_handle);
+  return grub_efi_system_table->boot_services->load_image (
+      boot_policy, parent_image_handle, file_path, source_buffer, source_size,
+      image_handle);
+}
+
+grub_efi_status_t
+grub_efi_start_image (grub_efi_handle_t image_handle,
+                     grub_efi_uintn_t *exit_data_size,
+                     grub_efi_char16_t **exit_data)
+{
+  if (override_loader != NULL)
+    return override_loader->start_image (image_handle, exit_data_size,
+                                        exit_data);
+  return grub_efi_system_table->boot_services->start_image (
+      image_handle, exit_data_size, exit_data);
+}
+
+grub_efi_status_t
+grub_efi_unload_image (grub_efi_handle_t image_handle)
+{
+  if (override_loader != NULL)
+    return override_loader->unload_image (image_handle);
+  return grub_efi_system_table->boot_services->unload_image (image_handle);
+}
grub-core/loader/efi/chainloader.c +5 -8
index 1de98f783..eb833b678 100644
@@ -50,14 +50,12 @@ grub_chainloader_unload (void *context)
 {
   grub_efi_handle_t image_handle = (grub_efi_handle_t) context;
   grub_efi_loaded_image_t *loaded_image;
-  grub_efi_boot_services_t *b;
 
   loaded_image = grub_efi_get_loaded_image (image_handle);
   if (loaded_image != NULL)
     grub_free (loaded_image->load_options);
 
-  b = grub_efi_system_table->boot_services;
-  b->unload_image (image_handle);
+  grub_efi_unload_image (image_handle);
 
   grub_dl_unref (my_mod);
   return GRUB_ERR_NONE;
@@ -73,7 +71,7 @@ grub_chainloader_boot (void *context)
   grub_efi_char16_t *exit_data = NULL;
 
   b = grub_efi_system_table->boot_services;
-  status = b->start_image (image_handle, &exit_data_size, &exit_data);
+  status = grub_efi_start_image (image_handle, &exit_data_size, &exit_data);
   if (status != GRUB_EFI_SUCCESS)
     {
       if (exit_data)
@@ -343,9 +341,8 @@ grub_cmd_chainloader (grub_command_t cmd __attribute__ ((unused)),
     }
 #endif
 
-  status = b->load_image (0, grub_efi_image_handle, file_path,
-                         boot_image, size,
-                         &image_handle);
+  status = grub_efi_load_image (0, grub_efi_image_handle, file_path,
+                               boot_image, size, &image_handle);
   if (status != GRUB_EFI_SUCCESS)
     {
       if (status == GRUB_EFI_OUT_OF_RESOURCES)
@@ -422,7 +419,7 @@ grub_cmd_chainloader (grub_command_t cmd __attribute__ ((unused)),
     b->free_pages (address, pages);
 
   if (image_handle != NULL)
-    b->unload_image (image_handle);
+    grub_efi_unload_image (image_handle);
 
   grub_dl_unref (my_mod);
 
grub-core/loader/efi/linux.c +5 -7
index bfbd95aee..58be3c9f8 100644
@@ -187,7 +187,6 @@ grub_arch_efi_linux_boot_image (grub_addr_t addr, grub_size_t size, char *args)
 {
   grub_efi_memory_mapped_device_path_t *mempath;
   grub_efi_handle_t image_handle;
-  grub_efi_boot_services_t *b;
   grub_efi_status_t status;
   grub_efi_loaded_image_t *loaded_image;
   int len;
@@ -207,10 +206,9 @@ grub_arch_efi_linux_boot_image (grub_addr_t addr, grub_size_t size, char *args)
   mempath[1].header.subtype = GRUB_EFI_END_ENTIRE_DEVICE_PATH_SUBTYPE;
   mempath[1].header.length = sizeof (grub_efi_device_path_t);
 
-  b = grub_efi_system_table->boot_services;
-  status = b->load_image (0, grub_efi_image_handle,
-                         (grub_efi_device_path_t *) mempath,
-                         (void *) addr, size, &image_handle);
+  status = grub_efi_load_image (0, grub_efi_image_handle,
+                               (grub_efi_device_path_t *)mempath,
+                               (void *)addr, size, &image_handle);
   if (status != GRUB_EFI_SUCCESS)
     return grub_error (GRUB_ERR_BAD_OS, "cannot load image");
 
@@ -235,14 +233,14 @@ grub_arch_efi_linux_boot_image (grub_addr_t addr, grub_size_t size, char *args)
                            (grub_uint8_t *) args, len, NULL);
 
   grub_dprintf ("linux", "starting image %p\n", image_handle);
-  status = b->start_image (image_handle, 0, NULL);
+  status = grub_efi_start_image (image_handle, 0, NULL);
 
   /* When successful, not reached */
   grub_error (GRUB_ERR_BAD_OS, "start_image() returned 0x%" PRIxGRUB_EFI_UINTN_T, status);
   grub_efi_free_pages ((grub_addr_t) loaded_image->load_options,
                       GRUB_EFI_BYTES_TO_PAGES (loaded_image->load_options_size));
 unload:
-  b->unload_image (image_handle);
+  grub_efi_unload_image (image_handle);
 
   return grub_errno;
 }
include/grub/efi/efi.h +37 -1
index 194adc1f7..6b517a1ea 100644
@@ -132,6 +132,43 @@ grub_err_t grub_arch_efi_linux_load_image_header(grub_file_t file,
 grub_err_t grub_arch_efi_linux_boot_image(grub_addr_t addr, grub_size_t size,
                                            char *args);
 
+grub_efi_status_t
+EXPORT_FUNC (grub_efi_load_image) (grub_efi_boolean_t boot_policy,
+                                  grub_efi_handle_t parent_image_handle,
+                                  grub_efi_device_path_t *file_path,
+                                  void *source_buffer, grub_efi_uintn_t source_size,
+                                  grub_efi_handle_t *image_handle);
+
+grub_efi_status_t
+EXPORT_FUNC (grub_efi_start_image) (grub_efi_handle_t image_handle,
+                                   grub_efi_uintn_t *exit_data_size,
+                                   grub_efi_char16_t **exit_data);
+
+grub_efi_status_t
+EXPORT_FUNC (grub_efi_unload_image) (grub_efi_handle_t image_handle);
+
+typedef struct grub_efi_loader
+{
+  grub_efi_status_t (__grub_efi_api *load_image) (grub_efi_boolean_t boot_policy,
+                                  grub_efi_handle_t parent_image_handle,
+                                  grub_efi_device_path_t *file_path,
+                                  void *source_buffer,
+                                  grub_efi_uintn_t source_size,
+                                  grub_efi_handle_t *image_handle);
+
+  grub_efi_status_t (__grub_efi_api *start_image) (grub_efi_handle_t image_handle,
+                                   grub_efi_uintn_t *exit_data_size,
+                                   grub_efi_char16_t **exit_data);
+
+  grub_efi_status_t (__grub_efi_api *unload_image) (grub_efi_handle_t image_handle);
+} grub_efi_loader_t;
+
+grub_err_t
+EXPORT_FUNC (grub_efi_register_loader) (const grub_efi_loader_t *loader);
+
+grub_err_t
+EXPORT_FUNC (grub_efi_unregister_loader) (const grub_efi_loader_t *loader);
+
 grub_addr_t grub_efi_section_addr (const char *section);
 
 void grub_efi_mm_init (void);
--

2.39.2

Quoted 4 lines

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel

--
Regards
Vladimir 'phcoder' Serbinenko

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel

author
#25 lore raw

PATCH 14/15 efi: Use shim's loader protocol for EFI image verification and loading

In reply to Mate Kukri
---
 grub-core/kern/efi/sb.c      | 39 +++++++++++++-----------------------
 grub-core/loader/efi/linux.c | 16 ---------------
 include/grub/efi/api.h       |  5 +++++
 include/grub/efi/efi.h       | 19 +++++++++++-------
 include/grub/efi/sb.h        |  3 ---
 5 files changed, 31 insertions(+), 51 deletions(-)
grub-core/kern/efi/sb.c +14 -25
index 8d3e41360..d3de39599 100644
@@ -31,8 +31,9 @@
 #include <grub/verify.h>
 
 static grub_guid_t shim_lock_guid = GRUB_EFI_SHIM_LOCK_GUID;
+static grub_guid_t shim_loader_guid = GRUB_EFI_SHIM_IMAGE_LOADER_GUID;
 
-static bool shim_lock_enabled = false;
+static grub_efi_loader_t *shim_loader = NULL;
 
 /*
  * Determine whether we're in secure boot mode.
@@ -95,14 +96,6 @@ grub_efi_get_secureboot (void)
   if (!(attr & GRUB_EFI_VARIABLE_RUNTIME_ACCESS) && *moksbstate == 1)
     {
       secureboot = GRUB_EFI_SECUREBOOT_MODE_DISABLED;
-      /*
-       * TODO: Replace this all with shim's LoadImage protocol, delegating policy to it.
-       *
-       * We need to set shim_lock_enabled here because we disabled secure boot
-       * validation *inside* shim but not in the firmware, so we set this variable
-       * here to trigger that code path, whereas the actual verifier is not enabled.
-       */
-      shim_lock_enabled = true;
       goto out;
     }
 
@@ -183,14 +176,16 @@ shim_lock_verifier_init (grub_file_t io __attribute__ ((unused)),
 static grub_err_t
 shim_lock_verifier_write (void *context __attribute__ ((unused)), void *buf, grub_size_t size)
 {
-  grub_efi_shim_lock_protocol_t *sl = grub_efi_locate_protocol (&shim_lock_guid, 0);
+  grub_efi_handle_t image_handle;
 
-  if (!sl)
-    return grub_error (GRUB_ERR_ACCESS_DENIED, N_("shim_lock protocol not found"));
+  if (!shim_loader)
+    return grub_error (GRUB_ERR_ACCESS_DENIED, N_("shim loader protocol not found"));
 
-  if (sl->verify (buf, size) != GRUB_EFI_SUCCESS)
+  if (shim_loader->load_image (false, grub_efi_image_handle, NULL, buf, size, &image_handle) != GRUB_EFI_SUCCESS)
     return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("bad shim signature"));
 
+  shim_loader->unload_image(image_handle);
+
   return GRUB_ERR_NONE;
 }
 
@@ -205,11 +200,10 @@ void
 grub_shim_lock_verifier_setup (void)
 {
   struct grub_module_header *header;
-  grub_efi_shim_lock_protocol_t *sl =
-    grub_efi_locate_protocol (&shim_lock_guid, 0);
+  shim_loader = grub_efi_locate_protocol (&shim_loader_guid, 0);
 
-  /* shim_lock is missing, check if GRUB image is built with --disable-shim-lock. */
-  if (!sl)
+  /* shim loader protocol is missing, check if GRUB image is built with --disable-shim-lock. */
+  if (!shim_loader)
     {
       FOR_MODULES (header)
 	{
@@ -222,17 +216,12 @@ grub_shim_lock_verifier_setup (void)
   if (grub_efi_get_secureboot () != GRUB_EFI_SECUREBOOT_MODE_ENABLED)
     return;
 
+  /* register loader */
+  grub_efi_register_loader(shim_loader);
+
   /* Enforce shim_lock_verifier. */
   grub_verifier_register (&shim_lock_verifier);
 
-  shim_lock_enabled = true;
-
   grub_env_set ("shim_lock", "y");
   grub_env_export ("shim_lock");
 }
-
-bool
-grub_is_shim_lock_enabled (void)
-{
-  return shim_lock_enabled;
-}
grub-core/loader/efi/linux.c +0 -16
index 58be3c9f8..99365536a 100644
@@ -460,22 +460,6 @@ grub_cmd_linux (grub_command_t cmd __attribute__ ((unused)),
 
   grub_dl_ref (my_mod);
 
-  if (grub_is_shim_lock_enabled () == true)
-    {
-#if defined(__i386__) || defined(__x86_64__)
-      grub_dprintf ("linux", "shim_lock enabled, falling back to legacy Linux kernel loader\n");
-
-      err = grub_cmd_linux_x86_legacy (cmd, argc, argv);
-
-      if (err == GRUB_ERR_NONE)
-	return GRUB_ERR_NONE;
-      else
-	goto fail;
-#else
-      grub_dprintf ("linux", "shim_lock enabled, trying Linux kernel EFI stub loader\n");
-#endif
-    }
-
   if (argc == 0)
     {
       grub_error (GRUB_ERR_BAD_ARGUMENT, N_("filename expected"));
include/grub/efi/api.h +5 -0
index b686e8afe..9ae908729 100644
@@ -364,6 +364,11 @@
     { 0xab, 0xb6, 0x3d, 0xd8, 0x10, 0xdd, 0x8b, 0x23 } \
   }
 
+#define GRUB_EFI_SHIM_IMAGE_LOADER_GUID \
+  { 0x1f492041, 0xfadb, 0x4e59, \
+    {0x9e, 0x57, 0x7c, 0xaf, 0xe7, 0x3a, 0x55, 0xab } \
+  }
+
 #define GRUB_EFI_RNG_PROTOCOL_GUID \
   { 0x3152bca5, 0xeade, 0x433d, \
     { 0x86, 0x2e, 0xc0, 0x1c, 0xdc, 0x29, 0x1f, 0x44 } \
include/grub/efi/efi.h +12 -7
index 6b517a1ea..cf78f3d71 100644
@@ -150,15 +150,20 @@ EXPORT_FUNC (grub_efi_unload_image) (grub_efi_handle_t image_handle);
 typedef struct grub_efi_loader
 {
   grub_efi_status_t (__grub_efi_api *load_image) (grub_efi_boolean_t boot_policy,
-				   grub_efi_handle_t parent_image_handle,
-				   grub_efi_device_path_t *file_path,
-				   void *source_buffer,
-				   grub_efi_uintn_t source_size,
-				   grub_efi_handle_t *image_handle);
+						  grub_efi_handle_t parent_image_handle,
+						  grub_efi_device_path_t *file_path,
+						  void *source_buffer,
+						  grub_efi_uintn_t source_size,
+						  grub_efi_handle_t *image_handle);
 
   grub_efi_status_t (__grub_efi_api *start_image) (grub_efi_handle_t image_handle,
-				    grub_efi_uintn_t *exit_data_size,
-				    grub_efi_char16_t **exit_data);
+						   grub_efi_uintn_t *exit_data_size,
+						   grub_efi_char16_t **exit_data);
+
+  grub_efi_status_t (__grub_efi_api *exit) (grub_efi_handle_t image_handle,
+					    grub_efi_status_t exit_status,
+					    grub_efi_uintn_t exit_data_size,
+					    grub_efi_char16_t *exit_data);
 
   grub_efi_status_t (__grub_efi_api *unload_image) (grub_efi_handle_t image_handle);
 } grub_efi_loader_t;
include/grub/efi/sb.h +0 -3
index 49a9ad01c..bf8d2db5f 100644
@@ -31,9 +31,6 @@
 extern grub_uint8_t
 EXPORT_FUNC (grub_efi_get_secureboot) (void);
 
-extern bool
-EXPORT_FUNC (grub_is_shim_lock_enabled) (void);
-
 extern void
 grub_shim_lock_verifier_setup (void);
 #else
Signature · 7 lines
2.39.2


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
author
#26 lore raw

PATCH 15/15 efi: Disallow fallback to legacy Linux loader when shim says NX is required.

In reply to Mate Kukri
---
 grub-core/loader/efi/linux.c | 41 +++++++++++++++++++++++++++++++-----
 1 file changed, 36 insertions(+), 5 deletions(-)
grub-core/loader/efi/linux.c +36 -5
index 99365536a..e44692c92 100644
@@ -450,6 +450,35 @@ grub_cmd_initrd (grub_command_t cmd __attribute__ ((unused)),
   return grub_errno;
 }
 
+#define GRUB_MOK_POLICY_NX_REQUIRED   0x1
+
+static int
+grub_efi_check_nx_required (void)
+{
+  grub_efi_status_t status;
+  grub_guid_t guid = GRUB_EFI_SHIM_LOCK_GUID;
+  grub_size_t mok_policy_sz = 0;
+  char *mok_policy = NULL;
+  grub_uint32_t mok_policy_attrs = 0;
+
+  status = grub_efi_get_variable_with_attributes ("MokPolicy", &guid,
+                                                  &mok_policy_sz,
+                                                  (void **)&mok_policy,
+                                                  &mok_policy_attrs);
+  if (status == GRUB_EFI_NOT_FOUND ||
+      mok_policy_sz == 0 ||
+      mok_policy == NULL)
+    return 1;
+
+  if (mok_policy_sz != 1 ||
+      (mok_policy[0] & GRUB_MOK_POLICY_NX_REQUIRED) ||
+      (mok_policy_attrs != (GRUB_EFI_VARIABLE_BOOTSERVICE_ACCESS |
+                           GRUB_EFI_VARIABLE_RUNTIME_ACCESS)))
+    return 1;
+
+  return 0;
+}
+
 static grub_err_t
 grub_cmd_linux (grub_command_t cmd __attribute__ ((unused)),
 		int argc, char *argv[])
@@ -472,21 +501,23 @@ grub_cmd_linux (grub_command_t cmd __attribute__ ((unused)),
 
   kernel_size = grub_file_size (file);
 
-  if (grub_arch_efi_linux_load_image_header (file, &lh) != GRUB_ERR_NONE)
 #if !defined(__i386__) && !defined(__x86_64__)
+  if (grub_arch_efi_linux_load_image_header (file, &lh) != GRUB_ERR_NONE)
     goto fail;
 #else
-    goto fallback;
-
-  if (!initrd_use_loadfile2)
+  if (grub_arch_efi_linux_load_image_header (file, &lh) != GRUB_ERR_NONE ||
+      !initrd_use_loadfile2)
     {
+      /* We cannot use the legacy loader when NX is required */
+      if (grub_efi_check_nx_required())
+        goto fail;
+
       /*
        * This is a EFI stub image but it is too old to implement the LoadFile2
        * based initrd loading scheme, and Linux/x86 does not support the DT
        * based method either. So fall back to the x86-specific loader that
        * enters Linux in EFI mode but without going through its EFI stub.
        */
-fallback:
       grub_file_close (file);
       return grub_cmd_linux_x86_legacy (cmd, argc, argv);
     }
Signature · 7 lines
2.39.2


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
#27 lore raw
In reply to Mate Kukri
Quoted 7 lines

Future work:
- Completely disable non-NX compatible loaders when heap allocation are marked NX. This should be independent from the NX-enforcement flag and Secure Boot status. (Note that this is non-crtitical for security, as non-UEFI/Linux loaders are disabled by SB lockdown, but would be nice to avoid crashes for unsuspecting users on future hardware).
- Implement NX in non-Linux loaders where applicable.

I think it applies to all loader actually and first part is unnecessarry.

Path number 15 is missing

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel

author
#28 lore raw

Hi Vladimir,
Thanks for the reviews, I'll get back to addressing your comments next week. In the meantime, I am not sure what happened to patch 15/15, but I at least tried sending it, and it seems to be available in the archive
here: https://lists.gnu.org/archive/html/grub-devel/2024-05/msg00221.html
Mate

Quoted 9 lines · Vladimir 'phcoder' Serbinenko
Quoted 8 lines

Future work:
- Completely disable non-NX compatible loaders when heap allocation are marked NX. This should be independent from the NX-enforcement flag and Secure Boot status. (Note that this is non-crtitical for security, as non-UEFI/Linux loaders are disabled by SB lockdown, but would be nice to avoid crashes for unsuspecting users on future hardware).
- Implement NX in non-Linux loaders where applicable.

Quoted 8 lines

I think it applies to all loader actually and first part is unnecessarry.

Path number 15 is missing

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel