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