Hasty Briefsbeta

Bilingual

Poison, redzones and shadows: inside KASAN

2 days ago
  • #Memory Sanitizer
  • #Kernel Security
  • #Linux Development
  • The Linux kernel primarily uses C, which is prone to memory errors like undefined behavior and buffer overflows, necessitating tools like KASAN for early detection.
  • KASAN (Kernel Address Sanitizer) is a runtime checker that detects out-of-bounds accesses and use-after-free errors, requiring build-time compiler instrumentation and shadow memory for tracking.
  • Enabling KASAN involves setting CONFIG_KASAN, with tunable parameters like inline vs. outlined instrumentation, hardware support, and memory type tracking (e.g., vmalloc, stack).
  • A virtualized setup with virtme-ng allows safe testing of KASAN, including loading kasan_test module to generate detailed error reports with stack traces and memory state information.
  • KASAN uses shadow memory, reserving 1/8 of system memory to track kernel memory state, with a direct mapping formula: shadow_byte = (target_addr >> 3) + KASAN_SHADOW_OFFSET.
  • Shadow memory values indicate accessibility: 0x00 means fully accessible, while positive values (e.g., 0x03) indicate partial accessibility, and negative values mark inaccessible regions.
  • Memory is 'unpoisoned' (shadow set to 0) on allocation and 'poisoned' (marked with tags like KASAN_SLAB_FREE) on deallocation, with redzones to catch overflows.
  • Compiler instrumentation adds checks before memory accesses via functions like __asan_load8 or inline code, with options for outline (call-based) or inline (code-expanded) modes affecting performance and size.
  • KASAN also covers global variables, stack memory (via CONFIG_KASAN_STACK), and uses quarantine for use-after-free detection, with architecture-specific variants (e.g., tag-based) for reduced overhead.