Listen to this Post

Introduction:
Modern adversaries no longer rely on simple malware signatures—they abuse legitimate identity protocols, steal authentication tokens, and systematically disable telemetry sources like AMSI and ETW to operate undetected. Traditional detection rules that fire on single indicators fail under these conditions, leaving security teams blind to active compromises. This article explores how advanced threat hunting and detection engineering methodologies—validated by both defensive professionals and top red teamers—enable organizations to build behavioral detections that remain resilient even when attackers actively evade endpoint visibility.
Learning Objectives:
- Understand the principles of high-order behavioral detection engineering that withstand common evasion techniques including AMSI/ETW patching
- Learn to detect adversary-in-the-middle (AiTM) phishing, Entra ID token theft, and stolen token abuse from compromised machines
- Build vendor-agnostic detection logic transferable across SIEM, XDR, and cloud platforms without relying on product-specific shortcuts
- Develop the ability to reason through false positives, visibility gaps, and compensating detections in real enterprise environments
You Should Know:
- The Shift from Indicator-Based to Behavioral Detection Engineering
Traditional detection engineering focuses on writing rules for known indicators—file hashes, IP addresses, or domain names. This approach fails against modern adversaries who continuously change infrastructure and employ living-off-the-land techniques. Advanced detection engineering shifts the focus to behavioral patterns that identify how attackers operate rather than what tools they use.
The course “Advanced Threat Hunting and Detection Engineering in the Enterprise” emphasizes building detections around anomalies in behavior rather than single attack signatures. Instead of writing a detection for one specific C2 framework, you learn to break the attack down to its most general behavioral components—making it significantly harder for attackers to bypass.
Step-by-Step Approach to Behavioral Detection Design:
- Map the adversary TTP: Start with MITRE ATT&CK mapping—understand what the adversary does, not just what tool they use. For example, rather than detecting “Cobalt Strike beacon,” detect “process making outbound HTTPS connections with low URI diversity”.
-
Identify the behavioral anomaly: Determine what normal looks like in your environment. For token theft, this might be “same user authentication from geographically impossible locations within minutes” or “refresh token usage from a new device without prior MFA.”
-
Write detection logic that observes the behavior: Use KQL (Kusto Query Language) for Microsoft environments or Sigma for cross-platform rules. Focus on patterns—time series anomalies, statistical deviations, or sequence correlations.
-
Test against evasion: Simulate AMSI/ETW patching, direct syscalls, and other evasion techniques to see if your detection still fires. Over 90% of realistic lab scenarios include telemetry reduction techniques to stress-test detections.
-
Tune for false positives: Real environments generate noise. Analyze false positives systematically—adjust thresholds, add contextual filters, or implement compensating detections.
Linux Command Example – Detecting Suspicious Outbound Connections:
Monitor for unusual outbound connections with low URI diversity (potential C2 beaconing)
sudo tcpdump -i any -1 'tcp[bash] & (tcp-syn) != 0' | awk '{print $5}' | sort | uniq -c | sort -1r
Check for processes connecting to external IPs with no DNS resolution
sudo netstat -tunap | grep ESTABLISHED | grep -v ":443|:80" | awk '{print $5}' | cut -d: -f1 | sort | uniq -c
Hunt for processes making connections to low-reputation domains
curl -s "https://api.threatintelligence.com/domain/reputation?domain=example.com" | jq '.reputation'
Windows PowerShell Example – Detecting Beaconing Behavior:
Identify processes with high outbound connection counts to external IPs
Get-1etTCPConnection | Where-Object {$<em>.RemoteAddress -1otmatch '^(10.|172.16.|192.168.|127.)'} |
Group-Object OwningProcess |
Select-Object Name, Count |
Where-Object {$</em>.Count -gt 50} |
ForEach-Object { Get-Process -Id $_.Name -ErrorAction SilentlyContinue }
Check for processes with low URI diversity in web proxy logs (simulated)
Get-Content .\proxy_logs.csv |
Group-Object {($_ -split ',')[bash]} | Assuming column 2 is destination URI
Where-Object {$_.Count -lt 3} |
Select-Object Name, Count
- Detecting AiTM Phishing and Entra ID Token Theft
Adversary-in-the-middle phishing frameworks like Evilginx and Tycoon 2FA proxy authentication sessions to steal session tokens, bypassing MFA entirely. Tycoon 2FA, attributed to Storm-1747, is currently the most prolific Phishing-as-a-Service platform targeting Microsoft 365 and Google Workspace.
How AiTM Attacks Work:
- Victim clicks phishing link → lands on attacker-controlled proxy site
- Proxy authenticates to legitimate Entra ID/Google on behalf of victim
- MFA challenge is proxied to victim—they complete it
4. Attacker captures authenticated session token
- Token is replayed from attacker infrastructure to access victim’s data
Detection Strategy – Behavioral Correlation:
Rather than detecting the phishing site itself (which changes constantly), detect the abnormal token usage:
- Geolocation anomalies: Token used from IP in different country within minutes of legitimate authentication
- Device fingerprint mismatch: Token used from device with different user-agent, OS, or browser fingerprint
- Unusual scope or resource access: Token requesting Graph API permissions or SharePoint access inconsistent with normal behavior
- Inbox rule creation: AiTM attackers frequently create forwarding rules to maintain persistence
KQL Query for Entra ID Token Anomaly Detection:
// Detect potential token replay - same user, different locations in short time SigninLogs | where TimeGenerated > ago(1h) | where AuthenticationRequirement == "multiFactorAuthentication" | summarize LocationCount = dcount(Location), IPs = make_set(IPAddress), Devices = make_set(DeviceInfo) by UserPrincipalName, bin(TimeGenerated, 5m) | where LocationCount > 1 | project UserPrincipalName, TimeGenerated, LocationCount, IPs, Devices // Detect token theft via unusual refresh token usage AADNonInteractiveUserSignInLogs | where TimeGenerated > ago(24h) | where TokenIssuerType == "RefreshToken" | summarize TokenRefreshCount = count(), DistinctIPs = dcount(IPAddress), DistinctLocations = dcount(Location) by UserPrincipalName, bin(TimeGenerated, 15m) | where TokenRefreshCount > 10 or DistinctLocations > 2
Windows Command – Detecting Rogue Device Registration (Token Persistence):
List all Entra ID registered devices for a user (requires AzureAD module)
Get-AzureADDevice -All $true |
Where-Object {$_.ApproximateLastLogonTimestamp -gt (Get-Date).AddDays(-7)} |
Select-Object DisplayName, DeviceId, TrustType, ApproximateLastLogonTimestamp
Check for devices registered from unexpected locations or with unusual names
Get-AzureADDevice -All $true |
Where-Object {$<em>.DisplayName -match "^(DESKTOP|PC|LAPTOP|WINDOWS)" -and
$</em>.TrustType -eq "Workplace"} |
Format-Table DisplayName, DeviceId, TrustType
Linux (using Azure CLI) – Enumerate Entra ID Devices:
List all devices with their registration timestamps
az ad device list --query "[].{displayName:displayName, deviceId:deviceId, createdDateTime:createdDateTime, trustType:trustType}" --output table
Identify devices created within last 24 hours
az ad device list --query "[?createdDateTime > '$(date -u -d '24 hours ago' '+%Y-%m-%dT%H:%M:%SZ')']" --output table
3. Building Detections Resilient to EDR Evasion Techniques
Modern adversaries don’t just execute malware—they actively disable the telemetry that detection engineers rely on. Common evasion techniques include AMSI patching, ETW suppression, direct syscalls (bypassing user-mode hooks), and process hollowing.
Understanding AMSI and ETW Evasion:
- AMSI (Anti-Malware Scan Interface): Scans scripts and in-memory content before execution. Attackers patch AMSI in memory to prevent scanning.
- ETW (Event Tracing for Windows): Provides telemetry to security tools. Attackers disable ETW providers or kill ETW sessions to prevent event logging.
- Direct Syscalls: Bypass user-mode API hooks by invoking kernel syscalls directly, avoiding EDR user-mode detection.
Detection Strategy – Focus on the Evasion Attempt Itself:
Rather than detecting the payload (which may be obfuscated), detect the telemetry tampering:
- Monitor for AMSI patch attempts: Look for memory writes to `amsi.dll` in non-standard contexts or suspicious process memory modifications
- Detect ETW provider disablement: Monitor for `Microsoft-Windows-Kernel-EventTracing` events where providers are being disabled
- Identify direct syscall usage: Processes that bypass standard Windows APIs and invoke syscalls directly are highly suspicious
- Watch for suspicious process creation chains: Attackers often use
rundll32.exe,regsvr32.exe, or `mshta.exe` to execute shellcode
KQL Query for Detecting Evasion Attempts:
// Detect potential AMSI/ETW patching via suspicious process behavior DeviceProcessEvents | where Timestamp > ago(24h) | where ProcessCommandLine contains "amsi" or ProcessCommandLine contains "ETW" or ProcessCommandLine contains "syscall" | project Timestamp, DeviceName, AccountName, ProcessName, ProcessCommandLine, InitiatingProcessFileName // Detect processes making direct syscalls (bypassing user-mode hooks) DeviceEvents | where Timestamp > ago(24h) | where ActionType == "Syscall" // Requires EDR with syscall telemetry | summarize SyscallCount = count() by DeviceName, AccountName, ProcessName | where SyscallCount > 100 | project DeviceName, AccountName, ProcessName, SyscallCount
Windows PowerShell – Detect AMSI Patching Attempts:
Monitor for AMSI patch attempts using Event Tracing
Requires administrative privileges and ETW consumer
Query Security Event Log for suspicious AMSI-related events
Get-WinEvent -LogName "Microsoft-Windows-AMSI/Operational" |
Where-Object {$_.Id -in 4001, 4002, 4003} | AMSI scan events
Select-Object TimeCreated, Id, Message |
Format-Table -AutoSize
Check for memory modification of AMSI in suspicious processes
Get-Process | Where-Object {$<em>.Modules.ModuleName -contains "amsi.dll"} |
Select-Object Name, Id, @{N="AMSI_Loaded";E={$</em>.Modules | Where-Object {$_.ModuleName -eq "amsi.dll"}}}
Linux – Detect Telemetry Tampering (Auditd Rules):
Add audit rule to monitor modifications to critical security libraries sudo auditctl -w /usr/lib/libc.so.6 -p wa -k libc_modification sudo auditctl -w /etc/ld.so.preload -p wa -k preload_modification Monitor for suspicious ptrace usage (often used for process injection) sudo auditctl -a always,exit -S ptrace -k process_injection Check audit logs for tampering attempts sudo ausearch -k libc_modification --format text sudo ausearch -k process_injection --format text
- Cloud Identity Detection: Entra ID and Token Protection
Identity-based attacks represent the most significant threat to modern enterprises. Attackers compromise credentials, steal tokens, and abuse OAuth applications to maintain persistence. Microsoft Entra ID provides linkable identifiers—session IDs and unique token identifiers—that enable advanced threat hunting across identity and workload logs.
Key Detection Scenarios:
- Token Replay Detection: Correlate Unique Token Identifiers (UTIs) from Entra ID sign-in logs with Exchange Online audit logs or Graph activity logs to trace token usage across services.
-
Rogue Device Registration: Attackers use tools like ROADtools to register devices with Entra ID via legitimate APIs, replay stolen tokens, and manipulate token lifecycles.
-
OAuth App Abuse: Malicious OAuth applications with excessive permissions (e.g., Mail.Read, Files.ReadWrite) that persist after user sessions end.
KQL Query – Token Replay Detection Across Services:
// Correlate sign-in events with Exchange activity using linkable identifiers SigninLogs | where TimeGenerated > ago(1h) | where ResourceDisplayName == "Microsoft Exchange" | project UserPrincipalName, CorrelationId, IPAddress, Location, AuthenticationRequirement | join kind=inner ( AuditLogs | where TimeGenerated > ago(1h) | where OperationName == "MailboxLogin" | extend UserPrincipalName = tostring(InitiatedBy.user.userPrincipalName) | project UserPrincipalName, OperationName, ClientIPAddress, ClientInfoString ) on UserPrincipalName | where IPAddress != ClientIPAddress | project UserPrincipalName, SigninIP = IPAddress, SigninLocation = Location, ExchangeIP = ClientIPAddress, ExchangeClient = ClientInfoString
Detection of Rogue Device Registration (KQL):
// Detect suspicious device registration events
AuditLogs
| where TimeGenerated > ago(7d)
| where OperationName == "Add device"
| extend DeviceName = tostring(TargetResources[bash].displayName)
| extend DeviceId = tostring(TargetResources[bash].id)
| extend DeviceOSType = tostring(TargetResources[bash].modifiedProperties[?(@.displayName == 'deviceOSType')].newValue)
| extend InitiatedByUser = tostring(InitiatedBy.user.userPrincipalName)
| project TimeGenerated, InitiatedByUser, DeviceName, DeviceId, DeviceOSType,
IPAddress = tostring(InitiatedBy.user.ipAddress)
// Flag devices with unusual OS types or from unexpected IPs
| where DeviceOSType !in ("Windows", "iOS", "Android", "macOS")
Azure CLI – Audit OAuth Applications and Permissions:
List all enterprise applications with their permissions
az ad app list --all --query "[].{appId:appId, displayName:displayName, requiredResourceAccess:requiredResourceAccess}" --output table
Identify applications with high-risk permissions
az ad app list --all --query "[?contains(requiredResourceAccess[].resourceAccess[].id, 'Mail.Read') || contains(requiredResourceAccess[].resourceAccess[].id, 'Files.ReadWrite')].displayName" --output tsv
Check for service principals with admin consent granted
az ad sp list --all --query "[?servicePrincipalType == 'Application' && appRoleAssignmentRequired == null].{displayName:displayName, appId:appId}" --output table
5. Cross-Platform Detection Logic and Vendor-Agnostic Design
One of the most valuable principles in modern detection engineering is vendor-agnostic design—writing detection logic that works across SIEMs, XDRs, and cloud platforms. This approach ensures your detection program survives tool migrations and maintains consistency across hybrid environments.
Core Principles:
- Focus on telemetry fields, not tool-specific schemas: Write detections that reference common fields (e.g.,
process.name,user.name,source.ip) rather than vendor-specific field names. -
Use Sigma as a translation layer: Sigma rules can be converted to Splunk, Elastic, QRadar, and other platforms.
-
Build detection logic around behavioral patterns: A detection for “process making outbound connections with low URI diversity” works whether you’re using Sysmon, EDR telemetry, or web proxy logs.
Example – Vendor-Agnostic Detection for C2 Beaconing:
Sigma rule for detecting potential C2 beaconing via low URI diversity title: Potential C2 Beaconing - Low URI Diversity status: experimental description: Detects internal hosts communicating with external domains using only 1-2 unique URIs logsource: category: proxy product: web detection: selection: c-uri|count: - "<=2" c-ip: - "!internal_ips" condition: selection falsepositives: - Legitimate API calls with limited endpoints - Health checks or status pings level: medium
KQL to Sigma Translation Example – Token Anomaly Detection:
// Original KQL for Entra ID token anomaly SigninLogs | where TimeGenerated > ago(1h) | summarize DistinctIPs = dcount(IPAddress) by UserPrincipalName | where DistinctIPs > 3
Translated Sigma (pseudocode for cross-platform):
title: Multiple Authentication IPs - Same User logsource: product: cloud service: authentication detection: selection: timeframe: 1h user: "" source_ip|count: ">3" condition: selection
6. Practical Lab Exercises and Realistic Testing
The most effective way to build detection engineering skills is through hands-on practice in realistic environments that simulate full attack chains under EDR evasion conditions. Effective labs should include:
- Full attack chain emulation using C2 frameworks like Cobalt Strike, Nighthawk, or Sliver
- Telemetry reduction scenarios where AMSI and ETW are patched to test detection resilience
- Real false positives that mirror production environment noise
- Visibility gap analysis—understanding what cannot be detected and building compensating controls
Sample Lab Exercise – Detecting Cobalt Strike Beaconing:
Scenario: A compromised workstation is beaconing to an external C2 server with low URI diversity and periodic sleep intervals.
Detection Approach:
1. Collect web proxy logs for the timeframe
- Identify internal hosts communicating with low-prevalence domains or IPs
- Count unique URIs per destination—Cobalt Strike beacons typically use only 1-2 URIs
- Correlate with process creation—which process initiated the connections?
KQL Detection Query:
// Detect potential Cobalt Strike beaconing via proxy logs
DeviceNetworkEvents
| where Timestamp > ago(24h)
| where RemoteIP !in (InternalIPRange) // Filter internal IPs
| extend Destination = strcat(RemoteIP, ":", RemotePort)
| summarize UniqueURIs = dcount(RemoteUrl),
ConnectionCount = count(),
FirstSeen = min(Timestamp),
LastSeen = max(Timestamp)
by DeviceName, Destination, InitiatingProcessFileName
| where UniqueURIs <= 2 and ConnectionCount > 10
| extend BeaconInterval = datetime_diff('second', LastSeen, FirstSeen) / ConnectionCount
| project DeviceName, Destination, InitiatingProcessFileName, UniqueURIs, ConnectionCount, BeaconInterval
| where BeaconInterval between (30 .. 300) // Typical beacon intervals 30s-5min
Linux Detection Using Zeek/Bro Logs:
Analyze Zeek HTTP logs for low URI diversity per destination
cat http.log | \
jq -r 'select(.id.resp_h != "10.0.0.0/8" and .id.resp_h != "172.16.0.0/12" and .id.resp_h != "192.168.0.0/16") |
[.id.resp_h, .uri] | @csv' | \
sort | uniq -c | \
awk -F, '{print $1, $2}' | \
sort -k1,1nr | \
head -20
Detect periodic beaconing patterns using Zeek connection logs
cat conn.log | \
jq -r 'select(.id.resp_h != "internal") | [.id.orig_h, .id.resp_h, .duration] | @csv' | \
awk -F, '{sum[$1","$2]+=$3; count[$1","$2]++} END {for(i in sum) print i","sum[bash]/count[bash]}' | \
sort -t, -k3,3nr
What Undercode Say:
- Detection engineering must shift from indicator-based to behavior-based logic—attackers change tools constantly, but their operational patterns remain consistent. Building detections around anomalies in behavior rather than specific tool signatures ensures long-term resilience.
-
Red team validation is essential—claiming detection effectiveness is meaningless until tested against offensive practitioners who actively try to bypass them. The most robust detections are those validated by both defensive engineers and red teamers.
-
Telemetry visibility is the foundation—you cannot detect what you cannot see. Understanding where visibility gaps exist (e.g., AMSI/ETW patching disabling telemetry) and building compensating detections is critical for mature programs.
-
Vendor-agnostic design ensures longevity—detection logic tied to specific platforms becomes obsolete when tools change. Writing detections around common telemetry fields and behavioral patterns future-proofs your detection program.
-
Hands-on practice under realistic conditions is non-1egotiable—theory alone doesn’t build detection engineering capability. Labs that simulate full attack chains with telemetry reduction and false positives are essential for developing operational expertise.
Prediction:
-
+1 Detection engineering will evolve toward autonomous detection generation—AI-assisted tools that analyze adversary TTPs and automatically generate behavioral detection logic across multiple platforms, significantly reducing manual rule-writing overhead.
-
+1 The demand for vendor-agnostic detection engineers will surge as organizations adopt multi-cloud and multi-SIEM architectures. Professionals who can write detection logic transferable across platforms will command premium compensation.
-
-1 Adversary-in-the-middle phishing attacks will continue to bypass MFA at scale as PhaaS platforms like Tycoon 2FA evolve with better evasion and anti-detection capabilities. Organizations relying solely on MFA without behavioral detection will face increasing compromise rates.
-
-1 Telemetry tampering techniques (AMSI/ETW patching, direct syscalls) will become commoditized in offensive frameworks, making it significantly harder for EDRs to rely on user-mode telemetry. Detection engineers must shift to kernel-level and network-based telemetry sources.
-
+1 Continuous Access Evaluation (CAE) and token protection features in Entra ID will become standard defensive controls, enabling real-time token revocation and reducing the window of opportunity for token replay attacks.
-
-1 The skill gap in advanced detection engineering will widen as attack techniques grow more sophisticated, leaving many organizations unable to build or maintain effective detection programs internally.
-
+1 Community-driven detection libraries (Sigma, KQL repositories, detection-as-code) will mature into essential resources, enabling smaller teams to adopt advanced detection logic without building everything from scratch.
▶️ Related Video (82% Match):
https://www.youtube.com/watch?v=-nQc8rKR43A
🎯Let’s Practice For Free:
🎓 Live Courses & Certifications:
Join Undercode Academy for Verified Certifications
🚀 Request a Custom Project:
Secure, high-velocity infrastructure and disruptive technological engineering. Contact our engineering team for high-tier development and proprietary systems:
[email protected]
💎 Smart Architecture | 🛡️ Secure by Design | ⭐ Trusted by Thousands
IT/Security Reporter URL:
Reported By: Mehmetergene Threathunting – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


