incident response

Collecting Volatile Evidence from Compromised Hosts

Collect volatile forensic evidence from a compromised system following order of volatility, preserving memory, network connections, processes, and system state before they are lost.

chain-of-custodydfirforensicsincident-responsememory-forensicsvolatile-evidence
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

When to Use

  • Security incident confirmed and compromised host identified
  • Before system isolation, shutdown, or remediation begins
  • Memory-resident malware suspected (fileless attacks)
  • Need to capture network connections, running processes, and system state
  • Legal proceedings may require forensic evidence preservation
  • Incident requires root cause analysis with volatile data

Prerequisites

  • Forensic collection toolkit on USB or network share (trusted tools)
  • WinPmem/LiME for memory acquisition
  • Write-blocker or forensic workstation for disk imaging
  • Chain of custody documentation forms
  • Secure evidence storage with integrity verification
  • Authorization to collect evidence (legal/HR approval for insider cases)

Workflow

Step 1: Prepare Collection Environment

# Mount forensic USB toolkit (do NOT install tools on compromised system)
# Verify toolkit integrity
sha256sum /mnt/forensic_usb/tools/* > /tmp/toolkit_hashes.txt
diff /mnt/forensic_usb/tools/known_good_hashes.txt /tmp/toolkit_hashes.txt
 
# Create evidence output directory with timestamps
EVIDENCE_DIR="/mnt/evidence/$(hostname)_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$EVIDENCE_DIR"
echo "Collection started: $(date -u)" > "$EVIDENCE_DIR/collection_log.txt"
echo "Collector: $(whoami)" >> "$EVIDENCE_DIR/collection_log.txt"
echo "System: $(hostname)" >> "$EVIDENCE_DIR/collection_log.txt"

Step 2: Capture System Memory (Highest Volatility)

# Windows - WinPmem memory acquisition
winpmem_mini_x64.exe "$EVIDENCE_DIR\memdump_$(hostname).raw"
 
# Linux - LiME kernel module for memory acquisition
insmod /mnt/forensic_usb/lime.ko "path=$EVIDENCE_DIR/memdump_$(hostname).lime format=lime"
 
# Linux - Alternative using /proc/kcore
dd if=/proc/kcore of="$EVIDENCE_DIR/kcore_dump.raw" bs=1M
 
# macOS - osxpmem
osxpmem -o "$EVIDENCE_DIR/memdump_$(hostname).aff4"
 
# Hash the memory dump immediately
sha256sum "$EVIDENCE_DIR/memdump_"* > "$EVIDENCE_DIR/memory_hash.sha256"

Step 3: Capture Network State

# Active network connections
# Windows
netstat -anob > "$EVIDENCE_DIR/netstat_connections.txt" 2>&1
Get-NetTCPConnection | Export-Csv "$EVIDENCE_DIR/tcp_connections.csv" -NoTypeInformation
Get-NetUDPEndpoint | Export-Csv "$EVIDENCE_DIR/udp_endpoints.csv" -NoTypeInformation
 
# Linux
ss -tulnp > "$EVIDENCE_DIR/socket_stats.txt"
netstat -anp > "$EVIDENCE_DIR/netstat_all.txt" 2>/dev/null
cat /proc/net/tcp > "$EVIDENCE_DIR/proc_net_tcp.txt"
cat /proc/net/udp > "$EVIDENCE_DIR/proc_net_udp.txt"
 
# ARP cache
arp -a > "$EVIDENCE_DIR/arp_cache.txt"
 
# Routing table
route print > "$EVIDENCE_DIR/routing_table.txt"  # Windows
ip route show > "$EVIDENCE_DIR/routing_table.txt"  # Linux
 
# DNS cache
ipconfig /displaydns > "$EVIDENCE_DIR/dns_cache.txt"  # Windows
# Linux: varies by resolver, check systemd-resolve or nscd
systemd-resolve --statistics > "$EVIDENCE_DIR/dns_stats.txt" 2>/dev/null
 
# Active firewall rules
netsh advfirewall show allprofiles > "$EVIDENCE_DIR/firewall_rules.txt"  # Windows
iptables -L -n -v > "$EVIDENCE_DIR/iptables_rules.txt"  # Linux

Step 4: Capture Running Processes

# Windows - Detailed process list
tasklist /V /FO CSV > "$EVIDENCE_DIR/process_list_verbose.csv"
wmic process list full > "$EVIDENCE_DIR/wmic_process_full.txt"
Get-Process | Select-Object Id,ProcessName,Path,StartTime,CPU,WorkingSet |
  Export-Csv "$EVIDENCE_DIR/ps_processes.csv" -NoTypeInformation
 
# Windows - Process with command line and parent
wmic process get ProcessId,Name,CommandLine,ParentProcessId,ExecutablePath /FORMAT:CSV > \
  "$EVIDENCE_DIR/process_commandlines.csv"
 
# Linux - Full process tree
ps auxwwf > "$EVIDENCE_DIR/process_tree.txt"
ps -eo pid,ppid,user,args --forest > "$EVIDENCE_DIR/process_forest.txt"
cat /proc/*/cmdline 2>/dev/null | tr '\0' ' ' > "$EVIDENCE_DIR/proc_cmdline_all.txt"
 
# Process modules/DLLs loaded
# Windows
listdlls.exe -accepteula > "$EVIDENCE_DIR/loaded_dlls.txt"
# Linux
for pid in $(ls /proc/ | grep -E '^[0-9]+$'); do
  echo "=== PID $pid ===" >> "$EVIDENCE_DIR/proc_maps.txt"
  cat "/proc/$pid/maps" 2>/dev/null >> "$EVIDENCE_DIR/proc_maps.txt"
done
 
# Open file handles
handle.exe -accepteula > "$EVIDENCE_DIR/open_handles.txt"  # Windows (Sysinternals)
lsof > "$EVIDENCE_DIR/open_files.txt"  # Linux

Step 5: Capture Logged-in Users and Sessions

# Windows
query user > "$EVIDENCE_DIR/logged_in_users.txt"
query session > "$EVIDENCE_DIR/active_sessions.txt"
net session > "$EVIDENCE_DIR/net_sessions.txt" 2>&1
net use > "$EVIDENCE_DIR/mapped_drives.txt" 2>&1
 
# Linux
who > "$EVIDENCE_DIR/who_output.txt"
w > "$EVIDENCE_DIR/w_output.txt"
last -50 > "$EVIDENCE_DIR/last_logins.txt"
lastlog > "$EVIDENCE_DIR/lastlog.txt"
cat /var/log/auth.log | tail -200 > "$EVIDENCE_DIR/recent_auth.txt" 2>/dev/null

Step 6: Capture System Configuration State

# System time (critical for timeline)
date -u > "$EVIDENCE_DIR/system_time_utc.txt"
w32tm /query /status > "$EVIDENCE_DIR/ntp_status.txt"  # Windows
ntpq -p > "$EVIDENCE_DIR/ntp_status.txt"  # Linux
 
# Environment variables
set > "$EVIDENCE_DIR/environment_vars.txt"  # Windows
env > "$EVIDENCE_DIR/environment_vars.txt"  # Linux
 
# Scheduled tasks / Cron jobs
schtasks /query /fo CSV /v > "$EVIDENCE_DIR/scheduled_tasks.csv"  # Windows
crontab -l > "$EVIDENCE_DIR/crontab_current.txt" 2>/dev/null  # Linux
ls -la /etc/cron.* > "$EVIDENCE_DIR/cron_dirs.txt" 2>/dev/null
 
# Services
sc queryex type=service state=all > "$EVIDENCE_DIR/services_all.txt"  # Windows
systemctl list-units --type=service --all > "$EVIDENCE_DIR/systemd_services.txt"  # Linux
 
# Windows Registry - key autostart locations
reg export "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" "$EVIDENCE_DIR/reg_run_hklm.reg" /y
reg export "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" "$EVIDENCE_DIR/reg_run_hkcu.reg" /y
reg export "HKLM\SYSTEM\CurrentControlSet\Services" "$EVIDENCE_DIR/reg_services.reg" /y

Step 7: Hash All Evidence and Document Chain of Custody

# Generate SHA256 hashes for all collected evidence
cd "$EVIDENCE_DIR"
sha256sum * > evidence_manifest.sha256
 
# Create chain of custody record
cat > "$EVIDENCE_DIR/chain_of_custody.txt" << EOF
CHAIN OF CUSTODY RECORD
========================
Case ID: IR-YYYY-NNN
Collection Date: $(date -u)
Collected By: $(whoami)
System: $(hostname)
System IP: $(hostname -I 2>/dev/null || ipconfig | grep IPv4)
Collection Method: Live forensic collection via trusted USB toolkit
 
Evidence Items:
$(ls -la "$EVIDENCE_DIR/" | grep -v chain_of_custody)
 
SHA256 Manifest: evidence_manifest.sha256
Transfer: [TO BE COMPLETED]
Storage Location: [TO BE COMPLETED]
EOF

Key Concepts

Concept Description
Order of Volatility RFC 3227 - Collect most volatile data first: registers > cache > memory > disk
Live Forensics Collecting evidence from a running system before shutdown
Chain of Custody Documentation tracking evidence handling from collection to court
Forensic Soundness Ensuring evidence collection doesn't alter the original evidence
Trusted Tools Using verified tools from external media, not from the compromised system
Evidence Integrity SHA256 hashing of all evidence immediately after collection
Locard's Exchange Principle Every contact leaves a trace - minimize investigator artifacts

Tools & Systems

Tool Purpose
WinPmem Windows memory acquisition
LiME (Linux Memory Extractor) Linux kernel memory acquisition
Sysinternals Suite Process, handle, and DLL analysis (Windows)
Velociraptor Remote forensic collection at scale
KAPE (Kroll Artifact Parser) Automated artifact collection on Windows
CyLR Cross-platform live response collection
GRR Rapid Response Remote live forensics framework

Common Scenarios

  1. Fileless Malware Attack: PowerShell-based attack with no files on disk. Memory dump is critical evidence containing the malicious scripts.
  2. Active C2 Session: Attacker has live connection. Network connections and process data reveal C2 infrastructure.
  3. Insider Data Theft: Employee copying files. Process list, mapped drives, and network connections show exfiltration activity.
  4. Compromised Web Server: Web shell detected. Memory may contain additional backdoors not yet written to disk.
  5. Lateral Movement in Progress: Attacker moving between systems. Authentication tokens and network sessions in memory reveal scope.

Output Format

  • Memory dump file (.raw or .lime format) with SHA256 hash
  • Network state captures (connections, ARP, DNS, routes)
  • Process listings with command lines and parent processes
  • User session and authentication data
  • System configuration snapshots
  • Evidence manifest with SHA256 checksums
  • Chain of custody documentation
Source materials

References and resources

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

References 3

api-reference.md2.0 KB

API Reference: Collecting Volatile Evidence from Compromised Host

RFC 3227 Order of Volatility

Priority Source Persistence
1 CPU registers, cache Nanoseconds
2 Physical memory (RAM) Power cycle
3 Network state Seconds-minutes
4 Running processes Minutes
5 Disk (filesystem) Persistent
6 Remote logging / monitoring Persistent
7 Physical configuration Persistent
8 Archival media Long-term

Memory Acquisition Tools

Tool Platform Command
AVML Linux avml /path/to/output.lime
WinPmem Windows winpmem_mini_x64.exe output.raw
LiME Linux insmod lime.ko "path=/tmp/mem.lime format=lime"
Magnet RAM Capture Windows GUI-based acquisition

Linux Collection Commands

# Network connections
ss -tunap > /evidence/netstat.txt
 
# Process list with tree
ps auxwwf > /evidence/processes.txt
 
# Open files
lsof -nP > /evidence/open_files.txt
 
# Network config
ip addr show > /evidence/ifconfig.txt
ip route show > /evidence/routes.txt
ip neigh show > /evidence/arp.txt
 
# Logged-in users
w > /evidence/users.txt
last -50 > /evidence/last_logins.txt
 
# Cron jobs
crontab -l > /evidence/crontab.txt
ls -la /etc/cron.d/ >> /evidence/crontab.txt

Windows Collection Commands

:: Network connections
netstat -anob > C:\evidence\netstat.txt
 
:: Process list
tasklist /V /FO CSV > C:\evidence\processes.csv
wmic process get ProcessId,Name,CommandLine /format:csv > C:\evidence\wmic_procs.csv
 
:: Network config
ipconfig /all > C:\evidence\ipconfig.txt
route print > C:\evidence\routes.txt
arp -a > C:\evidence\arp.txt
 
:: DNS cache
ipconfig /displaydns > C:\evidence\dns_cache.txt
 
:: Scheduled tasks
schtasks /query /FO CSV /V > C:\evidence\schtasks.csv
 
:: Logged-in users
query user > C:\evidence\users.txt

Evidence Integrity

# Hash collected files
sha256sum /evidence/*.txt > /evidence/checksums.sha256
 
# Verify later
sha256sum -c /evidence/checksums.sha256
standards.md3.0 KB

Standards and Framework References - Volatile Evidence Collection

RFC 3227 - Guidelines for Evidence Collection and Archiving

  • Defines the order of volatility for digital evidence:
    1. Registers, cache
    2. Routing table, ARP cache, process table, kernel statistics, memory
    3. Temporary file systems
    4. Disk
    5. Remote logging and monitoring data
    6. Physical configuration, network topology
    7. Archival media
  • Key principles: minimize data alteration, document actions, use trusted tools
  • Reference: https://www.rfc-editor.org/rfc/rfc3227

NIST SP 800-86 - Guide to Integrating Forensic Techniques

  • Section 4: Using Data from Data Sources
    • 4.2: Data Files - Volatile and non-volatile OS data
    • 4.3: Operating System Data - Memory, processes, network connections
  • Forensic process: Collection, Examination, Analysis, Reporting
  • Emphasis on preserving data integrity through proper acquisition
  • Reference: https://csrc.nist.gov/pubs/sp/800/86/final

NIST SP 800-61 Rev. 3 - Evidence Handling

  • Respond (RS) function alignment:
    • RS.AN-03: Analysis to establish incident scope
  • Evidence must be collected in a forensically sound manner
  • Document all collection activities and maintain chain of custody

SANS DFIR - Live Evidence Collection Best Practices

  • Collect evidence from most volatile to least volatile
  • Use external trusted tools (not tools from compromised system)
  • Hash all evidence immediately after collection
  • Document system time offset from UTC
  • Minimize footprint on compromised system
  • Reference: https://www.sans.org/white-papers/

MITRE ATT&CK - Evidence Sources for Detection

Data Source ATT&CK Reference Evidence Type
Process (DS0009) Process creation, command line Running processes
Network Traffic (DS0029) Connection creation, flow Network connections
File (DS0022) File creation, modification Open handles, temp files
Windows Registry (DS0024) Registry key modification Autostart entries
Logon Session (DS0028) Logon creation Active user sessions
Module (DS0011) Module load Loaded DLLs/shared objects

ACPO Good Practice Guide for Digital Evidence

  • Principle 1: No action should change data on digital devices
  • Principle 2: Competent person must access original data when necessary
  • Principle 3: Audit trail of all processes applied to evidence
  • Principle 4: Person in charge ensures law and principles are adhered to

ISO/IEC 27037 - Guidelines for Identification, Collection, Acquisition, and Preservation

  • Defines procedures for handling digital evidence
  • Specifies requirements for first responders and forensic specialists
  • Covers volatile and non-volatile evidence acquisition
  • Emphasizes competency of evidence handlers

SWGDE Best Practices for Computer Forensics

  • Scientific Working Group on Digital Evidence
  • Standards for evidence acquisition, examination, and reporting
  • Quality assurance requirements for forensic processes
workflows.md3.9 KB

Volatile Evidence Collection - Detailed Workflow

Order of Volatility Collection Sequence

Priority 1: Memory (Most Volatile) - Collect First

  1. Connect forensic USB with memory acquisition tool
  2. Run memory dump tool from USB (NOT from compromised disk)
  3. Save memory image to external storage
  4. Record start time, end time, and memory size
  5. Generate SHA256 hash of memory image immediately
  6. Document any errors during acquisition

Priority 2: Network State

  1. Capture all active TCP/UDP connections with process IDs
  2. Capture ARP cache (maps IP to MAC addresses)
  3. Capture DNS resolver cache
  4. Capture routing table
  5. Capture active firewall rules
  6. Capture listening ports and associated processes
  7. Hash all network evidence files

Priority 3: Running Processes

  1. List all processes with full command lines
  2. List parent-child process relationships (process tree)
  3. List all loaded modules/DLLs per process
  4. List all open file handles per process
  5. List process network connections per PID
  6. Capture process creation timestamps
  7. Hash all process evidence files

Priority 4: User Sessions

  1. List all currently logged-in users
  2. List active remote sessions (RDP, SSH, SMB)
  3. List mapped network drives
  4. Capture recent authentication events
  5. List active tokens and session keys (if accessible)

Priority 5: System Configuration

  1. Capture system time and UTC offset
  2. Export autostart/persistence locations (Registry Run keys, crontab)
  3. List all services and their states
  4. Capture environment variables
  5. List installed software
  6. Export relevant event log entries

Priority 6: Temporary/Cache Data

  1. Capture browser history and cache (if relevant)
  2. Capture clipboard contents (if accessible)
  3. Capture temp directory contents
  4. Capture recent file lists
  5. Capture prefetch files (Windows)

Platform-Specific Collection Procedures

Windows Collection Checklist

[ ] Memory: WinPmem/Magnet RAM Capture
[ ] Processes: tasklist /V, wmic process, Get-Process
[ ] Network: netstat -anob, Get-NetTCPConnection
[ ] Users: query user, net session
[ ] Registry: Run keys, Services, Startup
[ ] Services: sc queryex, Get-Service
[ ] Scheduled Tasks: schtasks /query
[ ] DNS Cache: ipconfig /displaydns
[ ] ARP: arp -a
[ ] Firewall: netsh advfirewall
[ ] Event Logs: wevtutil (Security, System, Application)
[ ] Prefetch: %SystemRoot%\Prefetch\*
[ ] Time: w32tm /query /status

Linux Collection Checklist

[ ] Memory: LiME kernel module or /proc/kcore
[ ] Processes: ps auxwwf, /proc/*/cmdline, /proc/*/maps
[ ] Network: ss -tulnp, /proc/net/tcp, /proc/net/udp
[ ] Users: who, w, last
[ ] Cron: crontab -l, /etc/cron.*
[ ] Services: systemctl list-units
[ ] DNS: systemd-resolve, /etc/resolv.conf
[ ] ARP: ip neigh
[ ] Firewall: iptables -L -n -v, nftables
[ ] Logs: /var/log/auth.log, /var/log/syslog
[ ] Open Files: lsof
[ ] Time: timedatectl
[ ] Loaded Modules: lsmod

Evidence Integrity Procedures

Hashing Protocol

  1. Hash EVERY collected file immediately after creation
  2. Use SHA256 (minimum) - SHA512 preferred for legal cases
  3. Store hash manifest in separate file
  4. Verify hashes before and after any transfer
  5. Include hash in chain of custody documentation

Chain of Custody Requirements

  1. Record who collected each evidence item
  2. Record exact time of collection (UTC)
  3. Record collection method and tool version
  4. Record any transfer of evidence
  5. Record storage location and access controls
  6. Record any analysis performed on copies (never originals)

Common Pitfalls to Avoid

  1. Running tools from the compromised system's disk
  2. Forgetting to hash evidence immediately
  3. Not recording system time offset from UTC
  4. Installing collection tools on the compromised system
  5. Rebooting the system before memory collection
  6. Modifying file timestamps by browsing the filesystem
  7. Not documenting collection steps in real-time
  8. Collecting evidence without proper authorization

Scripts 2

agent.py7.0 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Volatile evidence collection agent for compromised hosts.

Collects volatile forensic artifacts following RFC 3227 order of volatility:
registers, memory, network state, running processes, disk, and logs.
Uses platform-native tools for live response evidence gathering.
"""

import sys
import json
import os
import datetime
import subprocess
import shlex
import platform
import hashlib


VOLATILITY_ORDER = [
    {"priority": 1, "source": "memory", "description": "Physical memory (RAM) dump",
     "tool_linux": "avml", "tool_windows": "winpmem_mini_x64.exe"},
    {"priority": 2, "source": "network_connections", "description": "Active network connections",
     "tool_linux": "ss -tunap", "tool_windows": "netstat -anob"},
    {"priority": 3, "source": "running_processes", "description": "Running process list with details",
     "tool_linux": "ps auxwwf", "tool_windows": "tasklist /V /FO CSV"},
    {"priority": 4, "source": "open_files", "description": "Open file handles",
     "tool_linux": "lsof -nP", "tool_windows": "handle64.exe -a"},
    {"priority": 5, "source": "network_config", "description": "Network interface configuration",
     "tool_linux": "ip addr show", "tool_windows": "ipconfig /all"},
    {"priority": 6, "source": "routing_table", "description": "Network routing table",
     "tool_linux": "ip route show", "tool_windows": "route print"},
    {"priority": 7, "source": "arp_cache", "description": "ARP cache entries",
     "tool_linux": "ip neigh show", "tool_windows": "arp -a"},
    {"priority": 8, "source": "dns_cache", "description": "DNS resolver cache",
     "tool_linux": "cat /etc/resolv.conf", "tool_windows": "ipconfig /displaydns"},
    {"priority": 9, "source": "logged_users", "description": "Currently logged-in users",
     "tool_linux": "w", "tool_windows": "query user"},
    {"priority": 10, "source": "scheduled_tasks", "description": "Scheduled tasks and cron jobs",
     "tool_linux": ["crontab -l", "ls /etc/cron.d/"], "tool_windows": "schtasks /query /FO CSV /V"},
]


def _run_single_cmd(cmd_str, timeout=60):
    """Run a single command string without shell, return stdout and stderr."""
    return subprocess.run(
        shlex.split(cmd_str), capture_output=True, text=True, timeout=timeout
    )


def collect_artifact(source_config, output_dir):
    """Collect a single volatile artifact."""
    is_windows = platform.system() == "Windows"
    cmd = source_config["tool_windows"] if is_windows else source_config["tool_linux"]
    source_name = source_config["source"]
    output_file = os.path.join(output_dir, source_name + ".txt")

    result = {
        "source": source_name,
        "priority": source_config["priority"],
        "command": cmd if isinstance(cmd, str) else "; ".join(cmd),
        "timestamp": datetime.datetime.utcnow().isoformat() + "Z",
        "status": "pending",
    }

    try:
        # Run multiple commands sequentially if cmd is a list, combining output
        if isinstance(cmd, list):
            combined_stdout = ""
            combined_stderr = ""
            last_rc = 0
            for sub_cmd in cmd:
                sub_proc = _run_single_cmd(sub_cmd, timeout=60)
                combined_stdout += sub_proc.stdout
                combined_stderr += sub_proc.stderr
                last_rc = sub_proc.returncode
            proc = type("CombinedResult", (), {
                "stdout": combined_stdout,
                "stderr": combined_stderr,
                "returncode": last_rc,
            })()
        else:
            proc = _run_single_cmd(cmd, timeout=60)
        result["status"] = "collected"
        result["output_lines"] = len(proc.stdout.splitlines())
        result["output_file"] = output_file
        result["exit_code"] = proc.returncode

        with open(output_file, "w", encoding="utf-8") as f:
            f.write("# Collected: {}\n".format(result["timestamp"]))
            f.write("# Command: {}\n".format(cmd))
            f.write("# Exit code: {}\n\n".format(proc.returncode))
            f.write(proc.stdout)
            if proc.stderr:
                f.write("\n# STDERR:\n" + proc.stderr)

        sha256 = hashlib.sha256(proc.stdout.encode()).hexdigest()
        result["sha256"] = sha256
    except subprocess.TimeoutExpired:
        result["status"] = "timeout"
    except Exception as e:
        result["status"] = "error"
        result["error"] = str(e)

    return result


def run_collection(output_dir, sources=None):
    """Run full volatile evidence collection."""
    os.makedirs(output_dir, exist_ok=True)
    if sources is None:
        sources = VOLATILITY_ORDER

    manifest = {
        "collection_start": datetime.datetime.utcnow().isoformat() + "Z",
        "hostname": platform.node(),
        "platform": platform.system(),
        "output_dir": output_dir,
        "artifacts": [],
    }

    for source_config in sorted(sources, key=lambda x: x["priority"]):
        if source_config["source"] == "memory":
            manifest["artifacts"].append({
                "source": "memory",
                "priority": 1,
                "status": "skipped",
                "note": "Memory dump requires elevated privileges and dedicated tool",
            })
            continue

        result = collect_artifact(source_config, output_dir)
        manifest["artifacts"].append(result)

    manifest["collection_end"] = datetime.datetime.utcnow().isoformat() + "Z"
    manifest["total_collected"] = sum(1 for a in manifest["artifacts"] if a["status"] == "collected")

    manifest_path = os.path.join(output_dir, "collection_manifest.json")
    with open(manifest_path, "w", encoding="utf-8") as f:
        json.dump(manifest, f, indent=2)
    manifest["manifest_file"] = manifest_path

    return manifest


if __name__ == "__main__":
    print("=" * 60)
    print("Volatile Evidence Collection Agent")
    print("RFC 3227 order of volatility, live response artifacts")
    print("=" * 60)
    print("  Platform: {}".format(platform.system()))
    print("  Hostname: {}".format(platform.node()))

    output_dir = sys.argv[1] if len(sys.argv) > 1 else os.path.join(
        os.path.expanduser("~"), "volatile_evidence_" + datetime.datetime.utcnow().strftime("%Y%m%d_%H%M%S")
    )

    print("\n--- RFC 3227 Volatility Order ---")
    for v in VOLATILITY_ORDER:
        tool = v["tool_windows"] if platform.system() == "Windows" else v["tool_linux"]
        print("  P{}: {:25s} [{}]".format(v["priority"], v["source"], tool))

    print("\n[*] Collecting volatile evidence to: {}".format(output_dir))
    manifest = run_collection(output_dir)

    print("\n--- Collection Results ---")
    for a in manifest["artifacts"]:
        status_marker = "+" if a["status"] == "collected" else "-"
        print("  [{}] P{}: {} -> {}".format(
            status_marker, a["priority"], a["source"], a["status"]))

    print("\nTotal collected: {}/{}".format(
        manifest["total_collected"], len(manifest["artifacts"])))
    print("Manifest: {}".format(manifest.get("manifest_file", "")))

    print("\n" + json.dumps({"artifacts_collected": manifest["total_collected"]}, indent=2))
process.py17.4 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
Volatile Evidence Collection Script

Collects volatile forensic evidence from a live system following
RFC 3227 order of volatility. Runs from external media.

Collects:
- Network connections and state
- Running processes with command lines
- Logged-in users and sessions
- System configuration and state
- DNS cache, ARP table, routing table
- Hashes all evidence files

Requirements:
    pip install psutil
"""

import argparse
import csv
import hashlib
import json
import logging
import os
import platform
import socket
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path

try:
    import psutil
except ImportError:
    print("Install psutil: pip install psutil")
    sys.exit(1)

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


class EvidenceCollector:
    """Collect volatile evidence from a live system."""

    def __init__(self, output_dir: str, case_id: str):
        self.case_id = case_id
        self.hostname = socket.gethostname()
        self.timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
        self.output_dir = os.path.join(output_dir, f"{self.hostname}_{self.timestamp}")
        os.makedirs(self.output_dir, exist_ok=True)
        self.evidence_manifest = []
        self.collection_log = []

        # Start collection log
        self._log_action("Collection initiated", f"Case: {case_id}, Host: {self.hostname}")
        self._log_action("System time", datetime.now(timezone.utc).isoformat())
        self._log_action("Platform", f"{platform.system()} {platform.release()}")
        self._log_action("Collector", os.getenv("USERNAME", os.getenv("USER", "unknown")))

    def _log_action(self, action: str, details: str):
        entry = {
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "action": action,
            "details": details,
        }
        self.collection_log.append(entry)
        logger.info(f"{action}: {details}")

    def _save_evidence(self, filename: str, content: str, category: str):
        filepath = os.path.join(self.output_dir, filename)
        with open(filepath, "w", encoding="utf-8", errors="replace") as f:
            f.write(content)
        file_hash = self._hash_file(filepath)
        self.evidence_manifest.append({
            "filename": filename,
            "category": category,
            "sha256": file_hash,
            "size_bytes": os.path.getsize(filepath),
            "collected_at": datetime.now(timezone.utc).isoformat(),
        })
        self._log_action(f"Evidence collected: {filename}", f"SHA256: {file_hash}")
        return filepath

    def _save_evidence_csv(self, filename: str, data: list, category: str):
        if not data:
            self._log_action(f"No data for {filename}", "Empty result set")
            return None
        filepath = os.path.join(self.output_dir, filename)
        with open(filepath, "w", newline="", encoding="utf-8") as f:
            writer = csv.DictWriter(f, fieldnames=data[0].keys())
            writer.writeheader()
            writer.writerows(data)
        file_hash = self._hash_file(filepath)
        self.evidence_manifest.append({
            "filename": filename,
            "category": category,
            "sha256": file_hash,
            "size_bytes": os.path.getsize(filepath),
            "collected_at": datetime.now(timezone.utc).isoformat(),
        })
        self._log_action(f"Evidence collected: {filename}", f"SHA256: {file_hash}, Rows: {len(data)}")
        return filepath

    @staticmethod
    def _hash_file(filepath: str) -> str:
        sha256 = hashlib.sha256()
        with open(filepath, "rb") as f:
            for chunk in iter(lambda: f.read(8192), b""):
                sha256.update(chunk)
        return sha256.hexdigest()

    def collect_network_connections(self):
        """Collect active network connections with process information."""
        self._log_action("Collecting", "Network connections")
        connections = []
        for conn in psutil.net_connections(kind="all"):
            try:
                proc_name = psutil.Process(conn.pid).name() if conn.pid else "N/A"
            except (psutil.NoSuchProcess, psutil.AccessDenied):
                proc_name = "N/A"
            connections.append({
                "fd": conn.fd,
                "family": str(conn.family),
                "type": str(conn.type),
                "local_address": f"{conn.laddr.ip}:{conn.laddr.port}" if conn.laddr else "",
                "remote_address": f"{conn.raddr.ip}:{conn.raddr.port}" if conn.raddr else "",
                "status": conn.status,
                "pid": conn.pid or "",
                "process_name": proc_name,
            })
        self._save_evidence_csv("network_connections.csv", connections, "network")

        # Also save in text format
        text_output = f"Network Connections - {datetime.now(timezone.utc).isoformat()}\n"
        text_output += f"{'='*80}\n"
        text_output += f"Total connections: {len(connections)}\n\n"
        for conn in connections:
            text_output += f"PID:{conn['pid']} ({conn['process_name']}) "
            text_output += f"{conn['local_address']} -> {conn['remote_address']} "
            text_output += f"[{conn['status']}]\n"
        self._save_evidence("network_connections.txt", text_output, "network")
        return connections

    def collect_arp_table(self):
        """Collect ARP cache."""
        self._log_action("Collecting", "ARP table")
        try:
            if platform.system() == "Windows":
                result = subprocess.run(["arp", "-a"], capture_output=True, text=True, timeout=10)
            else:
                result = subprocess.run(["ip", "neigh"], capture_output=True, text=True, timeout=10)
            self._save_evidence("arp_cache.txt", result.stdout, "network")
        except Exception as e:
            self._log_action("ARP collection failed", str(e))

    def collect_routing_table(self):
        """Collect routing table."""
        self._log_action("Collecting", "Routing table")
        try:
            if platform.system() == "Windows":
                result = subprocess.run(["route", "print"], capture_output=True, text=True, timeout=10)
            else:
                result = subprocess.run(["ip", "route", "show"], capture_output=True, text=True, timeout=10)
            self._save_evidence("routing_table.txt", result.stdout, "network")
        except Exception as e:
            self._log_action("Routing table collection failed", str(e))

    def collect_dns_cache(self):
        """Collect DNS resolver cache."""
        self._log_action("Collecting", "DNS cache")
        try:
            if platform.system() == "Windows":
                result = subprocess.run(["ipconfig", "/displaydns"], capture_output=True, text=True, timeout=30)
                if result.stdout:
                    self._save_evidence("dns_cache.txt", result.stdout, "network")
            else:
                # Linux - attempt systemd-resolved
                result = subprocess.run(
                    ["systemd-resolve", "--statistics"],
                    capture_output=True, text=True, timeout=10,
                )
                if result.stdout:
                    self._save_evidence("dns_stats.txt", result.stdout, "network")
        except Exception as e:
            self._log_action("DNS cache collection failed", str(e))

    def collect_running_processes(self):
        """Collect detailed information about all running processes."""
        self._log_action("Collecting", "Running processes")
        processes = []
        for proc in psutil.process_iter(
            ["pid", "ppid", "name", "username", "cmdline", "exe",
             "create_time", "status", "cpu_percent", "memory_percent",
             "num_threads", "connections"]
        ):
            try:
                info = proc.info
                cmdline = " ".join(info["cmdline"]) if info["cmdline"] else ""
                create_time = datetime.fromtimestamp(info["create_time"]).isoformat() if info["create_time"] else ""
                num_conns = len(info["connections"]) if info["connections"] else 0
                processes.append({
                    "pid": info["pid"],
                    "ppid": info["ppid"],
                    "name": info["name"],
                    "username": info["username"] or "",
                    "command_line": cmdline[:500],
                    "executable": info["exe"] or "",
                    "create_time": create_time,
                    "status": info["status"],
                    "cpu_percent": info["cpu_percent"],
                    "memory_percent": round(info["memory_percent"] or 0, 2),
                    "threads": info["num_threads"],
                    "network_connections": num_conns,
                })
            except (psutil.NoSuchProcess, psutil.AccessDenied):
                continue
        self._save_evidence_csv("running_processes.csv", processes, "processes")

        # Process tree text format
        tree_output = f"Process Tree - {datetime.now(timezone.utc).isoformat()}\n{'='*80}\n"
        tree_output += f"Total processes: {len(processes)}\n\n"
        for p in sorted(processes, key=lambda x: x["pid"]):
            tree_output += f"PID:{p['pid']} PPID:{p['ppid']} User:{p['username']} "
            tree_output += f"{p['name']} [{p['status']}]\n"
            if p["command_line"]:
                tree_output += f"  CMD: {p['command_line']}\n"
        self._save_evidence("process_tree.txt", tree_output, "processes")
        return processes

    def collect_open_files(self):
        """Collect open file handles for all processes."""
        self._log_action("Collecting", "Open file handles")
        open_files = []
        for proc in psutil.process_iter(["pid", "name"]):
            try:
                for f in proc.open_files():
                    open_files.append({
                        "pid": proc.info["pid"],
                        "process_name": proc.info["name"],
                        "file_path": f.path,
                        "fd": f.fd,
                        "mode": getattr(f, "mode", ""),
                    })
            except (psutil.NoSuchProcess, psutil.AccessDenied):
                continue
        if open_files:
            self._save_evidence_csv("open_files.csv", open_files, "processes")
        return open_files

    def collect_logged_in_users(self):
        """Collect information about currently logged-in users."""
        self._log_action("Collecting", "Logged-in users")
        users = []
        for user in psutil.users():
            users.append({
                "username": user.name,
                "terminal": user.terminal or "",
                "host": user.host or "",
                "started": datetime.fromtimestamp(user.started).isoformat(),
                "pid": getattr(user, "pid", ""),
            })
        self._save_evidence_csv("logged_in_users.csv", users, "users")

        # Text format
        text = f"Logged-in Users - {datetime.now(timezone.utc).isoformat()}\n{'='*80}\n"
        for u in users:
            text += f"User: {u['username']} | Terminal: {u['terminal']} | "
            text += f"Host: {u['host']} | Since: {u['started']}\n"
        self._save_evidence("logged_in_users.txt", text, "users")
        return users

    def collect_system_info(self):
        """Collect system configuration and state."""
        self._log_action("Collecting", "System information")
        boot_time = datetime.fromtimestamp(psutil.boot_time())
        info = {
            "hostname": self.hostname,
            "platform": platform.platform(),
            "architecture": platform.machine(),
            "processor": platform.processor(),
            "python_version": platform.python_version(),
            "boot_time": boot_time.isoformat(),
            "uptime_seconds": (datetime.now() - boot_time).total_seconds(),
            "cpu_count_physical": psutil.cpu_count(logical=False),
            "cpu_count_logical": psutil.cpu_count(logical=True),
            "memory_total_gb": round(psutil.virtual_memory().total / (1024**3), 2),
            "memory_used_percent": psutil.virtual_memory().percent,
            "disk_partitions": [
                {"device": p.device, "mountpoint": p.mountpoint, "fstype": p.fstype}
                for p in psutil.disk_partitions()
            ],
            "network_interfaces": {
                name: [{"address": addr.address, "family": str(addr.family)}
                       for addr in addrs]
                for name, addrs in psutil.net_if_addrs().items()
            },
        }
        self._save_evidence(
            "system_info.json",
            json.dumps(info, indent=2),
            "system",
        )
        return info

    def collect_services(self):
        """Collect running services (platform-specific)."""
        self._log_action("Collecting", "Running services")
        try:
            if platform.system() == "Windows":
                result = subprocess.run(
                    ["sc", "queryex", "type=", "service", "state=", "all"],
                    capture_output=True, text=True, timeout=30,
                )
                self._save_evidence("services_all.txt", result.stdout, "system")
            else:
                result = subprocess.run(
                    ["systemctl", "list-units", "--type=service", "--all", "--no-pager"],
                    capture_output=True, text=True, timeout=30,
                )
                self._save_evidence("systemd_services.txt", result.stdout, "system")
        except Exception as e:
            self._log_action("Service collection failed", str(e))

    def collect_scheduled_tasks(self):
        """Collect scheduled tasks / cron jobs."""
        self._log_action("Collecting", "Scheduled tasks")
        try:
            if platform.system() == "Windows":
                result = subprocess.run(
                    ["schtasks", "/query", "/fo", "CSV", "/v"],
                    capture_output=True, text=True, timeout=30,
                )
                self._save_evidence("scheduled_tasks.csv", result.stdout, "system")
            else:
                result = subprocess.run(
                    ["crontab", "-l"],
                    capture_output=True, text=True, timeout=10,
                )
                self._save_evidence("crontab.txt", result.stdout or "No crontab", "system")
        except Exception as e:
            self._log_action("Scheduled task collection failed", str(e))

    def collect_environment_variables(self):
        """Collect environment variables."""
        self._log_action("Collecting", "Environment variables")
        env_data = "\n".join(f"{k}={v}" for k, v in sorted(os.environ.items()))
        self._save_evidence("environment_variables.txt", env_data, "system")

    def finalize(self):
        """Generate evidence manifest and collection log."""
        # Save collection log
        log_path = os.path.join(self.output_dir, "collection_log.json")
        with open(log_path, "w") as f:
            json.dump(self.collection_log, f, indent=2)

        # Save evidence manifest
        manifest_path = os.path.join(self.output_dir, "evidence_manifest.json")
        manifest = {
            "case_id": self.case_id,
            "hostname": self.hostname,
            "collection_start": self.collection_log[0]["timestamp"] if self.collection_log else "",
            "collection_end": datetime.now(timezone.utc).isoformat(),
            "total_evidence_items": len(self.evidence_manifest),
            "evidence": self.evidence_manifest,
        }
        with open(manifest_path, "w") as f:
            json.dump(manifest, f, indent=2)

        # Generate SHA256 manifest text file
        hash_manifest = os.path.join(self.output_dir, "sha256_manifest.txt")
        with open(hash_manifest, "w") as f:
            for item in self.evidence_manifest:
                f.write(f"{item['sha256']}  {item['filename']}\n")

        logger.info(f"Collection complete. Evidence directory: {self.output_dir}")
        logger.info(f"Total evidence items: {len(self.evidence_manifest)}")
        return self.output_dir


def main():
    parser = argparse.ArgumentParser(description="Volatile Evidence Collection Tool")
    parser.add_argument("--case-id", required=True, help="Case/incident ID")
    parser.add_argument("--output-dir", default="./evidence_collection", help="Output directory")
    parser.add_argument("--skip-memory", action="store_true", help="Skip memory dump (use dedicated tool)")
    parser.add_argument("--collect-all", action="store_true", help="Collect all available evidence types")

    args = parser.parse_args()

    collector = EvidenceCollector(args.output_dir, args.case_id)

    if not args.skip_memory:
        logger.info("NOTE: For memory acquisition, use dedicated tools (WinPmem/LiME) from forensic USB")

    # Collect in order of volatility
    collector.collect_network_connections()
    collector.collect_arp_table()
    collector.collect_dns_cache()
    collector.collect_routing_table()
    collector.collect_running_processes()
    collector.collect_open_files()
    collector.collect_logged_in_users()
    collector.collect_system_info()
    collector.collect_services()
    collector.collect_scheduled_tasks()
    collector.collect_environment_variables()

    evidence_dir = collector.finalize()
    print(f"\nEvidence collection complete")
    print(f"Output directory: {evidence_dir}")
    print(f"Total items: {len(collector.evidence_manifest)}")


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 2.1 KB
Keep exploring