KASLR feature to randomize each loadable module
Subsystems (7)
v5 cover KASLR feature to randomize each loadable module
Hi,
This is V5 of the "KASLR feature to randomize each loadable module" patchset. The purpose is to increase the randomization and also to make the modules randomized in relation to each other instead of just the base, so that if one module leaks the location of the others can't be inferred.
V5 is the addition of a module_alloc micro benchmarking module. It can be used to see the performance and module area capacity differences between module_alloc algorithms. Because of the dataset of the module text section sizes is very large, I replaced it with a heuristic that generates module sizes that roughly approximate the real X86_64 modules. As a result the benchmarks are slightly different. If there is any interest in the real dataset I am happy to send it out.
Changes for V5:
- Add module_alloc test module
Changes for V4:
- Fix issue caused by KASAN, kmemleak being provided different allocation lengths (padding).
- Avoid kmalloc until sure its needed in __vmalloc_node_try_addr.
- Fixed issues reported by 0-day.
Changes for V3:
- Code cleanup based on internal feedback. (thanks to Dave Hansen and Andriy Shevchenko)
- Slight refactor of existing algorithm to more cleanly live along side new one.
- BPF synthetic benchmark
Changes for V2:
- New implementation of __vmalloc_node_try_addr based on the __vmalloc_node_range implementation, that only flushes TLB when needed.
- Modified module loading algorithm to try to reduce the TLB flushes further.
- Increase "random area" tries in order to increase the number of modules that can get high randomness.
- Increase "random area" size to 2/3 of module area in order to increase the number of modules that can get high randomness.
- Fix for 0day failures on other architectures.
- Fix for wrong debugfs permissions. (thanks to Jann Horn)
- Spelling fix. (thanks to Jann Horn)
- Data on module_alloc performance and TLB flushes. (brought up by Kees Cook and Jann Horn)
- Data on memory usage. (suggested by Jann)
Rick Edgecombe (4):
vmalloc: Add __vmalloc_node_try_addr function x86/modules: Increase randomization for modules
vmalloc: Add debugfs modfraginfo Kselftest for module text allocation benchmarking
arch/x86/include/asm/pgtable_64_types.h | 7 + arch/x86/kernel/module.c | 165 ++++++++-- include/linux/vmalloc.h | 3 + lib/Kconfig.debug | 10 + lib/Makefile | 1 + lib/test_mod_alloc.c | 446 ++++++++++++++++++++++++++ mm/vmalloc.c | 279 +++++++++++++++- tools/testing/selftests/bpf/test_mod_alloc.sh | 29 ++ 8 files changed, 915 insertions(+), 25 deletions(-) create mode 100644 lib/test_mod_alloc.c create mode 100755 tools/testing/selftests/bpf/test_mod_alloc.sh
Signature · 1 line
2.7.4
PATCH v5 1/4 vmalloc: Add __vmalloc_node_try_addr function
Create __vmalloc_node_try_addr function that tries to allocate at a specific address and supports caller specified behavior for whether any lazy purging happens if there is a collision.
This new function draws from the __vmalloc_node_range implementation. Attempts to merge the two into a single allocator resulted in logic that was difficult to follow, so they are left separate.
--- include/linux/vmalloc.h | 3 + mm/vmalloc.c | 177 +++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 179 insertions(+), 1 deletion(-)
include/linux/vmalloc.h +3 -0
@@ -82,6 +82,9 @@ extern void *__vmalloc_node_range(unsigned long size, unsigned long align, unsigned long start, unsigned long end, gfp_t gfp_mask, pgprot_t prot, unsigned long vm_flags, int node, const void *caller); +extern void *__vmalloc_node_try_addr (unsigned long addr,unsigned long size, +gfp_t gfp_mask,pgprot_t prot,unsigned long vm_flags, +int node,int try_purge,const void *caller);#ifndef CONFIG_MMU extern void *__vmalloc_node_flags (unsigned long size,int node,gfp_t flags); static inline void *__vmalloc_node_flags_caller(unsigned long size, int node,
mm/vmalloc.c +176 -1
195 lines not on this page · raw message
Signature · 1 line
2.7.4
PATCH v5 2/4 x86/modules: Increase randomization for modules
In reply to Rick EdgecombeThis changes the behavior of the KASLR logic for allocating memory for the text sections of loadable modules. It randomizes the location of each module text section with about 17 bits of entropy in typical use. This is enabled on X86_64 only. For 32 bit, the behavior is unchanged.
It refactors existing code around module randomization somewhat. There are now three different behaviors for x86 module_alloc depending on config. RANDOMIZE_BASE=n, and RANDOMIZE_BASE=y ARCH=x86_64, and RANDOMIZE_BASE=y ARCH=i386. The refactor of the existing code is to try to clearly show what those behaviors are without having three separate versions or threading the behaviors in a bunch of little spots. The reason it is not enabled on 32 bit yet is because the module space is much smaller and simulations haven't been run to see how it performs.
The new algorithm breaks the module space in two, a random area and a backup area. It first tries to allocate at a number of randomly located starting pages inside the random section without purging any lazy free vmap areas and triggering the associated TLB flush. If this fails, it will try again a number of times allowing for purges if needed. It also saves any position that could have succeeded if it was allowed to purge, which doubles the chances of finding a spot that would fit. Finally if those both fail to find a position it will allocate in the backup area. The backup area base will be offset in the same way as the current algorithm does for the base area, 1024 possible locations.
--- arch/x86/include/asm/pgtable_64_types.h | 7 ++ arch/x86/kernel/module.c | 165 +++++++++++++++++++++++++++----- 2 files changed, 149 insertions(+), 23 deletions(-)
arch/x86/include/asm/pgtable_64_types.h +7 -0
@@ -143,6 +143,13 @@ extern unsigned int ptrs_per_p4d;#define MODULES_END _AC(0xffffffffff000000, UL)#define MODULES_LEN (MODULES_END - MODULES_VADDR) +/* +* Dedicate the first part of the module space to a randomized area when KASLR +* is in use. Leave the remaining part for a fallback if we are unable to +* allocate in the random area. +*/ +#define MODULES_RAND_LEN PAGE_ALIGN((MODULES_LEN/3)*2) +#define ESPFIX_PGD_ENTRY _AC(-2, UL)#define ESPFIX_BASE_ADDR (ESPFIX_PGD_ENTRY << P4D_SHIFT)
arch/x86/kernel/module.c +142 -23
192 lines not on this page · raw message
Signature · 1 line
2.7.4
PATCH v5 3/4 vmalloc: Add debugfs modfraginfo
In reply to Rick EdgecombeAdd debugfs file "modfraginfo" for providing info on module space fragmentation. This can be used for determining if loadable module randomization is causing any problems for extreme module loading situations, like huge numbers of modules or extremely large modules.
Sample output when KASLR is enabled and X86_64 is configured:
Largest free space: 897912 kB Total free space: 1025424 kB
Allocations in backup area: 0
Sample output when just X86_64:
Largest free space: 897912 kB Total free space: 1025424 kB
--- mm/vmalloc.c | 102 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 101 insertions(+), 1 deletion(-)
mm/vmalloc.c +101 -1
@@ -18,6 +18,7 @@#include <linux/interrupt.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> +#include <linux/debugfs.h> #include <linux/debugobjects.h> #include <linux/kallsyms.h> #include <linux/list.h>
@@ -33,6 +34,7 @@#include <linux/bitops.h> #include <linux/uaccess.h> +#include <asm/setup.h> #include <asm/tlbflush.h> #include <asm/shmparam.h>
@@ -2919,7 +2921,105 @@ static int __init proc_vmalloc_init(void)proc_create_seq ("vmallocinfo" ,0400 ,NULL , &vmalloc_op);return 0 ; } -module_init (proc_vmalloc_init); +#else +static int __init proc_vmalloc_init (void ) +{ +return 0 ; +} +#endif + +#if defined(CONFIG_RANDOMIZE_BASE ) && defined(CONFIG_X86_64 ) +static inline unsigned long is_in_backup (unsigned long addr) +{ +return addr >=MODULES_VADDR +MODULES_RAND_LEN ; +} +#else +static inline unsigned long is_in_backup (unsigned long addr) +{ +return 0 ; +} +inline bool kaslr_enabled (void );#endif + +#if defined(CONFIG_DEBUG_FS ) && defined(CONFIG_X86_64 ) +static int modulefraginfo_debug_show (struct seq_file *m,void *v) +{ +unsigned long last_end =MODULES_VADDR ; +unsigned long total_free =0 ; +unsigned long largest_free =0 ; +unsigned long backup_cnt =0 ; +unsigned long gap; +struct vmap_area *prev, *cur =NULL ; + +spin_lock (&vmap_area_lock); + +if (!pvm_find_next_prev (MODULES_VADDR , &cur, &prev) || !cur) + goto done; + +for (; cur->va_end <=MODULES_END ; cur =list_next_entry (cur, list)) { +/* Don't count areas that are marked to be lazily freed */ +if (!(cur->flags &VM_LAZY_FREE )) { + backup_cnt +=is_in_backup (cur->va_start); + gap = cur->va_start - last_end; +if (gap > largest_free) + largest_free = gap; + total_free += gap; + last_end = cur->va_end; + } + +if (list_is_last (&cur->list, &vmap_area_list)) +break ; + } + +done: + gap = (MODULES_END - last_end); +if (gap > largest_free) + largest_free = gap; + total_free += gap; + +spin_unlock (&vmap_area_lock); + +seq_printf (m,"\tLargest free space:\t%lu kB\n" , largest_free /1024 ); +seq_printf (m,"\t Total free space:\t%lu kB\n" , total_free /1024 ); + +if (IS_ENABLED (CONFIG_RANDOMIZE_BASE ) &&kaslr_enabled ()) +seq_printf (m,"Allocations in backup area:\t%lu\n" , backup_cnt); + +return 0 ; +} + +static int proc_module_frag_debug_open (struct inode *inode,struct file *file) +{ +return single_open (file, modulefraginfo_debug_show,NULL ); +} + +static const struct file_operations debug_module_frag_operations = { + .open = proc_module_frag_debug_open, + .read = seq_read, + .llseek = seq_lseek, + .release = single_release, +}; + +static void __init debug_modfrag_init (void ) +{ +debugfs_create_file ("modfraginfo" ,0400 ,NULL ,NULL , + &debug_module_frag_operations); +} +#else /* defined(CONFIG_DEBUG_FS) && defined(CONFIG_X86_64) */ +static void __init debug_modfrag_init (void ) +{ +} +#endif + +#if defined(CONFIG_DEBUG_FS ) || defined(CONFIG_PROC_FS ) +static int __init info_vmalloc_init (void ) +{ +proc_vmalloc_init (); +debug_modfrag_init (); +return 0 ; +} + +module_init (info_vmalloc_init); +#endif
Signature · 1 line
2.7.4
PATCH v5 4/4 Kselftest for module text allocation benchmarking
In reply to Rick EdgecombeThis adds a test module in lib/, and a script in kselftest that does benchmarking on the allocation of memory in the module space. Performance here would have some small impact on kernel module insertions, BPF JIT insertions and kprobes. In the case of KASLR features for the module space, this module can be used to measure the allocation performance of different configurations. This module needs to be compiled into the kernel because module_alloc is not exported.
With some modification to the code, as explained in the comments, it can be enabled to measure TLB flushes as well.
There are two tests in the module. One allocates until failure in order to test module capacity and the other times allocating space in the module area. They both use module sizes that roughly approximate the distribution of in-tree X86_64 modules.
You can control the number of modules used in the tests like this:
echo m1000>/dev/mod_alloc_test
Run the test for module capacity like:
echo t1>/dev/mod_alloc_test
The other test will measure the allocation time, and for CONFG_X86_64 and CONFIG_RANDOMIZE_BASE, also give data on how often the a??backup area" is used.
Run the test for allocation time and backup area usage like:
echo t2>/dev/mod_alloc_test
The output will be something like this:
num all(ns) last(ns)
1000 1083 1099
Last module in backup count = 0
Total modules in backup = 0
Quoted 1 line
1 module in backup count = 0
To run a suite of allocation time tests for a collection of module numbers you can run:tools/testing/selftests/bpf/test_mod_alloc.sh
--- lib/Kconfig.debug | 10 + lib/Makefile | 1 + lib/test_mod_alloc.c | 446 ++++++++++++++++++++++++++ tools/testing/selftests/bpf/test_mod_alloc.sh | 29 ++ 4 files changed, 486 insertions(+) create mode 100644 lib/test_mod_alloc.c create mode 100755 tools/testing/selftests/bpf/test_mod_alloc.sh
lib/Kconfig.debug +10 -0
@@ -1883,6 +1883,16 @@ config TEST_BPF If unsure, say N. +config TEST_MOD_ALLOC + bool "Tests for module allocator/vmalloc" + help + This builds the "test_mod_alloc" module that performs performance + and functional tests on the module text section allocator. The module + uses X86_64 module text sizes for simulations, for other architectures + it will be less accurate. + + If unsure, say N. + config FIND_BIT_BENCHMARK tristate "Test find_bit functions" help
lib/Makefile +1 -0
@@ -58,6 +58,7 @@ UBSAN_SANITIZE_test_ubsan.o := y obj-$(CONFIG_TEST_KSTRTOX) += test-kstrtox.o obj-$(CONFIG_TEST_LIST_SORT) += test_list_sort.o obj-$(CONFIG_TEST_LKM) += test_module.o +obj-$(CONFIG_TEST_MOD_ALLOC) += test_mod_alloc.o obj-$(CONFIG_TEST_OVERFLOW) += test_overflow.o obj-$(CONFIG_TEST_RHASHTABLE) += test_rhashtable.o obj-$(CONFIG_TEST_SORT) += test_sort.o
lib/test_mod_alloc.c new file +446 -0
446 lines not on this page · raw message
tools/testing/selftests/bpf/test_mod_alloc.sh new file +29 -0
@@ -0,0 +1,29 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 +UNMOUNT_DEBUG_FS=0 +if ! mount | grep -q debugfs; then + if mount -t debugfs none /sys/kernel/debug/; then + UNMOUNT_DEBUG_FS=1 + else + echo "Could not mount debug fs." + exit 1 + fi +fi + +if [ ! -e /sys/kernel/debug/mod_alloc_test ]; then + echo "Test module not found, did you build kernel with TEST_MOD_ALLOC?" + exit 1 +fi + +echo "Beginning module_alloc performance tests." + +for i in `seq 1000 1000 8000`; do + echo m$i>/sys/kernel/debug/mod_alloc_test + echo t2>/sys/kernel/debug/mod_alloc_test +done + +echo "Module_alloc performance tests ended." + +if [ $UNMOUNT_DEBUG_FS -eq 1 ]; then + umount /sys/kernel/debug/ +fi
Signature · 1 line
2.7.4
kbuild test robot
build botRe: [PATCH v5 4/4] Kselftest for module text allocation benchmarking
Thank you for the patch! Yet something to improve:
Hi Rick,
Thank you for the patch! Yet something to improve:
[auto build test ERROR on linus/master]
[also build test ERROR on v4.19-rc3 next-20180913]
[if your patch is applied to the wrong git tree, please drop us a note to help improve the system]
url: https://github.com/0day-ci/linux/commits/Rick-Edgecombe/KASLR-feature-to-randomize-each-loadable-module/20180913-172302
config: sh-allmodconfig (attached as .config)
compiler: sh4-linux-gnu-gcc (Debian 7.2.0-11) 7.2.0
reproduce:
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross chmod +x ~/bin/make.cross
# save the attached .config to linux build tree
GCC_VERSION=7.2.0 make.cross ARCH=sh
All error/warnings (new ones prefixed by >>):
lib/test_mod_alloc.c: In function 'do_check':
>> lib/test_mod_alloc.c:129:15: error: 'MODULES_VADDR' undeclared (first use in this function); did you mean 'MODULE_SOFTDEP'?
if (start < MODULES_VADDR ||
^~~~~~~~~~~~~
MODULE_SOFTDEP
lib/test_mod_alloc.c:129:15: note: each undeclared identifier is reported only once for each function it appears in
>> lib/test_mod_alloc.c:130:26: error: 'MODULES_LEN' undeclared (first use in this function); did you mean 'MODULE_ALIGN'?
end > MODULES_VADDR + MODULES_LEN) {
^~~~~~~~~~~
MODULE_ALIGN
lib/test_mod_alloc.c: In function 'device_file_write':
>> lib/test_mod_alloc.c:404:2: warning: ignoring return value of 'copy_from_user', declared with attribute warn_unused_result [-Wunused-result]
copy_from_user(buf, user_buf, count);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>> lib/test_mod_alloc.c:407:3: warning: ignoring return value of 'kstrtol', declared with attribute warn_unused_result [-Wunused-result]
kstrtol(buf+1, 10, &new_mod_cnt);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
lib/test_mod_alloc.c:422:3: warning: ignoring return value of 'kstrtol', declared with attribute warn_unused_result [-Wunused-result]
kstrtol(buf + 1, 10, &iter);
^~~~~~~~~~~~~~~~~~~~~~~~~~~vim +129 lib/test_mod_alloc.c
89
90 static int do_check(void *ptr, unsigned long size)
91 {
92 int i;
93 unsigned long start = (unsigned long) ptr;
94 unsigned long end = calc_end(ptr, size);
95 unsigned long sum = 0;
96 unsigned long addr;
97
98 if (!start)
99 return 1;
100
101 for (i = 0; i < check_alloc_cnt; i++) {
102 struct check_alloc *cur_alloc = &(check_allocs[i]);
103
104 /* overlap end */
105 if (start >= cur_alloc->start && start < cur_alloc->vm_end) {
106 pr_info("overlap end\n");
107 return 1;
108 }
109
110 /* overlap start */
111 if (end >= cur_alloc->start && end < cur_alloc->start) {
112 pr_info("overlap start\n");
113 return 1;
114 }
115
116 /* overlap whole thing */
117 if (start <= cur_alloc->start && end > cur_alloc->vm_end) {
118 pr_info("overlap whole thing\n");
119 return 1;
120 }
121
122 /* inside */
123 if (start >= cur_alloc->start && end < cur_alloc->vm_end) {
124 pr_info("inside\n");
125 return 1;
126 }
127
128 /* bounds */
> 129 if (start < MODULES_VADDR ||
> 130 end > MODULES_VADDR + MODULES_LEN) { 131 pr_info("out of bounds\n");
132 return 1;
133 }
134 for (addr = cur_alloc->start;
135 addr < cur_alloc->real_end;
136 addr += PAGE_SIZE) {
137 sum += *((unsigned long *) addr);
138 }
139 if (sum != 0)
140 pr_info("Memory was not zeroed\n");
141
142 kasan_check_read((void *)cur_alloc->start,
143 cur_alloc->vm_end - cur_alloc->start - PAGE_SIZE);
144 }
145 return 0;
146 }
147
---
0-DAY kernel test infrastructure Open Source Technology Center
https://lists.01.org/pipermail/kbuild-all Intel Corporation
kbuild test robot
build botRe: [PATCH v5 4/4] Kselftest for module text allocation benchmarking
In reply to Rick EdgecombeThank you for the patch! Yet something to improve:
Hi Rick,
Thank you for the patch! Yet something to improve:
[auto build test ERROR on linus/master]
[also build test ERROR on v4.19-rc3 next-20180913]
[if your patch is applied to the wrong git tree, please drop us a note to help improve the system]
url: https://github.com/0day-ci/linux/commits/Rick-Edgecombe/KASLR-feature-to-randomize-each-loadable-module/20180913-172302
config: openrisc-allyesconfig (attached as .config)
compiler: or1k-linux-gcc (GCC) 6.0.0 20160327 (experimental)
reproduce:
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross chmod +x ~/bin/make.cross
# save the attached .config to linux build tree
make.cross ARCH=openrisc
All errors (new ones prefixed by >>):
lib/test_mod_alloc.c: In function 'do_check':
>> lib/test_mod_alloc.c:129:15: error: 'MODULES_VADDR' undeclared (first use in this function)
if (start < MODULES_VADDR ||
^~~~~~~~~~~~~
lib/test_mod_alloc.c:129:15: note: each undeclared identifier is reported only once for each function it appears in
>> lib/test_mod_alloc.c:130:26: error: 'MODULES_LEN' undeclared (first use in this function)
end > MODULES_VADDR + MODULES_LEN) {
^~~~~~~~~~~
lib/test_mod_alloc.c: In function 'device_file_write':
lib/test_mod_alloc.c:404:2: warning: ignoring return value of 'copy_from_user', declared with attribute warn_unused_result [-Wunused-result]
copy_from_user(buf, user_buf, count);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
lib/test_mod_alloc.c:407:3: warning: ignoring return value of 'kstrtol', declared with attribute warn_unused_result [-Wunused-result]
kstrtol(buf+1, 10, &new_mod_cnt);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
lib/test_mod_alloc.c:422:3: warning: ignoring return value of 'kstrtol', declared with attribute warn_unused_result [-Wunused-result]
kstrtol(buf + 1, 10, &iter);
^~~~~~~~~~~~~~~~~~~~~~~~~~~vim +/MODULES_VADDR +129 lib/test_mod_alloc.c
89
90 static int do_check(void *ptr, unsigned long size)
91 {
92 int i;
93 unsigned long start = (unsigned long) ptr;
94 unsigned long end = calc_end(ptr, size);
95 unsigned long sum = 0;
96 unsigned long addr;
97
98 if (!start)
99 return 1;
100
101 for (i = 0; i < check_alloc_cnt; i++) {
102 struct check_alloc *cur_alloc = &(check_allocs[i]);
103
104 /* overlap end */
105 if (start >= cur_alloc->start && start < cur_alloc->vm_end) {
106 pr_info("overlap end\n");
107 return 1;
108 }
109
110 /* overlap start */
111 if (end >= cur_alloc->start && end < cur_alloc->start) {
112 pr_info("overlap start\n");
113 return 1;
114 }
115
116 /* overlap whole thing */
117 if (start <= cur_alloc->start && end > cur_alloc->vm_end) {
118 pr_info("overlap whole thing\n");
119 return 1;
120 }
121
122 /* inside */
123 if (start >= cur_alloc->start && end < cur_alloc->vm_end) {
124 pr_info("inside\n");
125 return 1;
126 }
127
128 /* bounds */
> 129 if (start < MODULES_VADDR ||
> 130 end > MODULES_VADDR + MODULES_LEN) { 131 pr_info("out of bounds\n");
132 return 1;
133 }
134 for (addr = cur_alloc->start;
135 addr < cur_alloc->real_end;
136 addr += PAGE_SIZE) {
137 sum += *((unsigned long *) addr);
138 }
139 if (sum != 0)
140 pr_info("Memory was not zeroed\n");
141
142 kasan_check_read((void *)cur_alloc->start,
143 cur_alloc->vm_end - cur_alloc->start - PAGE_SIZE);
144 }
145 return 0;
146 }
147
---
0-DAY kernel test infrastructure Open Source Technology Center
https://lists.01.org/pipermail/kbuild-all Intel Corporation