feat: add 4 new cybersecurity skills - UEBA insider threat, BeyondCorp zero trust, Linux kernel rootkits, CobaltStrike beacon hunting

This commit is contained in:
mukul975
2026-03-11 00:48:50 +01:00
parent 85fce5551d
commit ff3a9ce224
16 changed files with 1371 additions and 0 deletions
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 Mahipal
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,42 @@
---
name: analyzing-linux-kernel-rootkits
description: 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.
domain: cybersecurity
subdomain: digital-forensics
tags: [rootkit, linux, kernel, volatility3, memory-forensics, malware-analysis, rkhunter, forensics]
version: "1.0"
author: mahipal
license: Apache-2.0
---
# Analyzing Linux Kernel Rootkits
## 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.
## 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.
@@ -0,0 +1,92 @@
# API Reference: Analyzing Linux Kernel Rootkits
## Volatility3 Linux Plugins
```bash
# 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)
```bash
# Generate ISF from running kernel
vol -f memory.lime banners.Banners
# Download matching ISF from:
# https://github.com/volatilityfoundation/volatility3#symbol-tables
```
## rkhunter Commands
```bash
# 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
```bash
# 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
- Volatility3 Linux Plugins: https://volatility3.readthedocs.io/en/latest/volatility3.plugins.linux.html
- LiME: https://github.com/504ensicsLabs/LiME
- rkhunter: http://rkhunter.sourceforge.net/
- MITRE T1014 Rootkit: https://attack.mitre.org/techniques/T1014/
@@ -0,0 +1,177 @@
#!/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 collections import defaultdict
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()