T1221 Microsoft Sentinel · KQL

Detect Template Injection in Microsoft Sentinel

Adversaries abuse template references embedded in Office Open XML (OOXML) documents and RTF files to conceal and deliver malicious payloads. DOCX, XLSX, and PPTX files are ZIP archives containing an XML relationship file (word/_rels/document.xml.rels) that can reference an external template URL via an attachedTemplate relationship. When the document is opened, the Office application fetches the remote template, which may deliver VBA macros, exploits, or shellcode that are absent from the original lure document — bypassing static file analysis. RTF files can be modified to include a \*\template control word pointing to a remote URL, triggering a fetch on open. Both vectors are used to deliver malicious macros (APT28 remote template macro delivery), execute exploits (Confucius, WarzoneRAT via RTF exploit embedding), or capture NTLM credentials by injecting SMB UNC paths that trigger forced authentication (Dragonfly, DarkHydrus/Phishery). Real-world campaigns frequently deliver these lures via phishing (T1566) or tainted shared content (T1080). The technique is effective because the initial document contains no traditional indicators — no embedded VBA, no OLE streams, no scripts — making gateway scanning and sandboxes that do not perform dynamic network fetching ineffective.

MITRE ATT&CK

Tactic
Defense Evasion
Technique
T1221 Template Injection
Canonical reference
https://attack.mitre.org/techniques/T1221/

KQL Detection Query

Microsoft Sentinel (KQL)
kusto
let OfficeApps = dynamic(["winword.exe", "excel.exe", "powerpnt.exe", "mspub.exe", "msaccess.exe", "visio.exe"]);
let MicrosoftInfra = dynamic([
  "microsoft.com", "office.com", "live.com", "microsoftonline.com",
  "windows.net", "sharepoint.com", "officecdn.microsoft.com",
  "officecdna.microsoft.com", "skype.com", "bing.com", "msecnd.net",
  "msftncsi.com", "trafficmanager.net", "azure.com", "azurefd.net"
]);
// Branch 1: Office apps fetching remote templates via HTTP/HTTPS from non-Microsoft hosts
let RemoteHTTPFetch = DeviceNetworkEvents
| where Timestamp > ago(24h)
| where InitiatingProcessFileName in~ (OfficeApps)
| where RemotePort in (80, 443, 8080, 8443)
| where RemoteIPType == "Public"
| where not(RemoteUrl has_any (MicrosoftInfra))
| extend AlertType = "RemoteTemplateFetch"
| extend RiskDetail = strcat("Office process ", InitiatingProcessFileName, " fetched external URL: ", RemoteUrl)
| project Timestamp, DeviceName, AccountName, InitiatingProcessFileName,
          InitiatingProcessCommandLine, InitiatingProcessId,
          RemoteIP, RemotePort, RemoteUrl, AlertType, RiskDetail;
// Branch 2: Office apps connecting to SMB port — forced NTLM authentication
let ForcedAuthSMB = DeviceNetworkEvents
| where Timestamp > ago(24h)
| where InitiatingProcessFileName in~ (OfficeApps)
| where RemotePort == 445
| where RemoteIPType in ("Public", "Private")
| extend AlertType = "ForcedAuthSMB_NTLMCapture"
| extend RiskDetail = strcat("Office process ", InitiatingProcessFileName, " initiated SMB connection to ", RemoteIP, ":445 — potential NTLM hash capture")
| project Timestamp, DeviceName, AccountName, InitiatingProcessFileName,
          InitiatingProcessCommandLine, InitiatingProcessId,
          RemoteIP, RemotePort, RemoteUrl, AlertType, RiskDetail;
// Branch 3: Child process spawned directly by Office — indicates payload execution post-template-load
let OfficeChildExec = DeviceProcessEvents
| where Timestamp > ago(24h)
| where InitiatingProcessFileName in~ (OfficeApps)
| where FileName in~ ("cmd.exe", "powershell.exe", "pwsh.exe", "wscript.exe",
                       "cscript.exe", "mshta.exe", "rundll32.exe", "regsvr32.exe",
                       "certutil.exe", "bitsadmin.exe", "wmic.exe", "msiexec.exe",
                       "svchost.exe", "conhost.exe")
| extend AlertType = "OfficeChildProcess_PostTemplateExec"
| extend RiskDetail = strcat("Office process ", InitiatingProcessFileName, " spawned ", FileName, " — possible macro/exploit execution after template load")
| project Timestamp, DeviceName, AccountName, FileName, ProcessCommandLine,
          InitiatingProcessFileName, InitiatingProcessCommandLine,
          AlertType, RiskDetail;
RemoteHTTPFetch
| union ForcedAuthSMB
| union (OfficeChildExec | project Timestamp, DeviceName, AccountName,
          InitiatingProcessFileName, InitiatingProcessCommandLine,
          InitiatingProcessId = "", RemoteIP = "", RemotePort = 0,
          RemoteUrl = "", AlertType, RiskDetail)
| sort by Timestamp desc
high severity high confidence

Three-branch detection for T1221 Template Injection using Microsoft Defender for Endpoint tables. Branch 1 (DeviceNetworkEvents) detects Office applications fetching remote HTTP/HTTPS resources from non-Microsoft infrastructure — the network call triggered when an OOXML document with an injected attachedTemplate relationship is opened. Branch 2 (DeviceNetworkEvents) detects Office applications initiating SMB (port 445) connections indicative of Forced Authentication attacks where injected UNC paths cause NTLM credential leakage. Branch 3 (DeviceProcessEvents) detects child processes spawned by Office applications, indicating a remote template containing macros or exploits was successfully fetched and executed. Microsoft infrastructure URLs are explicitly excluded to reduce noise from legitimate Office telemetry and update connections.

Data Sources

Network Traffic: Network Connection CreationProcess: Process CreationMicrosoft Defender for Endpoint

Required Tables

DeviceNetworkEventsDeviceProcessEvents

False Positives & Tuning

  • Corporate document management systems (SharePoint on-premise, Confluence, custom DMS) that serve legitimate .dotx/.dotm template files to Office clients — add their hostnames/IPs to the exclusion list
  • Office Click-to-Run (C2R) update and telemetry processes share the same process names and may make external connections — validate against known Microsoft CDN IP ranges
  • Macro-enabled templates in enterprise environments where business workflows legitimately use remote templates (e.g., HR or finance template servers) — allowlist specific internal template server FQDNs
  • Branch 3 child process detection will fire on legitimate Office add-ins, COM automation, and scripted Office workflows (e.g., VBA calling WScript for file operations) — baseline expected parent-child pairs per environment
  • RTF documents produced by legal or financial software platforms that embed legitimate template references to external servers
Download portable Sigma rule (.yml)

Other platforms for T1221


Testing Methodology

Validate this detection against 5 adversary techniques from Atomic Red Team. Each test below lists the behaviour to exercise and the telemetry you should expect to see. Executable commands and cleanup steps are available with Pro.

  1. Test 1OOXML Remote Template Injection — DOCX with External attachedTemplate

    Expected signal: When document is opened in Word: Sysmon Event ID 3 with Image=winword.exe, DestinationIp=127.0.0.1, DestinationPort=8080. Sysmon Event ID 22 (DNS Query) if a FQDN is used instead of localhost. DeviceNetworkEvents in MDE will show InitiatingProcessFileName=winword.exe with RemoteIP=127.0.0.1 and RemotePort=8080. The connection will be refused (no listener) but the event fires before the TCP RST.

  2. Test 2RTF Template Injection — \*\template Control Word with HTTP URL

    Expected signal: When opened in Word: Sysmon Event ID 3 with Image=winword.exe, DestinationIp=127.0.0.1, DestinationPort=8080. DeviceFileEvents may show the RTF file being read from its download location. The RTF \*\template control word triggers the same network fetch mechanism as the OOXML attachedTemplate relationship.

  3. Test 3Forced Authentication via SMB UNC Template Reference

    Expected signal: Sysmon Event ID 3 with Image=winword.exe, DestinationPort=445, DestinationIp=127.0.0.1. On a real attack with an external IP: Security Event ID 4648 (explicit credential use) or 4624 (NTLM logon type 3) on the domain controller. Sysmon Event ID 22 may show DNS lookup if a hostname is used instead of IP. DeviceNetworkEvents in MDE shows InitiatingProcessFileName=winword.exe, RemotePort=445.

  4. Test 4Phishery-style Template URL Injection into Existing DOCX

    Expected signal: File creation events (Sysmon EventCode=11) for both the original and injected DOCX in %TEMP%. When the injected DOCX is opened: Sysmon EventCode=3 from winword.exe to 127.0.0.1:8080. The manipulation of the ZIP archive using System.IO.Compression is visible as PowerShell process events (Sysmon EventCode=1) before the Office network event — the chain of PowerShell→file creation→Office network connection is the full kill chain telemetry.

  5. Test 5Verify Template Injection Document Structure — Manual Inspection

    Expected signal: PowerShell process creation (Sysmon EventCode=1) with command line containing System.IO.Compression.ZipFile. No network events — this is static analysis only. The script outputs the injected URL to the console, confirming the template injection payload is present before any execution occurs.

Unlock Pro Content

Get the full detection package for T1221 including response playbook, investigation guide, and atomic red team tests.

Response PlaybookInvestigation GuideHunting QueriesAtomic Red Team TestsTuning Guidance

Related Detections