<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: performing-sandbox-evasion-analysis
description: >-
  Identify and analyze sandbox evasion techniques used by malware to detect
  virtualized environments, delay execution, and bypass automated analysis
  systems.
domain: cybersecurity
subdomain: malware-analysis
tags:
  - sandbox-evasion
  - anti-analysis
  - anti-vm
  - anti-debug
  - time-based-evasion
  - malware-analysis
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1497"]
---

# Performing Sandbox Evasion Analysis

## Overview

Malware employs sandbox evasion to detect automated analysis environments and alter behavior — either terminating, sleeping, or executing benign logic to avoid triggering detections. Techniques include VM detection (CPUID checks, registry artifacts, MAC address prefixes), timing-based evasion (sleep calls, RDTSC delta checks), user interaction requirements (mouse movement, click counts), and environment fingerprinting (process count thresholds, username checks, screen resolution). Analysts must identify these checks statically, patch or bypass them dynamically, and document the evasion taxonomy.

## Prerequisites

- x64dbg / x32dbg with ScyllaHide (anti-anti-debug plugin)
- Ghidra or IDA for static identification of evasion code
- CAPE / Any.run / Joe Sandbox with evasion monitoring
- Pafish (Paranoid Fish) for environment evasion testing
- al-khaser for comprehensive anti-analysis technique testing
- Python 3.10+ with `pefile`, `yara-python`, `capstone`

## Key Concepts

### Evasion Categories

| Category | Technique | Detection |
|----------|-----------|-----------|
| Anti-VM | CPUID hypervisor bit, VM-specific registry keys | Static string/import analysis |
| Anti-Debug | IsDebuggerPresent, NtQueryInformationProcess | Import analysis, API monitoring |
| Timing | Sleep(>5min), RDTSC delta, GetTickCount | Behavioral monitoring, patching |
| User Interaction | Mouse movement, click counters, dialog boxes | Sandbox UI simulation |
| Environment | Process count > 50, RAM > 4GB, disk > 100GB | Environment fingerprinting |

### Common Anti-VM Checks

- **CPUID leaf 0x1**: Hypervisor bit (ECX bit 31)
- **Registry**: `HKLM\SOFTWARE\VMware`, `HKLM\SYSTEM\*\VBoxGuest`
- **MAC prefix**: `00:0C:29` (VMware), `08:00:27` (VirtualBox)
- **WMI**: `Win32_ComputerSystem.Model` contains "Virtual"
- **Filenames**: `vmtoolsd.exe`, `VBoxService.exe` in process list

## Workflow

### Step 1: Static Identification of Evasion Code

```bash
# Search for anti-VM strings
strings -a sample.exe | grep -iE "vmware|virtualbox|qemu|sandbox|vbox|hypervisor"

# Search for anti-debug API imports
python3 -c "
import pefile
pe = pefile.PE('sample.exe')
anti_debug = ['IsDebuggerPresent', 'CheckRemoteDebuggerPresent',
    'NtQueryInformationProcess', 'OutputDebugString', 'GetTickCount',
    'QueryPerformanceCounter', 'NtQuerySystemInformation']
if hasattr(pe, 'DIRECTORY_ENTRY_IMPORT'):
    for entry in pe.DIRECTORY_ENTRY_IMPORT:
        for imp in entry.imports:
            if imp.name and imp.name.decode() in anti_debug:
                print(f'⚠ Anti-debug: {entry.dll.decode()}: {imp.name.decode()}')
"

# YARA scan for evasion patterns
yara -s sandbox_evasion.yar sample.exe
```

### Step 2: Identify Timing-Based Evasion

```bash
# Ghidra script to find Sleep/delay calls
# Look for: Sleep(>300000), NtDelayExecution, GetTickCount delta > 5min
analyzeHeadless /tmp/project Evasion -import sample.exe \
    -postScript FindSleepCalls.py

# radare2 — find Sleep imports and their arguments
r2 -qc 'aaa; axt @sym.imp.Sleep' sample.exe

# In x64dbg: Set conditional breakpoint on Sleep
# bp Sleep condition: rcx > 300000
# Action: set rcx = 0 (skip long sleep)
```

### Step 3: Bypass Anti-Debug in x64dbg

```
# ScyllaHide plugin (comprehensive anti-anti-debug)
# Plugins → ScyllaHide → Options
# Enable: NtQueryInformationProcess, IsDebuggerPresent,
#         NtQuerySystemInformation, GetTickCount, RDTSC

# Manual patches:
# PEB.BeingDebugged = 0 (offset 0x2 in PEB)
bp IsDebuggerPresent
# When hit: set EAX=0, then execute return

# Patch RDTSC timing checks
bp rdtsc
# When hit: normalize return values
```

### Step 4: Analyze Environment Fingerprinting

```python
#!/usr/bin/env python3
"""Identify environment fingerprinting checks in disassembly."""
import re

EVASION_INDICATORS = {
    "vm_detection": [
        r"VMwareVMware", r"VBoxGuest", r"QEMU", r"Xen",
        r"0x40000000",  # CPUID hypervisor leaf
        r"00:0C:29", r"08:00:27",  # VM MAC prefixes
    ],
    "anti_debug": [
        r"IsDebuggerPresent", r"NtQueryInformationProcess",
        r"CheckRemoteDebuggerPresent", r"int\s+0x2d",
    ],
    "timing": [
        r"GetTickCount", r"QueryPerformanceCounter",
        r"rdtsc", r"timeGetTime",
    ],
    "environment": [
        r"GetCursorPos", r"GetForegroundWindow",
        r"GlobalMemoryStatusEx", r"GetDiskFreeSpaceEx",
    ],
}

def scan_binary(filepath: str) -> dict:
    with open(filepath, "rb") as f:
        data = f.read().decode(errors="replace")
    results: dict[str, list[str]] = {}
    for category, patterns in EVASION_INDICATORS.items():
        matches = []
        for pat in patterns:
            if re.search(pat, data, re.IGNORECASE):
                matches.append(pat)
        if matches:
            results[category] = matches
    return results

print(scan_binary("sample.exe"))
```

### Step 5: Document Evasion Taxonomy

```bash
# Run al-khaser or Pafish to enumerate all evasion vectors
# Cross-reference findings with MITRE ATT&CK
# T1497.001 — System Checks (VM detection)
# T1497.002 — User Activity Based Checks
# T1497.003 — Time Based Evasion
# T1622    — Debugger Evasion
```

## YARA Rule

```yara
rule Sandbox_Evasion_Checks {
    meta:
        description = "Detects sandbox and anti-analysis evasion techniques"
        author = "NERF"
        date = "2026-03-17"
        mitre_attack = "T1497"
        severity = "medium"
    strings:
        $vm1 = "VMwareVMware" ascii wide
        $vm2 = "VBoxGuest" ascii wide
        $vm3 = "QEMU" ascii wide
        $vm4 = "SbieDll" ascii wide
        $dbg1 = "IsDebuggerPresent" ascii
        $dbg2 = "CheckRemoteDebuggerPresent" ascii
        $dbg3 = "NtQueryInformationProcess" ascii
        $env1 = "GetCursorPos" ascii
        $env2 = "GlobalMemoryStatusEx" ascii
        $time1 = { 0F 31 }  // rdtsc instruction
    condition:
        uint16(0) == 0x5A4D and
        (2 of ($vm*) or 2 of ($dbg*) or ($time1 and any of ($env*)))
}
```

## Detection

```yaml
title: Sandbox Evasion Analysis Detection
id: 00496e66-f0c5-48a7-9667-520053a7c0be
status: experimental
description: Detects suspicious activity related to performing sandbox evasion analysis techniques in malware analysis context
logsource:
  category: process_creation
  product: windows
detection:
  selection:
    CommandLine: "*performing*sandbox*"
  condition: selection
level: high
tags:
  - attack.t1497
  - attack.execution
falsepositives:
  - Sandbox detonation environments analyzing submitted samples
```

## Verification

- [ ] Anti-VM checks identified (CPUID, registry, MAC, WMI)
- [ ] Anti-debug techniques catalogued with bypass methods
- [ ] Timing-based evasion documented (Sleep values, RDTSC)
- [ ] Environment fingerprinting checks mapped
- [ ] All evasion bypassed — real payload extracted
- [ ] Evasion techniques mapped to MITRE ATT&CK (T1497, T1622)
- [ ] Sandbox configuration recommendations documented

## References

- [MITRE ATT&CK T1497 — Virtualization/Sandbox Evasion](https://attack.mitre.org/techniques/T1497/)
- [al-khaser — Anti-Analysis Techniques](https://github.com/LordNoteworthy/al-khaser)
- [Pafish — Paranoid Fish](https://github.com/a0rtega/pafish)
- [CheckPoint — Evasion Techniques Encyclopedia](https://evasions.checkpoint.com/)
