Detection Playbook: Visual Basic (T1059.005)

T1059.005 · 2026-06-17

Visual Basic

Execution
Linux macOS Windows
MITRE ATT&CK →
Technique Visual Basic (T1059.005)
Tactic Execution
Platforms Linux, macOS, Windows

Overview

Visual Basic (VB) and its derivatives — Visual Basic for Applications (VBA) and VBScript — are scripting and programming languages that adversaries abuse to execute malicious code on target systems. Attackers commonly embed VBA macros in weaponized Office documents delivered via phishing, or invoke VBScript directly through the Windows Script Host (wscript.exe / cscript.exe) to download payloads, establish persistence, or run arbitrary commands without compiling a standalone binary.

VB-based execution is one of the most prevalent initial-access and execution vectors seen in real-world intrusions — from commodity malware campaigns to nation-state operations — because the tooling is built into Windows by default and historically trusted by users. Every security team needs reliable detection here because a single missed macro execution can be the first link in a chain leading to ransomware deployment or data exfiltration.

Attacker Perspective

Attackers abuse VB and its derivatives at multiple stages of the kill chain, exploiting the language’s deep integration with the Windows operating system and Microsoft Office ecosystem.

  • Malicious Office Macros (VBA): A phishing email delivers a .docm or .xlsm file containing a VBA macro that auto-executes on open (AutoOpen / Workbook_Open), drops a second-stage payload to %TEMP%, and launches it via Shell() or CreateObject("WScript.Shell").Run.
  • VBScript via Windows Script Host: Attackers invoke wscript.exe malicious.vbs or cscript.exe /nologo stage2.vbs to download a remote payload using MSXML2.XMLHTTP or WinHttp.WinHttpRequest objects and write it to disk with ADODB.Stream.
  • HTML Application (HTA) with VBScript: A .hta file served from an attacker-controlled server or delivered as an attachment is executed by mshta.exe, running embedded VBScript that spawns cmd.exe or powershell.exe for follow-on execution — a common pattern in tools like LOLBAS-based loaders.
  • Encoded / Obfuscated VBScript: Adversaries use string concatenation, Chr() character encoding, or Execute() / Eval() calls to obfuscate VBScript payloads, evading static signature detection while still running through the standard wscript.exe or cscript.exe hosts.

This technique is attractive because the execution engines are present on every default Windows installation, the file types are widely trusted by end users, and legacy macro-based workflows in many organizations make aggressive blocking politically difficult.

Detection Strategy

Required Telemetry

  • Windows Process Creation (Event ID 4688): Enable via GPO — Computer Configuration → Windows Settings → Security Settings → Advanced Audit Policy → Detailed Tracking → Audit Process Creation = Success. Also enable command-line logging: HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\Audit → ProcessCreationIncludeCmdLine_Enabled = 1. This is mandatory — without command-line arguments, most VB detections are nearly useless.
  • Sysmon Process Creation (Event ID 1): Deploy Sysmon with a configuration that captures CommandLine, ParentImage, ParentCommandLine, Hashes, and User. This is the preferred telemetry source over native 4688 because it includes parent process details in a single event. Use the SwiftOnSecurity or Olaf Hartong Sysmon config as a baseline.
  • Sysmon Network Connection (Event ID 3): Enable in Sysmon config to catch outbound connections initiated by wscript.exe, cscript.exe, mshta.exe, or Office processes. Captures destination IP, port, and the initiating process.
  • Sysmon File Creation (Event ID 11): Captures files written to disk by script hosts or Office applications. Useful for detecting payload drops to %TEMP%, %APPDATA%, or C:\Users\Public\.
  • Windows Script Host Script Block Logging: For VBScript, there is no native equivalent to PowerShell’s script block logging (Event ID 4104). Compensate by ensuring process creation command-line logging is active and that endpoint security tools (EDR) capture script content where possible.
  • Microsoft Office Macro Logging (Event ID 4104-equivalent via AMSI): Enable AMSI integration for Office macros via: HKLM\SOFTWARE\Microsoft\AMSI → Enable = 1 (present on Office 365 / 2019+). AMSI-scanned macro content will appear in Windows Defender / EDR telemetry and Windows Event Log under Application log (source: Microsoft-Windows-AMSI).
  • Windows Security Log — Object Access (Event ID 4663): Enable file auditing on sensitive directories (%TEMP%, %APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup) to catch payload writes. Enable via: Advanced Audit Policy → Object Access → Audit File System = Success, Failure.
  • DNS Query Logs: Capture DNS requests from endpoints (via Sysmon Event ID 22 — DNSEvent — or network DNS logging). Malicious VBScripts frequently beacon to C2 domains immediately after execution.
  • Email Gateway Logs: Log attachment filenames, file types, and sender/recipient metadata. Required to reconstruct initial delivery of malicious .docm, .xlsm, .vbs, or .hta files.
  • EDR Telemetry: If available (CrowdStrike, Microsoft Defender for Endpoint, SentinelOne, etc.), EDR provides script content, memory injection events, and process trees that greatly accelerate investigation. Ensure agents are deployed and reporting.

Key Indicators

  • Suspicious parent-child process relationship: Log source: Sysmon Event ID 1 or Windows Event ID 4688. Field: ParentImage. Watch for Office applications spawning script hosts — ParentImage contains WINWORD.EXE, EXCEL.EXE, OUTLOOK.EXE, or POWERPNT.EXE and Image (child) contains wscript.exe, cscript.exe, mshta.exe, cmd.exe, powershell.exe, or rundll32.exe.
  • Script host executing a file from a user-writable directory: Log source: Sysmon Event ID 1. Fields: Image = wscript.exe or cscript.exe; CommandLine contains paths like %TEMP%, %APPDATA%, C:\Users\Public\, or C:\ProgramData\. Example: CommandLine = "wscript.exe C:\Users\Public\update.vbs".
  • VBScript initiating network connections: Log source: Sysmon Event ID 3. Fields: Image = wscript.exe or cscript.exe; Initiated = true; DestinationPort = 80, 443, or non-standard ports. Any outbound connection from a script host to an external IP is high-fidelity.
  • HTA execution via mshta.exe with remote URL: Log source: Sysmon Event ID 1. Field: CommandLine contains mshta.exe AND a URL pattern such as http:// or https://. Example: CommandLine = "mshta.exe http://192.168.1.50/payload.hta".
  • Obfuscation indicators in VBScript command line: Log source: Sysmon Event ID 1 or EDR. Field: CommandLine contains high-frequency use of Chr(, Execute(, Eval(, or string concatenation patterns like "" & "" combined with wscript.exe or cscript.exe.
  • Office process writing executable or script files: Log source: Sysmon Event ID 11. Fields: Image contains WINWORD.EXE or EXCEL.EXE; TargetFilename ends in .exe, .dll, .vbs, .ps1, .bat, .hta, or .js. Any Office process dropping a binary or script to disk is a high-confidence indicator.
  • Suspicious DNS queries from script hosts: Log source: Sysmon Event ID 22. Fields: Image = wscript.exe or cscript.exe; QueryName resolves to a recently registered domain, DGA-like hostname, or known threat intelligence IOC.
  • AMSI block event for Office macro: Log source: Windows Application Event Log or EDR. Source: Microsoft-Windows-AMSI. Look for scan results indicating malicious content was detected in a VBA macro context — even blocked attempts indicate someone received and opened a malicious document.

Detection Logic

Rule 1 (Broad — High Sensitivity): Office Application Spawning Script Host or Shell
IF ParentImage IN ["WINWORD.EXE","EXCEL.EXE","OUTLOOK.EXE","POWERPNT.EXE"] AND Image IN ["wscript.exe","cscript.exe","mshta.exe","cmd.exe","powershell.exe","rundll32.exe","regsvr32.exe"] THEN alert

This catches the most common macro-based execution pattern: an Office document spawning a script host or shell. Expect moderate alert volume — legitimate macros in some enterprises do spawn cmd.exe (e.g., for printing or file operations). Start here to build a baseline, then apply tuning exclusions over two to three weeks before tightening.

Rule 2 (Medium Precision): Script Host Executing File from User-Writable Location
IF Image IN ["wscript.exe","cscript.exe"] AND CommandLine MATCHES REGEX "(AppData|Temp|Public|ProgramData|Downloads)" AND NOT CommandLine MATCHES "(known_admin_script_path)" THEN alert

This targets the payload-drop-then-execute pattern where VBScript is written to a non-standard location before execution. Lower false-positive rate than Rule 1 because legitimate administrative VBScript is rarely run from user temp directories. Expect low-to-medium volume.

Rule 3 (High Precision): Script Host Making Outbound Network Connection
IF Image IN ["wscript.exe","cscript.exe"] AND EventID = 3 AND Initiated = true AND DestinationIsExternal = true AND NOT DestinationIP IN [approved_internal_ranges] THEN alert

Catches VBScript used as a downloader or C2 beacon — a high-confidence indicator because legitimate administrative VBScripts almost never initiate outbound internet connections. Expect very low false-positive volume; treat most matches as requiring immediate investigation.

Rule 4 (High Precision): mshta.exe Executing Remote URL
IF Image = "mshta.exe" AND CommandLine MATCHES REGEX "(http://|https://|\\\\[0-9]{1,3}\.)" AND NOT ParentImage IN ["explorer.exe"] AND NOT CommandLine MATCHES known_helpdesk_hta_paths THEN alert

Targets HTA-based VBScript delivery — one of the most reliable LOLBAS execution patterns. Legitimate uses of mshta.exe with remote URLs are extremely rare in most enterprises, making this a near-high-fidelity alert with minimal tuning required.

Tuning Guidance

  • Legitimate Office macros for business processes: Many finance, HR, and operations teams rely on VBA macros that invoke cmd.exe for file manipulation or printing. Identify these by interviewing stakeholders, capture the exact parent process and command-line pattern, and add specific exclusions such as ParentImage = "EXCEL.EXE" AND CommandLine CONTAINS "C:\Finance\Scripts\report_export.vbs". Never exclude broadly by parent process alone.
  • Software deployment and management tools: SCCM, Intune, and some RMM agents invoke wscript.exe or cscript.exe to run legitimate administrative scripts. Exclude by adding ParentImage IN ["ccmexec.exe","msiexec.exe"] combined with a path condition like CommandLine CONTAINS "C:\Windows\CCM\" to avoid over-broadening.
  • IT helpdesk and support tooling: Some support tools use mshta.exe to render local HTA-based UI. Exclude known tool paths: CommandLine CONTAINS known_helpdesk_tool_path AND ParentImage = "helpdesk_tool.exe". Document all exclusions with a business justification and review quarterly.
  • Scheduled tasks running legacy VBScript: Many organizations have legacy scheduled tasks that invoke wscript.exe with known scripts. Identify these via Task Scheduler logs (Event ID 200/201), build an allowlist of specific CommandLine values, and exclude them from Rule 1 and Rule 2. Ensure allowlisted scripts are stored in controlled directories (not %TEMP%).
  • Developer and test workstations: Developers testing VBA or VBScript locally will generate frequent alerts. Tag developer machines in your asset inventory and apply a separate, more permissive detection threshold for those hosts — but do not exclude them entirely, as developer machines are also high-value targets.

When the Alert Fires: Investigation Steps

  1. Verify the alert is real: Pull the raw event from your SIEM using the specific Event ID and host identifier from the alert — confirm the CommandLine, Image, and ParentImage fields are present and match what the rule fired on. A missing or malformed event may indicate a logging gap rather than a true positive.
  2. Identify the affected host and user: Record the hostname, IP address, operating system version, and the SubjectUserName (from Event ID 4688) or User field (Sysmon Event ID 1) associated with the execution. Flag immediately if the account is a domain admin, service account, or executive — these require escalation before proceeding.
  3. Pull the full process tree: In your EDR or SIEM, pivot on the ProcessGuid (Sysmon) or ProcessId to reconstruct the full parent-child chain going at least four levels up and down. Confirm whether the chain starts from an Office application, browser, or email client — this determines the likely delivery mechanism and shapes your containment priority.
  4. Retrieve and analyze the script content: If the CommandLine references a .vbs or .hta file on disk, retrieve the file immediately using your EDR’s live response capability or a forensic agent before it can be deleted. If the script is obfuscated, deobfuscate it manually or via a sandbox (e.g., Any.run, Hybrid Analysis) to understand the full intended behavior.
  5. Check for network connections and file drops: Query Sysmon Event ID 3 for outbound connections from the script host process during and after execution, and Event ID 11 for any files written to disk. Document all destination IPs and domains, and check them against threat intelligence (VirusTotal, Shodan, internal TI feeds). Note any new executables, scripts, or DLLs dropped to user-writable paths.
  6. Search for lateral movement from this host: Query Windows Security Event ID 4624 (logon) and 4648 (explicit credential use) on domain controllers and adjacent hosts for sessions originating from the affected host in the 24 hours following the execution event. Also check Sysmon Event ID 3 for SMB (port 445), RDP (port 3389), or WMI (port 135) connections initiated by the host.
  7. Assess persistence mechanisms: Query Sysmon Event ID 13 (registry value set) for modifications to autorun keys such as HKCU\Software\Microsoft\Windows\CurrentVersion\Run, and Event ID 11 for files written to Startup folder paths. Also check Task Scheduler logs (Windows Event ID 4698 — Scheduled Task Created) and services (Event ID 7045) for anything created within the timeframe of the execution. If any persistence is found, escalate immediately to a confirmed incident.

Response Playbook

Containment

  • Isolate the host — do not power it off: Use your EDR console (CrowdStrike Network Containment, MDE Isolate Device, SentinelOne Network Quarantine) to cut the host off from all network communication while preserving it for forensics. Powering off destroys volatile memory artifacts including running processes, network connections, and in-memory payloads.
  • Disable the affected user account: In Active Directory, disable the account immediately via Disable-ADAccount -Identity <username> or through the AD Users and Computers console. If the account has active Kerberos tickets, invalidate them by resetting the password and running klist purge on all known hosts where the user has active sessions.
  • Block identified C2 IPs and domains: Submit all confirmed or suspected C2 destinations to your perimeter firewall team and DNS filtering solution (Umbrella, Zscaler, internal DNS RPZ) for immediate blocking. Create the block with a time-stamped comment referencing the incident ticket for auditability.
  • Kill the malicious process: If the EDR isolation does not terminate the process automatically, use EDR live response to kill the specific wscript.exe, cscript.exe, or mshta.exe process by PID. Verify termination by re-querying the process list — do not assume the kill succeeded.
  • Revoke active sessions and tokens: If the affected user account has active O365 / Azure AD sessions, revoke all refresh tokens via: Revoke-AzureADUserAllRefreshToken -ObjectId <user_object_id>. Check for any OAuth application grants or API keys the account may have accessed and revoke those as well.

Eradication

  • Remove identified persistence mechanisms: Delete any malicious scheduled tasks found (via schtasks /delete /tn "<taskname>" /f), remove registry Run key entries using reg delete with the full key path, and delete any files in Startup folders. Document each artifact removed with its full path, hash, and registry key value before deletion.
  • Delete all dropped payloads and tools: Remove every file identified during the investigation from all affected hosts — including any secondary stages, downloaded executables, or injected DLLs. Calculate SHA-256 hashes before deletion and submit them to your threat intelligence platform as IOCs for future detection.
  • Reset credentials for all exposed accounts: Force password resets for the primary affected user and any additional accounts the malicious process touched or that were used for lateral movement. If the host was a workstation, also rotate any service account credentials cached locally (check LSA secrets and Credential Manager).
  • Check lateral movement targets for backdoors: For every host the affected user authenticated to during the compromise window, run a targeted sweep using your EDR for the same IOCs (file hashes, registry keys, process names). Do not assume contamination stopped at the initial host.
  • Rotate exposed secrets and API keys: If the macro or VBScript accessed credential stores, browser saved passwords, or any application secrets (API keys, database connection strings), treat all of them as compromised and rotate immediately. Notify application owners so dependent services can be updated.

Recovery

  • Re-image if confidence in clean state is low: If the full scope of attacker activity cannot be definitively established, re-image the endpoint from a known-good baseline rather than attempting manual cleanup. This is the only way to achieve high confidence that no rootkit or deep persistence mechanism was missed.
  • Re-enable the user account only after verification: Before re-enabling the account, confirm with the investigation team that no persistence tied to that identity remains on any host. Communicate the re-enable action to the user’s manager and instruct the user to report any further anomalies immediately.
  • Monitor the affected host and user for 72 hours post-remediation: Create a targeted detection rule in your SIEM that generates high-priority alerts for any script host execution, outbound connection, or privilege use by the affected account or from the remediated host’s IP for at least 72 hours. Treat any alert during this window as a potential re-compromise.
  • Document the full timeline and capture lessons learned: Write a complete incident timeline from initial phishing delivery (if identified) through containment, eradication, and recovery. Record every IOC, MITRE ATT&CK technique mapped, and every detection gap identified. Share the timeline in the post-incident review meeting within five business days.
  • Update detection rules with new IOCs: Add all confirmed file hashes, C2 domains, IP addresses, and command-line patterns discovered during the investigation to your SIEM detection rules and threat intelligence platform. Review whether the original alert fired quickly enough — if dwell time was greater than four hours, identify the specific gap and address it before closing the ticket.

Stay Ahead

Get daily threat intelligence and detection playbooks.

Free. No account. No email. Follow in Feedly, Inoreader, or any RSS reader.