xref: /linux/kernel/module/strict_rwx.c (revision 84b9b44b)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Module strict rwx
4  *
5  * Copyright (C) 2015 Rusty Russell
6  */
7 
8 #include <linux/module.h>
9 #include <linux/mm.h>
10 #include <linux/vmalloc.h>
11 #include <linux/set_memory.h>
12 #include "internal.h"
13 
14 static void module_set_memory(const struct module *mod, enum mod_mem_type type,
15 			      int (*set_memory)(unsigned long start, int num_pages))
16 {
17 	const struct module_memory *mod_mem = &mod->mem[type];
18 
19 	set_vm_flush_reset_perms(mod_mem->base);
20 	set_memory((unsigned long)mod_mem->base, mod_mem->size >> PAGE_SHIFT);
21 }
22 
23 /*
24  * Since some arches are moving towards PAGE_KERNEL module allocations instead
25  * of PAGE_KERNEL_EXEC, keep module_enable_x() independent of
26  * CONFIG_STRICT_MODULE_RWX because they are needed regardless of whether we
27  * are strict.
28  */
29 void module_enable_x(const struct module *mod)
30 {
31 	for_class_mod_mem_type(type, text)
32 		module_set_memory(mod, type, set_memory_x);
33 }
34 
35 void module_enable_ro(const struct module *mod, bool after_init)
36 {
37 	if (!IS_ENABLED(CONFIG_STRICT_MODULE_RWX))
38 		return;
39 #ifdef CONFIG_STRICT_MODULE_RWX
40 	if (!rodata_enabled)
41 		return;
42 #endif
43 
44 	module_set_memory(mod, MOD_TEXT, set_memory_ro);
45 	module_set_memory(mod, MOD_INIT_TEXT, set_memory_ro);
46 	module_set_memory(mod, MOD_RODATA, set_memory_ro);
47 	module_set_memory(mod, MOD_INIT_RODATA, set_memory_ro);
48 
49 	if (after_init)
50 		module_set_memory(mod, MOD_RO_AFTER_INIT, set_memory_ro);
51 }
52 
53 void module_enable_nx(const struct module *mod)
54 {
55 	if (!IS_ENABLED(CONFIG_STRICT_MODULE_RWX))
56 		return;
57 
58 	for_class_mod_mem_type(type, data)
59 		module_set_memory(mod, type, set_memory_nx);
60 }
61 
62 int module_enforce_rwx_sections(Elf_Ehdr *hdr, Elf_Shdr *sechdrs,
63 				char *secstrings, struct module *mod)
64 {
65 	const unsigned long shf_wx = SHF_WRITE | SHF_EXECINSTR;
66 	int i;
67 
68 	if (!IS_ENABLED(CONFIG_STRICT_MODULE_RWX))
69 		return 0;
70 
71 	for (i = 0; i < hdr->e_shnum; i++) {
72 		if ((sechdrs[i].sh_flags & shf_wx) == shf_wx) {
73 			pr_err("%s: section %s (index %d) has invalid WRITE|EXEC flags\n",
74 			       mod->name, secstrings + sechdrs[i].sh_name, i);
75 			return -ENOEXEC;
76 		}
77 	}
78 
79 	return 0;
80 }
81