1 /* SPDX-License-Identifier: GPL-2.0-only */ 2 #ifndef _LINUX_RANDOMIZE_KSTACK_H 3 #define _LINUX_RANDOMIZE_KSTACK_H 4 5 #ifdef CONFIG_RANDOMIZE_KSTACK_OFFSET 6 #include <linux/kernel.h> 7 #include <linux/jump_label.h> 8 #include <linux/percpu-defs.h> 9 10 DECLARE_STATIC_KEY_MAYBE(CONFIG_RANDOMIZE_KSTACK_OFFSET_DEFAULT, 11 randomize_kstack_offset); 12 DECLARE_PER_CPU(u32, kstack_offset); 13 14 /* 15 * Do not use this anywhere else in the kernel. This is used here because 16 * it provides an arch-agnostic way to grow the stack with correct 17 * alignment. Also, since this use is being explicitly masked to a max of 18 * 10 bits, stack-clash style attacks are unlikely. For more details see 19 * "VLAs" in Documentation/process/deprecated.rst 20 */ 21 void *__builtin_alloca(size_t size); 22 /* 23 * Use, at most, 10 bits of entropy. We explicitly cap this to keep the 24 * "VLA" from being unbounded (see above). 10 bits leaves enough room for 25 * per-arch offset masks to reduce entropy (by removing higher bits, since 26 * high entropy may overly constrain usable stack space), and for 27 * compiler/arch-specific stack alignment to remove the lower bits. 28 */ 29 #define KSTACK_OFFSET_MAX(x) ((x) & 0x3FF) 30 31 /* 32 * These macros must be used during syscall entry when interrupts and 33 * preempt are disabled, and after user registers have been stored to 34 * the stack. 35 */ 36 #define add_random_kstack_offset() do { \ 37 if (static_branch_maybe(CONFIG_RANDOMIZE_KSTACK_OFFSET_DEFAULT, \ 38 &randomize_kstack_offset)) { \ 39 u32 offset = raw_cpu_read(kstack_offset); \ 40 u8 *ptr = __builtin_alloca(KSTACK_OFFSET_MAX(offset)); \ 41 /* Keep allocation even after "ptr" loses scope. */ \ 42 asm volatile("" :: "r"(ptr) : "memory"); \ 43 } \ 44 } while (0) 45 46 #define choose_random_kstack_offset(rand) do { \ 47 if (static_branch_maybe(CONFIG_RANDOMIZE_KSTACK_OFFSET_DEFAULT, \ 48 &randomize_kstack_offset)) { \ 49 u32 offset = raw_cpu_read(kstack_offset); \ 50 offset ^= (rand); \ 51 raw_cpu_write(kstack_offset, offset); \ 52 } \ 53 } while (0) 54 #else /* CONFIG_RANDOMIZE_KSTACK_OFFSET */ 55 #define add_random_kstack_offset() do { } while (0) 56 #define choose_random_kstack_offset(rand) do { } while (0) 57 #endif /* CONFIG_RANDOMIZE_KSTACK_OFFSET */ 58 59 #endif 60