<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
<!-- NERF is a trademark of defconxt. -->
---
name: implementing-email-sandboxing
description: >-
  Implement and configure email sandboxing for dynamic analysis of attachments
  and URLs. Covers detonation policies, evasion-resistant sandbox configuration,
  verdict integration with email gateways, and detection of sandbox-aware malware.
domain: cybersecurity
subdomain: email-security
tags:
  - sandboxing
  - malware-analysis
  - detonation
  - attachment-analysis
  - url-rewriting
  - evasion
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1566.001", "T1204.002", "T1027"]
  tools: [python3, curl, jq, yara]
---

# Implementing Email Sandboxing

## Overview

Email sandboxing detonates suspicious attachments and URLs in isolated
environments to detect malicious behavior before delivery. Effective
implementation requires evasion-resistant configurations, proper verdict
thresholds, URL rewriting for time-of-click protection, and integration
with SIEM for retrospective analysis when verdicts change.

## Prerequisites

| Requirement | Purpose |
|---|---|
| Sandbox platform | Detonation environment (cloud or on-prem) |
| Email gateway integration | Route attachments/URLs to sandbox |
| YARA rules | Static pre-filtering before detonation |
| API access | Submit samples and retrieve verdicts |

## Workflow

### Step 1: Configure Detonation Policies

```python
# Define file types requiring sandbox analysis
DETONATE_EXTENSIONS = {
    "high": [".exe", ".dll", ".scr", ".bat", ".cmd", ".ps1", ".vbs",
             ".js", ".wsf", ".hta", ".msi"],
    "medium": [".doc", ".docm", ".xls", ".xlsm", ".ppt", ".pptm",
               ".pdf", ".rtf", ".zip", ".rar", ".7z", ".iso", ".img"],
    "low": [".docx", ".xlsx", ".pptx", ".txt", ".csv"],
}

# Sample detonation policy
POLICY = {
    "max_file_size_mb": 50,
    "detonation_timeout_sec": 300,
    "os_profiles": ["win10_22h2", "win11_23h2"],
    "enable_network": True,
    "extract_archives": True,
    "max_archive_depth": 3,
    "redetonate_on_sig_update": True,
}
```

### Step 2: Pre-Filter with YARA

```bash
# Static scan before sandbox submission
cat <<'EOF' > email_prefilter.yar
rule Suspicious_Macro_Document {
    meta:
        description = "Document with suspicious macro indicators"
    strings:
        $vba1 = "AutoOpen" ascii
        $vba2 = "Document_Open" ascii
        $shell = "Shell" ascii
        $powershell = "powershell" ascii nocase
        $wscript = "WScript" ascii nocase
    condition:
        uint16(0) == 0xCFD0 and ($vba1 or $vba2) and ($shell or $powershell or $wscript)
}
EOF

yara email_prefilter.yar attachment.doc
```

### Step 3: API Integration for Submission

```python
import hashlib
from typing import Any

def submit_to_sandbox(file_path: str, api_url: str, api_key: str) -> dict[str, Any]:
    """Submit a file to the sandbox for analysis."""
    import requests

    with open(file_path, "rb") as f:
        file_data = f.read()

    sha256 = hashlib.sha256(file_data).hexdigest()

    # Check if already analyzed
    check = requests.get(
        f"{api_url}/reports/{sha256}",
        headers={"Authorization": f"Bearer {api_key}"},
        timeout=30,
    )
    if check.status_code == 200:
        return {"status": "cached", "sha256": sha256, "report": check.json()}

    # Submit for analysis
    resp = requests.post(
        f"{api_url}/submit",
        headers={"Authorization": f"Bearer {api_key}"},
        files={"file": (file_path, file_data)},
        data={"timeout": 300, "env": "win10_22h2"},
        timeout=60,
    )
    return {"status": "submitted", "sha256": sha256, "task_id": resp.json().get("task_id")}
```

### Step 4: URL Rewriting for Time-of-Click Protection

```bash
# Test URL rewriting is active
# Original URL should be wrapped in sandbox proxy
echo "Original: https://evil.com/payload"
echo "Rewritten: https://sandbox.example.com/v1/url?target=aHR0cHM6Ly9ldmlsLmNvbS9wYXlsb2Fk"

# Verify rewritten URLs resolve through sandbox
curl -sI "https://sandbox.example.com/v1/url?target=aHR0cHM6Ly9ldmlsLmNvbS9wYXlsb2Fk" | head -5
```

## Detection Opportunities

| Signal | Source | Description |
|--------|--------|-------------|
| Sandbox verdict change | Sandbox API | Retroactive detection — clean-to-malicious |
| Detonation evasion | Sandbox logs | Sample sleeps, checks VM artifacts, exits |
| High-risk bypass | Email gateway | File type not routed to sandbox |

```yaml
title: Email Sandboxing Detection
id: a72ace60-651a-4caf-b55c-7ad7dd8da964
status: experimental
description: Detects suspicious activity related to implementing email sandboxing techniques in email security context
logsource:
  category: email
  service: exchange
detection:
  selection:
    Subject: "*urgent*"
  condition: selection
level: medium
tags:
  - attack.t1566.001
  - attack.t1204.002
  - attack.t1027
  - attack.initial_access
falsepositives:
  - Bulk email migration by authorized IT administration tools
```

## Verification

- [ ] All high-risk file types routed to sandbox before delivery
- [ ] Detonation timeout sufficient for delayed payloads (≥300s)
- [ ] Multiple OS profiles configured for evasion resistance
- [ ] URL rewriting active for all inbound links
- [ ] Retroactive verdict changes trigger message recall
- [ ] YARA pre-filtering reduces unnecessary sandbox load

## References

- [MITRE T1566.001 — Spearphishing Attachment](https://attack.mitre.org/techniques/T1566/001/)
- [MITRE T1027 — Obfuscated Files](https://attack.mitre.org/techniques/T1027/)
- [YARA Documentation](https://yara.readthedocs.io/)

---
v1.0 | Validated: 2026-03-18
