kasan_test_module.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. *
  4. * Copyright (c) 2014 Samsung Electronics Co., Ltd.
  5. * Author: Andrey Ryabinin <a.ryabinin@samsung.com>
  6. */
  7. #define pr_fmt(fmt) "kasan: test: " fmt
  8. #include <linux/mman.h>
  9. #include <linux/module.h>
  10. #include <linux/printk.h>
  11. #include <linux/slab.h>
  12. #include <linux/uaccess.h>
  13. #include "kasan.h"
  14. static noinline void __init copy_user_test(void)
  15. {
  16. char *kmem;
  17. char __user *usermem;
  18. size_t size = 128 - KASAN_GRANULE_SIZE;
  19. int __maybe_unused unused;
  20. kmem = kmalloc(size, GFP_KERNEL);
  21. if (!kmem)
  22. return;
  23. usermem = (char __user *)vm_mmap(NULL, 0, PAGE_SIZE,
  24. PROT_READ | PROT_WRITE | PROT_EXEC,
  25. MAP_ANONYMOUS | MAP_PRIVATE, 0);
  26. if (IS_ERR(usermem)) {
  27. pr_err("Failed to allocate user memory\n");
  28. kfree(kmem);
  29. return;
  30. }
  31. OPTIMIZER_HIDE_VAR(size);
  32. pr_info("out-of-bounds in copy_from_user()\n");
  33. unused = copy_from_user(kmem, usermem, size + 1);
  34. pr_info("out-of-bounds in copy_to_user()\n");
  35. unused = copy_to_user(usermem, kmem, size + 1);
  36. pr_info("out-of-bounds in __copy_from_user()\n");
  37. unused = __copy_from_user(kmem, usermem, size + 1);
  38. pr_info("out-of-bounds in __copy_to_user()\n");
  39. unused = __copy_to_user(usermem, kmem, size + 1);
  40. pr_info("out-of-bounds in __copy_from_user_inatomic()\n");
  41. unused = __copy_from_user_inatomic(kmem, usermem, size + 1);
  42. pr_info("out-of-bounds in __copy_to_user_inatomic()\n");
  43. unused = __copy_to_user_inatomic(usermem, kmem, size + 1);
  44. pr_info("out-of-bounds in strncpy_from_user()\n");
  45. unused = strncpy_from_user(kmem, usermem, size + 1);
  46. vm_munmap((unsigned long)usermem, PAGE_SIZE);
  47. kfree(kmem);
  48. }
  49. static int __init kasan_test_module_init(void)
  50. {
  51. /*
  52. * Temporarily enable multi-shot mode. Otherwise, KASAN would only
  53. * report the first detected bug and panic the kernel if panic_on_warn
  54. * is enabled.
  55. */
  56. bool multishot = kasan_save_enable_multi_shot();
  57. copy_user_test();
  58. kasan_restore_multi_shot(multishot);
  59. return -EAGAIN;
  60. }
  61. module_init(kasan_test_module_init);
  62. MODULE_LICENSE("GPL");