kmsan.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. .. SPDX-License-Identifier: GPL-2.0
  2. .. Copyright (C) 2022, Google LLC.
  3. ===================================
  4. The Kernel Memory Sanitizer (KMSAN)
  5. ===================================
  6. KMSAN is a dynamic error detector aimed at finding uses of uninitialized
  7. values. It is based on compiler instrumentation, and is quite similar to the
  8. userspace `MemorySanitizer tool`_.
  9. An important note is that KMSAN is not intended for production use, because it
  10. drastically increases kernel memory footprint and slows the whole system down.
  11. Usage
  12. =====
  13. Building the kernel
  14. -------------------
  15. In order to build a kernel with KMSAN you will need a fresh Clang (14.0.6+).
  16. Please refer to `LLVM documentation`_ for the instructions on how to build Clang.
  17. Now configure and build the kernel with CONFIG_KMSAN enabled.
  18. Example report
  19. --------------
  20. Here is an example of a KMSAN report::
  21. =====================================================
  22. BUG: KMSAN: uninit-value in test_uninit_kmsan_check_memory+0x1be/0x380 [kmsan_test]
  23. test_uninit_kmsan_check_memory+0x1be/0x380 mm/kmsan/kmsan_test.c:273
  24. kunit_run_case_internal lib/kunit/test.c:333
  25. kunit_try_run_case+0x206/0x420 lib/kunit/test.c:374
  26. kunit_generic_run_threadfn_adapter+0x6d/0xc0 lib/kunit/try-catch.c:28
  27. kthread+0x721/0x850 kernel/kthread.c:327
  28. ret_from_fork+0x1f/0x30 ??:?
  29. Uninit was stored to memory at:
  30. do_uninit_local_array+0xfa/0x110 mm/kmsan/kmsan_test.c:260
  31. test_uninit_kmsan_check_memory+0x1a2/0x380 mm/kmsan/kmsan_test.c:271
  32. kunit_run_case_internal lib/kunit/test.c:333
  33. kunit_try_run_case+0x206/0x420 lib/kunit/test.c:374
  34. kunit_generic_run_threadfn_adapter+0x6d/0xc0 lib/kunit/try-catch.c:28
  35. kthread+0x721/0x850 kernel/kthread.c:327
  36. ret_from_fork+0x1f/0x30 ??:?
  37. Local variable uninit created at:
  38. do_uninit_local_array+0x4a/0x110 mm/kmsan/kmsan_test.c:256
  39. test_uninit_kmsan_check_memory+0x1a2/0x380 mm/kmsan/kmsan_test.c:271
  40. Bytes 4-7 of 8 are uninitialized
  41. Memory access of size 8 starts at ffff888083fe3da0
  42. CPU: 0 PID: 6731 Comm: kunit_try_catch Tainted: G B E 5.16.0-rc3+ #104
  43. Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.14.0-2 04/01/2014
  44. =====================================================
  45. The report says that the local variable ``uninit`` was created uninitialized in
  46. ``do_uninit_local_array()``. The third stack trace corresponds to the place
  47. where this variable was created.
  48. The first stack trace shows where the uninit value was used (in
  49. ``test_uninit_kmsan_check_memory()``). The tool shows the bytes which were left
  50. uninitialized in the local variable, as well as the stack where the value was
  51. copied to another memory location before use.
  52. A use of uninitialized value ``v`` is reported by KMSAN in the following cases:
  53. - in a condition, e.g. ``if (v) { ... }``;
  54. - in an indexing or pointer dereferencing, e.g. ``array[v]`` or ``*v``;
  55. - when it is copied to userspace or hardware, e.g. ``copy_to_user(..., &v, ...)``;
  56. - when it is passed as an argument to a function, and
  57. ``CONFIG_KMSAN_CHECK_PARAM_RETVAL`` is enabled (see below).
  58. The mentioned cases (apart from copying data to userspace or hardware, which is
  59. a security issue) are considered undefined behavior from the C11 Standard point
  60. of view.
  61. Disabling the instrumentation
  62. -----------------------------
  63. A function can be marked with ``__no_kmsan_checks``. Doing so makes KMSAN
  64. ignore uninitialized values in that function and mark its output as initialized.
  65. As a result, the user will not get KMSAN reports related to that function.
  66. Another function attribute supported by KMSAN is ``__no_sanitize_memory``.
  67. Applying this attribute to a function will result in KMSAN not instrumenting
  68. it, which can be helpful if we do not want the compiler to interfere with some
  69. low-level code (e.g. that marked with ``noinstr`` which implicitly adds
  70. ``__no_sanitize_memory``).
  71. This however comes at a cost: stack allocations from such functions will have
  72. incorrect shadow/origin values, likely leading to false positives. Functions
  73. called from non-instrumented code may also receive incorrect metadata for their
  74. parameters.
  75. As a rule of thumb, avoid using ``__no_sanitize_memory`` explicitly.
  76. It is also possible to disable KMSAN for a single file (e.g. main.o)::
  77. KMSAN_SANITIZE_main.o := n
  78. or for the whole directory::
  79. KMSAN_SANITIZE := n
  80. in the Makefile. Think of this as applying ``__no_sanitize_memory`` to every
  81. function in the file or directory. Most users won't need KMSAN_SANITIZE, unless
  82. their code gets broken by KMSAN (e.g. runs at early boot time).
  83. Support
  84. =======
  85. In order for KMSAN to work the kernel must be built with Clang, which so far is
  86. the only compiler that has KMSAN support. The kernel instrumentation pass is
  87. based on the userspace `MemorySanitizer tool`_.
  88. The runtime library only supports x86_64 at the moment.
  89. How KMSAN works
  90. ===============
  91. KMSAN shadow memory
  92. -------------------
  93. KMSAN associates a metadata byte (also called shadow byte) with every byte of
  94. kernel memory. A bit in the shadow byte is set iff the corresponding bit of the
  95. kernel memory byte is uninitialized. Marking the memory uninitialized (i.e.
  96. setting its shadow bytes to ``0xff``) is called poisoning, marking it
  97. initialized (setting the shadow bytes to ``0x00``) is called unpoisoning.
  98. When a new variable is allocated on the stack, it is poisoned by default by
  99. instrumentation code inserted by the compiler (unless it is a stack variable
  100. that is immediately initialized). Any new heap allocation done without
  101. ``__GFP_ZERO`` is also poisoned.
  102. Compiler instrumentation also tracks the shadow values as they are used along
  103. the code. When needed, instrumentation code invokes the runtime library in
  104. ``mm/kmsan/`` to persist shadow values.
  105. The shadow value of a basic or compound type is an array of bytes of the same
  106. length. When a constant value is written into memory, that memory is unpoisoned.
  107. When a value is read from memory, its shadow memory is also obtained and
  108. propagated into all the operations which use that value. For every instruction
  109. that takes one or more values the compiler generates code that calculates the
  110. shadow of the result depending on those values and their shadows.
  111. Example::
  112. int a = 0xff; // i.e. 0x000000ff
  113. int b;
  114. int c = a | b;
  115. In this case the shadow of ``a`` is ``0``, shadow of ``b`` is ``0xffffffff``,
  116. shadow of ``c`` is ``0xffffff00``. This means that the upper three bytes of
  117. ``c`` are uninitialized, while the lower byte is initialized.
  118. Origin tracking
  119. ---------------
  120. Every four bytes of kernel memory also have a so-called origin mapped to them.
  121. This origin describes the point in program execution at which the uninitialized
  122. value was created. Every origin is associated with either the full allocation
  123. stack (for heap-allocated memory), or the function containing the uninitialized
  124. variable (for locals).
  125. When an uninitialized variable is allocated on stack or heap, a new origin
  126. value is created, and that variable's origin is filled with that value. When a
  127. value is read from memory, its origin is also read and kept together with the
  128. shadow. For every instruction that takes one or more values, the origin of the
  129. result is one of the origins corresponding to any of the uninitialized inputs.
  130. If a poisoned value is written into memory, its origin is written to the
  131. corresponding storage as well.
  132. Example 1::
  133. int a = 42;
  134. int b;
  135. int c = a + b;
  136. In this case the origin of ``b`` is generated upon function entry, and is
  137. stored to the origin of ``c`` right before the addition result is written into
  138. memory.
  139. Several variables may share the same origin address, if they are stored in the
  140. same four-byte chunk. In this case every write to either variable updates the
  141. origin for all of them. We have to sacrifice precision in this case, because
  142. storing origins for individual bits (and even bytes) would be too costly.
  143. Example 2::
  144. int combine(short a, short b) {
  145. union ret_t {
  146. int i;
  147. short s[2];
  148. } ret;
  149. ret.s[0] = a;
  150. ret.s[1] = b;
  151. return ret.i;
  152. }
  153. If ``a`` is initialized and ``b`` is not, the shadow of the result would be
  154. 0xffff0000, and the origin of the result would be the origin of ``b``.
  155. ``ret.s[0]`` would have the same origin, but it will never be used, because
  156. that variable is initialized.
  157. If both function arguments are uninitialized, only the origin of the second
  158. argument is preserved.
  159. Origin chaining
  160. ~~~~~~~~~~~~~~~
  161. To ease debugging, KMSAN creates a new origin for every store of an
  162. uninitialized value to memory. The new origin references both its creation stack
  163. and the previous origin the value had. This may cause increased memory
  164. consumption, so we limit the length of origin chains in the runtime.
  165. Clang instrumentation API
  166. -------------------------
  167. Clang instrumentation pass inserts calls to functions defined in
  168. ``mm/kmsan/nstrumentation.c`` into the kernel code.
  169. Shadow manipulation
  170. ~~~~~~~~~~~~~~~~~~~
  171. For every memory access the compiler emits a call to a function that returns a
  172. pair of pointers to the shadow and origin addresses of the given memory::
  173. typedef struct {
  174. void *shadow, *origin;
  175. } shadow_origin_ptr_t
  176. shadow_origin_ptr_t __msan_metadata_ptr_for_load_{1,2,4,8}(void *addr)
  177. shadow_origin_ptr_t __msan_metadata_ptr_for_store_{1,2,4,8}(void *addr)
  178. shadow_origin_ptr_t __msan_metadata_ptr_for_load_n(void *addr, uintptr_t size)
  179. shadow_origin_ptr_t __msan_metadata_ptr_for_store_n(void *addr, uintptr_t size)
  180. The function name depends on the memory access size.
  181. The compiler makes sure that for every loaded value its shadow and origin
  182. values are read from memory. When a value is stored to memory, its shadow and
  183. origin are also stored using the metadata pointers.
  184. Handling locals
  185. ~~~~~~~~~~~~~~~
  186. A special function is used to create a new origin value for a local variable and
  187. set the origin of that variable to that value::
  188. void __msan_poison_alloca(void *addr, uintptr_t size, char *descr)
  189. Access to per-task data
  190. ~~~~~~~~~~~~~~~~~~~~~~~
  191. At the beginning of every instrumented function KMSAN inserts a call to
  192. ``__msan_get_context_state()``::
  193. kmsan_context_state *__msan_get_context_state(void)
  194. ``kmsan_context_state`` is declared in ``include/linux/kmsan.h``::
  195. struct kmsan_context_state {
  196. char param_tls[KMSAN_PARAM_SIZE];
  197. char retval_tls[KMSAN_RETVAL_SIZE];
  198. char va_arg_tls[KMSAN_PARAM_SIZE];
  199. char va_arg_origin_tls[KMSAN_PARAM_SIZE];
  200. u64 va_arg_overflow_size_tls;
  201. char param_origin_tls[KMSAN_PARAM_SIZE];
  202. depot_stack_handle_t retval_origin_tls;
  203. };
  204. This structure is used by KMSAN to pass parameter shadows and origins between
  205. instrumented functions (unless the parameters are checked immediately by
  206. ``CONFIG_KMSAN_CHECK_PARAM_RETVAL``).
  207. Passing uninitialized values to functions
  208. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  209. Clang's MemorySanitizer instrumentation has an option,
  210. ``-fsanitize-memory-param-retval``, which makes the compiler check function
  211. parameters passed by value, as well as function return values.
  212. The option is controlled by ``CONFIG_KMSAN_CHECK_PARAM_RETVAL``, which is
  213. enabled by default to let KMSAN report uninitialized values earlier.
  214. Please refer to the `LKML discussion`_ for more details.
  215. Because of the way the checks are implemented in LLVM (they are only applied to
  216. parameters marked as ``noundef``), not all parameters are guaranteed to be
  217. checked, so we cannot give up the metadata storage in ``kmsan_context_state``.
  218. String functions
  219. ~~~~~~~~~~~~~~~~
  220. The compiler replaces calls to ``memcpy()``/``memmove()``/``memset()`` with the
  221. following functions. These functions are also called when data structures are
  222. initialized or copied, making sure shadow and origin values are copied alongside
  223. with the data::
  224. void *__msan_memcpy(void *dst, void *src, uintptr_t n)
  225. void *__msan_memmove(void *dst, void *src, uintptr_t n)
  226. void *__msan_memset(void *dst, int c, uintptr_t n)
  227. Error reporting
  228. ~~~~~~~~~~~~~~~
  229. For each use of a value the compiler emits a shadow check that calls
  230. ``__msan_warning()`` in the case that value is poisoned::
  231. void __msan_warning(u32 origin)
  232. ``__msan_warning()`` causes KMSAN runtime to print an error report.
  233. Inline assembly instrumentation
  234. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  235. KMSAN instruments every inline assembly output with a call to::
  236. void __msan_instrument_asm_store(void *addr, uintptr_t size)
  237. , which unpoisons the memory region.
  238. This approach may mask certain errors, but it also helps to avoid a lot of
  239. false positives in bitwise operations, atomics etc.
  240. Sometimes the pointers passed into inline assembly do not point to valid memory.
  241. In such cases they are ignored at runtime.
  242. Runtime library
  243. ---------------
  244. The code is located in ``mm/kmsan/``.
  245. Per-task KMSAN state
  246. ~~~~~~~~~~~~~~~~~~~~
  247. Every task_struct has an associated KMSAN task state that holds the KMSAN
  248. context (see above) and a per-task flag disallowing KMSAN reports::
  249. struct kmsan_context {
  250. ...
  251. bool allow_reporting;
  252. struct kmsan_context_state cstate;
  253. ...
  254. }
  255. struct task_struct {
  256. ...
  257. struct kmsan_context kmsan;
  258. ...
  259. }
  260. KMSAN contexts
  261. ~~~~~~~~~~~~~~
  262. When running in a kernel task context, KMSAN uses ``current->kmsan.cstate`` to
  263. hold the metadata for function parameters and return values.
  264. But in the case the kernel is running in the interrupt, softirq or NMI context,
  265. where ``current`` is unavailable, KMSAN switches to per-cpu interrupt state::
  266. DEFINE_PER_CPU(struct kmsan_ctx, kmsan_percpu_ctx);
  267. Metadata allocation
  268. ~~~~~~~~~~~~~~~~~~~
  269. There are several places in the kernel for which the metadata is stored.
  270. 1. Each ``struct page`` instance contains two pointers to its shadow and
  271. origin pages::
  272. struct page {
  273. ...
  274. struct page *shadow, *origin;
  275. ...
  276. };
  277. At boot-time, the kernel allocates shadow and origin pages for every available
  278. kernel page. This is done quite late, when the kernel address space is already
  279. fragmented, so normal data pages may arbitrarily interleave with the metadata
  280. pages.
  281. This means that in general for two contiguous memory pages their shadow/origin
  282. pages may not be contiguous. Consequently, if a memory access crosses the
  283. boundary of a memory block, accesses to shadow/origin memory may potentially
  284. corrupt other pages or read incorrect values from them.
  285. In practice, contiguous memory pages returned by the same ``alloc_pages()``
  286. call will have contiguous metadata, whereas if these pages belong to two
  287. different allocations their metadata pages can be fragmented.
  288. For the kernel data (``.data``, ``.bss`` etc.) and percpu memory regions
  289. there also are no guarantees on metadata contiguity.
  290. In the case ``__msan_metadata_ptr_for_XXX_YYY()`` hits the border between two
  291. pages with non-contiguous metadata, it returns pointers to fake shadow/origin regions::
  292. char dummy_load_page[PAGE_SIZE] __attribute__((aligned(PAGE_SIZE)));
  293. char dummy_store_page[PAGE_SIZE] __attribute__((aligned(PAGE_SIZE)));
  294. ``dummy_load_page`` is zero-initialized, so reads from it always yield zeroes.
  295. All stores to ``dummy_store_page`` are ignored.
  296. 2. For vmalloc memory and modules, there is a direct mapping between the memory
  297. range, its shadow and origin. KMSAN reduces the vmalloc area by 3/4, making only
  298. the first quarter available to ``vmalloc()``. The second quarter of the vmalloc
  299. area contains shadow memory for the first quarter, the third one holds the
  300. origins. A small part of the fourth quarter contains shadow and origins for the
  301. kernel modules. Please refer to ``arch/x86/include/asm/pgtable_64_types.h`` for
  302. more details.
  303. When an array of pages is mapped into a contiguous virtual memory space, their
  304. shadow and origin pages are similarly mapped into contiguous regions.
  305. References
  306. ==========
  307. E. Stepanov, K. Serebryany. `MemorySanitizer: fast detector of uninitialized
  308. memory use in C++
  309. <https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/43308.pdf>`_.
  310. In Proceedings of CGO 2015.
  311. .. _MemorySanitizer tool: https://clang.llvm.org/docs/MemorySanitizer.html
  312. .. _LLVM documentation: https://llvm.org/docs/GettingStarted.html
  313. .. _LKML discussion: https://lore.kernel.org/all/[email protected]/