kmsan.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. .. SPDX-License-Identifier: GPL-2.0
  2. .. Copyright (C) 2022, Google LLC.
  3. ===============================
  4. 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. KMSAN checks can also be temporarily disabled for the current task using
  84. ``kmsan_disable_current()`` and ``kmsan_enable_current()`` calls. Each
  85. ``kmsan_enable_current()`` call must be preceded by a
  86. ``kmsan_disable_current()`` call; these call pairs may be nested. One needs to
  87. be careful with these calls, keeping the regions short and preferring other
  88. ways to disable instrumentation, where possible.
  89. Support
  90. =======
  91. In order for KMSAN to work the kernel must be built with Clang, which so far is
  92. the only compiler that has KMSAN support. The kernel instrumentation pass is
  93. based on the userspace `MemorySanitizer tool`_.
  94. The runtime library only supports x86_64 at the moment.
  95. How KMSAN works
  96. ===============
  97. KMSAN shadow memory
  98. -------------------
  99. KMSAN associates a metadata byte (also called shadow byte) with every byte of
  100. kernel memory. A bit in the shadow byte is set iff the corresponding bit of the
  101. kernel memory byte is uninitialized. Marking the memory uninitialized (i.e.
  102. setting its shadow bytes to ``0xff``) is called poisoning, marking it
  103. initialized (setting the shadow bytes to ``0x00``) is called unpoisoning.
  104. When a new variable is allocated on the stack, it is poisoned by default by
  105. instrumentation code inserted by the compiler (unless it is a stack variable
  106. that is immediately initialized). Any new heap allocation done without
  107. ``__GFP_ZERO`` is also poisoned.
  108. Compiler instrumentation also tracks the shadow values as they are used along
  109. the code. When needed, instrumentation code invokes the runtime library in
  110. ``mm/kmsan/`` to persist shadow values.
  111. The shadow value of a basic or compound type is an array of bytes of the same
  112. length. When a constant value is written into memory, that memory is unpoisoned.
  113. When a value is read from memory, its shadow memory is also obtained and
  114. propagated into all the operations which use that value. For every instruction
  115. that takes one or more values the compiler generates code that calculates the
  116. shadow of the result depending on those values and their shadows.
  117. Example::
  118. int a = 0xff; // i.e. 0x000000ff
  119. int b;
  120. int c = a | b;
  121. In this case the shadow of ``a`` is ``0``, shadow of ``b`` is ``0xffffffff``,
  122. shadow of ``c`` is ``0xffffff00``. This means that the upper three bytes of
  123. ``c`` are uninitialized, while the lower byte is initialized.
  124. Origin tracking
  125. ---------------
  126. Every four bytes of kernel memory also have a so-called origin mapped to them.
  127. This origin describes the point in program execution at which the uninitialized
  128. value was created. Every origin is associated with either the full allocation
  129. stack (for heap-allocated memory), or the function containing the uninitialized
  130. variable (for locals).
  131. When an uninitialized variable is allocated on stack or heap, a new origin
  132. value is created, and that variable's origin is filled with that value. When a
  133. value is read from memory, its origin is also read and kept together with the
  134. shadow. For every instruction that takes one or more values, the origin of the
  135. result is one of the origins corresponding to any of the uninitialized inputs.
  136. If a poisoned value is written into memory, its origin is written to the
  137. corresponding storage as well.
  138. Example 1::
  139. int a = 42;
  140. int b;
  141. int c = a + b;
  142. In this case the origin of ``b`` is generated upon function entry, and is
  143. stored to the origin of ``c`` right before the addition result is written into
  144. memory.
  145. Several variables may share the same origin address, if they are stored in the
  146. same four-byte chunk. In this case every write to either variable updates the
  147. origin for all of them. We have to sacrifice precision in this case, because
  148. storing origins for individual bits (and even bytes) would be too costly.
  149. Example 2::
  150. int combine(short a, short b) {
  151. union ret_t {
  152. int i;
  153. short s[2];
  154. } ret;
  155. ret.s[0] = a;
  156. ret.s[1] = b;
  157. return ret.i;
  158. }
  159. If ``a`` is initialized and ``b`` is not, the shadow of the result would be
  160. 0xffff0000, and the origin of the result would be the origin of ``b``.
  161. ``ret.s[0]`` would have the same origin, but it will never be used, because
  162. that variable is initialized.
  163. If both function arguments are uninitialized, only the origin of the second
  164. argument is preserved.
  165. Origin chaining
  166. ~~~~~~~~~~~~~~~
  167. To ease debugging, KMSAN creates a new origin for every store of an
  168. uninitialized value to memory. The new origin references both its creation stack
  169. and the previous origin the value had. This may cause increased memory
  170. consumption, so we limit the length of origin chains in the runtime.
  171. Clang instrumentation API
  172. -------------------------
  173. Clang instrumentation pass inserts calls to functions defined in
  174. ``mm/kmsan/nstrumentation.c`` into the kernel code.
  175. Shadow manipulation
  176. ~~~~~~~~~~~~~~~~~~~
  177. For every memory access the compiler emits a call to a function that returns a
  178. pair of pointers to the shadow and origin addresses of the given memory::
  179. typedef struct {
  180. void *shadow, *origin;
  181. } shadow_origin_ptr_t
  182. shadow_origin_ptr_t __msan_metadata_ptr_for_load_{1,2,4,8}(void *addr)
  183. shadow_origin_ptr_t __msan_metadata_ptr_for_store_{1,2,4,8}(void *addr)
  184. shadow_origin_ptr_t __msan_metadata_ptr_for_load_n(void *addr, uintptr_t size)
  185. shadow_origin_ptr_t __msan_metadata_ptr_for_store_n(void *addr, uintptr_t size)
  186. The function name depends on the memory access size.
  187. The compiler makes sure that for every loaded value its shadow and origin
  188. values are read from memory. When a value is stored to memory, its shadow and
  189. origin are also stored using the metadata pointers.
  190. Handling locals
  191. ~~~~~~~~~~~~~~~
  192. A special function is used to create a new origin value for a local variable and
  193. set the origin of that variable to that value::
  194. void __msan_poison_alloca(void *addr, uintptr_t size, char *descr)
  195. Access to per-task data
  196. ~~~~~~~~~~~~~~~~~~~~~~~
  197. At the beginning of every instrumented function KMSAN inserts a call to
  198. ``__msan_get_context_state()``::
  199. kmsan_context_state *__msan_get_context_state(void)
  200. ``kmsan_context_state`` is declared in ``include/linux/kmsan.h``::
  201. struct kmsan_context_state {
  202. char param_tls[KMSAN_PARAM_SIZE];
  203. char retval_tls[KMSAN_RETVAL_SIZE];
  204. char va_arg_tls[KMSAN_PARAM_SIZE];
  205. char va_arg_origin_tls[KMSAN_PARAM_SIZE];
  206. u64 va_arg_overflow_size_tls;
  207. char param_origin_tls[KMSAN_PARAM_SIZE];
  208. depot_stack_handle_t retval_origin_tls;
  209. };
  210. This structure is used by KMSAN to pass parameter shadows and origins between
  211. instrumented functions (unless the parameters are checked immediately by
  212. ``CONFIG_KMSAN_CHECK_PARAM_RETVAL``).
  213. Passing uninitialized values to functions
  214. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  215. Clang's MemorySanitizer instrumentation has an option,
  216. ``-fsanitize-memory-param-retval``, which makes the compiler check function
  217. parameters passed by value, as well as function return values.
  218. The option is controlled by ``CONFIG_KMSAN_CHECK_PARAM_RETVAL``, which is
  219. enabled by default to let KMSAN report uninitialized values earlier.
  220. Please refer to the `LKML discussion`_ for more details.
  221. Because of the way the checks are implemented in LLVM (they are only applied to
  222. parameters marked as ``noundef``), not all parameters are guaranteed to be
  223. checked, so we cannot give up the metadata storage in ``kmsan_context_state``.
  224. String functions
  225. ~~~~~~~~~~~~~~~~
  226. The compiler replaces calls to ``memcpy()``/``memmove()``/``memset()`` with the
  227. following functions. These functions are also called when data structures are
  228. initialized or copied, making sure shadow and origin values are copied alongside
  229. with the data::
  230. void *__msan_memcpy(void *dst, void *src, uintptr_t n)
  231. void *__msan_memmove(void *dst, void *src, uintptr_t n)
  232. void *__msan_memset(void *dst, int c, uintptr_t n)
  233. Error reporting
  234. ~~~~~~~~~~~~~~~
  235. For each use of a value the compiler emits a shadow check that calls
  236. ``__msan_warning()`` in the case that value is poisoned::
  237. void __msan_warning(u32 origin)
  238. ``__msan_warning()`` causes KMSAN runtime to print an error report.
  239. Inline assembly instrumentation
  240. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  241. KMSAN instruments every inline assembly output with a call to::
  242. void __msan_instrument_asm_store(void *addr, uintptr_t size)
  243. , which unpoisons the memory region.
  244. This approach may mask certain errors, but it also helps to avoid a lot of
  245. false positives in bitwise operations, atomics etc.
  246. Sometimes the pointers passed into inline assembly do not point to valid memory.
  247. In such cases they are ignored at runtime.
  248. Runtime library
  249. ---------------
  250. The code is located in ``mm/kmsan/``.
  251. Per-task KMSAN state
  252. ~~~~~~~~~~~~~~~~~~~~
  253. Every task_struct has an associated KMSAN task state that holds the KMSAN
  254. context (see above) and a per-task counter disallowing KMSAN reports::
  255. struct kmsan_context {
  256. ...
  257. unsigned int depth;
  258. struct kmsan_context_state cstate;
  259. ...
  260. }
  261. struct task_struct {
  262. ...
  263. struct kmsan_context kmsan;
  264. ...
  265. }
  266. KMSAN contexts
  267. ~~~~~~~~~~~~~~
  268. When running in a kernel task context, KMSAN uses ``current->kmsan.cstate`` to
  269. hold the metadata for function parameters and return values.
  270. But in the case the kernel is running in the interrupt, softirq or NMI context,
  271. where ``current`` is unavailable, KMSAN switches to per-cpu interrupt state::
  272. DEFINE_PER_CPU(struct kmsan_ctx, kmsan_percpu_ctx);
  273. Metadata allocation
  274. ~~~~~~~~~~~~~~~~~~~
  275. There are several places in the kernel for which the metadata is stored.
  276. 1. Each ``struct page`` instance contains two pointers to its shadow and
  277. origin pages::
  278. struct page {
  279. ...
  280. struct page *shadow, *origin;
  281. ...
  282. };
  283. At boot-time, the kernel allocates shadow and origin pages for every available
  284. kernel page. This is done quite late, when the kernel address space is already
  285. fragmented, so normal data pages may arbitrarily interleave with the metadata
  286. pages.
  287. This means that in general for two contiguous memory pages their shadow/origin
  288. pages may not be contiguous. Consequently, if a memory access crosses the
  289. boundary of a memory block, accesses to shadow/origin memory may potentially
  290. corrupt other pages or read incorrect values from them.
  291. In practice, contiguous memory pages returned by the same ``alloc_pages()``
  292. call will have contiguous metadata, whereas if these pages belong to two
  293. different allocations their metadata pages can be fragmented.
  294. For the kernel data (``.data``, ``.bss`` etc.) and percpu memory regions
  295. there also are no guarantees on metadata contiguity.
  296. In the case ``__msan_metadata_ptr_for_XXX_YYY()`` hits the border between two
  297. pages with non-contiguous metadata, it returns pointers to fake shadow/origin regions::
  298. char dummy_load_page[PAGE_SIZE] __attribute__((aligned(PAGE_SIZE)));
  299. char dummy_store_page[PAGE_SIZE] __attribute__((aligned(PAGE_SIZE)));
  300. ``dummy_load_page`` is zero-initialized, so reads from it always yield zeroes.
  301. All stores to ``dummy_store_page`` are ignored.
  302. 2. For vmalloc memory and modules, there is a direct mapping between the memory
  303. range, its shadow and origin. KMSAN reduces the vmalloc area by 3/4, making only
  304. the first quarter available to ``vmalloc()``. The second quarter of the vmalloc
  305. area contains shadow memory for the first quarter, the third one holds the
  306. origins. A small part of the fourth quarter contains shadow and origins for the
  307. kernel modules. Please refer to ``arch/x86/include/asm/pgtable_64_types.h`` for
  308. more details.
  309. When an array of pages is mapped into a contiguous virtual memory space, their
  310. shadow and origin pages are similarly mapped into contiguous regions.
  311. References
  312. ==========
  313. E. Stepanov, K. Serebryany. `MemorySanitizer: fast detector of uninitialized
  314. memory use in C++
  315. <https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/43308.pdf>`_.
  316. In Proceedings of CGO 2015.
  317. .. _MemorySanitizer tool: https://clang.llvm.org/docs/MemorySanitizer.html
  318. .. _LLVM documentation: https://llvm.org/docs/GettingStarted.html
  319. .. _LKML discussion: https://lore.kernel.org/all/20220614144853.3693273-1-glider@google.com/