kasan.rst 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. The Kernel Address Sanitizer (KASAN)
  2. ====================================
  3. Overview
  4. --------
  5. KernelAddressSANitizer (KASAN) is a dynamic memory safety error detector
  6. designed to find out-of-bound and use-after-free bugs. KASAN has three modes:
  7. 1. generic KASAN (similar to userspace ASan),
  8. 2. software tag-based KASAN (similar to userspace HWASan),
  9. 3. hardware tag-based KASAN (based on hardware memory tagging).
  10. Software KASAN modes (1 and 2) use compile-time instrumentation to insert
  11. validity checks before every memory access, and therefore require a compiler
  12. version that supports that.
  13. Generic KASAN is supported in both GCC and Clang. With GCC it requires version
  14. 8.3.0 or later. Any supported Clang version is compatible, but detection of
  15. out-of-bounds accesses for global variables is only supported since Clang 11.
  16. Tag-based KASAN is only supported in Clang.
  17. Currently generic KASAN is supported for the x86_64, arm64, xtensa, s390 and
  18. and riscv architectures, and tag-based KASAN modes are supported only for arm64.
  19. Usage
  20. -----
  21. To enable KASAN configure kernel with::
  22. CONFIG_KASAN = y
  23. and choose between CONFIG_KASAN_GENERIC (to enable generic KASAN),
  24. CONFIG_KASAN_SW_TAGS (to enable software tag-based KASAN), and
  25. CONFIG_KASAN_HW_TAGS (to enable hardware tag-based KASAN).
  26. For software modes, you also need to choose between CONFIG_KASAN_OUTLINE and
  27. CONFIG_KASAN_INLINE. Outline and inline are compiler instrumentation types.
  28. The former produces smaller binary while the latter is 1.1 - 2 times faster.
  29. Both software KASAN modes work with both SLUB and SLAB memory allocators,
  30. while the hardware tag-based KASAN currently only support SLUB.
  31. For better error reports that include stack traces, enable CONFIG_STACKTRACE.
  32. To augment reports with last allocation and freeing stack of the physical page,
  33. it is recommended to enable also CONFIG_PAGE_OWNER and boot with page_owner=on.
  34. Error reports
  35. ~~~~~~~~~~~~~
  36. A typical out-of-bounds access generic KASAN report looks like this::
  37. ==================================================================
  38. BUG: KASAN: slab-out-of-bounds in kmalloc_oob_right+0xa8/0xbc [test_kasan]
  39. Write of size 1 at addr ffff8801f44ec37b by task insmod/2760
  40. CPU: 1 PID: 2760 Comm: insmod Not tainted 4.19.0-rc3+ #698
  41. Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1 04/01/2014
  42. Call Trace:
  43. dump_stack+0x94/0xd8
  44. print_address_description+0x73/0x280
  45. kasan_report+0x144/0x187
  46. __asan_report_store1_noabort+0x17/0x20
  47. kmalloc_oob_right+0xa8/0xbc [test_kasan]
  48. kmalloc_tests_init+0x16/0x700 [test_kasan]
  49. do_one_initcall+0xa5/0x3ae
  50. do_init_module+0x1b6/0x547
  51. load_module+0x75df/0x8070
  52. __do_sys_init_module+0x1c6/0x200
  53. __x64_sys_init_module+0x6e/0xb0
  54. do_syscall_64+0x9f/0x2c0
  55. entry_SYSCALL_64_after_hwframe+0x44/0xa9
  56. RIP: 0033:0x7f96443109da
  57. RSP: 002b:00007ffcf0b51b08 EFLAGS: 00000202 ORIG_RAX: 00000000000000af
  58. RAX: ffffffffffffffda RBX: 000055dc3ee521a0 RCX: 00007f96443109da
  59. RDX: 00007f96445cff88 RSI: 0000000000057a50 RDI: 00007f9644992000
  60. RBP: 000055dc3ee510b0 R08: 0000000000000003 R09: 0000000000000000
  61. R10: 00007f964430cd0a R11: 0000000000000202 R12: 00007f96445cff88
  62. R13: 000055dc3ee51090 R14: 0000000000000000 R15: 0000000000000000
  63. Allocated by task 2760:
  64. save_stack+0x43/0xd0
  65. kasan_kmalloc+0xa7/0xd0
  66. kmem_cache_alloc_trace+0xe1/0x1b0
  67. kmalloc_oob_right+0x56/0xbc [test_kasan]
  68. kmalloc_tests_init+0x16/0x700 [test_kasan]
  69. do_one_initcall+0xa5/0x3ae
  70. do_init_module+0x1b6/0x547
  71. load_module+0x75df/0x8070
  72. __do_sys_init_module+0x1c6/0x200
  73. __x64_sys_init_module+0x6e/0xb0
  74. do_syscall_64+0x9f/0x2c0
  75. entry_SYSCALL_64_after_hwframe+0x44/0xa9
  76. Freed by task 815:
  77. save_stack+0x43/0xd0
  78. __kasan_slab_free+0x135/0x190
  79. kasan_slab_free+0xe/0x10
  80. kfree+0x93/0x1a0
  81. umh_complete+0x6a/0xa0
  82. call_usermodehelper_exec_async+0x4c3/0x640
  83. ret_from_fork+0x35/0x40
  84. The buggy address belongs to the object at ffff8801f44ec300
  85. which belongs to the cache kmalloc-128 of size 128
  86. The buggy address is located 123 bytes inside of
  87. 128-byte region [ffff8801f44ec300, ffff8801f44ec380)
  88. The buggy address belongs to the page:
  89. page:ffffea0007d13b00 count:1 mapcount:0 mapping:ffff8801f7001640 index:0x0
  90. flags: 0x200000000000100(slab)
  91. raw: 0200000000000100 ffffea0007d11dc0 0000001a0000001a ffff8801f7001640
  92. raw: 0000000000000000 0000000080150015 00000001ffffffff 0000000000000000
  93. page dumped because: kasan: bad access detected
  94. Memory state around the buggy address:
  95. ffff8801f44ec200: fc fc fc fc fc fc fc fc fb fb fb fb fb fb fb fb
  96. ffff8801f44ec280: fb fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
  97. >ffff8801f44ec300: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03
  98. ^
  99. ffff8801f44ec380: fc fc fc fc fc fc fc fc fb fb fb fb fb fb fb fb
  100. ffff8801f44ec400: fb fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
  101. ==================================================================
  102. The header of the report provides a short summary of what kind of bug happened
  103. and what kind of access caused it. It's followed by a stack trace of the bad
  104. access, a stack trace of where the accessed memory was allocated (in case bad
  105. access happens on a slab object), and a stack trace of where the object was
  106. freed (in case of a use-after-free bug report). Next comes a description of
  107. the accessed slab object and information about the accessed memory page.
  108. In the last section the report shows memory state around the accessed address.
  109. Internally KASAN tracks memory state separately for each memory granule, which
  110. is either 8 or 16 aligned bytes depending on KASAN mode. Each number in the
  111. memory state section of the report shows the state of one of the memory
  112. granules that surround the accessed address.
  113. For generic KASAN the size of each memory granule is 8. The state of each
  114. granule is encoded in one shadow byte. Those 8 bytes can be accessible,
  115. partially accessible, freed or be a part of a redzone. KASAN uses the following
  116. encoding for each shadow byte: 0 means that all 8 bytes of the corresponding
  117. memory region are accessible; number N (1 <= N <= 7) means that the first N
  118. bytes are accessible, and other (8 - N) bytes are not; any negative value
  119. indicates that the entire 8-byte word is inaccessible. KASAN uses different
  120. negative values to distinguish between different kinds of inaccessible memory
  121. like redzones or freed memory (see mm/kasan/kasan.h).
  122. In the report above the arrows point to the shadow byte 03, which means that
  123. the accessed address is partially accessible. For tag-based KASAN modes this
  124. last report section shows the memory tags around the accessed address
  125. (see the `Implementation details`_ section).
  126. Boot parameters
  127. ~~~~~~~~~~~~~~~
  128. Hardware tag-based KASAN mode (see the section about various modes below) is
  129. intended for use in production as a security mitigation. Therefore, it supports
  130. boot parameters that allow to disable KASAN competely or otherwise control
  131. particular KASAN features.
  132. - ``kasan=off`` or ``=on`` controls whether KASAN is enabled (default: ``on``).
  133. - ``kasan.mode=sync`` or ``=async`` controls whether KASAN is configured in
  134. synchronous or asynchronous mode of execution (default: ``sync``).
  135. Synchronous mode: a bad access is detected immediately when a tag
  136. check fault occurs.
  137. Asynchronous mode: a bad access detection is delayed. When a tag check
  138. fault occurs, the information is stored in hardware (in the TFSR_EL1
  139. register for arm64). The kernel periodically checks the hardware and
  140. only reports tag faults during these checks.
  141. - ``kasan.stacktrace=off`` or ``=on`` disables or enables alloc and free stack
  142. traces collection (default: ``on``).
  143. - ``kasan.fault=report`` or ``=panic`` controls whether to only print a KASAN
  144. report or also panic the kernel (default: ``report``). Note, that tag
  145. checking gets disabled after the first reported bug.
  146. For developers
  147. ~~~~~~~~~~~~~~
  148. Software KASAN modes use compiler instrumentation to insert validity checks.
  149. Such instrumentation might be incompatible with some part of the kernel, and
  150. therefore needs to be disabled. To disable instrumentation for specific files
  151. or directories, add a line similar to the following to the respective kernel
  152. Makefile:
  153. - For a single file (e.g. main.o)::
  154. KASAN_SANITIZE_main.o := n
  155. - For all files in one directory::
  156. KASAN_SANITIZE := n
  157. Implementation details
  158. ----------------------
  159. Generic KASAN
  160. ~~~~~~~~~~~~~
  161. From a high level perspective, KASAN's approach to memory error detection is
  162. similar to that of kmemcheck: use shadow memory to record whether each byte of
  163. memory is safe to access, and use compile-time instrumentation to insert checks
  164. of shadow memory on each memory access.
  165. Generic KASAN dedicates 1/8th of kernel memory to its shadow memory (e.g. 16TB
  166. to cover 128TB on x86_64) and uses direct mapping with a scale and offset to
  167. translate a memory address to its corresponding shadow address.
  168. Here is the function which translates an address to its corresponding shadow
  169. address::
  170. static inline void *kasan_mem_to_shadow(const void *addr)
  171. {
  172. return ((unsigned long)addr >> KASAN_SHADOW_SCALE_SHIFT)
  173. + KASAN_SHADOW_OFFSET;
  174. }
  175. where ``KASAN_SHADOW_SCALE_SHIFT = 3``.
  176. Compile-time instrumentation is used to insert memory access checks. Compiler
  177. inserts function calls (__asan_load*(addr), __asan_store*(addr)) before each
  178. memory access of size 1, 2, 4, 8 or 16. These functions check whether memory
  179. access is valid or not by checking corresponding shadow memory.
  180. GCC 5.0 has possibility to perform inline instrumentation. Instead of making
  181. function calls GCC directly inserts the code to check the shadow memory.
  182. This option significantly enlarges kernel but it gives x1.1-x2 performance
  183. boost over outline instrumented kernel.
  184. Generic KASAN also reports the last 2 call stacks to creation of work that
  185. potentially has access to an object. Call stacks for the following are shown:
  186. call_rcu() and workqueue queuing.
  187. Generic KASAN is the only mode that delays the reuse of freed object via
  188. quarantine (see mm/kasan/quarantine.c for implementation).
  189. Software tag-based KASAN
  190. ~~~~~~~~~~~~~~~~~~~~~~~~
  191. Software tag-based KASAN requires software memory tagging support in the form
  192. of HWASan-like compiler instrumentation (see HWASan documentation for details).
  193. Software tag-based KASAN is currently only implemented for arm64 architecture.
  194. Software tag-based KASAN uses the Top Byte Ignore (TBI) feature of arm64 CPUs
  195. to store a pointer tag in the top byte of kernel pointers. Like generic KASAN
  196. it uses shadow memory to store memory tags associated with each 16-byte memory
  197. cell (therefore it dedicates 1/16th of the kernel memory for shadow memory).
  198. On each memory allocation software tag-based KASAN generates a random tag, tags
  199. the allocated memory with this tag, and embeds this tag into the returned
  200. pointer.
  201. Software tag-based KASAN uses compile-time instrumentation to insert checks
  202. before each memory access. These checks make sure that tag of the memory that
  203. is being accessed is equal to tag of the pointer that is used to access this
  204. memory. In case of a tag mismatch software tag-based KASAN prints a bug report.
  205. Software tag-based KASAN also has two instrumentation modes (outline, that
  206. emits callbacks to check memory accesses; and inline, that performs the shadow
  207. memory checks inline). With outline instrumentation mode, a bug report is
  208. simply printed from the function that performs the access check. With inline
  209. instrumentation a brk instruction is emitted by the compiler, and a dedicated
  210. brk handler is used to print bug reports.
  211. Software tag-based KASAN uses 0xFF as a match-all pointer tag (accesses through
  212. pointers with 0xFF pointer tag aren't checked). The value 0xFE is currently
  213. reserved to tag freed memory regions.
  214. Software tag-based KASAN currently only supports tagging of
  215. kmem_cache_alloc/kmalloc and page_alloc memory.
  216. Hardware tag-based KASAN
  217. ~~~~~~~~~~~~~~~~~~~~~~~~
  218. Hardware tag-based KASAN is similar to the software mode in concept, but uses
  219. hardware memory tagging support instead of compiler instrumentation and
  220. shadow memory.
  221. Hardware tag-based KASAN is currently only implemented for arm64 architecture
  222. and based on both arm64 Memory Tagging Extension (MTE) introduced in ARMv8.5
  223. Instruction Set Architecture, and Top Byte Ignore (TBI).
  224. Special arm64 instructions are used to assign memory tags for each allocation.
  225. Same tags are assigned to pointers to those allocations. On every memory
  226. access, hardware makes sure that tag of the memory that is being accessed is
  227. equal to tag of the pointer that is used to access this memory. In case of a
  228. tag mismatch a fault is generated and a report is printed.
  229. Hardware tag-based KASAN uses 0xFF as a match-all pointer tag (accesses through
  230. pointers with 0xFF pointer tag aren't checked). The value 0xFE is currently
  231. reserved to tag freed memory regions.
  232. Hardware tag-based KASAN currently only supports tagging of
  233. kmem_cache_alloc/kmalloc and page_alloc memory.
  234. If the hardware doesn't support MTE (pre ARMv8.5), hardware tag-based KASAN
  235. won't be enabled. In this case all boot parameters are ignored.
  236. Note, that enabling CONFIG_KASAN_HW_TAGS always results in in-kernel TBI being
  237. enabled. Even when kasan.mode=off is provided, or when the hardware doesn't
  238. support MTE (but supports TBI).
  239. Hardware tag-based KASAN only reports the first found bug. After that MTE tag
  240. checking gets disabled.
  241. What memory accesses are sanitised by KASAN?
  242. --------------------------------------------
  243. The kernel maps memory in a number of different parts of the address
  244. space. This poses something of a problem for KASAN, which requires
  245. that all addresses accessed by instrumented code have a valid shadow
  246. region.
  247. The range of kernel virtual addresses is large: there is not enough
  248. real memory to support a real shadow region for every address that
  249. could be accessed by the kernel.
  250. By default
  251. ~~~~~~~~~~
  252. By default, architectures only map real memory over the shadow region
  253. for the linear mapping (and potentially other small areas). For all
  254. other areas - such as vmalloc and vmemmap space - a single read-only
  255. page is mapped over the shadow area. This read-only shadow page
  256. declares all memory accesses as permitted.
  257. This presents a problem for modules: they do not live in the linear
  258. mapping, but in a dedicated module space. By hooking in to the module
  259. allocator, KASAN can temporarily map real shadow memory to cover
  260. them. This allows detection of invalid accesses to module globals, for
  261. example.
  262. This also creates an incompatibility with ``VMAP_STACK``: if the stack
  263. lives in vmalloc space, it will be shadowed by the read-only page, and
  264. the kernel will fault when trying to set up the shadow data for stack
  265. variables.
  266. CONFIG_KASAN_VMALLOC
  267. ~~~~~~~~~~~~~~~~~~~~
  268. With ``CONFIG_KASAN_VMALLOC``, KASAN can cover vmalloc space at the
  269. cost of greater memory usage. Currently this is only supported on x86.
  270. This works by hooking into vmalloc and vmap, and dynamically
  271. allocating real shadow memory to back the mappings.
  272. Most mappings in vmalloc space are small, requiring less than a full
  273. page of shadow space. Allocating a full shadow page per mapping would
  274. therefore be wasteful. Furthermore, to ensure that different mappings
  275. use different shadow pages, mappings would have to be aligned to
  276. ``KASAN_GRANULE_SIZE * PAGE_SIZE``.
  277. Instead, KASAN shares backing space across multiple mappings. It allocates
  278. a backing page when a mapping in vmalloc space uses a particular page
  279. of the shadow region. This page can be shared by other vmalloc
  280. mappings later on.
  281. KASAN hooks into the vmap infrastructure to lazily clean up unused shadow
  282. memory.
  283. To avoid the difficulties around swapping mappings around, KASAN expects
  284. that the part of the shadow region that covers the vmalloc space will
  285. not be covered by the early shadow page, but will be left
  286. unmapped. This will require changes in arch-specific code.
  287. This allows ``VMAP_STACK`` support on x86, and can simplify support of
  288. architectures that do not have a fixed module region.
  289. CONFIG_KASAN_KUNIT_TEST and CONFIG_KASAN_MODULE_TEST
  290. ----------------------------------------------------
  291. KASAN tests consist of two parts:
  292. 1. Tests that are integrated with the KUnit Test Framework. Enabled with
  293. ``CONFIG_KASAN_KUNIT_TEST``. These tests can be run and partially verified
  294. automatically in a few different ways, see the instructions below.
  295. 2. Tests that are currently incompatible with KUnit. Enabled with
  296. ``CONFIG_KASAN_MODULE_TEST`` and can only be run as a module. These tests can
  297. only be verified manually, by loading the kernel module and inspecting the
  298. kernel log for KASAN reports.
  299. Each KUnit-compatible KASAN test prints a KASAN report if an error is detected.
  300. Then the test prints its number and status.
  301. When a test passes::
  302. ok 28 - kmalloc_double_kzfree
  303. When a test fails due to a failed ``kmalloc``::
  304. # kmalloc_large_oob_right: ASSERTION FAILED at lib/test_kasan.c:163
  305. Expected ptr is not null, but is
  306. not ok 4 - kmalloc_large_oob_right
  307. When a test fails due to a missing KASAN report::
  308. # kmalloc_double_kzfree: EXPECTATION FAILED at lib/test_kasan.c:629
  309. Expected kasan_data->report_expected == kasan_data->report_found, but
  310. kasan_data->report_expected == 1
  311. kasan_data->report_found == 0
  312. not ok 28 - kmalloc_double_kzfree
  313. At the end the cumulative status of all KASAN tests is printed. On success::
  314. ok 1 - kasan
  315. Or, if one of the tests failed::
  316. not ok 1 - kasan
  317. There are a few ways to run KUnit-compatible KASAN tests.
  318. 1. Loadable module
  319. ~~~~~~~~~~~~~~~~~~
  320. With ``CONFIG_KUNIT`` enabled, ``CONFIG_KASAN_KUNIT_TEST`` can be built as
  321. a loadable module and run on any architecture that supports KASAN by loading
  322. the module with insmod or modprobe. The module is called ``test_kasan``.
  323. 2. Built-In
  324. ~~~~~~~~~~~
  325. With ``CONFIG_KUNIT`` built-in, ``CONFIG_KASAN_KUNIT_TEST`` can be built-in
  326. on any architecure that supports KASAN. These and any other KUnit tests enabled
  327. will run and print the results at boot as a late-init call.
  328. 3. Using kunit_tool
  329. ~~~~~~~~~~~~~~~~~~~
  330. With ``CONFIG_KUNIT`` and ``CONFIG_KASAN_KUNIT_TEST`` built-in, it's also
  331. possible use ``kunit_tool`` to see the results of these and other KUnit tests
  332. in a more readable way. This will not print the KASAN reports of the tests that
  333. passed. Use `KUnit documentation <https://www.kernel.org/doc/html/latest/dev-tools/kunit/index.html>`_
  334. for more up-to-date information on ``kunit_tool``.
  335. .. _KUnit: https://www.kernel.org/doc/html/latest/dev-tools/kunit/index.html