# 沙箱编排与自动化

## 沙箱选型

| 沙箱 | 类型 | 速度 | 逃逸检测 | 推荐场景 |
|------|:--:|------|:--:|------|
| CAPE v2 | 开源 | 中 | 强 | 深度分析 + YARA 集成 |
| ASD Azul | 开源 | 快 | 中 | 大规模批量分类 |
| Joe Sandbox | 商业 | 中 | 极强 | 高价值样本深度分析 |
| ANY.RUN | 商业云 | 快 | 中 | 交互式快速分诊 |
| Triage | 商业云 | 极快 | 弱 | 批量初筛 |
| Cuckoo v3 | 开源 | 慢 | 弱 | 学习/研究 |

## CAPE Sandbox 部署

```bash
# Ubuntu 22.04+
git clone https://github.com/kevoreilly/CAPEv2
cd CAPEv2
sudo ./cape2.sh base    # 安装依赖
sudo ./cape2.sh all     # 完整安装

# Web 界面: http://localhost:8000
# API: http://localhost:8000/apiv2/

# 提交样本
curl -F "file=@sample.exe" http://localhost:8000/apiv2/tasks/create/file/

# 批量提交
for f in samples/*.exe; do
    curl -F "file=@$f" http://localhost:8000/apiv2/tasks/create/file/
done
```

## 自动化分析管道

```python
# 多沙箱串联管道
import requests
import time

def analyze_sample(filepath):
    """提交样本到多个沙箱并汇总结果"""
    results = {}

    # 1. 快速分诊（Triage）
    triage_result = submit_to_triage(filepath)
    results['triage'] = triage_result

    # 2. 如果 triage 判定可疑 → 深度分析
    if triage_result['score'] >= 5:
        cape_result = submit_to_cape(filepath)
        results['cape'] = cape_result

        # 3. YARA 规则扫描
        yara_matches = run_yara(filepath, 'rules/')
        results['yara'] = yara_matches

        # 4. Sigma 规则生成
        if cape_result.get('behaviors'):
            sigma_rules = generate_sigma(cape_result['behaviors'])
            results['sigma'] = sigma_rules

    # 5. IOC 汇总
    iocs = extract_iocs(results)
    results['iocs'] = iocs

    return results

def submit_to_cape(filepath):
    resp = requests.post(
        'http://cape:8000/apiv2/tasks/create/file/',
        files={'file': open(filepath, 'rb')},
        data={'timeout': 300, 'enforce_timeout': True}
    )
    task_id = resp.json()['task_id']

    # 轮询等待完成
    while True:
        status = requests.get(
            f'http://cape:8000/apiv2/tasks/view/{task_id}'
        ).json()['task']['status']
        if status == 'reported':
            break
        time.sleep(5)

    return requests.get(
        f'http://cape:8000/apiv2/tasks/report/{task_id}/json/'
    ).json()
```

## ASD Azul 集成

```bash
# Azul — 2026 年 ASD 发布的免费大规模分析平台
git clone https://github.com/AustralianSignalsDirectorate/azul
cd azul

# 批量导入样本
azul import samples/ --tags "phishing_campaign_202605"

# 应用 YARA 规则
azul scan --yara rules/anti_vm_rules.yar

# Snort 规则检测
azul scan --snort rules/c2_detection.rules

# 自动提取 IOC
azul export --format stix2 --output iocs.json

# 自定义插件
azul plugin add custom_unpacker.py  # 添加自定义解包逻辑
```

## 反沙箱对抗

### 常见沙箱逃逸技术

```text
1. 定时延迟
   → Sleep(120000) // 2分钟，超出沙箱超时
   → 检测: Hook Sleep → 加速时间

2. 用户交互检测
   → GetTickCount() 检查鼠标移动
   → 检测: 模拟用户交互

3. 磁盘大小检测
   → GetDiskFreeSpaceEx < 60GB
   → 检测: 扩展虚拟磁盘

4. 特定文件/进程检测
   → C:\agent\agent.pyw (CAPE)
   → 检测: 重命名检测组件

5. WMI 虚拟机检测
   → Win32_ComputerSystem.Manufacturer = "VMware, Inc."
   → 检测: 修改 SMBIOS

6. MAC 地址检测
   → 00:0C:29 (VMware OUI), 08:00:27 (VirtualBox)
   → 检测: 随机 MAC
```

### CAPE 反逃逸配置

```python
# CAPE 配置
[processing]
# 启用反反分析
antievasion = yes

# 模拟人机交互
human_interaction = yes

# 最小运行时间
timeout = 600

# 检测特定技术
detect_sleep_skip = yes
detect_debugger_check = yes
detect_vm_check = yes
```

## IOC 自动化提取

```python
def extract_iocs(analysis_results):
    iocs = {
        'network': {'ip': [], 'domain': [], 'url': [], 'user_agent': []},
        'host': {'files': [], 'registry': [], 'mutex': [], 'services': []},
        'mitre': [],
        'hashes': {}
    }

    # CAPE → IOC 提取
    if 'cape' in analysis_results:
        cape = analysis_results['cape']
        behavior = cape.get('behavior', {})

        # 网络 IOC
        for conn in behavior.get('network', {}).get('tcp', []):
            iocs['network']['ip'].append(conn['dst'])
        for dns in behavior.get('network', {}).get('dns', []):
            iocs['network']['domain'].append(dns['request'])

        # 文件 IOC
        for dropped in behavior.get('dropped', []):
            iocs['host']['files'].append(dropped['path'])

        # Mutex
        for mutex in behavior.get('summary', {}).get('mutex', []):
            iocs['host']['mutex'].append(mutex)

    # YARA → MITRE 映射
    if 'yara' in analysis_results:
        for match in analysis_results['yara']:
            if 'mitre_id' in match.get('meta', {}):
                iocs['mitre'].extend(match['meta']['mitre_id'].split(','))

    return iocs
```

Source: CAPE v2 docs, ASD Azul documentation, Joe Sandbox v44, Anti-VM YARA Library (2026)
