stackleak.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. #include <linux/stackleak.h>
  13. asmlinkage void stackleak_erase(void)
  14. {
  15. /* It would be nice not to have 'kstack_ptr' and 'boundary' on stack */
  16. unsigned long kstack_ptr = current->lowest_stack;
  17. unsigned long boundary = (unsigned long)end_of_stack(current);
  18. unsigned int poison_count = 0;
  19. const unsigned int depth = STACKLEAK_SEARCH_DEPTH / sizeof(unsigned long);
  20. /* Check that 'lowest_stack' value is sane */
  21. if (unlikely(kstack_ptr - boundary >= THREAD_SIZE))
  22. kstack_ptr = boundary;
  23. /* Search for the poison value in the kernel stack */
  24. while (kstack_ptr > boundary && poison_count <= depth) {
  25. if (*(unsigned long *)kstack_ptr == STACKLEAK_POISON)
  26. poison_count++;
  27. else
  28. poison_count = 0;
  29. kstack_ptr -= sizeof(unsigned long);
  30. }
  31. /*
  32. * One 'long int' at the bottom of the thread stack is reserved and
  33. * should not be poisoned (see CONFIG_SCHED_STACK_END_CHECK=y).
  34. */
  35. if (kstack_ptr == boundary)
  36. kstack_ptr += sizeof(unsigned long);
  37. /*
  38. * Now write the poison value to the kernel stack. Start from
  39. * 'kstack_ptr' and move up till the new 'boundary'. We assume that
  40. * the stack pointer doesn't change when we write poison.
  41. */
  42. if (on_thread_stack())
  43. boundary = current_stack_pointer;
  44. else
  45. boundary = current_top_of_stack();
  46. while (kstack_ptr < boundary) {
  47. *(unsigned long *)kstack_ptr = STACKLEAK_POISON;
  48. kstack_ptr += sizeof(unsigned long);
  49. }
  50. /* Reset the 'lowest_stack' value for the next syscall */
  51. current->lowest_stack = current_top_of_stack() - THREAD_SIZE/64;
  52. }