diff options
Diffstat (limited to 'kernel/stackleak.c')
-rw-r--r-- | kernel/stackleak.c | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/kernel/stackleak.c b/kernel/stackleak.c new file mode 100644 index 000000000000..deba0d8992f9 --- /dev/null +++ b/kernel/stackleak.c | |||
@@ -0,0 +1,62 @@ | |||
1 | // SPDX-License-Identifier: GPL-2.0 | ||
2 | /* | ||
3 | * This code fills the used part of the kernel stack with a poison value | ||
4 | * before returning to userspace. It's part of the STACKLEAK feature | ||
5 | * ported from grsecurity/PaX. | ||
6 | * | ||
7 | * Author: Alexander Popov <alex.popov@linux.com> | ||
8 | * | ||
9 | * STACKLEAK reduces the information which kernel stack leak bugs can | ||
10 | * reveal and blocks some uninitialized stack variable attacks. | ||
11 | */ | ||
12 | |||
13 | #include <linux/stackleak.h> | ||
14 | |||
15 | asmlinkage void stackleak_erase(void) | ||
16 | { | ||
17 | /* It would be nice not to have 'kstack_ptr' and 'boundary' on stack */ | ||
18 | unsigned long kstack_ptr = current->lowest_stack; | ||
19 | unsigned long boundary = (unsigned long)end_of_stack(current); | ||
20 | unsigned int poison_count = 0; | ||
21 | const unsigned int depth = STACKLEAK_SEARCH_DEPTH / sizeof(unsigned long); | ||
22 | |||
23 | /* Check that 'lowest_stack' value is sane */ | ||
24 | if (unlikely(kstack_ptr - boundary >= THREAD_SIZE)) | ||
25 | kstack_ptr = boundary; | ||
26 | |||
27 | /* Search for the poison value in the kernel stack */ | ||
28 | while (kstack_ptr > boundary && poison_count <= depth) { | ||
29 | if (*(unsigned long *)kstack_ptr == STACKLEAK_POISON) | ||
30 | poison_count++; | ||
31 | else | ||
32 | poison_count = 0; | ||
33 | |||
34 | kstack_ptr -= sizeof(unsigned long); | ||
35 | } | ||
36 | |||
37 | /* | ||
38 | * One 'long int' at the bottom of the thread stack is reserved and | ||
39 | * should not be poisoned (see CONFIG_SCHED_STACK_END_CHECK=y). | ||
40 | */ | ||
41 | if (kstack_ptr == boundary) | ||
42 | kstack_ptr += sizeof(unsigned long); | ||
43 | |||
44 | /* | ||
45 | * Now write the poison value to the kernel stack. Start from | ||
46 | * 'kstack_ptr' and move up till the new 'boundary'. We assume that | ||
47 | * the stack pointer doesn't change when we write poison. | ||
48 | */ | ||
49 | if (on_thread_stack()) | ||
50 | boundary = current_stack_pointer; | ||
51 | else | ||
52 | boundary = current_top_of_stack(); | ||
53 | |||
54 | while (kstack_ptr < boundary) { | ||
55 | *(unsigned long *)kstack_ptr = STACKLEAK_POISON; | ||
56 | kstack_ptr += sizeof(unsigned long); | ||
57 | } | ||
58 | |||
59 | /* Reset the 'lowest_stack' value for the next syscall */ | ||
60 | current->lowest_stack = current_top_of_stack() - THREAD_SIZE/64; | ||
61 | } | ||
62 | |||