[PATCH] module: Harden STRICT_MODULE_RWX

Peter Zijlstra
2020-04-03T16:37:23Z

We're very close to enforcing W^X memory, refuse to load modules that
violate this principle per construction.

Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Cc: Jessica Yu <jeyu@kernel.org>
Cc: Kees Cook <keescook@chromium.org>
---
kernel/module.c | 24 ++++++++++++++++++++++++
1 file changed, 24 insertions(+)

--- a/kernel/module.c
+++ b/kernel/module.c
@@ -2044,9 +2044,28 @@ static void module_enable_x(const struct
frob_text(&mod->core_layout, set_memory_x);
frob_text(&mod->init_layout, set_memory_x);
}
+
+static int module_rwx_sections(Elf_Ehdr *hdr, Elf_Shdr *sechdrs,
+ char *secstrings, struct module *mod)
+{
+ int i;
+
+ for (i = 0; i < hdr->e_shnum; i++) {
+ if (sechdrs[i].sh_flags & (SHF_EXECINSTR|SHF_WRITE))
+ return -ENOEXEC;
+ }
+
+ return 0;
+}
+
#else /* !CONFIG_ARCH_HAS_STRICT_MODULE_RWX */
static void module_enable_nx(const struct module *mod) { }
static void module_enable_x(const struct module *mod) { }
+static int module_rwx_sections(Elf_Ehdr *hdr, Elf_Shdr *sechdrs,
+ char *secstrings, struct module *mod)
+{
+ return 0;
+}
#endif /* CONFIG_ARCH_HAS_STRICT_MODULE_RWX */

@@ -3378,6 +3397,11 @@ static struct module *layout_and_allocat
if (err < 0)
return ERR_PTR(err);

+ err = module_rwx_sections(info->hdr, info->sechdrs,
+ info->secstrings, info->mod);
+ if (err < 0)
+ return ERR_PTR(err);
+
/* We will do a special allocation for per-cpu sections later. */
info->sechdrs[info->index.pcpu].sh_flags &= ~(unsigned long)SHF_ALLOC;