Skip to contentSkip to conversation

KASLR feature to randomize each loadable module

PATCH Superseded Rick Edgecombe 3 participants 16 messages Sep 13, 2018 – Sep 24, 2018

Subsystems (7)

v6 of 9 Superseded Latest is v9 →

lore
Share & tools
lore
#0 lore raw

v6 cover KASLR feature to randomize each loadable module

Hi,

This is V6 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.

V6 is just a fix for 0-day arch=SH report, and made the error handling code more robust in case this gets used for something unforeseeable in the future.

Changes for V6:
- 0-day build fixes by removing un-needed functional testing, more error handling

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                          | 354 ++++++++++++++++++++++++++
 mm/vmalloc.c                                  | 279 +++++++++++++++++++-
 tools/testing/selftests/bpf/test_mod_alloc.sh |  29 +++
 8 files changed, 823 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
#1 lore raw

PATCH v6 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
index 398e9c9..c7712c8 100644
@@ -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
Reviewed-by on v6 1/4
#2 lore raw

Re: [PATCH v6 1/4] vmalloc: Add __vmalloc_node_try_addr function

Quoted 9 lines · Rick Edgecombe

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.

I'd love to get some more mm folks to look this over too.

-Kees

Signature · 2 lines
Kees Cook
Pixel Security
#3 lore raw

PATCH v6 2/4 x86/modules: Increase randomization for modules

In reply to Rick Edgecombe

This 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
index 04edd2d..5e26369 100644
@@ -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
#4 lore raw

Re: [PATCH v6 2/4] x86/modules: Increase randomization for modules

Quoted 24 lines · Rick Edgecombe

This 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.

Quoted 1 line

I'm excited to get fine-grained module randomization. I think it's a good first step to getting other fine-grained KASLR in other places. Thanks for working on this!

Quoted 98 lines
---
 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
index 04edd2d..5e26369 100644
@@ -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 +43 -15
index f58336a..d50a0a0 100644
@@ -48,34 +48,151 @@ do {                                                       \
 } while (0)
 #endif
 
-#ifdef CONFIG_RANDOMIZE_BASE
+#if defined(CONFIG_X86_64) && defined(CONFIG_RANDOMIZE_BASE)
+static inline unsigned long get_modules_rand_len(void)
+{
+       return MODULES_RAND_LEN;
+}
+#else
+static inline unsigned long get_modules_rand_len(void)
+{
+       BUILD_BUG();
+       return 0;
+}
+
+inline bool kaslr_enabled(void);
+#endif
+
+static inline int kaslr_randomize_each_module(void)
+{
+       return IS_ENABLED(CONFIG_RANDOMIZE_BASE)
+               && IS_ENABLED(CONFIG_X86_64)
+               && kaslr_enabled();
+}
+
+static inline int kaslr_randomize_base(void)
+{
+       return IS_ENABLED(CONFIG_RANDOMIZE_BASE)
+               && !IS_ENABLED(CONFIG_X86_64)
+               && kaslr_enabled();
+}
+
 static unsigned long module_load_offset;
+static const unsigned long NR_NO_PURGE = 5000;
+static const unsigned long NR_TRY_PURGE = 5000;
 
 /* Mutex protects the module_load_offset. */
 static DEFINE_MUTEX(module_kaslr_mutex);
 
 static unsigned long int get_module_load_offset(void)
 {
-       if (kaslr_enabled()) {
-               mutex_lock(&module_kaslr_mutex);
-               /*
-                * Calculate the module_load_offset the first time this
-                * code is called. Once calculated it stays the same until
-                * reboot.
-                */
-               if (module_load_offset == 0)
-                       module_load_offset =
-                               (get_random_int() % 1024 + 1) * PAGE_SIZE;
-               mutex_unlock(&module_kaslr_mutex);
-       }
+       mutex_lock(&module_kaslr_mutex);
+       /*
+        * Calculate the module_load_offset the first time this
+        * code is called. Once calculated it stays the same until
+        * reboot.
+        */
+       if (module_load_offset == 0)
+               module_load_offset = (get_random_int() % 1024 + 1) * PAGE_SIZE;
+       mutex_unlock(&module_kaslr_mutex);
+
        return module_load_offset;
 }
-#else
-static unsigned long int get_module_load_offset(void)
+
+static unsigned long get_module_vmalloc_start(void)

arch/x86/kernel/module.c do { \ · line 111

Quoted 10 lines
arch/x86/kernel/module.c +8 -1
 {
-       return 0;
+       if (kaslr_randomize_each_module())
+               return MODULES_VADDR + get_modules_rand_len()
+                                       + get_module_load_offset();
+       else if (kaslr_randomize_base())
+               return MODULES_VADDR + get_module_load_offset();
+
+       return MODULES_VADDR;
+}

I would find this much more readable as:

static unsigned long get_module_vmalloc_start(void)

{
       unsigned long addr = MODULES_VADDR;

       if (kaslr_randomize_base())
              addr += get_module_load_offset();

       if (kaslr_randomize_each_module())
               addr += get_modules_rand_len();

       return addr;
}
Quoted 94 lines
arch/x86/kernel/module.c +83 -3
+
+static void *try_module_alloc(unsigned long addr, unsigned long size,
+                                       int try_purge)
+{
+       const unsigned long vm_flags = 0;
+
+       return __vmalloc_node_try_addr(addr, size, GFP_KERNEL, PAGE_KERNEL_EXEC,
+                                       vm_flags, NUMA_NO_NODE, try_purge,
+                                       __builtin_return_address(0));
+}
+
+/*
+ * Find a random address to try that won't obviously not fit. Random areas are
+ * allowed to overflow into the backup area
+ */
+static unsigned long get_rand_module_addr(unsigned long size)
+{
+       unsigned long nr_max_pos = (MODULES_LEN - size) / MODULE_ALIGN + 1;
+       unsigned long nr_rnd_pos = get_modules_rand_len() / MODULE_ALIGN;
+       unsigned long nr_pos = min(nr_max_pos, nr_rnd_pos);
+
+       unsigned long module_position_nr = get_random_long() % nr_pos;
+       unsigned long offset = module_position_nr * MODULE_ALIGN;
+
+       return MODULES_VADDR + offset;
+}
+
+/*
+ * Try to allocate in the random area. First 5000 times without purging, then
+ * 5000 times with purging. If these fail, return NULL.
+ */
+static void *try_module_randomize_each(unsigned long size)
+{
+       void *p = NULL;
+       unsigned int i;
+       unsigned long last_lazy_free_blocked = 0;
+
+       /* This will have a guard page */
+       unsigned long va_size = PAGE_ALIGN(size) + PAGE_SIZE;
+
+       if (!kaslr_randomize_each_module())
+               return NULL;
+
+       /* Make sure there is at least one address that might fit. */
+       if (va_size < PAGE_ALIGN(size) || va_size > MODULES_LEN)
+               return NULL;
+
+       /* Try to find a spot that doesn't need a lazy purge */
+       for (i = 0; i < NR_NO_PURGE; i++) {
+               unsigned long addr = get_rand_module_addr(va_size);
+
+               /* First try to avoid having to purge */
+               p = try_module_alloc(addr, size, 0);
+
+               /*
+                * Save the last value that was blocked by a
+                * lazy purge area.
+                */
+               if (IS_ERR(p) && PTR_ERR(p) == -EUCLEAN)
+                       last_lazy_free_blocked = addr;
+               else if (!IS_ERR(p))
+                       return p;
+       }
+
+       /* Try the most recent spot that could be used after a lazy purge */
+       if (last_lazy_free_blocked) {
+               p = try_module_alloc(last_lazy_free_blocked, size, 1);
+
+               if (!IS_ERR(p))
+                       return p;
+       }
+
+       /* Look for more spots and allow lazy purges */
+       for (i = 0; i < NR_TRY_PURGE; i++) {
+               unsigned long addr = get_rand_module_addr(va_size);
+
+               /* Give up and allow for purges */
+               p = try_module_alloc(addr, size, 1);
+
+               if (!IS_ERR(p))
+                       return p;
+       }
+       return NULL;
 }
-#endif
 
 void *module_alloc(unsigned long size)
 {
@@ -84,16 +201,18 @@ void *module_alloc(unsigned long size)
        if (PAGE_ALIGN(size) > MODULES_LEN)
                return NULL;
 
-       p = __vmalloc_node_range(size, MODULE_ALIGN,
-                                   MODULES_VADDR + get_module_load_offset(),

arch/x86/kernel/module.c void *module_alloc(unsigned long size) · line 210

Quoted 10 lines
arch/x86/kernel/module.c +7 -3
-                                   MODULES_END, GFP_KERNEL,
-                                   PAGE_KERNEL_EXEC, 0, NUMA_NO_NODE,
-                                   __builtin_return_address(0));
+       p = try_module_randomize_each(size);
+
+       if (!p)
+               p = __vmalloc_node_range(size, MODULE_ALIGN,
+                               get_module_vmalloc_start(), MODULES_END,
+                               GFP_KERNEL, PAGE_KERNEL_EXEC, 0,
+                               NUMA_NO_NODE, __builtin_return_address(0));

Instead of having two open-coded __vmalloc_node_range() calls left in this after the change, can this be done in terms of a call to try_module_alloc() instead? I see they're slightly different, but it might be nice for making the two paths share more code.

Quoted 10 lines
arch/x86/kernel/module.c +1 -2
+
        if (p && (kasan_module_alloc(p, size) < 0)) {
                vfree(p);
                return NULL;
        }
-
        return p;
 }
 
--
Quoted 2 lines

2.7.4

Looks promising!

-Kees

Signature · 2 lines
Kees Cook
Pixel Security
#5 lore raw

Re: [PATCH v6 2/4] x86/modules: Increase randomization for modules

Quoted 7 lines · Kees Cook

On Thu, Sep 13, 2018 at 2:31 PM, Rick Edgecombe <[email protected]> wrote:
I would find this much more readable as:
static unsigned long get_module_vmalloc_start(void) {
       unsigned long addr = MODULES_VADDR;

Quoted 8 lines

       if (kaslr_randomize_base())
              addr += get_module_load_offset();

       if (kaslr_randomize_each_module())
               addr += get_modules_rand_len();

       return addr;
}

Thanks, that looks better.

Quoted 16 lines
Quoted 16 lines

 void *module_alloc(unsigned long size)
 {

arch/x86/kernel/module.c +3 -5
@@ -84,16 +201,18 @@ void *module_alloc(unsigned long size)
         if (PAGE_ALIGN(size) > MODULES_LEN)
                 return NULL;
 
-       p = __vmalloc_node_range(size, MODULE_ALIGN,
-                                   MODULES_VADDR +
 get_module_load_offset(),
-                                   MODULES_END, GFP_KERNEL,
-                                   PAGE_KERNEL_EXEC, 0, NUMA_NO_NODE,
-                                   __builtin_return_address(0));
+       p = try_module_randomize_each(size);
+
+       if (!p)
Quoted 8 lines

arch/x86/kernel/module.c void *module_alloc(unsigned long size) · line 210

Quoted 4 lines
arch/x86/kernel/module.c +4 -0
+               p = __vmalloc_node_range(size, MODULE_ALIGN,
+                               get_module_vmalloc_start(), MODULES_END,
+                               GFP_KERNEL, PAGE_KERNEL_EXEC, 0,
+                               NUMA_NO_NODE, __builtin_return_address(0));

Instead of having two open-coded __vmalloc_node_range() calls left in this after the change, can this be done in terms of a call to try_module_alloc() instead? I see they're slightly different, but it might be nice for making the two paths share more code.

Not sure what you mean. Across the whole change, there is one call to __vmalloc_node_range, and one to __vmalloc_node_try_addr.

#6 lore raw

Re: [PATCH v6 2/4] x86/modules: Increase randomization for modules

Quoted 42 lines · Rick P
Quoted 4 lines · Kees Cook

On Thu, Sep 13, 2018 at 2:31 PM, Rick Edgecombe <[email protected]> wrote:
I would find this much more readable as:
static unsigned long get_module_vmalloc_start(void)

Quoted 11 lines
{
       unsigned long addr = MODULES_VADDR;

       if (kaslr_randomize_base())
              addr += get_module_load_offset();

       if (kaslr_randomize_each_module())
               addr += get_modules_rand_len();

       return addr;
}

Thanks, that looks better.

Quoted 16 lines
Quoted 16 lines

void *module_alloc(unsigned long size)
{

arch/x86/kernel/module.c +3 -5
@@ -84,16 +201,18 @@ void *module_alloc(unsigned long size)
        if (PAGE_ALIGN(size) > MODULES_LEN)
                return NULL;
 
-       p = __vmalloc_node_range(size, MODULE_ALIGN,
-                                   MODULES_VADDR +
 get_module_load_offset(),
-                                   MODULES_END, GFP_KERNEL,
-                                   PAGE_KERNEL_EXEC, 0, NUMA_NO_NODE,
-                                   __builtin_return_address(0));
+       p = try_module_randomize_each(size);
+
+       if (!p)
Quoted 8 lines

arch/x86/kernel/module.c void *module_alloc(unsigned long size) · line 210

Quoted 4 lines
arch/x86/kernel/module.c +4 -0
+               p = __vmalloc_node_range(size, MODULE_ALIGN,
+                               get_module_vmalloc_start(), MODULES_END,
+                               GFP_KERNEL, PAGE_KERNEL_EXEC, 0,
+                               NUMA_NO_NODE, __builtin_return_address(0));

Instead of having two open-coded __vmalloc_node_range() calls left in this after the change, can this be done in terms of a call to try_module_alloc() instead? I see they're slightly different, but it might be nice for making the two paths share more code.

Quoted 2 lines

Not sure what you mean. Across the whole change, there is one call to __vmalloc_node_range, and one to __vmalloc_node_try_addr.

I guess I meant the vmalloc calls -- one for node_range and one for node_try_addr. I was wondering if the logic could be combined in some way so that the __vmalloc_node_range() could be made in terms of the the helper that try_module_randomize_each() uses. But this could just be me hoping for nice-to-read changes. ;)

-Kees

Signature · 2 lines
Kees Cook
Pixel Security
#7 lore raw

Re: [PATCH v6 2/4] x86/modules: Increase randomization for modules

Quoted 8 lines · Kees Cook
Quoted 6 lines · Rick P
Quoted 4 lines

Instead of having two open-coded __vmalloc_node_range() calls left in this after the change, can this be done in terms of a call to try_module_alloc() instead? I see they're slightly different, but it might be nice for making the two paths share more code.

Not sure what you mean. Across the whole change, there is one call to __vmalloc_node_range, and one to __vmalloc_node_try_addr.

Quoted 7 lines

I guess I meant the vmalloc calls -- one for node_range and one for node_try_addr. I was wondering if the logic could be combined in some way so that the __vmalloc_node_range() could be made in terms of the the helper that try_module_randomize_each() uses. But this could just be me hoping for nice-to-read changes. ;)

-Kees

One thing I had been considering was to move the whole "try random locations, then use backup" logic to vmalloc.c, and just have parameters for random area size, number of tries, etc. This way it could be possibly be re-used for other architectures for modules. Also on our list is to look at randomizing vmalloc space (especially stacks), which may or may not involve using a similar method.

So maybe bit pre-mature refactoring, but would also clean up the code in module.c. Do you think it would be worth it?

Thanks,

Rick

#8 lore raw

Re: [PATCH v6 2/4] x86/modules: Increase randomization for modules

Quoted 16 lines · Rick P
Quoted 8 lines · Kees Cook
Quoted 6 lines · Rick P
Quoted 4 lines

Instead of having two open-coded __vmalloc_node_range() calls left in this after the change, can this be done in terms of a call to try_module_alloc() instead? I see they're slightly different, but it might be nice for making the two paths share more code.

Not sure what you mean. Across the whole change, there is one call to __vmalloc_node_range, and one to __vmalloc_node_try_addr.

Quoted 7 lines

I guess I meant the vmalloc calls -- one for node_range and one for node_try_addr. I was wondering if the logic could be combined in some way so that the __vmalloc_node_range() could be made in terms of the the helper that try_module_randomize_each() uses. But this could just be me hoping for nice-to-read changes. ;)

-Kees

Quoted 8 lines

One thing I had been considering was to move the whole "try random locations, then use backup" logic to vmalloc.c, and just have parameters for random area size, number of tries, etc. This way it could be possibly be re-used for other architectures for modules. Also on our list is to look at randomizing vmalloc space (especially stacks), which may or may not involve using a similar method.

So maybe bit pre-mature refactoring, but would also clean up the code in module.c. Do you think it would be worth it?

I'd love to hear thoughts from -mm folks. Andrew, Matthew?

-Kees

Signature · 2 lines
Kees Cook
Pixel Security
#9 lore raw

PATCH v6 3/4 vmalloc: Add debugfs modfraginfo

In reply to Rick Edgecombe

Add 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
index 1954458..a44b902 100644
@@ -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
Reviewed-by on v6 3/4
#10 lore raw

Re: [PATCH v6 3/4] vmalloc: Add debugfs modfraginfo

Quoted 10 lines · Rick Edgecombe

Add 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
Quoted 5 lines

Sample output when just X86_64:
Largest free space: 897912 kB
Total free space: 1025424 kB

I like having these statistics available!

Quoted 84 lines
---
 mm/vmalloc.c | 102 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 101 insertions(+), 1 deletion(-)
mm/vmalloc.c +54 -1
index 1954458..a44b902 100644
@@ -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)

mm/vmalloc.c static int __init proc_vmalloc_init(void) · line 2988

Quoted 10 lines
mm/vmalloc.c +10 -0
+               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);

I don't think the IS_ENABLED is needed here?

I wonder if there is a better way to arrange this code that uses fewer ifdefs, etc. Maybe a single CONFIG that capture whether or not fine-grained module randomization is built in, like:

config RANDOMIZE_FINE_MODULE

    def_bool y if RANDOMIZE_BASE && X86_64

#ifdef CONFIG_RANDOMIZE_FINE_MODULE
...
#endif

But that doesn't capture the DEBUG_FS and PROC_FS bits ... so ... maybe not worth it. I guess, either way:

-Kees

Signature · 2 lines
Kees Cook
Pixel Security
#11 lore raw

Re: [PATCH v6 3/4] vmalloc: Add debugfs modfraginfo

Quoted 18 lines · Kees Cook
Quoted 9 lines · Rick Edgecombe
mm/vmalloc.c +9 -0
+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 /
Quoted 6 lines

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);

I don't think the IS_ENABLED is needed here?

The reason for this is that for ARCH=um, CONFIG_X86_64 is defined but kaslr_enabled is not. kaslr_enabled is declared above to protect against a compiler error.

So IS_ENABLED(CONFIG_RANDOMIZE_BASE) is protecting kaslr_enabled from causing a linker error. It gets constant evaluated to 0 and the compiler optimizes out the kaslr_enabled call. Thought it was better to guard with CONFIG_RANDOMIZE_BASE than with CONFIG_UM, to try to catch the broader situation. I guess I could move it to a helper inside ifdefs instead. Was trying to keep the ifdef-ed code down.

Quoted 7 lines

I wonder if there is a better way to arrange this code that uses fewer ifdefs, etc. Maybe a single CONFIG that capture whether or not fine-grained module randomization is built in, like:

config RANDOMIZE_FINE_MODULE
    def_bool y if RANDOMIZE_BASE && X86_64

Quoted 6 lines

#ifdef CONFIG_RANDOMIZE_FINE_MODULE
...
#endif

But that doesn't capture the DEBUG_FS and PROC_FS bits ... so ... maybe not worth it. I guess, either way:

Hmmm, didn't know about that. Would clean it up some at least.

I wish the debugfs info could be in module.c to help with this IFDEFs, but it needs vmalloc internals. MODULES_VADDR is not standardized across the ARCH's as well, so this was my best attempt to implement this without having to make changes in other architectures.

Quoted 4 lines

-Kees

#12 lore raw

Re: [PATCH v6 3/4] vmalloc: Add debugfs modfraginfo

Quoted 23 lines · Rick P
Quoted 18 lines · Kees Cook
Quoted 14 lines · Rick Edgecombe
mm/vmalloc.c +9 -0
+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);

mm/vmalloc.c +4 -0
+       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",
Quoted 1 line

backup_cnt);

I don't think the IS_ENABLED is needed here?

The reason for this is that for ARCH=um, CONFIG_X86_64 is defined but kaslr_enabled is not. kaslr_enabled is declared above to protect against a compiler error.

Quoted 5 lines

So IS_ENABLED(CONFIG_RANDOMIZE_BASE) is protecting kaslr_enabled from causing a linker error. It gets constant evaluated to 0 and the compiler optimizes out the kaslr_enabled call. Thought it was better to guard with CONFIG_RANDOMIZE_BASE than with CONFIG_UM, to try to catch the broader situation. I guess I could move it to a helper inside ifdefs instead. Was trying to keep the ifdef-ed code down.

Ah yes, UM. Perhaps kaslr_enabled() could be defined somewhere so that it would link sanely? (Maybe in module.h?)

Quoted 11 lines
Quoted 11 lines

I wonder if there is a better way to arrange this code that uses fewer ifdefs, etc. Maybe a single CONFIG that capture whether or not fine-grained module randomization is built in, like:

config RANDOMIZE_FINE_MODULE

    def_bool y if RANDOMIZE_BASE && X86_64

#ifdef CONFIG_RANDOMIZE_FINE_MODULE
...
#endif

Quoted 8 lines
Quoted 2 lines

But that doesn't capture the DEBUG_FS and PROC_FS bits ... so ... maybe not worth it. I guess, either way:

Hmmm, didn't know about that. Would clean it up some at least.

I wish the debugfs info could be in module.c to help with this IFDEFs, but it needs vmalloc internals. MODULES_VADDR is not standardized across the ARCH's as well, so this was my best attempt to implement this without having to make changes in other architectures.

Yeah, I've long wanted to try to sandardize the module+vmalloc guts, but it's just different enough in each architecture that it eludes people.

-Kees

Signature · 2 lines
Kees Cook
Pixel Security
#13 lore raw

PATCH v6 4/4 Kselftest for module text allocation benchmarking

In reply to Rick Edgecombe

This 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 “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                          | 354 ++++++++++++++++++++++++++
 tools/testing/selftests/bpf/test_mod_alloc.sh |  29 +++
 4 files changed, 394 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
index 4966c4f..c6c147c 100644
@@ -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
index ca3f7eb..3d5923e 100644
@@ -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 +354 -0

354 lines not on this page · raw message

tools/testing/selftests/bpf/test_mod_alloc.sh new file +29 -0
new file mode 100755
index 0000000..e9aea57
@@ -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
#14 lore raw

Re: [PATCH v6 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-rc4 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/20180914-064826
config: microblaze-allyesconfig (attached as .config)
compiler: microblaze-linux-gcc (GCC) 8.1.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=8.1.0 make.cross ARCH=microblaze

All errors (new ones prefixed by >>):

lib/test_mod_alloc.o: In function `device_file_write':

>> (.text+0x6b8): undefined reference to `__divdi3'

(.text+0x724): undefined reference to `__divdi3'
.exit.data' referenced in section .exit.text' of drivers/tty/n_hdlc.o: defined in discarded section .exit.data' of drivers/tty/n_hdlc.o .exit.data' referenced in section .exit.text' of drivers/tty/n_hdlc.o: defined in discarded section .exit.data' of drivers/tty/n_hdlc.o drivers/android/binder.o: In function `binder_thread_write':
drivers/android/.tmp_gl_binder.o:(.text+0xd3c4): undefined reference to __user_bad' drivers/android/.tmp_gl_binder.o:(.text+0xd3f0): undefined reference to __user_bad' drivers/android/.tmp_gl_binder.o:(.text+0xd868): undefined reference to __user_bad' drivers/android/.tmp_gl_binder.o:(.text+0xdfe8): undefined reference to __user_bad' drivers/android/.tmp_gl_binder.o:(.text+0xe5c8): undefined reference to `__user_bad'

---
0-DAY kernel test infrastructure Open Source Technology Center
https://lists.01.org/pipermail/kbuild-all Intel Corporation

#15 lore raw
In reply to Rick Edgecombe
Quoted 4 lines · Rick Edgecombe

This is V6 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.

I'm excited for this! :)

Quoted 5 lines

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

Yay for self-tests! This is much appreciated.

-Kees

Signature · 2 lines
Kees Cook
Pixel Security