Understanding KASAN: Kernel Address Sanitizer for Detecting Memory Errors in Linux
The article introduces KASAN, a Kernel Address Sanitizer for Linux that uses shadow memory and redzones to accurately detect out‑of‑bounds accesses, use‑after‑free, and double‑free errors, explains its underlying mechanisms, shows how to enable it in the kernel, and provides extensive example code and log analysis.
In the vast and complex "code jungle" of the Linux kernel, memory management is a critical and tricky area. Out‑of‑bounds memory errors are like hidden ghosts that can cause crashes or data corruption at any time, troubling developers and operators.
Traditional detection methods are inefficient and often miss subtle bugs. Manual debugging is time‑consuming and error‑prone.
KASAN (Kernel Address Sanitizer) brings a breakthrough by precisely locating such memory errors using powerful mechanisms.
1. KASAN Overview
KASAN is a Linux‑kernel tool that monitors memory usage, detecting out‑of‑bounds accesses and use‑after‑free situations.
These errors can lead to crashes, data loss, or security vulnerabilities that attackers may exploit.
As kernel code grows, memory bugs become harder to find; KASAN acts as a "fire‑eye" that quickly uncovers them, improving stability and security.
2. Powerful Features of KASAN
KASAN excels at three main checks: out‑of‑bounds access, use‑after‑free, and uninitialized memory.
2.1 Out‑of‑Bounds Detection
KASAN uses a shadow‑memory technique: for every 8 bytes of real memory, 1 byte of shadow memory records access permissions. When a program accesses memory, KASAN checks the corresponding shadow byte to verify legality.
Example: a network driver writes past a buffer; KASAN immediately reports the overflow with address, size, and stack trace.
2.2 Use‑After‑Free Detection
When memory is freed, KASAN marks its shadow byte as inaccessible. Any later access triggers a detailed error report.
Example: a device driver frees a buffer but later accesses it; KASAN catches the mistake and shows the call stack.
2.3 Uninitialized Memory Detection
KASAN tags newly allocated memory as uninitialized. Any read before proper initialization is reported.
Example: a filesystem driver reads from an uninitialized buffer; KASAN flags the issue.
3. How KASAN Works
KASAN adds extra memory (shadow memory) to track the state of each real memory byte. The shadow region uses a 1:8 ratio, meaning roughly 12.5% of RAM is reserved for bookkeeping.
Each 8‑byte block is represented by a shadow byte: 0x00 means fully accessible, values 1‑7 indicate partially accessible, and special values (e.g., 0xFC, 0xFB, 0xFF) mark redzones, freed memory, or other illegal states.
During every load or store, the compiler inserts KASAN checks that compute the shadow address (real address >> 3) and verify the shadow byte. If the check fails, KASAN aborts the operation and prints a report containing the faulting address, access size, type (read/write), and a full call trace.
4. Using KASAN
4.1 Enabling KASAN When Building the Kernel
1. Install build tools (gcc, make, etc.).
sudo apt-get update
sudo apt-get install build-essential libncurses-dev bison flex libssl-dev libelf-dev2. Download the kernel source.
wget https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.10.tar.xz
tar -xf linux-5.10.tar.xz
cd linux-5.103. Run make menuconfig and enable Kernel Address Sanitizer (KASAN) under Kernel Hacking → Memory Debugging . Optionally enable inline or outlined allocation for performance vs size trade‑offs.
4. Compile the kernel (e.g., make -j$(nproc) ).
5. Install modules and the new kernel ( make modules_install && make install ), then reboot.
4.2 Runtime Detection and Reporting
When the system runs with KASAN enabled, it automatically checks each memory access. Errors are logged to the kernel ring buffer and can be viewed with dmesg | grep -i kasan .
Typical log entries include the bug type, function name, offending address, access size, and a stack trace.
5. KASAN Example Source Code
The following module demonstrates various KASAN error types.
5.1 Out‑of‑Bounds Examples
#define KASAN_FREE_PAGE 0xFF /* page was freed */
#define KASAN_PAGE_REDZONE 0xFE /* redzone for kmalloc_large */
#define KASAN_KMALLOC_REDZONE 0xFC /* redzone inside slub object */
#define KASAN_KMALLOC_FREE 0xFB /* object was freed */
#define KASAN_GLOBAL_REDZONE 0xFA /* redzone for global variable */
static noinline void __init kmalloc_oob_right(void)
{
char *ptr;
size_t size = 123;
pr_info("out-of-bounds to right\n");
ptr = kmalloc(size, GFP_KERNEL);
if (!ptr) { pr_err("Allocation failed\n"); return; }
ptr[size] = 'x'; // overflow
kfree(ptr);
}
/* Additional functions kmalloc_oob_left, kmalloc_node_oob_right, ... */5.2 Use‑After‑Free Examples
static noinline void __init kmalloc_uaf(void)
{
char *ptr;
size_t size = 10;
pr_info("use-after-free\n");
ptr = kmalloc(size, GFP_KERNEL);
if (!ptr) { pr_err("Allocation failed\n"); return; }
kfree(ptr);
*(ptr + 8) = 'x'; // use after free
}5.3 Double‑Free Example
static noinline void __init kmalloc_double_free_test(void)
{
char *ptr;
size_t size = 123;
pr_info("double-free\n");
ptr = kmalloc(size, GFP_KERNEL);
if (!ptr) { pr_err("Allocation failed\n"); return; }
kfree(ptr);
kfree(ptr); // double free
}The module’s kmalloc_tests_init function sequentially invokes each test while KASAN’s multi‑shot mode is enabled, then returns -EAGAIN to keep the kernel alive for further testing.
6. Log Output and Analysis
Running insmod test_kasan.ko produces logs such as:
BUG: KASAN: use-after-free in kmalloc_uaf+0x84/0xb8 [test_kasan]
Write of size 1 at addr ffffffc0336d9208 by task insmod/1204
...The log shows the bug type, offending function, address, and a stack trace that points directly to the line where the illegal access occurs. Similar logs are generated for out‑of‑bounds and double‑free cases.
Using gdb with the module’s symbols allows developers to view the exact source line, e.g., *(ptr + 8) = 'x'; for a use‑after‑free.
7. Conclusion
KASAN provides a robust, kernel‑level memory debugging facility that dramatically simplifies the detection of memory safety bugs, improves kernel reliability, and helps prevent security vulnerabilities caused by out‑of‑bounds accesses, use‑after‑free, and uninitialized memory.
Deepin Linux
Research areas: Windows & Linux platforms, C/C++ backend development, embedded systems and Linux kernel, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.