# How CAPEv2 Detects and Counters Anti-Sandbox Evasion Techniques

> Discover how CAPEv2 defeats anti-sandbox evasion with YARA rules behavioral analysis and environmental noise injection. Protect your systems effectively against sophisticated threats.

- Repository: [Kevin O'Reilly/capev2](https://github.com/kevoreilly/capev2)
- Tags: deep-dive
- Published: 2026-03-05

---

**CAPEv2 employs a defense-in-depth strategy combining static YARA rules, runtime behavioral signatures, and active environmental noise injection to both identify and neutralize anti-sandbox evasion attempts.**

CAPEv2 (the successor to Cuckoo Sandbox) is an open-source malware analysis system designed to safely execute and monitor suspicious samples. To maintain analysis fidelity against increasingly evasive malware, the sandbox implements comprehensive mechanisms to **detect and counter anti-sandbox evasion techniques** through both passive detection and active countermeasures. The system maps observed behaviors to standardized taxonomies like MITRE ATT&CK and MAEC, providing analysts with structured intelligence on evasion attempts.

## Static Detection via YARA and CAPA

CAPEv2 begins detection before execution through static analysis rules that match known evasion code patterns.

### YARA Anti-Analysis Rules

The repository maintains a curated rule set in `analyzer/windows/data/yara/AntiCuckoo.yar` that identifies common anti-sandbox artifacts. These rules detect virtualization checks, timing tricks, and known sandbox API calls within the binary prior to execution. The [`.yara-ci.yml`](https://github.com/kevoreilly/capev2/blob/main/.yara-ci.yml) pipeline ensures these rules remain current through automated testing on each commit.

### MITRE ATT&CK Mapping with CAPA

The CAPA integration module ([`lib/cuckoo/common/integrations/capa.py`](https://github.com/kevoreilly/capev2/blob/main/lib/cuckoo/common/integrations/capa.py)) maps low-level API calls to specific tactics. When malware calls `CheckRemoteDebuggerPresent` or `IsDebuggerPresent`, CAPEv2 translates these into MITRE ATT&CK techniques such as `anti-analysis/anti-debugging/debugger-detection`, providing standardized classification of evasion behaviors.

## Runtime Behavioral Scoring and Classification

During dynamic analysis, CAPEv2 monitors execution to identify behavioral indicators of evasion attempts.

### Signature-Based Detection

The analysis engine generates behavioral signatures categorized by evasion type. When a sample exhibits suspicious activity—such as reading VM-specific registry keys or calling `GetTickCount` to detect time-skipping—the engine emits signature names including `antivm`, `antisandbox`, `antiav`, `antiemu`, and `antidbg`. These signatures feed directly into the final report generation.

### Risk Scoring System

Located in [`lib/cuckoo/common/scoring.py`](https://github.com/kevoreilly/capev2/blob/main/lib/cuckoo/common/scoring.py), the scoring algorithm parses detected signatures and assigns elevated "malware" scores to samples exhibiting anti-analysis categories. The system assigns higher risk ratings to samples attempting **anti-sandbox**, **anti-vm**, or **anti-debug** activities, flagging them for priority review in the UI.

### MAEC5 Capability Mapping

The reporting module [`modules/reporting/maec5.py`](https://github.com/kevoreilly/capev2/blob/main/modules/reporting/maec5.py) translates raw signatures into structured MAEC capabilities. The capability mapping dictionary categorizes evasion techniques as follows:

```python

# modules/reporting/maec5.py (excerpt)

capability_mappings = {
    "antivm": {"name": "anti-behavioral-analysis", "refined_capabilities": [{"name": "anti-vm"}]},
    "antiav": {"name": "anti-detection", "refined_capabilities": [{"name": "anti-virus-evasion"}]},
    "antisandbox": {"name": "anti-behavioral-analysis", "refined_capabilities": [{"name": "anti-sandbox"}]},
    "antidbg": {"name": "anti-code-analysis", "refined_capabilities": [{"name": "anti-debugging"}]},
    "antiemu": {"name": "anti-behavioral-analysis", "refined_capabilities": [{"name": "anti-emulation"}]},
}

```

These mappings appear in the final JSON and HTML reports, explicitly tagging which anti-sandbox techniques were observed during analysis.

## Active Counter-Measures and Environmental Deception

CAPEv2 actively manipulates the analysis environment to defeat heuristic-based evasion checks.

### Recent Files Population

The auxiliary module [`analyzer/windows/modules/auxiliary/recentfiles.py`](https://github.com/kevoreilly/capev2/blob/main/analyzer/windows/modules/auxiliary/recentfiles.py) defeats recent-file heuristics by generating realistic user activity. Many malware samples check for recent-document history as a sandbox presence indicator. The module creates random files in desktop, documents, and downloads folders, then registers them with the Windows Shell API:

```python

# analyzer/windows/modules/auxiliary/recentfiles.py

def start(self):
    if not self.enabled:
        return
    dirpath = self.get_path()               # resolves known shell folder ID

    for _ in range(random.randint(5, 10)):
        filename = random_string(10, random.randint(10, 20))
        ext = random.choice(self.extensions)
        filepath = os.path.join(dirpath, f"{filename}.{ext}")
        open(filepath, "wb").write(os.urandom(random.randint(30, 999999)))
        SHELL32.SHAddToRecentDocs(SHARD_PATHA, filepath)   # adds to recent‑files list

```

### Process List Camouflage

Specialized analysis packages `js_antivm` and `doc_antivm` (located in `analyzer/windows/modules/packages/`) defeat simple VM-detection tricks that count processes or look for missing UI components. Before executing the payload, these packages launch **20 Calculator** instances (`calc.exe`) to inflate the process list and simulate normal user activity.

### Environment Randomization

The provisioning scripts [`utils/vpn2cape.py`](https://github.com/kevoreilly/capev2/blob/main/utils/vpn2cape.py) and [`utils/router_manager.py`](https://github.com/kevoreilly/capev2/blob/main/utils/router_manager.py) randomize network topology, MAC addresses, and VM resources during environment setup. This prevents malware from fingerprinting the sandbox infrastructure through static hardware or network identifiers.

## Configuration and Usage Examples

Enable countermeasures through the configuration system or submission parameters.

### Enabling Recent Files Population

Configure the auxiliary module via [`conf/analysis.conf`](https://github.com/kevoreilly/capev2/blob/main/conf/analysis.conf):

```ini

# conf/analysis.conf (or a custom .conf in $CAPE_ROOT/conf)

[analysis]

# Turn on the RecentFiles helper to defeat recent‑file checks

recentfiles = true

```

Alternatively, toggle at runtime:

```python
from lib.common.config import Config

cfg = Config()
cfg.recentfiles = True      # forces the auxiliary to run

```

### Using Anti-VM Packages

Submit samples with specialized packages to activate process camouflage:

```bash

# Submit a JavaScript sample with the anti‑VM package

capev2-submit -p js_antivm /path/to/malicious.js

```

The `js_antivm` package executes the sample with `wscript.exe` only after marking the analysis as `free` (to ignore background processes) and launching the dummy Calculator windows.

### Inspecting Detection Results

Extract anti-sandbox capabilities from the generated report:

```python
import json

with open("reports/analysis_001.json") as f:
    report = json.load(f)

# Print all detected anti‑analysis capabilities

caps = [sig["name"] for sig in report.get("signatures", [])
        if sig["name"] in ("antivm", "antisandbox", "antiav", "antiemu", "antidbg")]
print("Anti‑analysis capabilities:", caps)

```

## Summary

- **Static detection** via `AntiCuckoo.yar` and CAPA integration identifies evasion code before execution and maps API calls to MITRE ATT&CK techniques.
- **Behavioral analysis** generates signatures (`antivm`, `antisandbox`, etc.) that the scoring system weights heavily to prioritize evasive samples.
- **MAEC5 reporting** ([`modules/reporting/maec5.py`](https://github.com/kevoreilly/capev2/blob/main/modules/reporting/maec5.py)) standardizes evasion classifications for automated processing and threat intelligence sharing.
- **Active countermeasures** include the `recentfiles` auxiliary for history spoofing and anti-VM packages that launch dummy processes to mask virtualization artifacts.
- **Infrastructure randomization** via VPN and router management scripts prevents hardware fingerprinting across analysis runs.

## Frequently Asked Questions

### How does CAPEv2 detect if malware is checking for a virtual machine?

CAPEv2 detects VM-checking behavior through multiple layers. The YARA rules in `analyzer/windows/data/yara/AntiCuckoo.yar` match static VM-detection code patterns, while runtime monitoring captures API calls like `cpuid` or registry queries for VM-specific keys (e.g., `HKLM\SOFTWARE\VMware`). These trigger the `antivm` behavioral signature, which the scoring system weights heavily in the final risk assessment.

### What is the purpose of launching 20 Calculator instances in CAPEv2?

The 20 Calculator instances serve as **process list camouflage** to defeat heuristic checks. Many malware samples detect sandboxes by counting running processes or checking for minimal user activity. By launching multiple `calc.exe` windows before execution, the `js_antivm` and `doc_antivm` packages simulate a busy, legitimate user environment, causing simple enumeration-based evasion logic to fail.

### How can I enable anti-sandbox countermeasures in my CAPEv2 analysis?

Enable the **RecentFiles** auxiliary by setting `recentfiles = true` in [`conf/analysis.conf`](https://github.com/kevoreilly/capev2/blob/main/conf/analysis.conf). For process camouflage, submit samples with the appropriate anti-VM package flag (e.g., `-p js_antivm`). These configurations require no code recompilation and can be toggled per-analysis based on the expected threat level or sample type.

### Where does CAPEv2 store anti-sandbox detection results in the final report?

Detection results appear in the `signatures` array of the JSON report (typically `reports/analysis_*.json`), with specific entries for `antivm`, `antisandbox`, `antiav`, `antiemu`, and `antidbg`. The MAEC5 reporting module enriches these with standardized capability mappings, storing the structured data under `capabilities` fields that align with MITRE ATT&CK and MAEC taxonomies for automated parsing by downstream security tools.