--- name: malware-dynamic-analysis description: Execute and monitor malware in controlled sandbox environments. Use when you need to observe runtime behavior, capture network traffic, monitor process activity, analyze file/registry changes, or understand actual malware functionality beyond static analysis. Guides safe execution with Procmon, Wireshark, Process Hacker (now System Informer), Sysmon, and automated sandboxes. --- # Malware Dynamic Analysis Safely execute and comprehensively monitor malware behavior in isolated environments for professional malware research and enterprise security operations. ## When to Use This Skill Use this skill when you need to: - Execute malware safely in an isolated environment - Monitor runtime behavior (processes, files, registry, network) - Capture and analyze network traffic and C2 communications - Validate hypotheses from static analysis - Extract runtime-decrypted strings or configurations - Document actual malware functionality for reports - Create behavioral IOCs and detection signatures - Analyze process injection and code execution techniques ## ⚠️ Safety First - Pre-Execution Checklist **CRITICAL:** Never execute malware outside a properly isolated environment. Before ANY execution: - [ ] Snapshot taken of clean VM state - [ ] Network isolated (host-only or INetSim simulation) - [ ] No shared folders enabled - [ ] No clipboard sharing - [ ] Time sync disabled - [ ] Monitoring tools ready and running - [ ] Analysis persona active (no personal info) - [ ] Emergency shutdown plan ready **If ANY checkbox fails - DO NOT EXECUTE** ## Dynamic Analysis Workflow ### Phase 1: Environment Preparation (10 minutes) **1. Verify VM Isolation:** ```bash # Check network adapter settings # Should be: Host-only or NAT with INetSim # Test internet connectivity (should fail or hit INetSim) ping 8.8.8.8 nslookup google.com # Verify no shared folders net use # Windows df -h # Linux # Check time sync (should be disabled) w32tm /query /status # Windows ``` **2. Start Monitoring Tools:** Launch in this order: 1. **Procmon** (Process Monitor) - File/Registry/Process activity 2. **Wireshark** - Network traffic capture 3. **System Informer** - Process/memory monitoring 4. **Regshot** - Take "before" snapshot (optional) See `references/tool_setup.md` for detailed configuration. **3. Establish Baseline:** - Take note of running processes - Document open network connections - Record current registry state (if using Regshot) ### Phase 2: Malware Execution (Variable Duration) **Execute the Sample:** ```powershell # For PE executables .\sample.exe # With arguments (if required) .\sample.exe /install /silent # For DLLs rundll32.exe sample.dll,DllMain rundll32.exe sample.dll,ExportedFunction # For scripts powershell.exe -ExecutionPolicy Bypass -File sample.ps1 cscript.exe //NoLogo sample.vbs wscript.exe sample.js ``` **Observation Duration:** - **Minimum:** 5 minutes (most malware acts quickly) - **Standard:** 15 minutes (catch delayed execution) - **Extended:** 60+ minutes (for time-based evasion) **What to Watch:** - New processes spawned - Network connections initiated - Files created/modified/deleted - Registry keys modified - CPU/Memory usage spikes - Pop-ups or UI changes - Error messages ### Phase 3: Process Monitoring **Using System Informer:** **Track New Processes:** 1. Watch for new entries in process list 2. Note parent-child relationships 3. Document command-line arguments 4. Check process integrity levels 5. Monitor memory allocations **Identify Process Injection:** - Look for RWX (Read-Write-Execute) memory regions - Check for threads in unexpected processes - Monitor for process hollowing indicators - Watch for CreateRemoteThread calls **Memory Analysis:** ``` Right-click process → Memory → Inspect Look for: - Suspicious memory regions (RWX permissions) - Injected DLLs (not in system path) - Decoded strings in memory - Configuration data Right-click process → Create Dump File → Save for later Volatility analysis ``` **Handles Analysis:** ``` Double-click process → Handles tab Look for: - Mutexes (process synchronization objects) - Named pipes (inter-process communication) - File handles (what files are open) - Registry key handles ``` ### Phase 4: File System Monitoring **Using Procmon (Process Monitor):** **Configure Filters:** ``` Filter → Add: - Process Name → is → sample.exe → Include - Operation → contains → File → Include - Operation → contains → Reg → Include - Process Name → is → explorer.exe → Exclude - Process Name → is → svchost.exe → Exclude (unless suspicious) ``` **Monitor File Operations:** Look for: - **CreateFile** - Files being created - **WriteFile** - Files being modified - **DeleteFile** - Files being deleted - **SetRenameInformationFile** - Files being renamed **Key Locations to Watch:** ``` C:\Users\\AppData\Local\Temp\ C:\Users\\AppData\Roaming\ C:\ProgramData\ C:\Windows\Temp\ C:\Users\\AppData\Local\ ``` **Extract Dropped Files:** ```powershell # Find recently created files (last 5 minutes) Get-ChildItem -Path C:\ -Recurse -ErrorAction SilentlyContinue | Where-Object {$_.CreationTime -gt (Get-Date).AddMinutes(-5)} # Hash all dropped files Get-ChildItem -Path C:\Users\\AppData\Local\Temp\ | Get-FileHash -Algorithm SHA256 | Format-Table Hash, Path ``` **Save Evidence:** - Copy dropped files to evidence folder - Calculate hashes - Document file paths and timestamps - Preserve file metadata ### Phase 5: Registry Monitoring **Using Procmon:** **Filter for Registry Operations:** ``` Operation → contains → Reg → Include ``` **Common Registry Operations:** - **RegCreateKey** - Creating new keys - **RegSetValue** - Writing values - **RegQueryValue** - Reading values - **RegDeleteKey** - Deleting keys **Critical Registry Locations:** **Persistence Mechanisms:** ``` HKCU\Software\Microsoft\Windows\CurrentVersion\Run HKLM\Software\Microsoft\Windows\CurrentVersion\Run HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders HKLM\System\CurrentControlSet\Services (new services) ``` **Configuration Storage:** ``` HKCU\Software\ HKLM\Software\ ``` **Manual Registry Inspection:** ```cmd # Export specific key for analysis reg export "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" run_keys.reg # Query specific value reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" ``` **Using Regshot (Alternative):** ``` 1. Take 1st shot (before execution) 2. Execute malware 3. Take 2nd shot (after execution) 4. Compare → generates HTML report of all changes ``` ### Phase 6: Network Behavior Analysis **Using Wireshark:** **Start Capture:** ``` Capture → Options → Select network adapter → Start ``` **Display Filters:** ``` # DNS queries dns # HTTP traffic http # HTTPS/TLS tls # Specific IP address ip.addr == 192.168.1.100 # Specific port tcp.port == 443 || udp.port == 443 ``` **What to Capture:** **DNS Queries:** ```bash # Extract all DNS queries tshark -r capture.pcapng -Y dns.qry.name -T fields -e dns.qry.name | sort -u Look for: - Domain names contacted - DGA (Domain Generation Algorithm) patterns - Fast-flux DNS indicators - Known C2 domains ``` **HTTP/HTTPS Traffic:** ```bash # Extract HTTP requests tshark -r capture.pcapng -Y http.request -T fields -e http.host -e http.request.uri # Extract User-Agent strings tshark -r capture.pcapng -Y http -T fields -e http.user_agent | sort -u Look for: - C2 server URLs - Download locations - POST data (exfiltration) - Suspicious User-Agents - Beacon patterns (regular intervals) ``` **TCP/UDP Connections:** ```powershell # Real-time connection monitoring netstat -ano | findstr ESTABLISHED # Using TCPView (Sysinternals) tcpview.exe Look for: - Destination IPs and ports - Connection frequency (beaconing) - Data transfer volumes - Unusual protocols ``` **Analyze Network Patterns:** **C2 Communication:** - Regular beacon intervals (e.g., every 60 seconds) - Consistent packet sizes - Encrypted payloads - Known C2 infrastructure **Data Exfiltration:** - Large outbound transfers - POST requests with encoded data - DNS tunneling (large TXT records) - Non-standard protocols **Extract Network IOCs:** ```bash # All contacted IPs tshark -r capture.pcapng -T fields -e ip.dst | sort -u | grep -v "192.168\|10.0\|127.0" # All contacted domains tshark -r capture.pcapng -Y dns -T fields -e dns.qry.name | sort -u # All URLs tshark -r capture.pcapng -Y http.request -T fields -e http.host -e http.request.uri | awk '{print "http://"$1$2}' ``` ### Phase 7: Advanced Monitoring **Using Sysmon (Windows Event Logging):** **Setup:** ```powershell # Install with SwiftOnSecurity config sysmon64.exe -accepteula -i sysmonconfig.xml # View logs Get-WinEvent -LogName "Microsoft-Windows-Sysmon/Operational" -MaxEvents 100 | Format-List ``` **Key Event IDs:** - **Event ID 1** - Process Creation - **Event ID 3** - Network Connection - **Event ID 5** - Process Terminated - **Event ID 7** - Image Loaded (DLL) - **Event ID 8** - CreateRemoteThread (injection) - **Event ID 10** - Process Access - **Event ID 11** - File Created - **Event ID 12/13** - Registry Events **Query Specific Events:** ```powershell # Process creation events Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Sysmon/Operational'; ID=1} | Format-List # Network connections Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Sysmon/Operational'; ID=3} | Format-List # Export for analysis wevtutil epl Microsoft-Windows-Sysmon/Operational C:\evidence\sysmon_logs.evtx ``` **Using Noriben (Automated Procmon):** ```bash # Run Noriben with automatic malware execution python Noriben.py --cmd sample.exe --timeout 300 # Output: Noriben_.txt with parsed behavior summary ``` Benefits: - Automates Procmon collection - Filters noise automatically - Generates readable report - Timestamps all activities ### Phase 8: Persistence Analysis **Check All Persistence Mechanisms:** **Run Keys:** ```powershell # Current User Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" # Local Machine Get-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run" # RunOnce keys Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce" Get-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce" ``` **Scheduled Tasks:** ```powershell Get-ScheduledTask | Where-Object {$_.TaskName -notlike "Microsoft*"} | Format-Table # Detailed task info Get-ScheduledTask -TaskName "SuspiciousTask" | Get-ScheduledTaskInfo ``` **Services:** ```powershell # Recently created services Get-Service | Where-Object {$_.StartType -ne "Disabled"} | Format-Table # Service details sc query sc qc ``` **Startup Folder:** ```powershell # Check startup folders dir "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup" dir "$env:PROGRAMDATA\Microsoft\Windows\Start Menu\Programs\Startup" ``` **WMI Event Subscriptions:** ```powershell Get-WmiObject -Namespace root\Subscription -Class __EventFilter Get-WmiObject -Namespace root\Subscription -Class __EventConsumer Get-WmiObject -Namespace root\Subscription -Class __FilterToConsumerBinding ``` ### Phase 9: Artifact Collection **Export All Evidence:** **Process Monitor:** ``` File → Save → All Events → CSV format → Save as: procmon_output.csv ``` **Wireshark:** ``` File → Export Specified Packets → All packets → Save as: network_capture.pcapng ``` **System Informer:** ``` File → Save All → processes.txt (Optional) Right-click process → Create dump file → memory_dump.dmp ``` **Regshot:** ``` Compare → Output to HTML → Save as: registry_changes.html ``` **Sysmon Logs:** ```powershell wevtutil epl Microsoft-Windows-Sysmon/Operational C:\evidence\sysmon.evtx ``` **Dropped Files:** ```powershell # Copy all dropped files with hashes $evidence = "C:\evidence\dropped_files" New-Item -Path $evidence -ItemType Directory -Force Get-ChildItem -Path "C:\Users\\AppData\Local\Temp" | ForEach-Object { Copy-Item $_.FullName -Destination $evidence Get-FileHash $_.FullName -Algorithm SHA256 } ``` **Screenshots:** - Take screenshots of any visible UI - Capture error messages - Document unusual behavior ### Phase 10: Cleanup and Reset **Before Reverting VM:** 1. ✅ All evidence exported and saved 2. ✅ Hashes calculated for all artifacts 3. ✅ Network captures saved 4. ✅ Process dumps saved (if needed) 5. ✅ Screenshots organized **Revert to Clean Snapshot:** ``` VMware: VM → Snapshot → Revert to Snapshot VirtualBox: Machine → Close → Restore current snapshot ``` **Verify Clean State:** - Check no malware artifacts remain - Verify monitoring tools reset - Confirm network settings correct ## Automated Sandbox Analysis ### ANY.RUN (Interactive Cloud Sandbox) **When to Use:** - Need quick behavioral analysis - Want to interact with malware during execution - Need visual demonstration of behavior - Time-constrained analysis **Workflow:** 1. Upload sample to https://app.any.run 2. Select Windows version (7/8/10/11) 3. Choose network simulation (Internet or No connection) 4. Click "Run" 5. Interact if needed (click buttons, enter passwords) 6. Monitor real-time: - Process tree - Network requests - File operations - Registry changes 7. Download artifacts: - PCAP file - Process dumps - Dropped files - IOCs (JSON/CSV) **Advantages:** - Fast results (5-10 minutes) - Visual process tree - Archived for future reference - No local resources needed **Limitations:** - Sample uploaded to cloud (privacy concern) - VM-aware malware may not execute - Limited to preset Windows versions ### Joe Sandbox / Hybrid Analysis **API Submission (if available):** ```bash # Submit to Joe Sandbox jbxapi submit sample.exe --systems win10x64 # Check status jbxapi status # Download report jbxapi download --type html > joe_report.html jbxapi download --type json > joe_report.json ``` **Report Analysis:** - Behavior summary - Network communications - File system changes - Screenshots - MITRE ATT&CK mapping - YARA rule suggestions ### Local Sandboxes (CAPE, Cuckoo) **For Enterprise/Private Analysis:** - Complete control over environment - No sample disclosure - Customizable VM configurations - Automated at scale See `references/sandbox_setup.md` for local sandbox installation. ## Common Dynamic Analysis Scenarios ### Scenario 1: Ransomware Execution **Preparation:** - Create test files in common locations - Monitor C:\Users\\Documents closely - Watch for file extension changes **Observe:** - File encryption activity - Ransom note creation - Desktop wallpaper changes - Process names (often legitimate-sounding) **Capture:** - Screenshot of ransom note - List of encrypted file extensions - C2 communication (if any) - Bitcoin wallet addresses ### Scenario 2: Trojan/RAT Behavior **Preparation:** - Set up fake C2 listener (ncat) - Monitor for reverse shell attempts **Observe:** - Persistence mechanism creation - C2 beacon intervals - Command execution - Keylogging indicators - Screen capture attempts **Capture:** - C2 traffic (PCAP) - Executed commands - Exfiltrated data - Persistence registry keys ### Scenario 3: Dropper/Loader Analysis **Preparation:** - Monitor network for secondary payload downloads - Watch temp directories closely **Observe:** - Initial dropper execution - Secondary payload download - Payload execution - Cleanup of dropper **Capture:** - All dropped files and hashes - Download URLs - Full execution chain (parent → child processes) ### Scenario 4: Infostealer Execution **Preparation:** - Populate browser with test credentials - Create test cryptocurrency wallets - Add test email client **Observe:** - Browser profile access - Credential file reads - Data staging (zip/archive creation) - Exfiltration attempts **Capture:** - Accessed credential stores - Exfiltration destinations - Data encoding methods ## Behavioral IOC Extraction **From Dynamic Analysis, Extract:** **Process IOCs:** ``` Process Name: sample.exe Parent Process: explorer.exe Command Line: C:\Users\Public\sample.exe /install Child Processes: cmd.exe, powershell.exe Mutex: Global\UniqueMalwareMutex ``` **File IOCs:** ``` Created Files: - C:\Users\\AppData\Local\Temp\payload.exe (SHA256: abc123...) - C:\ProgramData\config.dat Modified Files: - C:\Users\\Documents\*.locked (ransomware) Deleted Files: - %TEMP%\dropper.exe (self-deletion) ``` **Registry IOCs:** ``` Created Keys: HKCU\Software\Microsoft\Windows\CurrentVersion\Run\WindowsDefender Value: C:\Users\Public\malware.exe Modified Keys: HKLM\System\CurrentControlSet\Services\ ``` **Network IOCs:** ``` DNS Queries: - malicious-c2[.]com - backup-server[.]tk HTTP Requests: - hxxp://malicious-c2[.]com/api/checkin User-Agent: Mozilla/4.0 (compatible; MSIE 6.0) IP Connections: - 192.168.1.100:443 (C2 server) - 10.0.0.50:8080 (data exfiltration) ``` ## Quality Checklist Before concluding dynamic analysis: **Execution Environment:** - [ ] VM properly isolated (verified) - [ ] All monitoring tools captured data - [ ] Execution time sufficient (15+ minutes minimum) - [ ] Clean snapshot available for re-analysis **Process Monitoring:** - [ ] All spawned processes documented - [ ] Process tree captured - [ ] Command-line arguments recorded - [ ] Process injection observed (if any) - [ ] Memory dumps saved (if relevant) **File System:** - [ ] All dropped files identified and hashed - [ ] File paths documented - [ ] Dropped files saved to evidence - [ ] File modifications logged - [ ] Deletion activities recorded **Registry:** - [ ] Persistence mechanisms identified - [ ] Registry changes documented - [ ] Configuration keys noted - [ ] Registry export saved **Network:** - [ ] Full PCAP captured - [ ] DNS queries extracted - [ ] C2 servers identified - [ ] Network protocols documented - [ ] Data exfiltration noted **Evidence Collection:** - [ ] All artifacts exported - [ ] Hashes calculated - [ ] Timestamps recorded (UTC) - [ ] Screenshots saved - [ ] Logs organized in case folder **Analysis Completeness:** - [ ] Behaviors match static analysis predictions - [ ] Unexpected behaviors investigated - [ ] IOCs validated and defanged - [ ] Findings documented for report ## Best Practices ### Do: - Always take VM snapshot before execution - Run monitoring tools BEFORE executing malware - Document observations in real-time - Capture evidence continuously - Verify network isolation - Use multiple monitoring tools - Save everything (disk is cheap) - Test IOCs for accuracy - Document timeline of events ### Don't: - Execute without proper isolation - Trust timestamps from malware - Assume short execution time is sufficient - Execute on production systems (NEVER!) - Share VM with other activities - Enable internet without INetSim - Forget to export evidence before reverting - Rely on single monitoring tool - Skip documentation during execution ### Time-Based Evasion: - Some malware delays execution (sleep evasion) - Set extended observation period (60+ minutes) - Monitor for scheduled tasks - Check for triggers (time, date, system events) ### VM Detection Evasion: - Some malware detects VMs and doesn't execute - Use pafish-free VM configurations - Modify VM artifacts (MAC addresses, system info) - See `references/anti_analysis_bypass.md` ## Integration with Report Writing Dynamic analysis provides: - **Execution Flow** → Report: Technical Analysis section - **Process Activity** → Report: Behavior Analysis - **Network IOCs** → Report: Network Indicators - **File IOCs** → Report: File Indicators - **Persistence** → Report: Persistence Mechanisms - **Screenshots** → Report: Appendix - **Timeline** → Report: Execution Timeline Use findings to: - Validate static analysis hypotheses - Create behavioral YARA rules - Write Sigma detection rules - Develop hunting queries - Document MITRE ATT&CK techniques ## Tool Reference For detailed tool setup, filtering, and configuration: - `references/tool_setup.md` - Procmon, Wireshark, System Informer configuration - `references/sandbox_setup.md` - Local sandbox installation - `references/anti_analysis_bypass.md` - Bypassing VM detection and sleep evasion ## Example Usage **User request:** "Help me safely execute this ransomware sample and document its behavior" **Workflow:** 1. Verify VM isolation and safety checklist 2. Guide monitoring tool setup (Procmon, Wireshark, System Informer) 3. Execute sample with observation 4. Document process creation and injection 5. Capture file encryption behavior 6. Extract ransom note and C2 communications 7. Collect all artifacts 8. Generate behavioral IOCs 9. Create timeline of execution 10. Prepare findings for report integration