<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: performing-dynamic-analysis
description: >-
  Execute malware samples in controlled sandbox environments to observe runtime
  behavior including file system, registry, network, and process activity.
domain: cybersecurity
subdomain: malware-analysis
tags:
  - dynamic-analysis
  - sandbox
  - behavioral-analysis
  - network-capture
  - api-monitoring
  - capa
  - process-monitor
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1587.001"]
---

# Performing Dynamic Analysis

## Overview

Dynamic analysis involves executing malware in a controlled environment to observe its runtime behavior — file system modifications, registry changes, network communications, process creation, and API calls. This complements static analysis by revealing behaviors hidden behind obfuscation, packing, or anti-analysis techniques. Effective dynamic analysis requires proper sandbox configuration, network simulation, artifact collection, and behavioral correlation with MITRE ATT&CK techniques.

## Prerequisites

- Isolated analysis VM (FlareVM/REMnux) with snapshots
- CAPE Sandbox, Cuckoo Sandbox, or Any.run access
- Procmon (Sysinternals) for Windows API monitoring
- FakeNet-NG or INetSim for network simulation
- Wireshark/tcpdump for network capture
- Sysmon configured for comprehensive logging
- Python 3.10+ with `capa`, `requests`
- No production network access from analysis VM

## Key Concepts

### Sandbox Evasion Techniques

Malware commonly checks for analysis environments before executing payload:

| Technique | Check | Bypass |
|-----------|-------|--------|
| VM detection | Registry keys, MAC prefix, CPUID | Harden VM, remove artifacts |
| Debugger detection | `IsDebuggerPresent`, timing checks | ScyllaHide, TitanHide |
| User interaction | Mouse movement, click count | Auto-click scripts |
| Environment checks | Username, domain, file count | Realistic environment setup |
| Time bombs | Delayed execution, date checks | Accelerate clock, patch sleep |
| Hardware checks | CPU count, RAM size, disk size | Allocate realistic resources |

### Behavioral Categories

| Category | Artifacts | Tools |
|----------|-----------|-------|
| File system | Created/modified/deleted files | Procmon, Sysmon |
| Registry | Persistence keys, configuration | Procmon, Regshot |
| Network | C2 communication, downloads | FakeNet-NG, Wireshark |
| Process | Spawned processes, injection | Procmon, Process Hacker |
| API calls | Suspicious function usage | API Monitor, x64dbg |

## Workflow

### Step 1: Environment Preparation

```bash
# Snapshot clean VM state
# VirtualBox example:
VBoxManage snapshot "AnalysisVM" take "clean_state"

# Start network simulation
sudo inetsim --data-dir /var/lib/inetsim --report-dir /var/log/inetsim &

# OR use FakeNet-NG
sudo fakenet-ng --config fakenet.cfg &

# Start packet capture
sudo tcpdump -i eth0 -w /tmp/capture.pcap &

# Start Procmon (Windows VM)
# Procmon.exe /Quiet /Minimized /BackingFile /tmp/procmon.pml

# Take filesystem baseline with Regshot
# Regshot → 1st shot
```

### Step 2: Execute Sample

```bash
# Execute with timeout (Linux)
timeout 300 ./sample.elf

# Execute with monitoring (Windows - via PowerShell)
# Start-Process -FilePath "sample.exe" -PassThru | Tee-Object -Variable proc
# Start-Sleep -Seconds 300
# Stop-Process -Id $proc.Id -Force

# For DLLs
rundll32.exe malicious.dll,DllMain
rundll32.exe malicious.dll,#1  # By ordinal

# For scripts
cscript.exe malicious.js
wscript.exe malicious.vbs
powershell.exe -File malicious.ps1
```

### Step 3: Collect Behavioral Artifacts

```python
#!/usr/bin/env python3
"""Collect and correlate behavioral artifacts from dynamic analysis."""
import json
import subprocess
from pathlib import Path
from datetime import datetime

def collect_filesystem_changes(baseline_dir: str, current_dir: str) -> dict:
    """Compare filesystem state before/after execution."""
    baseline = set()
    current = set()

    for p in Path(baseline_dir).rglob("*"):
        if p.is_file():
            baseline.add(str(p.relative_to(baseline_dir)))

    for p in Path(current_dir).rglob("*"):
        if p.is_file():
            current.add(str(p.relative_to(current_dir)))

    return {
        "created": sorted(current - baseline),
        "deleted": sorted(baseline - current),
        "total_changes": len(current - baseline) + len(baseline - current),
    }

def parse_pcap_summary(pcap_path: str) -> dict:
    """Extract network summary from PCAP."""
    result = {"dns_queries": [], "http_requests": [], "tcp_connections": []}
    try:
        # DNS queries
        dns_out = subprocess.run(
            ["tshark", "-r", pcap_path, "-Y", "dns.qry.name", "-T", "fields",
             "-e", "dns.qry.name"],
            capture_output=True, text=True, timeout=30,
        )
        result["dns_queries"] = sorted(set(dns_out.stdout.strip().split("\n")))

        # HTTP requests
        http_out = subprocess.run(
            ["tshark", "-r", pcap_path, "-Y", "http.request", "-T", "fields",
             "-e", "http.host", "-e", "http.request.uri", "-e", "http.request.method"],
            capture_output=True, text=True, timeout=30,
        )
        for line in http_out.stdout.strip().split("\n"):
            if line.strip():
                result["http_requests"].append(line.strip())

    except (subprocess.TimeoutExpired, FileNotFoundError):
        result["error"] = "tshark not available or timed out"

    return result
```

### Step 4: Capability Analysis with CAPA

```bash
# Run capa against sample
capa sample.exe -j > capa_results.json

# Run against unpacked/dumped samples
capa unpacked.exe -v

# Common capability categories:
# - communication: HTTP client, DNS resolution, socket operations
# - persistence: registry modification, scheduled tasks, services
# - defense-evasion: process injection, anti-debugging, anti-VM
# - collection: clipboard access, screen capture, keylogging
# - execution: shellcode execution, process creation
```

### Step 5: Behavioral Report Generation

```python
def generate_behavioral_report(
    sample_hash: str,
    filesystem_changes: dict,
    network_activity: dict,
    capa_results: dict,
) -> dict:
    """Generate comprehensive behavioral analysis report."""
    report = {
        "sample_hash": sample_hash,
        "analysis_timestamp": datetime.utcnow().isoformat(),
        "verdict": "unknown",
        "risk_score": 0,
        "behaviors": {
            "filesystem": filesystem_changes,
            "network": network_activity,
            "capabilities": capa_results,
        },
        "mitre_attack": [],
        "iocs": {
            "domains": network_activity.get("dns_queries", []),
            "urls": network_activity.get("http_requests", []),
            "files_created": filesystem_changes.get("created", []),
        },
    }

    # Score based on behaviors
    score = 0
    if filesystem_changes.get("created"):
        score += 10
    if network_activity.get("dns_queries"):
        score += 20
    if network_activity.get("http_requests"):
        score += 25

    if score >= 50:
        report["verdict"] = "malicious"
    elif score >= 25:
        report["verdict"] = "suspicious"

    report["risk_score"] = min(score, 100)
    return report
```

## Detection

```yaml
title: Dynamic Analysis Detection
id: ef2e3ee7-e761-47f4-8a0a-261e5e62b891
status: experimental
description: Detects suspicious activity related to performing dynamic analysis techniques in malware analysis context
logsource:
  category: process_creation
  product: windows
detection:
  selection:
    CommandLine: "*performing*dynamic*"
  condition: selection
level: high
tags:
  - attack.t1587.001
  - attack.execution
falsepositives:
  - Sandbox detonation environments analyzing submitted samples
```

## Verification

- [ ] Analysis VM snapshot taken before execution
- [ ] Network simulation active (no real internet access)
- [ ] Sample executed with appropriate timeout
- [ ] File system changes documented
- [ ] Registry modifications captured
- [ ] Network traffic captured and analyzed
- [ ] Process tree documented
- [ ] CAPA capabilities identified
- [ ] Behavioral report generated with MITRE mapping
- [ ] VM restored to clean snapshot

## References

- [CAPE Sandbox](https://github.com/kevoreilly/CAPEv2)
- [FakeNet-NG - Network Simulation](https://github.com/mandiant/flare-fakenet-ng)
- [CAPA - Capability Detection](https://github.com/mandiant/capa)
- [Sysinternals Procmon](https://learn.microsoft.com/en-us/sysinternals/downloads/procmon)
- [MITRE ATT&CK - Execution Techniques](https://attack.mitre.org/tactics/TA0002/)
