Phishing
Adversaries may send phishing messages to gain access to victim systems. All forms of phishing are electronically delivered social engineering. Phishing can be targeted (spearphishing) against a specific individual, company, or industry, or non-targeted such as mass malware spam campaigns. Adversaries send victims emails containing malicious attachments or links, typically to execute malicious code on victim systems or steal credentials. Phishing may also be conducted via third-party services like social media platforms, via voice-based callback lures directing victims to call a phone number and then download malware or install remote management tools, or through thread hijacking by injecting malicious content into existing email conversations. Email spoofing, manipulation of authentication headers, and abuse of compromised legitimate accounts are common evasion techniques used to bypass automated security tooling and human suspicion alike.
What is T1566 Phishing?
Phishing (T1566) maps to the Initial Access tactic — the adversary is trying to get into your network in MITRE ATT&CK.
This page provides production-ready detection logic for Phishing, covering the data sources and telemetry it touches: Application Log: Application Log Content, Network Traffic: Network Traffic Content, Microsoft Defender for Office 365, Microsoft 365 Defender Advanced Hunting. The queries below are rated high severity at high confidence, and ship for 7 SIEM platforms — KQL, SPL, Elastic, QRadar, Sumo, YARA-L, LogScale.
MITRE ATT&CK
- Tactic
- Initial Access
- Technique
- T1566 Phishing
- Canonical reference
- https://attack.mitre.org/techniques/T1566/
let SuspiciousExtensions = dynamic([
".exe", ".dll", ".bat", ".cmd", ".ps1", ".vbs", ".js", ".hta", ".wsf",
".scr", ".pif", ".lnk", ".iso", ".img", ".cab", ".docm", ".xlsm", ".pptm", ".jar"
]);
let SuspiciousSubjectTerms = dynamic([
"invoice", "payment", "urgent", "verify", "suspended", "confirm",
"unusual activity", "password reset", "credentials", "wire transfer",
"action required", "shared with you", "security alert", "your account"
]);
// Signal 1: Inbound email with phishing or malware verdict from Microsoft Defender for Office 365
let EmailThreatEvents =
EmailEvents
| where Timestamp > ago(24h)
| where EmailDirection == "Inbound"
| where ThreatTypes has_any ("Phish", "Malware") or (DeliveryAction == "Blocked" and ConfidenceLevel == "High")
| extend AuthJson = parse_json(AuthenticationDetails)
| extend SPFResult = tostring(AuthJson.SPF)
| extend DKIMResult = tostring(AuthJson.DKIM)
| extend DMARCResult = tostring(AuthJson.DMARC)
| extend AuthFailed = (SPFResult =~ "Fail" or DKIMResult =~ "Fail" or DMARCResult =~ "Fail")
| extend SuspiciousSubject = Subject has_any (SuspiciousSubjectTerms)
| project Timestamp, NetworkMessageId, SenderFromAddress, SenderFromDomain,
SenderIPv4, RecipientEmailAddress, Subject, ThreatTypes, ConfidenceLevel,
DeliveryAction, DeliveryLocation, SuspiciousSubject,
AuthFailed, SPFResult, DKIMResult, DMARCResult;
// Signal 2: Attachment metadata — suspicious file extensions or malware family hits
let AttachmentSignals =
EmailAttachmentInfo
| where Timestamp > ago(24h)
| where FileName has_any (SuspiciousExtensions)
or isnotempty(MalwareFamily)
or ThreatTypes has_any ("Phish", "Malware")
| summarize
SuspiciousFiles = make_set(FileName, 10),
MalwareFamilies = make_set(MalwareFamily, 5),
AttachmentHashes = make_set(SHA256, 10)
by NetworkMessageId;
// Signal 3: URLs extracted from email body — collect domains for threat intel correlation
let UrlSignals =
EmailUrlInfo
| where Timestamp > ago(24h)
| summarize UrlCount = count(), LinkedDomains = make_set(UrlDomain, 20) by NetworkMessageId;
// Combine all signals and score
EmailThreatEvents
| join kind=leftouter AttachmentSignals on NetworkMessageId
| join kind=leftouter UrlSignals on NetworkMessageId
| extend HasMaliciousAttachment = isnotempty(SuspiciousFiles)
| extend ThreatScore =
toint(ThreatTypes has "Phish") * 3 +
toint(ThreatTypes has "Malware") * 3 +
toint(HasMaliciousAttachment) * 2 +
toint(AuthFailed) +
toint(SuspiciousSubject)
| where ThreatScore > 0
| project Timestamp, SenderFromAddress, SenderFromDomain, SenderIPv4,
RecipientEmailAddress, Subject, ThreatTypes, ConfidenceLevel,
DeliveryAction, DeliveryLocation,
SuspiciousFiles, MalwareFamilies, AttachmentHashes,
UrlCount, LinkedDomains,
SPFResult, DKIMResult, DMARCResult, AuthFailed,
SuspiciousSubject, ThreatScore, NetworkMessageId
| sort by ThreatScore desc, Timestamp desc Detects inbound phishing and malware-laden email delivery using Microsoft 365 Defender's EmailEvents, EmailAttachmentInfo, and EmailUrlInfo advanced hunting tables. Correlates email-level threat verdicts (Phish, Malware) from Defender for Office 365 with suspicious file extension attachments, malware family hits, authentication failures (SPF/DKIM/DMARC), and subject-line keyword matching. Assigns a composite ThreatScore to prioritize high-confidence phishing attempts over borderline signals. Requires Microsoft Defender for Office 365 Plan 2 or Microsoft 365 E5 for full table population.
Data Sources
Required Tables
False Positives
- Automated marketing and newsletter platforms (Mailchimp, Constant Contact, HubSpot) that send bulk email from shared infrastructure may trigger SPF/DKIM mismatches if not properly configured
- Internal security awareness phishing simulation platforms (KnowBe4, Proofpoint Security Awareness, Cofense) deliberately send fake phishing emails and should be allowlisted by sender domain
- Vendors or partners sending invoices or payment requests from cloud document-sharing services (DocuSign, Adobe Sign, Dropbox) may match subject-line keywords while being fully legitimate
- Email delivery failure notifications (NDRs, mailer-daemon bounces) forwarded through multiple hops may fail DMARC alignment without being malicious
- Internal IT helpdesk emails requesting credential resets or account verification may match SuspiciousSubjectTerms
Sigma rule & cross-platform mapping
The detection logic for Phishing (T1566) above is provided in a vendor-neutral
form so you can deploy it on any SIEM. The same logic is shipped here as native
KQL (Microsoft Sentinel / Defender), SPL (Splunk), Elastic (Elastic Security (EQL)), QRadar (IBM QRadar (AQL)), Sumo (Sumo Logic CSE), YARA-L (Google Chronicle / SecOps), LogScale (CrowdStrike LogScale (CQL)) queries. In Sigma terms, this detection targets the
following logsource:
logsource:
category: network_connection
product: windows Browse the community-maintained Sigma rules for this technique:
Platform-specific guides for T1566
References (14)
- https://attack.mitre.org/techniques/T1566/
- https://learn.microsoft.com/en-us/microsoft-365/security/office-365-security/anti-phishing-protection
- https://learn.microsoft.com/en-us/microsoft-365/security/office-365-security/anti-spoofing-protection
- https://learn.microsoft.com/en-us/defender-xdr/advanced-hunting-emailevents-table
- https://learn.microsoft.com/en-us/defender-xdr/advanced-hunting-emailattachmentinfo-table
- https://learn.microsoft.com/en-us/defender-xdr/advanced-hunting-emailurlinfo-table
- https://learn.microsoft.com/en-us/office/office-365-management-api/office-365-management-activity-api-schema#threatintelligence-complex-type
- https://krebsonsecurity.com/2024/03/thread-hijacking-phishes-that-prey-on-your-curiosity/
- https://unit42.paloaltonetworks.com/luna-moth-callback-phishing/
- https://www.cisa.gov/uscert/ncas/alerts/aa23-025a
- https://www.proofpoint.com/us/threat-reference/email-spoofing
- https://blog.cyberproof.com/blog/double-bounced-attacks-with-email-spoofing-2022-trends
- https://github.com/redcanaryco/atomic-red-team/blob/master/atomics/T1566/T1566.md
- https://github.com/SigmaHQ/sigma/tree/master/rules/cloud/m365
Testing Methodology
Validate this detection against 4 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.
- Test 1Phishing Email with Suspicious Attachment via PowerShell SMTP
Expected signal: EmailEvents table: Inbound email from spoofed sender domain with suspicious subject, DeliveryAction likely Junked or Blocked by Defender for Office 365. EmailAttachmentInfo: FileName='invoice_2026.pdf.ps1' with .ps1 extension flagged. O365 Management Activity: TIMailData event with Verdict='Phish' or 'Malware' in ThreatIntelligence workload. Exchange Admin Center Message Trace: full delivery path logged.
- Test 2Office Macro Execution Simulation — Word Spawning Command Shell
Expected signal: Sysmon Event ID 1 (Process Create): ParentImage=WINWORD.EXE, Image=cmd.exe, CommandLine='cmd.exe /c whoami > %TEMP%\phish_exec_test.txt'. Sysmon Event ID 11 (File Create): phish_exec_test.txt written to %TEMP%. Security Event ID 4688 (if command line auditing enabled): same parent-child relationship. Microsoft Defender may generate an alert for macro execution.
- Test 3Email Spoofing via DMARC-None Domain — Header From Mismatch
Expected signal: Email headers: Authentication-Results header will show DMARC=fail (due to From domain mismatch with envelope sender). Exchange Online: message trace showing delivery with DMARC fail result. O365 Management Activity: TIMailData or MessageDelivered event with authentication failure flags. Defender for Office 365: anti-spoofing intelligence may flag the mismatched From/Reply-To pattern.
- Test 4Callback Phishing Simulation — HTA File Dropper via Email Link
Expected signal: Sysmon Event ID 1: mshta.exe launched with HTA file path as argument. Sysmon Event ID 1 (child): cmd.exe spawned by mshta.exe with whoami command. Sysmon Event ID 11: callback_phish_test.txt created in %TEMP%. Security Event ID 4688: both mshta.exe and cmd.exe process creation events (if command line auditing enabled). Windows Defender may generate an alert for mshta.exe executing a locally-crafted HTA.
Response Playbook
Triage
- Confirm the email verdict in Microsoft 365 Defender: navigate to the Microsoft 365 Defender portal → Email & Collaboration → Explorer → search by NetworkMessageId. Review the full message trace including all recipients, delivery path, and threat verdict confidence.
- Examine the sender identity: compare P1Sender (envelope from) to P2Sender (header From) — a mismatch indicates spoofing. Check whether the sending domain has valid SPF, DKIM, and DMARC records using `nslookup -type=TXT <domain>` or MXToolbox.
- Assess delivery outcome: was the email Delivered, Junked, or Blocked? If Delivered, determine how many recipients received it. Use the Message Trace in the Exchange Admin Center or Security & Compliance portal to enumerate all affected mailboxes.
- Inspect all attachments: extract SHA256 hashes from EmailAttachmentInfo and query VirusTotal, Hybrid Analysis, or your sandbox. Check file extensions — double extensions (invoice.pdf.exe) or renamed executables are strong indicators.
- Extract all URLs from the email body and submit to a URL sandbox (URLScan.io, Joe Sandbox Cloud). Check if any redirect to credential harvesting pages, fake login portals, or payload delivery sites.
- Determine if any recipient clicked a link or opened an attachment: query UrlClickEvents for the NetworkMessageId. Check DeviceProcessEvents for Office applications spawning cmd.exe, powershell.exe, or other shells around the email delivery timestamp.
- Check if the sender domain is a lookalike: compare to known-good vendor domains using Levenshtein distance — 'microssoft.com', 'paypa1.com', or Unicode homoglyphs are common spearphishing indicators.
Containment
- If any recipient clicked the payload or opened an attachment: immediately isolate affected endpoints using EDR network isolation (Microsoft Defender for Endpoint: Isolate Device action). Preserve memory and disk image before remediation.
- Purge the phishing email from all recipient mailboxes using the Microsoft 365 Defender portal: Threat Explorer → select messages → Purge → Hard delete. Or via PowerShell: `Get-ComplianceSearchAction | New-ComplianceSearchAction -Purge -PurgeType HardDelete`.
- Block the sender domain and IP at the email gateway: add the SenderFromDomain and SenderIPv4 to the tenant block list in Microsoft 365 Defender → Policies & Rules → Threat Policies → Tenant Allow/Block Lists.
- If credential theft is suspected: force password reset for all recipients, revoke all active sessions and OAuth tokens using `Revoke-AzureADUserAllRefreshToken` or the Microsoft 365 admin center. Enable MFA if not already enforced.
- Block the phishing URL/domain at the proxy and DNS layer. For Microsoft 365 environments, add the domain to the tenant block list. For network-level blocking, update firewall rules or DNS RPZ.
- If a malicious attachment was opened: contain the host, quarantine the file hash in your EDR platform, and push the IOCs (SHA256, domain, IP) to your threat intel platform for cross-environment blocking.
Evidence Collection
- Raw email source (.eml): Export from the Microsoft 365 Defender portal via Email Entity page → Download email. Preserve the full MIME structure including all Received headers for IP trace analysis.
- Email headers: Extract and analyze all Received headers to trace the actual sending path. Key headers: X-Originating-IP, X-Forefront-Antispam-Report, X-Microsoft-Antispam, Authentication-Results.
- Microsoft 365 Message Trace: Run Get-MessageTrace in Exchange Online PowerShell for the 10-day window. For older messages, use Start-HistoricalSearch. Captures all delivery events including all recipients.
- Attachment forensics: Retrieve attachment hashes from EmailAttachmentInfo. Submit SHA256 to VirusTotal API. Detonate in sandbox. Collect dropped files, C2 IOCs, and behavioral indicators.
- URL detonation results: If Microsoft Safe Links detonated the URL, retrieve the detonation report from Threat Explorer. Otherwise submit to URLScan.io or a local sandbox.
- Defender for Office 365 threat intelligence report: In Microsoft 365 Defender portal, navigate to the email entity page for the NetworkMessageId — it shows the full threat analysis including detection technology and confidence.
- Endpoint forensics (if clicked): Collect DeviceProcessEvents, DeviceNetworkEvents, DeviceFileEvents for affected hosts in the ±30 minute window around the click timestamp. Preserve browser history, DNS cache, and proxy logs.
- Azure AD sign-in logs: Query AADSignInLogs for all recipients from the email delivery timestamp forward — look for logins from new IP addresses, unfamiliar geographies, or unusual user agents indicating credential theft.
Escalation Criteria
- ! Any recipient confirmed to have clicked a malicious link or opened an attachment — escalate to incident response immediately, treat as active compromise
- ! Post-click process execution detected: Office application (winword.exe, excel.exe, outlook.exe) spawning cmd.exe, powershell.exe, or mshta.exe — indicates macro or script execution from phishing document
- ! Credential harvesting confirmed: Azure AD sign-in from a new country or impossible travel scenario within 30 minutes of email delivery to a recipient
- ! More than 10 recipients targeted in a single campaign — indicates mass phishing or targeted spearphishing of an entire business unit, requiring executive notification
- ! Phishing email impersonating a C-suite executive (CEO fraud/BEC) — immediate escalation to legal and finance teams regardless of delivery outcome
- ! The phishing email bypassed all security controls and was delivered to the inbox (DeliveryAction=Delivered, DeliveryLocation=Inbox) — indicates a gap in email security posture requiring vendor escalation
- ! Sender domain passes SPF/DKIM/DMARC — indicates the attacker is using a compromised legitimate domain or has registered a convincing lookalike with valid authentication records
Investigation Guide
Forensic Artifacts
- >
Raw email file (.eml): Full MIME message with Received header chain — trace each hop's IP address against threat intel to identify actual sending infrastructure - >
Email headers: Authentication-Results header (SPF, DKIM, DMARC pass/fail), X-Originating-IP (original sending IP), Message-ID (unique identifier for cross-system correlation), X-Mailer (sending client fingerprint) - >
Microsoft 365: Message Trace logs in Exchange Admin Center — delivery path, timestamps, all recipients, and disposition for up to 90 days - >
Microsoft 365: Microsoft Defender for Office 365 Threat Explorer — full threat analysis, detonation results, and URL/attachment verdicts for each message - >
File System (Windows): `%TEMP%` and `%APPDATA%` directories for payloads dropped by opened attachments - >
File System (Windows): `%LOCALAPPDATA%\Microsoft\Office\` — Office temp files and recently opened documents - >
File System (Windows): `C:\Windows\Prefetch\` — prefetch entries for any executables launched from phishing attachments (WINWORD.EXE-*.pf, EXCEL.EXE-*.pf) - >
Registry (Windows): `HKCU\SOFTWARE\Microsoft\Office\<version>\<App>\Security\` — macro security settings and trust records for opened documents - >
Browser artifacts: History, cached pages, and cookies for phishing URLs accessed by the victim — located at `%APPDATA%\Local\Google\Chrome\User Data\Default\History` (Chrome) or `%APPDATA%\Roaming\Mozilla\Firefox\Profiles\*.default\places.sqlite` (Firefox) - >
DNS cache (Windows): `ipconfig /displaydns` — reveals phishing domains resolved by the endpoint after link click - >
Proxy logs: HTTP/HTTPS requests to phishing domains with referrer, user-agent, and response codes — critical for reconstructing click path and determining if credentials were submitted - >
Azure AD Sign-In Logs: Authentication events for targeted recipients — filter by IP, location, and user-agent to detect compromised sessions post-click
Tuning Guidance
Start by identifying and allowlisting all security awareness training platforms in your environment (KnowBe4, Proofpoint Security Awareness, Cofense) — their sending domains should be excluded from phishing alerts entirely using sender domain exceptions. Next, baseline your legitimate email vendors: bulk sending platforms (SendGrid, Mailchimp), invoice platforms (DocuSign, Coupa), and cloud storage notification senders frequently have subject lines matching SuspiciousSubjectTerms. Build an allowlist of known-good sender domains for these services. For the ThreatScore threshold, start at ThreatScore >= 2 to reduce noise while retaining high-fidelity detections. Tune up to ThreatScore >= 3 if your environment receives high volumes of spam that gets Junked with borderline verdicts. If your organization has strict DMARC enforcement (p=reject), the AuthFailed signal becomes highly reliable — weight it more heavily. For environments without Microsoft Defender for Office 365 Plan 2, the EmailAttachmentInfo and EmailUrlInfo tables may not be fully populated — fall back to DeviceProcessEvents-based hunting (Office spawning child processes) as a compensating control. Enable Microsoft 365 audit logging for all users and activate Defender for Office 365 Safe Attachments and Safe Links policies to maximize telemetry coverage.
Hunting Queries
Hunt for Office applications spawning known LOLBins or script interpreters — a strong post-phishing execution indicator. This pattern occurs when a victim opens a malicious attachment containing a macro, OLE object, or embedded script that launches a secondary process. Differs from the primary detection by targeting process execution rather than email delivery, catching phishing that bypassed email controls or was delivered via non-email channels.
// Hunt: Office applications spawning suspicious child processes — post-phishing macro or script execution
let OfficeApps = dynamic(["winword.exe", "excel.exe", "powerpnt.exe", "outlook.exe", "mspub.exe", "onenote.exe", "msaccess.exe"]);
let SuspiciousChildren = dynamic(["cmd.exe", "powershell.exe", "pwsh.exe", "wscript.exe", "cscript.exe", "mshta.exe", "rundll32.exe", "regsvr32.exe", "certutil.exe", "bitsadmin.exe", "wmic.exe", "msiexec.exe", "msbuild.exe", "installutil.exe"]);
DeviceProcessEvents
| where Timestamp > ago(7d)
| where InitiatingProcessFileName has_any (OfficeApps)
| where FileName has_any (SuspiciousChildren)
| project Timestamp, DeviceName, AccountName, FileName, ProcessCommandLine,
InitiatingProcessFileName, InitiatingProcessCommandLine
| sort by Timestamp desc index=wineventlog sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational" EventCode=1
(ParentImage="*\\winword.exe" OR ParentImage="*\\excel.exe" OR ParentImage="*\\powerpnt.exe"
OR ParentImage="*\\outlook.exe" OR ParentImage="*\\mspub.exe" OR ParentImage="*\\onenote.exe")
(Image="*\\cmd.exe" OR Image="*\\powershell.exe" OR Image="*\\wscript.exe"
OR Image="*\\cscript.exe" OR Image="*\\mshta.exe" OR Image="*\\rundll32.exe"
OR Image="*\\regsvr32.exe" OR Image="*\\certutil.exe" OR Image="*\\bitsadmin.exe"
OR Image="*\\wmic.exe" OR Image="*\\msiexec.exe")
| table _time, host, User, Image, CommandLine, ParentImage, ParentCommandLine
| sort - _time Hunts for Azure AD sign-ins occurring within 2 hours of a phishing email delivery to the same recipient — a strong indicator of credential harvesting success. A victim who received and clicked a phishing link, entered credentials on a fake login page, and is then signed into by the attacker will appear as a sign-in from a new IP or country shortly after email delivery. This pattern finds different events than the primary detection by correlating email delivery with authentication logs.
// Hunt: Impossible travel or new-country sign-in within 2 hours of phishing email delivery to the same recipient
let PhishingRecipients =
EmailEvents
| where Timestamp > ago(7d)
| where ThreatTypes has_any ("Phish", "Malware") and DeliveryAction == "Delivered"
| project EmailTimestamp=Timestamp, RecipientEmailAddress, NetworkMessageId;
PhishingRecipients
| join kind=inner (
AADSignInLogs
| where TimeGenerated > ago(7d)
| where ResultType == 0
| project SignInTime=TimeGenerated, UserPrincipalName, IPAddress, Location, UserAgent, AppDisplayName
) on $left.RecipientEmailAddress == $right.UserPrincipalName
| where SignInTime between (EmailTimestamp .. (EmailTimestamp + 2h))
| project EmailTimestamp, SignInTime, UserPrincipalName, NetworkMessageId, IPAddress, Location, UserAgent, AppDisplayName
| sort by EmailTimestamp desc index=o365 sourcetype="o365:management:activity" Workload=ThreatIntelligence Operation=TIMailData Verdict IN ("Phish","Malware","HighConfidencePhish")
| spath output=Recipients path=Recipients
| eval recipient=mvindex(Recipients, 0)
| eval email_time=_time
| join type=inner recipient [
index=azure sourcetype="azure:monitor:aad" operationName="Sign-in activity" properties.status.errorCode=0
| eval recipient=lower('properties.userPrincipalName')
| eval signin_time=_time
| table recipient, signin_time, properties.ipAddress, properties.location.countryOrRegion, properties.appDisplayName
]
| where (signin_time > email_time) AND (signin_time <= email_time + 7200)
| eval minutes_after=round((signin_time - email_time) / 60, 1)
| table _time, recipient, Verdict, "properties.ipAddress", "properties.location.countryOrRegion", "properties.appDisplayName", minutes_after
| sort - minutes_after Hunts for phishing emails sent from homoglyph or typosquatting domains that impersonate trusted brands. Looks for common substitutions (0 for o, 1 for l, doubled letters, subdomains like 'microsoft.support-portal.com'). This query finds different patterns than the primary detection because it does not rely on Defender for Office 365 verdict — it catches phishing that bypassed threat verdicts by targeting lookalike domains that haven't yet been flagged as malicious.
// Hunt: Homoglyph and typosquatting domain detection — senders using lookalike domains
let TrustedDomains = dynamic(["microsoft.com", "office.com", "paypal.com", "amazon.com", "google.com", "docusign.com", "dropbox.com"]);
EmailEvents
| where Timestamp > ago(7d)
| where EmailDirection == "Inbound"
| extend SenderDomainLen = strlen(SenderFromDomain)
| extend IsDirectLookalike = SenderFromDomain has_any (TrustedDomains)
| where not(IsDirectLookalike)
| where SenderFromDomain matches regex @"(micros+oft|0ffice|paypa[l1]|amaz[o0]n|g[o0]{2}gle|d[o0]cusign|dr[o0]pbox|[a-z0-9-]{4,}\.(support|secure|helpdesk|verify|login|account)[a-z0-9-]*)\."
| project Timestamp, SenderFromAddress, SenderFromDomain, RecipientEmailAddress, Subject, ThreatTypes, DeliveryAction
| sort by Timestamp desc index=o365 sourcetype="o365:management:activity" Workload=Exchange Operation=MessageDelivered
| spath output=SenderDomain path=SenderDomain
| where isnotnull(SenderDomain)
| eval IsLookalike=if(
match(lower(SenderDomain), "(micros{2,}oft|0ffice|paypa[l1]|amaz[o0]n|g[o0]{2}gle|d[o0]cusign|dr[o0]pbox|\.(support|secure|helpdesk|verify|login|account)[a-z0-9-]*(\.|$))"),
1, 0
)
| where IsLookalike=1
| spath output=Recipients path=Recipients
| spath output=Subject path=Subject
| table _time, SenderDomain, Recipients, Subject
| sort - _time Atomic Red Team Tests
Simulates sending a phishing email with a suspicious subject line and attachment name using PowerShell's built-in SMTP client. This tests whether your email security gateway and Defender for Office 365 detect and classify inbound phishing messages. The email is sent to an internal test mailbox. No malicious content is included — the attachment is a benign text file renamed with a suspicious double extension.
Command
$tempFile = "$env:TEMP\invoice_2026.pdf.ps1"
"Write-Output 'Atomic Test'" | Out-File $tempFile
$smtp = New-Object Net.Mail.SmtpClient('smtp.office365.com', 587)
$smtp.EnableSsl = $true
$smtp.Credentials = New-Object Net.NetworkCredential('[email protected]', 'YourPassword')
$msg = New-Object Net.Mail.MailMessage
$msg.From = '[email protected]'
$msg.To.Add('[email protected]')
$msg.Subject = 'URGENT: Invoice Payment Required - Action Required'
$msg.Body = 'Please review the attached invoice and process the payment immediately. Click here to confirm: http://paypa1-verify.example.com/confirm'
$attachment = New-Object Net.Mail.Attachment($tempFile)
$msg.Attachments.Add($attachment)
$smtp.Send($msg)
Write-Output 'Phishing simulation email sent' Cleanup
Remove-Item "$env:TEMP\invoice_2026.pdf.ps1" -ErrorAction SilentlyContinue Expected Telemetry
EmailEvents table: Inbound email from spoofed sender domain with suspicious subject, DeliveryAction likely Junked or Blocked by Defender for Office 365. EmailAttachmentInfo: FileName='invoice_2026.pdf.ps1' with .ps1 extension flagged. O365 Management Activity: TIMailData event with Verdict='Phish' or 'Malware' in ThreatIntelligence workload. Exchange Admin Center Message Trace: full delivery path logged.
Expected Detection
KQL: ThreatScore >= 3 due to ThreatTypes has 'Phish' (x3) + SuspiciousSubject match (x1) + SuspiciousFiles match for .ps1 extension (x2). SPL: Verdict='Phish' with SuspiciousSubject=1 and HasSuspiciousAttachment=1, ThreatScore >= 4. Alert severity: Critical.
Simulates the post-phishing execution phase where a victim opens a malicious document and a VBA macro executes a child process. Uses PowerShell COM automation to create a Word document with an AutoOpen macro that spawns cmd.exe. This tests whether your EDR and process-creation monitoring detect Office applications spawning unexpected child processes — a primary indicator of successful phishing attachment execution.
Command
$word = New-Object -ComObject Word.Application
$word.Visible = $false
$doc = $word.Documents.Add()
$vba = $doc.VBProject.VBComponents.Item(1)
$vba.CodeModule.AddFromString(@'
Sub AutoOpen()
Shell "cmd.exe /c whoami > %TEMP%\phish_exec_test.txt"
End Sub
')
$docPath = "$env:TEMP\phishing_test_invoice.docm"
$doc.SaveAs($docPath, 13)
$doc.Close()
$word.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null
Start-Process "$env:ProgramFiles\Microsoft Office\root\Office16\WINWORD.EXE" -ArgumentList $docPath
Start-Sleep -Seconds 5 Cleanup
Remove-Item "$env:TEMP\phishing_test_invoice.docm" -ErrorAction SilentlyContinue
Remove-Item "$env:TEMP\phish_exec_test.txt" -ErrorAction SilentlyContinue
Get-Process winword -ErrorAction SilentlyContinue | Stop-Process -Force Expected Telemetry
Sysmon Event ID 1 (Process Create): ParentImage=WINWORD.EXE, Image=cmd.exe, CommandLine='cmd.exe /c whoami > %TEMP%\phish_exec_test.txt'. Sysmon Event ID 11 (File Create): phish_exec_test.txt written to %TEMP%. Security Event ID 4688 (if command line auditing enabled): same parent-child relationship. Microsoft Defender may generate an alert for macro execution.
Expected Detection
KQL hunting query: DeviceProcessEvents with InitiatingProcessFileName='winword.exe' and FileName='cmd.exe'. SPL hunting query: Sysmon EventCode=1 with ParentImage=*winword.exe* and Image=*cmd.exe*. EDR alert: Office application spawning shell process.
Uses the swaks SMTP testing tool to send an email with a mismatched envelope sender (P1) and header From address (P2), simulating the header manipulation used in BEC (Business Email Compromise) and spearphishing campaigns. Tests whether your email gateway correctly applies DMARC alignment checks and whether Defender for Office 365 flags the authentication failure. Requires swaks installed on Linux.
Command
# Install swaks if needed: apt-get install -y swaks
# Send email with mismatched envelope sender (MAIL FROM) and header From
swaks \
--server smtp.yourorg.com \
--port 587 \
--tls \
--auth-user '[email protected]' \
--auth-password 'YourTestPassword' \
--from '[email protected]' \
--header 'From: CEO Name <[email protected]>' \
--header 'Reply-To: [email protected]' \
--to '[email protected]' \
--header 'Subject: Urgent Wire Transfer Request' \
--body 'Please process the attached wire transfer of $50,000 to our new vendor. I am in a meeting and cannot be reached by phone.' Expected Telemetry
Email headers: Authentication-Results header will show DMARC=fail (due to From domain mismatch with envelope sender). Exchange Online: message trace showing delivery with DMARC fail result. O365 Management Activity: TIMailData or MessageDelivered event with authentication failure flags. Defender for Office 365: anti-spoofing intelligence may flag the mismatched From/Reply-To pattern.
Expected Detection
KQL: AuthFailed=true due to DMARC=Fail in AuthenticationDetails. SuspiciousSubject=1 due to 'urgent' keyword match. SPL: AuthFailed=1 in SPL query. Alert: Medium severity (ThreatScore 1-2 depending on Defender verdict confidence).
Simulates the callback phishing technique (used by Royal ransomware, Luna Moth) where a victim is directed via email to download and open an HTA (HTML Application) file that executes code. Creates a benign HTA file and tests whether opening an HTA via a browser download triggers process monitoring alerts. The HTA runs mshta.exe which spawns wscript.exe — a common pattern in callback phishing campaigns.
Command
# Step 1: Create a benign HTA file simulating a callback phishing payload
$htaContent = @'
<html>
<head><title>Remote Support Tool</title></head>
<HTA:APPLICATION ID="RemoteSupport" APPLICATIONNAME="Remote Support" WINDOWSTATE="minimize" SHOWINTASKBAR="no" />
<script language="VBScript">
Set oShell = CreateObject("WScript.Shell")
oShell.Run "cmd.exe /c whoami > %TEMP%\callback_phish_test.txt", 0, False
Self.Close
</script>
</head><body></body>
</html>
'@
$htaPath = "$env:TEMP\support_tool_v2.hta"
$htaContent | Out-File -FilePath $htaPath -Encoding ASCII
# Step 2: Execute the HTA as a user would after downloading from a phishing link
Start-Process mshta.exe -ArgumentList $htaPath
Start-Sleep -Seconds 3
Write-Output "HTA execution complete. Check for callback_phish_test.txt in TEMP directory." Cleanup
Remove-Item "$env:TEMP\support_tool_v2.hta" -ErrorAction SilentlyContinue
Remove-Item "$env:TEMP\callback_phish_test.txt" -ErrorAction SilentlyContinue
Get-Process mshta -ErrorAction SilentlyContinue | Stop-Process -Force Expected Telemetry
Sysmon Event ID 1: mshta.exe launched with HTA file path as argument. Sysmon Event ID 1 (child): cmd.exe spawned by mshta.exe with whoami command. Sysmon Event ID 11: callback_phish_test.txt created in %TEMP%. Security Event ID 4688: both mshta.exe and cmd.exe process creation events (if command line auditing enabled). Windows Defender may generate an alert for mshta.exe executing a locally-crafted HTA.
Expected Detection
KQL hunting query: DeviceProcessEvents with InitiatingProcessFileName='mshta.exe' and FileName='cmd.exe' — this matches the callback phishing execution chain. SPL Sysmon query: EventCode=1 with ParentImage=*mshta.exe* and Image=*cmd.exe*. EDR alert: mshta.exe spawning shell process from non-standard path.