<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: building-automated-forensic-collection
description: >-
  Build automated forensic evidence collection pipelines for incident response
  including memory acquisition, disk imaging, log harvesting, timeline
  generation, and chain-of-custody tracking with integrity verification.
domain: cybersecurity
subdomain: security-operations-automation
tags:
  - forensics
  - evidence-collection
  - memory-acquisition
  - chain-of-custody
  - incident-response
  - automation
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1005"]
---

# Building Automated Forensic Collection

## Overview

When an incident is confirmed, evidence must be collected before containment
alters the system state. This technique automates forensic collection:
volatile data first (memory, network connections, running processes), then
non-volatile (disk images, logs), with cryptographic integrity hashing and
chain-of-custody tracking at every step.

Mode: `[MODE: INCIDENT]` — Evidence preservation under time pressure.

## Prerequisites

| Requirement | Details |
|---|---|
| Python 3.10+ with `hashlib`, `subprocess` | Required |
| Remote access to target systems (SSH, WinRM) | Required |
| Memory acquisition tools (LiME, WinPmem, AVML) | Required |
| Secure evidence storage with write-once capability | Required |

## Key Concepts

### Evidence Collection Order (RFC 3227)

```python
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any


COLLECTION_ORDER: list[str] = [
    "memory",          # Most volatile — collect first
    "network_state",   # Active connections, routing tables
    "running_processes",  # Process list, open files
    "system_logs",     # May be overwritten by log rotation
    "disk_image",      # Least volatile — collect last
]


@dataclass
class EvidenceItem:
    """A single collected evidence artifact."""

    item_id: str
    item_type: str
    source_host: str
    collection_time: str
    sha256_hash: str
    size_bytes: int
    collector: str
    storage_path: str
    notes: str = ""
```

### Chain of Custody Tracking

```python
import hashlib


@dataclass
class CustodyRecord:
    """Chain of custody entry for evidence tracking."""

    evidence_id: str
    action: str
    actor: str
    timestamp: str
    integrity_hash: str
    location: str
    notes: str = ""


def create_custody_chain(evidence: EvidenceItem) -> list[CustodyRecord]:
    """Initialize chain of custody for collected evidence."""
    return [CustodyRecord(
        evidence_id=evidence.item_id,
        action="collected",
        actor=evidence.collector,
        timestamp=evidence.collection_time,
        integrity_hash=evidence.sha256_hash,
        location=evidence.storage_path,
        notes=f"Initial collection from {evidence.source_host}",
    )]


def verify_evidence_integrity(
    file_path: str,
    expected_hash: str,
) -> dict[str, Any]:
    """Verify evidence file integrity against chain-of-custody hash."""
    sha256 = hashlib.sha256()
    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(8192), b""):
            sha256.update(chunk)
    actual = sha256.hexdigest()
    return {
        "file": file_path,
        "expected": expected_hash[:16] + "...",
        "actual": actual[:16] + "...",
        "integrity_valid": actual == expected_hash,
    }
```

### Volatile Data Collector

```python
import subprocess


def collect_volatile_data(hostname: str) -> dict[str, Any]:
    """Collect volatile system data via SSH."""
    collectors: dict[str, str] = {
        "network_connections": "ss -tunapl",
        "running_processes": "ps auxf",
        "logged_in_users": "who -a",
        "open_files": "lsof -nP 2>/dev/null | head -500",
        "routing_table": "ip route show",
        "arp_cache": "ip neigh show",
        "dns_cache": "resolvectl statistics 2>/dev/null || echo 'N/A'",
    }
    results: dict[str, Any] = {}
    for name, cmd in collectors.items():
        result = subprocess.run(
            ["ssh", hostname, cmd],
            capture_output=True, text=True, check=False, timeout=30,
        )
        results[name] = {
            "command": cmd,
            "stdout_lines": len(result.stdout.splitlines()),
            "collected": result.returncode == 0,
        }
    return results
```

## Workflow

### Step 1: Initiate Collection

```bash
node scripts/agent.js --action collect --target workstation-42 --case INC-001
```

### Step 2: Verify Evidence Integrity

```bash
node scripts/agent.js --action verify --case INC-001
```

### Step 3: Generate Chain of Custody Report

```bash
node scripts/agent.js --action custody-report --case INC-001
```

## Detection

```yaml
title: Automated Forensic Collection Detection
id: 506ef2d2-2558-484d-95ef-6537a0ec7743
status: experimental
description: Detects suspicious activity related to building automated forensic collection techniques in security operations automation context
logsource:
  category: process_creation
  product: linux
detection:
  selection:
    CommandLine: "*building*automated*"
  condition: selection
level: medium
tags:
  - attack.t1005
  - attack.discovery
falsepositives:
  - Orchestration platform executing approved automation workflows
```


**Detection Opportunities**

| Indicator | Source | Detection Logic |
|---|---|---|
| Automated Forensic Collection Detection | linux/process_creation | Sigma rule (medium) |
| ATT&CK Coverage | MITRE ATT&CK | T1005 |

## Verification

- [ ] Volatile data collected before containment actions
- [ ] SHA-256 hash computed at collection time
- [ ] Chain of custody initialized for every evidence item
- [ ] Evidence integrity verifiable at any point

## References

- [RFC 3227 — Guidelines for Evidence Collection](https://www.rfc-editor.org/rfc/rfc3227)
- [NIST SP 800-86 — Guide to Integrating Forensic Techniques](https://csrc.nist.gov/publications/detail/sp/800-86/final)
- [SANS Digital Forensics and Incident Response](https://www.sans.org/digital-forensics-incident-response/)
