self-protection.txt 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. # Kernel Self-Protection
  2. Kernel self-protection is the design and implementation of systems and
  3. structures within the Linux kernel to protect against security flaws in
  4. the kernel itself. This covers a wide range of issues, including removing
  5. entire classes of bugs, blocking security flaw exploitation methods,
  6. and actively detecting attack attempts. Not all topics are explored in
  7. this document, but it should serve as a reasonable starting point and
  8. answer any frequently asked questions. (Patches welcome, of course!)
  9. In the worst-case scenario, we assume an unprivileged local attacker
  10. has arbitrary read and write access to the kernel's memory. In many
  11. cases, bugs being exploited will not provide this level of access,
  12. but with systems in place that defend against the worst case we'll
  13. cover the more limited cases as well. A higher bar, and one that should
  14. still be kept in mind, is protecting the kernel against a _privileged_
  15. local attacker, since the root user has access to a vastly increased
  16. attack surface. (Especially when they have the ability to load arbitrary
  17. kernel modules.)
  18. The goals for successful self-protection systems would be that they
  19. are effective, on by default, require no opt-in by developers, have no
  20. performance impact, do not impede kernel debugging, and have tests. It
  21. is uncommon that all these goals can be met, but it is worth explicitly
  22. mentioning them, since these aspects need to be explored, dealt with,
  23. and/or accepted.
  24. ## Attack Surface Reduction
  25. The most fundamental defense against security exploits is to reduce the
  26. areas of the kernel that can be used to redirect execution. This ranges
  27. from limiting the exposed APIs available to userspace, making in-kernel
  28. APIs hard to use incorrectly, minimizing the areas of writable kernel
  29. memory, etc.
  30. ### Strict kernel memory permissions
  31. When all of kernel memory is writable, it becomes trivial for attacks
  32. to redirect execution flow. To reduce the availability of these targets
  33. the kernel needs to protect its memory with a tight set of permissions.
  34. #### Executable code and read-only data must not be writable
  35. Any areas of the kernel with executable memory must not be writable.
  36. While this obviously includes the kernel text itself, we must consider
  37. all additional places too: kernel modules, JIT memory, etc. (There are
  38. temporary exceptions to this rule to support things like instruction
  39. alternatives, breakpoints, kprobes, etc. If these must exist in a
  40. kernel, they are implemented in a way where the memory is temporarily
  41. made writable during the update, and then returned to the original
  42. permissions.)
  43. In support of this are (the poorly named) CONFIG_DEBUG_RODATA and
  44. CONFIG_DEBUG_SET_MODULE_RONX, which seek to make sure that code is not
  45. writable, data is not executable, and read-only data is neither writable
  46. nor executable.
  47. #### Function pointers and sensitive variables must not be writable
  48. Vast areas of kernel memory contain function pointers that are looked
  49. up by the kernel and used to continue execution (e.g. descriptor/vector
  50. tables, file/network/etc operation structures, etc). The number of these
  51. variables must be reduced to an absolute minimum.
  52. Many such variables can be made read-only by setting them "const"
  53. so that they live in the .rodata section instead of the .data section
  54. of the kernel, gaining the protection of the kernel's strict memory
  55. permissions as described above.
  56. For variables that are initialized once at __init time, these can
  57. be marked with the (new and under development) __ro_after_init
  58. attribute.
  59. What remains are variables that are updated rarely (e.g. GDT). These
  60. will need another infrastructure (similar to the temporary exceptions
  61. made to kernel code mentioned above) that allow them to spend the rest
  62. of their lifetime read-only. (For example, when being updated, only the
  63. CPU thread performing the update would be given uninterruptible write
  64. access to the memory.)
  65. #### Segregation of kernel memory from userspace memory
  66. The kernel must never execute userspace memory. The kernel must also never
  67. access userspace memory without explicit expectation to do so. These
  68. rules can be enforced either by support of hardware-based restrictions
  69. (x86's SMEP/SMAP, ARM's PXN/PAN) or via emulation (ARM's Memory Domains).
  70. By blocking userspace memory in this way, execution and data parsing
  71. cannot be passed to trivially-controlled userspace memory, forcing
  72. attacks to operate entirely in kernel memory.
  73. ### Reduced access to syscalls
  74. One trivial way to eliminate many syscalls for 64-bit systems is building
  75. without CONFIG_COMPAT. However, this is rarely a feasible scenario.
  76. The "seccomp" system provides an opt-in feature made available to
  77. userspace, which provides a way to reduce the number of kernel entry
  78. points available to a running process. This limits the breadth of kernel
  79. code that can be reached, possibly reducing the availability of a given
  80. bug to an attack.
  81. An area of improvement would be creating viable ways to keep access to
  82. things like compat, user namespaces, BPF creation, and perf limited only
  83. to trusted processes. This would keep the scope of kernel entry points
  84. restricted to the more regular set of normally available to unprivileged
  85. userspace.
  86. ### Restricting access to kernel modules
  87. The kernel should never allow an unprivileged user the ability to
  88. load specific kernel modules, since that would provide a facility to
  89. unexpectedly extend the available attack surface. (The on-demand loading
  90. of modules via their predefined subsystems, e.g. MODULE_ALIAS_*, is
  91. considered "expected" here, though additional consideration should be
  92. given even to these.) For example, loading a filesystem module via an
  93. unprivileged socket API is nonsense: only the root or physically local
  94. user should trigger filesystem module loading. (And even this can be up
  95. for debate in some scenarios.)
  96. To protect against even privileged users, systems may need to either
  97. disable module loading entirely (e.g. monolithic kernel builds or
  98. modules_disabled sysctl), or provide signed modules (e.g.
  99. CONFIG_MODULE_SIG_FORCE, or dm-crypt with LoadPin), to keep from having
  100. root load arbitrary kernel code via the module loader interface.
  101. ## Memory integrity
  102. There are many memory structures in the kernel that are regularly abused
  103. to gain execution control during an attack, By far the most commonly
  104. understood is that of the stack buffer overflow in which the return
  105. address stored on the stack is overwritten. Many other examples of this
  106. kind of attack exist, and protections exist to defend against them.
  107. ### Stack buffer overflow
  108. The classic stack buffer overflow involves writing past the expected end
  109. of a variable stored on the stack, ultimately writing a controlled value
  110. to the stack frame's stored return address. The most widely used defense
  111. is the presence of a stack canary between the stack variables and the
  112. return address (CONFIG_CC_STACKPROTECTOR), which is verified just before
  113. the function returns. Other defenses include things like shadow stacks.
  114. ### Stack depth overflow
  115. A less well understood attack is using a bug that triggers the
  116. kernel to consume stack memory with deep function calls or large stack
  117. allocations. With this attack it is possible to write beyond the end of
  118. the kernel's preallocated stack space and into sensitive structures. Two
  119. important changes need to be made for better protections: moving the
  120. sensitive thread_info structure elsewhere, and adding a faulting memory
  121. hole at the bottom of the stack to catch these overflows.
  122. ### Heap memory integrity
  123. The structures used to track heap free lists can be sanity-checked during
  124. allocation and freeing to make sure they aren't being used to manipulate
  125. other memory areas.
  126. ### Counter integrity
  127. Many places in the kernel use atomic counters to track object references
  128. or perform similar lifetime management. When these counters can be made
  129. to wrap (over or under) this traditionally exposes a use-after-free
  130. flaw. By trapping atomic wrapping, this class of bug vanishes.
  131. ### Size calculation overflow detection
  132. Similar to counter overflow, integer overflows (usually size calculations)
  133. need to be detected at runtime to kill this class of bug, which
  134. traditionally leads to being able to write past the end of kernel buffers.
  135. ## Statistical defenses
  136. While many protections can be considered deterministic (e.g. read-only
  137. memory cannot be written to), some protections provide only statistical
  138. defense, in that an attack must gather enough information about a
  139. running system to overcome the defense. While not perfect, these do
  140. provide meaningful defenses.
  141. ### Canaries, blinding, and other secrets
  142. It should be noted that things like the stack canary discussed earlier
  143. are technically statistical defenses, since they rely on a secret value,
  144. and such values may become discoverable through an information exposure
  145. flaw.
  146. Blinding literal values for things like JITs, where the executable
  147. contents may be partially under the control of userspace, need a similar
  148. secret value.
  149. It is critical that the secret values used must be separate (e.g.
  150. different canary per stack) and high entropy (e.g. is the RNG actually
  151. working?) in order to maximize their success.
  152. ### Kernel Address Space Layout Randomization (KASLR)
  153. Since the location of kernel memory is almost always instrumental in
  154. mounting a successful attack, making the location non-deterministic
  155. raises the difficulty of an exploit. (Note that this in turn makes
  156. the value of information exposures higher, since they may be used to
  157. discover desired memory locations.)
  158. #### Text and module base
  159. By relocating the physical and virtual base address of the kernel at
  160. boot-time (CONFIG_RANDOMIZE_BASE), attacks needing kernel code will be
  161. frustrated. Additionally, offsetting the module loading base address
  162. means that even systems that load the same set of modules in the same
  163. order every boot will not share a common base address with the rest of
  164. the kernel text.
  165. #### Stack base
  166. If the base address of the kernel stack is not the same between processes,
  167. or even not the same between syscalls, targets on or beyond the stack
  168. become more difficult to locate.
  169. #### Dynamic memory base
  170. Much of the kernel's dynamic memory (e.g. kmalloc, vmalloc, etc) ends up
  171. being relatively deterministic in layout due to the order of early-boot
  172. initializations. If the base address of these areas is not the same
  173. between boots, targeting them is frustrated, requiring an information
  174. exposure specific to the region.
  175. #### Structure layout
  176. By performing a per-build randomization of the layout of sensitive
  177. structures, attacks must either be tuned to known kernel builds or expose
  178. enough kernel memory to determine structure layouts before manipulating
  179. them.
  180. ## Preventing Information Exposures
  181. Since the locations of sensitive structures are the primary target for
  182. attacks, it is important to defend against exposure of both kernel memory
  183. addresses and kernel memory contents (since they may contain kernel
  184. addresses or other sensitive things like canary values).
  185. ### Unique identifiers
  186. Kernel memory addresses must never be used as identifiers exposed to
  187. userspace. Instead, use an atomic counter, an idr, or similar unique
  188. identifier.
  189. ### Memory initialization
  190. Memory copied to userspace must always be fully initialized. If not
  191. explicitly memset(), this will require changes to the compiler to make
  192. sure structure holes are cleared.
  193. ### Memory poisoning
  194. When releasing memory, it is best to poison the contents (clear stack on
  195. syscall return, wipe heap memory on a free), to avoid reuse attacks that
  196. rely on the old contents of memory. This frustrates many uninitialized
  197. variable attacks, stack content exposures, heap content exposures, and
  198. use-after-free attacks.
  199. ### Destination tracking
  200. To help kill classes of bugs that result in kernel addresses being
  201. written to userspace, the destination of writes needs to be tracked. If
  202. the buffer is destined for userspace (e.g. seq_file backed /proc files),
  203. it should automatically censor sensitive values.