arm, kaslr: randomize module base address

While we don't yet have text base address randomization in ARM, we can
do module base address randomization. This bumps the module base by up
to 4MiB.

Signed-off-by: Kees Cook <keescook@chromium.org>
diff --git a/arch/arm/Kconfig b/arch/arm/Kconfig
index a9c4e48..0bc1d82 100644
--- a/arch/arm/Kconfig
+++ b/arch/arm/Kconfig
@@ -1835,6 +1835,14 @@
 	help
 	  Say Y if you want to run Linux in a Virtual Machine on Xen on ARM.
 
+config RANDOMIZE_BASE
+	bool "Randomize the base address of loaded modules"
+	depends on MMU
+	default n
+	---help---
+	   Randomizes the base address at which kernel modules are loaded,
+	   with 10 bits of entropy. At most, this will create a 4MiB gap
+	   at the start of the kernel modules virtual address range.
 endmenu
 
 menu "Boot options"
diff --git a/arch/arm/kernel/module.c b/arch/arm/kernel/module.c
index 4f14b5c..c672845 100644
--- a/arch/arm/kernel/module.c
+++ b/arch/arm/kernel/module.c
@@ -19,6 +19,7 @@
 #include <linux/fs.h>
 #include <linux/string.h>
 #include <linux/gfp.h>
+#include <linux/random.h>
 
 #include <asm/pgtable.h>
 #include <asm/sections.h>
@@ -38,9 +39,48 @@
 #endif
 
 #ifdef CONFIG_MMU
+# ifdef CONFIG_RANDOMIZE_BASE
+static unsigned long module_load_offset;
+static int randomize_modules = 1;
+
+/* Mutex protects the module_load_offset. */
+static DEFINE_MUTEX(module_kaslr_mutex);
+
+static int __init parse_nokaslr(char *p)
+{
+	randomize_modules = 0;
+	return 0;
+}
+early_param("nokaslr", parse_nokaslr);
+
+static unsigned long int get_module_load_offset(void)
+{
+	if (randomize_modules) {
+		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)
+{
+	return 0;
+}
+# endif
+
 void *module_alloc(unsigned long size)
 {
-	void *p = __vmalloc_node_range(size, 1, MODULES_VADDR, MODULES_END,
+	void *p = __vmalloc_node_range(size, 1,
+				MODULES_VADDR + get_module_load_offset(),
+				MODULES_END,
 				GFP_KERNEL, PAGE_KERNEL_EXEC, 0, NUMA_NO_NODE,
 				__builtin_return_address(0));
 	if (!IS_ENABLED(CONFIG_ARM_MODULE_PLTS) || p)