--- name: sandbox-evasion-detection description: > Identify and defeat anti-analysis techniques used by malware to evade sandboxes, virtual machines, and debuggers. Use when analyzing samples that behave differently in analysis environments versus production systems, or when a sample appears to detect and avoid analysis. Covers VM detection, timing evasion, environment fingerprinting, anti-debugging, and countermeasures for each technique. Supports offline (static) and online (dynamic) analysis on Linux and Windows. --- # Sandbox Evasion Detection Identify anti-analysis techniques in malware samples and implement countermeasures to ensure the malware executes its full functionality during analysis. ## Prerequisites - **Linux**: `strings`, `objdump`, `python3`, `strace`, `ltrace` - **Windows**: Python 3, x64dbg/OllyDbg, Process Monitor, API Monitor - **Python packages**: `pefile`, `yara-python`, `capstone` (optional) - **Analysis VM**: VMware, VirtualBox, or QEMU/KVM with snapshot capability - **Optional**: IDA Pro / Ghidra for static analysis ## Step-by-Step Instructions ### Step 1: Check for VM/Sandbox Detection Code Scan the binary for indicators of VM/sandbox detection. **Using the evasion detector script:** ```bash python3 scripts/evasion_detector.py --file sample.exe python3 scripts/evasion_detector.py --file sample.exe --verbose --output report.json ``` **Manual string-based checks:** ```bash # VM vendor strings strings sample.exe | grep -iE "(vmware|virtualbox|vbox|qemu|xen|hyper-v|parallels|bochs|sandboxie)" # VM-specific files and registry keys strings sample.exe | grep -iE "(vmtoolsd|vboxservice|vboxtray|vmwaretray|vmmouse)" # Sandbox product names strings sample.exe | grep -iE "(cuckoomon|sbiedll|snxhk|avghooka|pstorec)" ``` **Check for VM detection APIs (Windows):** ```bash strings sample.exe | grep -iE "(IsDebuggerPresent|CheckRemoteDebugger|NtQueryInformationProcess|GetTickCount|QueryPerformanceCounter|rdtsc)" ``` See `references/vm-detection-artifacts.md` for a comprehensive list of artifacts checked by malware for each hypervisor. ### Step 2: Identify Timing-Based Evasion Malware uses timing checks to detect debugging or sandbox environments. **Common timing techniques:** | Technique | API/Instruction | Detection | |-----------|----------------|-----------| | RDTSC | `rdtsc` instruction | Look for `0F 31` opcode | | GetTickCount | `kernel32!GetTickCount` | Import table / strings | | QueryPerformanceCounter | `kernel32!QueryPerformanceCounter` | Import table | | timeGetTime | `winmm!timeGetTime` | Import table | | Sleep + check | `Sleep()` then time comparison | Behavioral pattern | | NtQuerySystemTime | `ntdll!NtQuerySystemTime` | Syscall pattern | **Static detection:** ```bash # Check for RDTSC instruction (opcode 0F 31) python3 -c " data = open('sample.exe', 'rb').read() offsets = [] for i in range(len(data)-1): if data[i] == 0x0F and data[i+1] == 0x31: offsets.append(hex(i)) if offsets: print(f'RDTSC instructions found at: {offsets}') else: print('No RDTSC instructions found') " ``` **Countermeasures:** - Patch `rdtsc` to return consistent values (x64dbg: CommandBar plugin) - Hook `GetTickCount` / `QueryPerformanceCounter` to return expected deltas - Use TitanHide or ScyllaHide to intercept timing calls - Set VM to use a fixed TSC rate ### Step 3: Detect Environment Fingerprinting Malware fingerprints the environment to identify analysis systems. **Common checks:** | Check | What Malware Looks For | |-------|----------------------| | Username | "admin", "user", "sandbox", "malware", "analyst", "virus" | | Computer name | "DESKTOP-", "WIN-", "SANDBOX", short/random names | | MAC address | VMware: `00:0C:29:*`, `00:50:56:*`; VBox: `08:00:27:*` | | Disk size | Less than 60-80 GB total | | RAM | Less than 2-4 GB | | CPU cores | Single core (VMs often have 1 core) | | Screen resolution | 800x600 or 1024x768 (default VM resolutions) | | Recent files | No recent documents, downloads, or browser history | | Installed software | No Office, browsers, or common applications | | Uptime | Very short uptime (just booted for analysis) | **Static detection:** ```bash python3 scripts/evasion_detector.py --file sample.exe --category environment ``` **Countermeasures (using environment masker):** ```bash # Configure a realistic analysis environment python3 scripts/environment_masker.py --apply-all python3 scripts/environment_masker.py --set-hostname "DESKTOP-A1B2C3D" python3 scripts/environment_masker.py --set-username "jsmith" python3 scripts/environment_masker.py --add-decoy-files ``` ### Step 4: Find Anti-Debugging Tricks Identify techniques used to detect or prevent debugging. **Windows anti-debug techniques:** ```bash # Check for anti-debug API imports strings sample.exe | grep -iE "(IsDebuggerPresent|NtQueryInformationProcess|CheckRemoteDebuggerPresent|OutputDebugString|NtSetInformationThread|NtQueryObject)" ``` **Common anti-debug categories:** 1. **PEB-based**: `IsDebuggerPresent`, direct PEB.BeingDebugged access 2. **NtQuery-based**: `NtQueryInformationProcess` with ProcessDebugPort 3. **Exception-based**: `INT 2D`, `INT 3` with SEH handler 4. **Timing-based**: Measure time between instructions 5. **Hardware breakpoint detection**: `GetThreadContext` checking DR registers 6. **Self-debugging**: `DebugActiveProcess` on self 7. **Parent process check**: Verify parent is `explorer.exe` **Countermeasures:** - Use ScyllaHide (x64dbg plugin) to hide debugger presence - Use TitanHide (kernel driver) for comprehensive hiding - Patch PEB.BeingDebugged flag: `mov byte ptr [PEB+2], 0` - Hook NtQueryInformationProcess to return clean values See `references/anti-debug-techniques.md` for a complete catalog with bypasses. ### Step 5: Identify Process and User Checks Malware may check for specific processes, users, or system configurations. **Process checks:** ```bash # Look for process enumeration APIs strings sample.exe | grep -iE "(CreateToolhelp32Snapshot|Process32First|Process32Next|EnumProcesses|OpenProcess|tasklist)" # Look for specific process names being checked strings sample.exe | grep -iE "(wireshark|procmon|procexp|ollydbg|x64dbg|idaq|ida64|fiddler|burpsuite|autoruns|tcpview|regmon|filemon)" ``` **User/system checks:** ```bash strings sample.exe | grep -iE "(GetUserName|GetComputerName|GetSystemInfo|GlobalMemoryStatusEx|GetDiskFreeSpace|GetSystemMetrics)" ``` **Countermeasures:** - Rename analysis tools to innocuous names - Run analysis tools from non-standard paths - Use process hiding techniques (kernel driver) - Ensure VM has realistic process list (browsers, Office, etc.) ### Step 6: Detect Delayed Execution Malware may delay execution to outlast sandbox analysis timeouts. **Common delay techniques:** | Technique | Description | |-----------|-------------| | `Sleep(long_time)` | Sleep for minutes/hours before executing | | API flooding | Make millions of benign API calls | | Large loops | Compute-intensive loops with no purpose | | Scheduled tasks | Create a scheduled task to run later | | WMI event subscriptions | Trigger on specific system events | | File system polling | Wait for a specific file/condition | **Detection:** ```bash # Check for Sleep calls with large values strings sample.exe | grep -iE "(Sleep|WaitForSingleObject|WaitForMultipleObjects|SetTimer|CreateTimerQueueTimer)" # Check for task scheduling strings sample.exe | grep -iE "(schtasks|at\.exe|ITaskScheduler|ITaskService)" ``` **Countermeasures:** - Hook `Sleep` to skip or reduce delays (API hooking / DLL injection) - Patch sleep calls in the binary (replace with NOPs) - Use sandbox features to accelerate time (Cuckoo: clock acceleration) - Set longer analysis timeouts (5-10 minutes minimum) ### Step 7: Find Geolocation and Language Checks Some malware only activates in specific regions or avoids certain countries. **Common geolocation checks:** ```bash # IP geolocation APIs strings sample.exe | grep -iE "(ipinfo\.io|ipapi\.co|geoip|maxmind|ip-api\.com|freegeoip)" # System locale/language checks strings sample.exe | grep -iE "(GetLocaleInfo|GetSystemDefaultLangID|GetUserDefaultLangID|GetKeyboardLayoutList)" # Country/region codes strings sample.exe | grep -iE "(RU|UA|BY|KZ|CIS|en-US|ru-RU|uk-UA)" ``` **Common patterns:** - Russian/CIS ransomware: Checks keyboard layout for Russian, exits if found - Region-targeted malware: Only executes in specific countries - Time zone checks: Validates system timezone matches target region **Countermeasures:** - Set keyboard layout matching target region - Configure system locale and timezone - Route analysis network through VPN in target country - Modify system language settings ### Step 8: Implement Countermeasures Apply all relevant countermeasures to ensure the malware executes fully. **Comprehensive environment preparation:** ```bash # Apply all countermeasures python3 scripts/environment_masker.py --apply-all # Or selectively: python3 scripts/environment_masker.py --set-hostname "DESKTOP-A1B2C3D" python3 scripts/environment_masker.py --set-username "jsmith" python3 scripts/environment_masker.py --spoof-mac "D4:3D:7E:12:34:56" python3 scripts/environment_masker.py --add-decoy-files python3 scripts/environment_masker.py --add-decoy-processes python3 scripts/environment_masker.py --install-indicators ``` **VM hardening checklist:** - [ ] Change VM hardware identifiers (BIOS, SMBIOS strings) - [ ] Set realistic hostname and username - [ ] Change MAC address to non-VM vendor - [ ] Install common applications (Office, browsers, Adobe Reader) - [ ] Add user files (documents, images, browser history) - [ ] Set minimum 2 CPU cores, 4 GB RAM - [ ] Set realistic screen resolution (1920x1080) - [ ] Ensure disk size > 100 GB (can be thin provisioned) - [ ] Set realistic uptime (hours/days, not minutes) - [ ] Remove or hide VM tools (VMware Tools, VBox Guest Additions) - [ ] Disable VM-specific devices or rename them - [ ] Add multiple network adapters **Binary patching approach:** When possible, directly patch the anti-analysis checks: 1. Identify the evasion check in disassembler 2. Patch the conditional jump to always continue execution 3. Or NOP out the entire check routine 4. Re-analyze the patched binary in the sandbox ## Output Format The evasion detector produces JSON output: ```json { "file": "sample.exe", "evasion_techniques": { "vm_detection": { "found": true, "indicators": ["VMware detection string", "CPUID VM check"], "severity": "high" }, "anti_debugging": { "found": true, "indicators": ["IsDebuggerPresent import", "NtQueryInformationProcess"], "severity": "medium" }, "timing_checks": { "found": false, "indicators": [], "severity": "none" }, "environment_checks": { "found": true, "indicators": ["Username check", "Process enumeration"], "severity": "medium" } }, "recommended_countermeasures": [ "Hide VM artifacts", "Use anti-anti-debug plugin", "Set realistic hostname/username" ] } ``` ## Tips - Always take a VM snapshot before applying countermeasures - Some malware uses multiple layers of evasion; defeating one may reveal another - Monitor the malware's behavior after defeating each evasion to see what changes - Document all evasion techniques found for the analysis report - Use API monitoring to catch runtime evasion checks not visible in static analysis - Consider using bare-metal analysis for highly evasive samples