The in-development Linux kernel 5.12 includes the implementation of the KFence (Kernel Electric Fence) mechanism, which checks memory operations by detecting buffer overflows, accesses to freed memory, and other similar errors.
This functionality was previously available in the kernel as the KASAN (kernel address sanitizer) build option β however, it was primarily positioned for debugging purposes. The KFence subsystem differs from KASAN in its high operational speed, allowing this feature to be used even in kernels of production systems.
Using it in production systems will enable the detection of memory operation errors that do not manifest during test runs and only appear under heavy workloads or prolonged operation (with high uptime). Additionally, applying KFence in production systems will significantly increase the number of machines involved in testing the kernel's memory operations.
Minimal overhead, independent of load, is achieved in KFence by inserting guard pages into the heap at fixed intervals. After the expiration of the current guard interval, KFence adds another guard page from the KFence object pool through the standard memory allocation system (SLAB or SLUB allocator) and starts a new time counter. Each KFence object is placed on a separate memory page, with the memory pages along the left and right edges forming the guard pages, the size of which is selected randomly.
Thus, pages containing objects are separated by guard pages, which are configured to generate a "page fault" on any access. To detect write operations that exceed buffer boundaries within object pages, additional "red zones" based on patterns are used, occupying memory not utilized by the objects, remaining due to memory page alignment. β+ββββ+ββββ+ββββ+ββββ+ββββ+β | xxxxxxxxx | O : | xxxxxxxxx | : O | xxxxxxxxx | | xxxxxxxxx | B : | xxxxxxxxx | : B | xxxxxxxxx | | x GUARD x | J : RED- | x GUARD x | RED- : J | x GUARD x | | xxxxxxxxx | E : ZONE | xxxxxxxxx | ZONE : E | xxxxxxxxx | | xxxxxxxxx | C : | xxxxxxxxx | : C | xxxxxxxxx | | xxxxxxxxx | T : | xxxxxxxxx | : T | xxxxxxxxx | β+ββββ+ββββ+ββββ+ββββ+ββββ+β
If an attempt is made to access an area beyond the buffer boundaries, the operation affects the protection page, resulting in the generation of a "page fault," which is intercepted by KFence and logs data about the identified issue. By default, KFence does not block the error and only logs a warning, but there is a setting called "panic_on_warn" that allows the kernel to enter a crash state in case of an error.
Source: opennet.ru
