digital forensics

Analyzing Linux Kernel Rootkits

Detect kernel-level rootkits in Linux memory dumps using Volatility3 linux plugins (check_syscall, lsmod, hidden_modules), rkhunter system scanning, and /proc vs /sys discrepancy analysis to identify hooked syscalls, hidden kernel modules, and tampered system structures.

forensicskernellinuxmalware-analysismemory-forensicsrkhunterrootkitvolatility3
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Overview

Linux kernel rootkits operate at ring 0, modifying kernel data structures to hide processes, files, network connections, and kernel modules from userspace tools. Detection requires either memory forensics (analyzing physical memory dumps with Volatility3) or cross-view analysis (comparing /proc, /sys, and kernel data structures for inconsistencies). This skill covers using Volatility3 Linux plugins to detect syscall table hooks, hidden kernel modules, and modified function pointers, supplemented by live system scanning with rkhunter and chkrootkit.

When to Use

  • When investigating security incidents that require analyzing linux kernel rootkits
  • When building detection rules or threat hunting queries for this domain
  • When SOC analysts need structured procedures for this analysis type
  • When validating security monitoring coverage for related attack techniques

Prerequisites

  • Volatility3 installed (pip install volatility3)
  • Linux memory dump (acquired via LiME, AVML, or /proc/kcore)
  • Volatility3 Linux symbol table (ISF) matching the target kernel version
  • rkhunter and chkrootkit for live system scanning
  • Reference known-good kernel image for comparison

Steps

Step 1: Acquire Memory Dump

Capture Linux physical memory using LiME kernel module or AVML for cloud instances.

Step 2: Analyze with Volatility3

Run linux.check_syscall, linux.lsmod, linux.hidden_modules, and linux.check_idt plugins to detect rootkit artifacts.

Step 3: Cross-View Analysis

Compare module lists from /proc/modules, lsmod, and /sys/module to identify modules hidden from one view but present in another.

Step 4: Live System Scanning

Run rkhunter and chkrootkit to detect known rootkit signatures, suspicious files, and modified system binaries.

Expected Output

JSON report containing detected syscall hooks, hidden kernel modules, modified IDT entries, suspicious /proc discrepancies, and rkhunter findings.

Example Output

$ sudo python3 rootkit_analyzer.py --memory /evidence/linux-mem.lime --profile Ubuntu2204
 
Linux Kernel Rootkit Analysis Report
=====================================
Memory Image: /evidence/linux-mem.lime
Kernel Version: 5.15.0-91-generic (Ubuntu 22.04 LTS)
Analysis Time: 2024-01-18 09:15:32 UTC
 
[+] Scanning syscall table for hooks...
    Syscall Table Base: 0xffffffff82200300
    Total syscalls checked: 449
 
    HOOKED SYSCALLS DETECTED:
    ┌─────────┬──────────────────┬──────────────────────┬──────────────────────┐
    │ NR      │ Syscall          │ Expected Address     │ Current Address      │
    ├─────────┼──────────────────┼──────────────────────┼──────────────────────┤
    │ 0       │ sys_read         │ 0xffffffff8139a0e0   │ 0xffffffffc0a12000   │
    │ 2       │ sys_open         │ 0xffffffff8139b340   │ 0xffffffffc0a12180   │
    │ 78      │ sys_getdents64   │ 0xffffffff813f5210   │ 0xffffffffc0a12300   │
    │ 62      │ sys_kill         │ 0xffffffff8110c4a0   │ 0xffffffffc0a12480   │
    └─────────┴──────────────────┴──────────────────────┴──────────────────────┘
    WARNING: 4 syscall hooks detected - rootkit behavior confirmed
 
[+] Checking for hidden kernel modules...
    Loaded modules (lsmod):         147
    Modules in kobject list:        149
    HIDDEN MODULES:
      - "netfilter_helper" at 0xffffffffc0a10000 (size: 12288)
      - "kworker_sched"    at 0xffffffffc0a14000 (size: 8192)
 
[+] Scanning /proc for discrepancies...
    Processes in task_struct list: 234
    Processes visible in /proc:   231
    HIDDEN PROCESSES:
      - PID 31337  cmd: "[kworker/0:3]"   (disguised as kernel thread)
      - PID 31442  cmd: "rsyslogd"         (fake, real rsyslogd is PID 892)
      - PID 31500  cmd: ""                 (unnamed process)
 
[+] Checking IDT entries...
    IDT entries scanned: 256
    Modified entries: 0 (clean)
 
[+] Running rkhunter scan...
    Checking for known rootkits:        68 variants checked
    Diamorphine rootkit:                WARNING - signatures match
    System binary checks:
      /usr/bin/ps:     MODIFIED (SHA-256 mismatch)
      /usr/bin/netstat: MODIFIED (SHA-256 mismatch)
      /usr/bin/ls:     MODIFIED (SHA-256 mismatch)
      /usr/sbin/ss:    OK
 
[+] Network analysis...
    Hidden connections (not in /proc/net/tcp):
      ESTABLISHED  0.0.0.0:0 -> 198.51.100.47:4443 (PID 31337)
      ESTABLISHED  0.0.0.0:0 -> 198.51.100.47:8080 (PID 31442)
 
Summary:
  Rootkit Type:         Loadable Kernel Module (LKM)
  Probable Family:      Diamorphine variant
  Syscall Hooks:        4 (read, open, getdents64, kill)
  Hidden Modules:       2
  Hidden Processes:     3
  Hidden Connections:   2 (C2: 198.51.100.47)
  Modified Binaries:    3 (/usr/bin/ps, netstat, ls)
  Risk Level:           CRITICAL
Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 1

api-reference.md2.5 KB

API Reference: Analyzing Linux Kernel Rootkits

Volatility3 Linux Plugins

# Check syscall table for hooks
vol -f memory.lime linux.check_syscall.Check_syscall
 
# List loaded kernel modules
vol -f memory.lime linux.lsmod.Lsmod
 
# Detect hidden kernel modules
vol -f memory.lime linux.hidden_modules.Hidden_modules
 
# Check IDT for hooks
vol -f memory.lime linux.check_idt.Check_idt
 
# List processes (detect hidden)
vol -f memory.lime linux.pslist.PsList
vol -f memory.lime linux.pstree.PsTree
 
# Check for modified cred structures
vol -f memory.lime linux.check_creds.Check_creds
 
# Network connections
vol -f memory.lime linux.sockstat.Sockstat
 
# JSON output
vol -f memory.lime linux.check_syscall.Check_syscall -r json > syscalls.json

Memory Acquisition Tools

Tool Command Use Case
LiME insmod lime.ko "path=/tmp/mem.lime format=lime" Linux kernel module
AVML avml /tmp/memory.raw Azure/cloud instances
/proc/kcore dd if=/proc/kcore of=mem.raw Quick (partial) dump

Volatility3 Symbol Tables (ISF)

# Generate ISF from running kernel
vol -f memory.lime banners.Banners
# Download matching ISF from:
# https://github.com/volatilityfoundation/volatility3#symbol-tables

rkhunter Commands

# Full system scan
rkhunter --check --skip-keypress --report-warnings-only
 
# Update signatures
rkhunter --update
 
# Check specific tests
rkhunter --check --enable rootkits,trojans,os_specific
 
# Output to log file
rkhunter --check --logfile /var/log/rkhunter.log

Known Linux Rootkits Detected

Rootkit Technique Volatility Plugin
Diamorphine Hidden module + syscall hook check_syscall, hidden_modules
Reptile Syscall hook + port knocking check_syscall
KBeast Syscall hook + /proc hiding check_syscall, hidden_modules
Adore-ng VFS hook + hidden files lsmod, check_syscall
Jynx2 LD_PRELOAD userspace pslist (parent check)

Cross-View Detection

# Compare /proc/modules vs /sys/module
diff <(cat /proc/modules | awk '{print $1}' | sort) \
     <(ls /sys/module/ | sort)
 
# Check for hidden processes
diff <(ls /proc/ | grep -E '^[0-9]+$' | sort -n) \
     <(ps -eo pid --no-headers | sort -n)

References

Scripts 1

agent.py6.9 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Linux Kernel Rootkit Detection Agent - analyzes memory dumps with Volatility3 and live system with rkhunter."""

import json
import argparse
import logging
import subprocess
import os
from datetime import datetime

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)


def run_vol3_plugin(memory_dump, plugin, isf_url=None):
    """Run a Volatility3 Linux plugin and return parsed output."""
    cmd = ["vol", "-f", memory_dump, plugin, "-r", "json"]
    if isf_url:
        cmd.extend(["--isf", isf_url])
    result = subprocess.run(cmd, capture_output=True, text=True, timeout=600)
    try:
        return json.loads(result.stdout) if result.stdout else []
    except json.JSONDecodeError:
        logger.error("Volatility3 %s output parse failed", plugin)
        return []


def check_syscall_hooks(memory_dump, isf_url=None):
    """Detect hooked system calls using linux.check_syscall."""
    results = run_vol3_plugin(memory_dump, "linux.check_syscall.Check_syscall", isf_url)
    hooked = []
    for entry in results:
        row = entry.get("__children", [entry]) if isinstance(entry, dict) else [entry]
        for item in row:
            symbol = item.get("Symbol", item.get("symbol", ""))
            module = item.get("Module", item.get("module", ""))
            if module and module != "kernel":
                hooked.append({
                    "syscall_number": item.get("Index", item.get("index", "")),
                    "expected_handler": symbol,
                    "actual_module": module,
                    "severity": "critical",
                    "indicator": "syscall_hook",
                })
    return hooked


def detect_hidden_modules(memory_dump, isf_url=None):
    """Detect hidden kernel modules using cross-view analysis."""
    lsmod_results = run_vol3_plugin(memory_dump, "linux.lsmod.Lsmod", isf_url)
    hidden_results = run_vol3_plugin(memory_dump, "linux.hidden_modules.Hidden_modules", isf_url)
    lsmod_names = set()
    for entry in lsmod_results:
        name = entry.get("Name", entry.get("name", ""))
        if name:
            lsmod_names.add(name)
    hidden = []
    for entry in hidden_results:
        name = entry.get("Name", entry.get("name", ""))
        if name:
            hidden.append({
                "module_name": name,
                "in_lsmod": name in lsmod_names,
                "severity": "critical",
                "indicator": "hidden_kernel_module",
                "detail": f"Module '{name}' hidden from standard listing",
            })
    return hidden


def check_idt_hooks(memory_dump, isf_url=None):
    """Check Interrupt Descriptor Table for hooks."""
    results = run_vol3_plugin(memory_dump, "linux.check_idt.Check_idt", isf_url)
    hooked = []
    for entry in results:
        module = entry.get("Module", entry.get("module", ""))
        if module and module != "kernel":
            hooked.append({
                "interrupt": entry.get("Index", ""),
                "handler_module": module,
                "severity": "critical",
                "indicator": "idt_hook",
            })
    return hooked


def run_rkhunter():
    """Run rkhunter rootkit scanner on live system."""
    cmd = ["rkhunter", "--check", "--skip-keypress", "--report-warnings-only", "--nocolors"]
    result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
    findings = []
    for line in result.stdout.split("\n"):
        line = line.strip()
        if "Warning:" in line or "[ Warning ]" in line:
            findings.append({
                "tool": "rkhunter",
                "finding": line.replace("Warning:", "").strip(),
                "severity": "high",
            })
    return findings


def check_proc_sys_discrepancy():
    """Compare /proc/modules with /sys/module for hidden modules."""
    findings = []
    proc_modules = set()
    sys_modules = set()
    try:
        with open("/proc/modules") as f:
            for line in f:
                proc_modules.add(line.split()[0])
    except (FileNotFoundError, PermissionError):
        return findings
    try:
        sys_modules = set(os.listdir("/sys/module"))
    except (FileNotFoundError, PermissionError):
        return findings
    only_in_sys = sys_modules - proc_modules
    for mod in only_in_sys:
        if not os.path.exists(f"/sys/module/{mod}/initstate"):
            continue
        findings.append({
            "module": mod, "indicator": "proc_sys_discrepancy",
            "severity": "high",
            "detail": f"Module '{mod}' in /sys/module but missing from /proc/modules",
        })
    return findings


def generate_report(syscall_hooks, hidden_mods, idt_hooks, rkhunter_findings, proc_findings, source):
    all_findings = syscall_hooks + hidden_mods + idt_hooks + rkhunter_findings + proc_findings
    critical = sum(1 for f in all_findings if f.get("severity") == "critical")
    return {
        "timestamp": datetime.utcnow().isoformat(),
        "analysis_source": source,
        "syscall_hooks": syscall_hooks,
        "hidden_modules": hidden_mods,
        "idt_hooks": idt_hooks,
        "rkhunter_warnings": rkhunter_findings,
        "proc_sys_discrepancies": proc_findings,
        "total_findings": len(all_findings),
        "critical_findings": critical,
        "rootkit_detected": critical > 0,
    }


def main():
    parser = argparse.ArgumentParser(description="Linux Kernel Rootkit Detection Agent")
    parser.add_argument("--memory-dump", help="Path to Linux memory dump for Volatility3 analysis")
    parser.add_argument("--isf-url", help="Volatility3 ISF symbol table URL")
    parser.add_argument("--live-scan", action="store_true", help="Run rkhunter + /proc analysis on live system")
    parser.add_argument("--output", default="rootkit_detection_report.json")
    args = parser.parse_args()

    syscall_hooks, hidden_mods, idt_hooks = [], [], []
    rkhunter_findings, proc_findings = [], []
    source = "none"
    if args.memory_dump:
        source = f"memory_dump:{args.memory_dump}"
        syscall_hooks = check_syscall_hooks(args.memory_dump, args.isf_url)
        hidden_mods = detect_hidden_modules(args.memory_dump, args.isf_url)
        idt_hooks = check_idt_hooks(args.memory_dump, args.isf_url)
    if args.live_scan:
        source = "live_system" if source == "none" else source + "+live_system"
        rkhunter_findings = run_rkhunter()
        proc_findings = check_proc_sys_discrepancy()
    report = generate_report(syscall_hooks, hidden_mods, idt_hooks, rkhunter_findings, proc_findings, source)
    with open(args.output, "w") as f:
        json.dump(report, f, indent=2, default=str)
    logger.info("Rootkit scan: %d findings (%d critical), rootkit detected: %s",
                report["total_findings"], report["critical_findings"], report["rootkit_detected"])
    print(json.dumps(report, indent=2, default=str))


if __name__ == "__main__":
    main()
Keep exploring