KQL Threat Hunting Cheat Sheet for Sentinel and Defender

Download: the cheat sheet as a Markdown file for your wiki or repo: kql-threat-hunting-cheat-sheet.md

How to use this cheat sheet

Every query below runs in Microsoft Sentinel or the Microsoft Defender XDR advanced hunting console (table names tell you which). Each one is written to be pasted, run, then narrowed: change the time window, add an account or device filter, and turn the ones that earn their keep into analytics rules. Thresholds are starting points for a small estate; tune them against your own baseline before alerting on them.

Conventions: ago(7d) for hunting, ago(1h) for near-real-time rules; summarize before where on aggregates; project last to keep results readable.

1. Identity: sign-ins and Entra ID (SigninLogs, AuditLogs)

Failed sign-ins by account, spot spraying and brute force

SigninLogs
| where TimeGenerated > ago(24h) and ResultType != 0
| summarize Failures = count(), Apps = dcount(AppDisplayName), IPs = dcount(IPAddress) by UserPrincipalName
| where Failures > 20 or IPs > 5
| order by Failures desc

Password spray signature: many accounts, few IPs, same error

SigninLogs
| where TimeGenerated > ago(6h) and ResultType in (50126, 50053, 50055, 50057)
| summarize Accounts = dcount(UserPrincipalName), Attempts = count() by IPAddress, bin(TimeGenerated, 1h)
| where Accounts > 15

Successful sign-in after a run of failures (possible compromise)

let failed = SigninLogs
| where TimeGenerated > ago(24h) and ResultType != 0
| summarize Failures = count(), LastFail = max(TimeGenerated) by UserPrincipalName, IPAddress
| where Failures >= 10;
SigninLogs
| where TimeGenerated > ago(24h) and ResultType == 0
| join kind=inner failed on UserPrincipalName, IPAddress
| where TimeGenerated > LastFail
| project TimeGenerated, UserPrincipalName, IPAddress, Failures, AppDisplayName, Location

Impossible travel: two countries within an hour

SigninLogs
| where TimeGenerated > ago(24h) and ResultType == 0
| extend Country = tostring(LocationDetails.countryOrRegion)
| summarize Countries = make_set(Country), n = dcount(Country) by UserPrincipalName, bin(TimeGenerated, 1h)
| where n > 1

Sign-ins without MFA to privileged roles (legacy auth or excluded policies)

SigninLogs
| where TimeGenerated > ago(7d) and ResultType == 0
| where AuthenticationRequirement == "singleFactorAuthentication"
| join kind=inner (IdentityInfo | where AssignedRoles has_any ("Global Administrator", "Privileged Role Administrator", "Security Administrator")
    | distinct AccountUPN) on $left.UserPrincipalName == $right.AccountUPN
| project TimeGenerated, UserPrincipalName, AppDisplayName, ClientAppUsed, IPAddress

Legacy authentication still in use

SigninLogs
| where TimeGenerated > ago(7d)
| where ClientAppUsed in ("Exchange ActiveSync", "IMAP4", "POP3", "SMTP", "Other clients", "Authenticated SMTP")
| summarize count() by UserPrincipalName, ClientAppUsed, AppDisplayName

New OAuth consent grants (consent phishing)

AuditLogs
| where TimeGenerated > ago(7d) and OperationName in ("Consent to application", "Add app role assignment grant to user")
| extend App = tostring(TargetResources[0].displayName), Actor = tostring(InitiatedBy.user.userPrincipalName)
| project TimeGenerated, Actor, App, OperationName, Result

Privileged role assignments and MFA method changes

AuditLogs
| where TimeGenerated > ago(7d)
| where OperationName in ("Add member to role", "Add eligible member to role", "User registered security info", "User deleted security info", "Update user")
| extend Actor = tostring(InitiatedBy.user.userPrincipalName), Target = tostring(TargetResources[0].userPrincipalName)
| project TimeGenerated, OperationName, Actor, Target, Result

Inbox rules that forward or delete (business email compromise)

OfficeActivity
| where TimeGenerated > ago(7d)
| where Operation in ("New-InboxRule", "Set-InboxRule", "UpdateInboxRules")
| extend P = parse_json(Parameters)
| where tostring(P) has_any ("ForwardTo", "ForwardAsAttachmentTo", "RedirectTo", "DeleteMessage")
| project TimeGenerated, UserId, Operation, ClientIP, Parameters

2. Endpoint: processes and persistence (DeviceProcessEvents, DeviceRegistryEvents)

Encoded or hidden PowerShell

DeviceProcessEvents
| where Timestamp > ago(7d) and FileName in~ ("powershell.exe", "pwsh.exe")
| where ProcessCommandLine has_any ("-enc", "-EncodedCommand", "-e ", "-w hidden", "-nop", "bypass", "IEX", "Invoke-Expression", "DownloadString", "FromBase64String")
| project Timestamp, DeviceName, AccountName, InitiatingProcessFileName, ProcessCommandLine

Office applications spawning shells or scripting engines

DeviceProcessEvents
| where Timestamp > ago(7d)
| where InitiatingProcessFileName in~ ("winword.exe", "excel.exe", "powerpnt.exe", "outlook.exe", "onenote.exe")
| where FileName in~ ("cmd.exe", "powershell.exe", "pwsh.exe", "wscript.exe", "cscript.exe", "mshta.exe", "rundll32.exe", "regsvr32.exe", "certutil.exe", "bitsadmin.exe")
| project Timestamp, DeviceName, AccountName, InitiatingProcessFileName, FileName, ProcessCommandLine

LOLBins used for download or execution

DeviceProcessEvents
| where Timestamp > ago(7d)
| where (FileName =~ "certutil.exe" and ProcessCommandLine has_any ("urlcache", "-decode", "-encode"))
   or (FileName =~ "mshta.exe" and ProcessCommandLine has_any ("http", "javascript", "vbscript"))
   or (FileName =~ "rundll32.exe" and ProcessCommandLine has_any ("javascript:", "url.dll", "shell32.dll,Control_RunDLL"))
   or (FileName =~ "regsvr32.exe" and ProcessCommandLine has_any ("/i:http", "scrobj.dll"))
   or (FileName =~ "bitsadmin.exe" and ProcessCommandLine has "transfer")
| project Timestamp, DeviceName, AccountName, FileName, ProcessCommandLine, InitiatingProcessFileName

Rare parent-child process pairs (baseline first, then alert on new pairs)

DeviceProcessEvents
| where Timestamp > ago(30d)
| summarize Count = count(), FirstSeen = min(Timestamp), Devices = dcount(DeviceId) by InitiatingProcessFileName, FileName
| where Count < 5 and FirstSeen > ago(7d)
| order by FirstSeen desc

New scheduled tasks and services

DeviceProcessEvents
| where Timestamp > ago(7d)
| where (FileName =~ "schtasks.exe" and ProcessCommandLine has "/create")
   or (FileName =~ "sc.exe" and ProcessCommandLine has "create")
| project Timestamp, DeviceName, AccountName, ProcessCommandLine, InitiatingProcessFileName

Run-key and startup persistence

DeviceRegistryEvents
| where Timestamp > ago(7d) and ActionType in ("RegistryValueSet", "RegistryKeyCreated")
| where RegistryKey has_any (@"\CurrentVersion\Run", @"\CurrentVersion\RunOnce", @"\Winlogon\Shell", @"\Winlogon\Userinit", @"\Image File Execution Options")
| project Timestamp, DeviceName, InitiatingProcessAccountName, InitiatingProcessFileName, RegistryKey, RegistryValueName, RegistryValueData

Credential dumping indicators: LSASS access

DeviceEvents
| where Timestamp > ago(7d) and ActionType == "OpenProcessApiCall"
| where FileName =~ "lsass.exe"
| where InitiatingProcessFileName !in~ ("MsMpEng.exe", "csrss.exe", "wininit.exe", "services.exe", "lsass.exe", "svchost.exe", "MsSense.exe", "SenseIR.exe")
| summarize count(), make_set(InitiatingProcessCommandLine, 5) by DeviceName, InitiatingProcessFileName, InitiatingProcessAccountName

Shadow copy deletion and recovery tampering (ransomware precursors)

DeviceProcessEvents
| where Timestamp > ago(7d)
| where ProcessCommandLine has_any ("vssadmin delete shadows", "wmic shadowcopy delete", "bcdedit /set {default} recoveryenabled no", "wbadmin delete catalog", "Get-WmiObject Win32_Shadowcopy")
| project Timestamp, DeviceName, AccountName, ProcessCommandLine, InitiatingProcessFileName

3. Network: beacons, DNS and exfiltration (DeviceNetworkEvents, DnsEvents, CommonSecurityLog)

Beaconing: regular intervals to the same destination

DeviceNetworkEvents
| where Timestamp > ago(24h) and RemoteIPType == "Public" and ActionType == "ConnectionSuccess"
| summarize Times = make_list(Timestamp) by DeviceName, RemoteIP, RemotePort, InitiatingProcessFileName
| where array_length(Times) > 20
| extend Sorted = array_sort_asc(Times)
| mv-apply s = Sorted to typeof(datetime) on ( summarize Intervals = make_list(datetime_diff("second", s, prev(s))) )
| extend Intervals = array_slice(Intervals, 1, -1)
| project DeviceName, RemoteIP, RemotePort, InitiatingProcessFileName, Connections = array_length(Times), Intervals

Eyeball Intervals for near-constant gaps, or use the stricter series_stats version, which flags destinations hit at a steady rate with low variance:

DeviceNetworkEvents
| where Timestamp > ago(24h) and RemoteIPType == "Public"
| make-series Hits = count() on Timestamp from ago(24h) to now() step 5m by DeviceName, RemoteIP
| extend (min_, min_idx, max_, max_idx, avg_, var_, stdev_) = series_stats(Hits)
| where avg_ > 0.5 and stdev_ < 0.6
| project DeviceName, RemoteIP, avg_, stdev_

Processes that should not talk to the internet

DeviceNetworkEvents
| where Timestamp > ago(7d) and RemoteIPType == "Public"
| where InitiatingProcessFileName in~ ("mshta.exe", "regsvr32.exe", "rundll32.exe", "certutil.exe", "wscript.exe", "cscript.exe", "notepad.exe", "calc.exe", "wmic.exe")
| project Timestamp, DeviceName, InitiatingProcessFileName, InitiatingProcessCommandLine, RemoteUrl, RemoteIP, RemotePort

Long or high-entropy DNS names (tunnelling and DGA)

DnsEvents
| where TimeGenerated > ago(24h)
| extend Sub = tostring(split(Name, ".")[0])
| where strlen(Name) > 50 or strlen(Sub) > 30
| summarize Queries = count(), Names = dcount(Name) by ClientIP, Domain = strcat_array(array_slice(split(Name, "."), -2, -1), ".")
| where Names > 50

Newly seen destination domains for the estate

let known = DeviceNetworkEvents | where Timestamp between (ago(30d) .. ago(1d)) | distinct RemoteUrl;
DeviceNetworkEvents
| where Timestamp > ago(1d) and isnotempty(RemoteUrl)
| join kind=leftanti known on RemoteUrl
| summarize Devices = dcount(DeviceName), First = min(Timestamp) by RemoteUrl, InitiatingProcessFileName
| order by Devices desc

Large outbound transfers per device (exfiltration)

CommonSecurityLog
| where TimeGenerated > ago(24h) and isnotempty(SentBytes)
| summarize OutMB = sum(SentBytes) / 1048576.0 by SourceIP, DestinationIP, DestinationPort
| where OutMB > 500
| order by OutMB desc

4. Windows security events (SecurityEvent)

Kerberoasting: TGS requests with RC4 for service accounts

SecurityEvent
| where TimeGenerated > ago(24h) and EventID == 4769
| where TicketEncryptionType == "0x17" and ServiceName !endswith "
 
quot; and ServiceName != "krbtgt" | summarize Services = dcount(ServiceName), Requests = count() by TargetUserName, IpAddress, bin(TimeGenerated, 10m) | where Services > 5

New local admin or group membership changes

SecurityEvent
| where TimeGenerated > ago(7d) and EventID in (4728, 4732, 4756)
| project TimeGenerated, Computer, SubjectAccount, MemberName, TargetAccount = TargetUserName, EventID

Account created then deleted within an hour

let created = SecurityEvent | where TimeGenerated > ago(7d) and EventID == 4720 | project Created = TimeGenerated, TargetUserName, Computer;
SecurityEvent
| where TimeGenerated > ago(7d) and EventID == 4726
| join kind=inner created on TargetUserName, Computer
| where TimeGenerated - Created < 1h
| project Created, Deleted = TimeGenerated, TargetUserName, Computer, SubjectAccount

Security log cleared

SecurityEvent
| where TimeGenerated > ago(30d) and EventID in (1102, 1100)
| project TimeGenerated, Computer, SubjectAccount, Activity

Explicit credential logons (runas, pass-the-hash patterns)

SecurityEvent
| where TimeGenerated > ago(24h) and EventID == 4648
| where TargetUserName !endswith "
 
quot; and SubjectUserName !endswith "
 
quot; | summarize Targets = dcount(TargetUserName), Hosts = dcount(TargetServerName) by SubjectUserName, Computer, bin(TimeGenerated, 1h) | where Targets > 5 or Hosts > 5

5. Coverage and hygiene

Which devices stopped reporting

DeviceInfo
| summarize Last = max(Timestamp) by DeviceName
| where Last < ago(3d)
| order by Last asc

Log sources gone quiet (ingestion gaps)

Usage
| where TimeGenerated > ago(7d)
| summarize LastSeen = max(TimeGenerated), GB = sum(Quantity) / 1024 by DataType
| where LastSeen < ago(12h)

Analytics rules that never fire (candidates for review)

SecurityAlert
| where TimeGenerated > ago(90d)
| summarize Alerts = count() by AlertName
| order by Alerts asc

Turning a query into a rule

  1. Run it over 30 days; note the volume and the top false positives.
  2. Add an exclusion table (a watchlist) rather than hard-coding exceptions.
  3. Set the rule frequency equal to the lookback (5 minutes / 5 minutes for near-real-time; 1 hour / 1 hour for most).
  4. Map it to MITRE ATT&CK in the rule (it feeds your coverage heatmap).
  5. Write the response step in the rule description: what the analyst does first.

Related guides: KQL threat hunting with Microsoft Sentinel, Detecting Kerberos and NTLM abuse, Measuring detection coverage with DeTT&CT.

Frequently asked questions

Do these queries work in both Microsoft Sentinel and Defender XDR advanced hunting?

Queries on Device* tables (DeviceProcessEvents, DeviceNetworkEvents, DeviceRegistryEvents, DeviceEvents, DeviceInfo) run in Defender XDR advanced hunting and in Sentinel if the Defender connector is enabled. SigninLogs, AuditLogs, SecurityEvent, OfficeActivity, DnsEvents, CommonSecurityLog and Usage are Sentinel tables.

Why do the thresholds look low?

They are tuned for a small estate (tens to a few hundred devices). Run each query over 30 days, look at the distribution, and set the threshold above your normal peak.

Can I use these as analytics rules straight away?

Use them for hunting first. Once you know the false-positive sources, add a watchlist for exclusions and create a scheduled rule with a frequency equal to the lookback window.

Is there a downloadable version?

Yes: a Markdown file with every query, suitable for a team wiki or Git repository, linked at the top of this page. It is free and needs no sign-up.

Free to use and share with attribution to ClearPath Security. No sign-up. If you want help applying it, talk to us.