Free Cheatsheet

KQL Query Reference

Detection queries for Microsoft Sentinel and Defender XDR, grouped by ATT&CK tactic, then the operators they are built from, each with a working security query. Copy, adapt, run. No account needed.

Part of the M365 & Entra ID Detection Reference This guide is one part of Ridgeline's unified M365 detection reference. See the full technique coverage map and the other guides in the set.

Part one is 92 detections for Microsoft Sentinel and Defender XDR advanced hunting, across identity, Microsoft 365, endpoint, Active Directory, Azure, AWS and DNS, grouped by ATT&CK 19 tactic and each tagged with its table, technique and confidence. Part two is the language they are built from: every string operator, the scalar and aggregation functions, joins, time series, outside data, performance and limits. Every query filters on its own table's time column. Set your own windows, ranges and thresholds before alerting on any of them.

Initial Access 7

Initial access is where the intrusion crosses your perimeter. On the endpoint the signal is a delivery container landing on disk; in the identity plane it is a successful sign-in that should not have happened.

Disk image files written to disk DeviceFileEventsT1566.001Medium

ISO, IMG and VHD files are delivery containers: opening one mounts it as a drive, and the files inside can skip the downloaded-from-the-internet mark that triggers warnings.

DeviceFileEvents | where Timestamp > ago(7d) | where ActionType == "FileCreated" | where FileName matches regex @"(?i)\.(iso|img|vhdx?)$" | project Timestamp, DeviceName, InitiatingProcessAccountName, FileName, FolderPath, InitiatingProcessFileName
Successful sign-ins from several countries in a day SigninLogsT1078.004Medium

Two countries in a day is travel, a VPN or a stolen credential. Read the apps and addresses together before deciding which.

SigninLogs | where TimeGenerated > ago(1d) | where ResultType == "0" | summarize Countries = make_set(Location), CountryCount = dcount(Location), IPs = make_set(IPAddress) by UserPrincipalName | where CountryCount > 1
Legacy authentication that succeeded SigninLogsT1078.004High

Legacy protocols cannot carry MFA, so a successful IMAP, POP or SMTP sign-in is a password alone working. If your Conditional Access blocks legacy authentication, any row here is a gap in that policy.

SigninLogs | where TimeGenerated > ago(7d) | where ResultType == "0" | where ClientAppUsed in ("Exchange ActiveSync", "IMAP4", "POP3", "Authenticated SMTP", "Other clients") | summarize SignIns = count(), IPs = make_set(IPAddress, 20) by UserPrincipalName, ClientAppUsed
Risky sign-in that succeeded anyway SigninLogsT1078.004High

Identity Protection scored the sign-in as risky and it still worked. Read ConditionalAccessStatus: notApplied means no policy acted on the risk at all.

SigninLogs | where TimeGenerated > ago(7d) | where ResultType == "0" | where RiskLevelDuringSignIn in ("medium", "high") | project TimeGenerated, UserPrincipalName, IPAddress, Location, RiskLevelDuringSignIn, RiskEventTypes_V2, ConditionalAccessStatus
Phishing link clicked through a warning UrlClickEventsT1566.002High

IsClickedThrough marks a user who reached the original URL. Contain these accounts first, then check what the URL served.

UrlClickEvents | where Timestamp > ago(7d) | where IsClickedThrough == true | project Timestamp, AccountUpn, Url, ActionType, ThreatTypes, IPAddress
Delivered mail carrying a disk image or script EmailAttachmentInfoEmailEventsT1566.001Medium

Disk images and script files are common containers for initial payloads because they are less often inspected than Office documents. Pivot the hash into the endpoint tables next.

EmailAttachmentInfo | where Timestamp > ago(7d) | where FileName matches regex @"(?i)\.(iso|img|vhdx?|js|vbs|hta|lnk)$" | join kind=inner (EmailEvents | where Timestamp > ago(7d) | where DeliveryAction == "Delivered" | project NetworkMessageId, Subject, DeliveryLocation) on NetworkMessageId | project Timestamp, RecipientEmailAddress, SenderFromAddress, FileName, Subject, DeliveryLocation
AWS root account console sign-in AWSCloudTrailT1078.004High

The root user should be used for a handful of account tasks and nothing else. Any console sign-in deserves a reason, and one without MFA deserves an incident.

AWSCloudTrail | where TimeGenerated > ago(30d) | where EventName == "ConsoleLogin" and UserIdentityType == "Root" | project TimeGenerated, SourceIpAddress, UserAgent, ErrorMessage, SessionMfaAuthenticated, RecipientAccountId
Tuning: Travel and multi-country sign-ins are noisy behind VPNs, cloud egress and mobile roaming. Baseline a week of your own sign-ins before alerting, and exclude your egress ranges by address, not by account.

Execution 6

Execution through tools that already sit on every host. powershell.exe, wmiprvse.exe and the Office applications are all legitimate, so read the command line and the parent process, which is where the intent shows.

Office application starting a script interpreter DeviceProcessEventsT1204.002Medium

Documents with macros or exploits start their payload this way. Word starting PowerShell is rarely legitimate.

DeviceProcessEvents | where Timestamp > ago(7d) | where InitiatingProcessFileName in~ ("winword.exe", "excel.exe", "powerpnt.exe", "outlook.exe") | where FileName in~ ("powershell.exe", "cmd.exe", "wscript.exe", "cscript.exe", "mshta.exe", "rundll32.exe") | summarize Count = count() by DeviceName, AccountName, InitiatingProcessFileName, FileName | order by Count desc
PowerShell with suspicious flags DeviceProcessEventsT1059.001Medium

Hidden windows, no profile, encoded commands and download functions are the flags attackers reach for. Each is used legitimately too, so read the whole command line.

DeviceProcessEvents | where Timestamp > ago(7d) | where FileName in~ ("powershell.exe", "pwsh.exe") | where ProcessCommandLine has_any ("-nop", "-noni", "-w hidden", "-enc", "-EncodedCommand", "bypass", "iex", "invoke-expression", "downloadstring", "Net.WebClient") | project Timestamp, DeviceName, AccountName, ProcessCommandLine, InitiatingProcessFileName
Processes started by WMI DeviceProcessEventsT1047Medium

WmiPrvSE.exe is the parent of anything started through WMI, locally or remotely. Rare children are the ones to read.

DeviceProcessEvents | where Timestamp > ago(7d) | where InitiatingProcessFileName =~ "wmiprvse.exe" | where FileName !in~ ("csc.exe", "mofcomp.exe") | summarize Count = count() by DeviceName, FileName, ProcessCommandLine | where Count < 5
Command run on an Azure virtual machine AzureActivityT1651Medium

Run Command executes a script as SYSTEM or root on the machine through the Azure control plane, with no network path to the host needed. The caller is the account to investigate.

AzureActivity | where TimeGenerated > ago(7d) | where OperationNameValue =~ "MICROSOFT.COMPUTE/VIRTUALMACHINES/RUNCOMMAND/ACTION" | project TimeGenerated, Caller, CallerIpAddress, ResourceGroup, _ResourceId, ActivityStatusValue
Service created to run a script interpreter DeviceRegistryEventsT1569.002High

A service whose ImagePath is a shell or script host is how remote execution tools and many intrusions run code as SYSTEM. Legitimate services point at their own binary.

DeviceRegistryEvents | where Timestamp > ago(7d) | where RegistryKey has @"\Services\" and RegistryValueName == "ImagePath" | where RegistryValueData has_any ("powershell", "cmd.exe /c", "cmd /c", "mshta", "rundll32") | project Timestamp, DeviceName, InitiatingProcessAccountName, RegistryKey, RegistryValueData, InitiatingProcessFileName
Service created on another host with sc.exe DeviceProcessEventsT1569.002Medium

sc \\host create builds a service on a remote machine: lateral movement without a third-party tool. Pair it with a logon to that host from this device.

DeviceProcessEvents | where Timestamp > ago(7d) | where FileName =~ "sc.exe" | where ProcessCommandLine matches regex @"(?i)\\\\[^\s]+\s+create" | project Timestamp, DeviceName, AccountName, ProcessCommandLine
Tuning: Command-line matching is medium confidence by nature, because administrators use the same flags. An Office application starting a script interpreter is the strongest of these four in most estates.

Persistence 11

Persistence is how an attacker survives a reboot or a password reset, which makes it one of the most valuable things to hunt: a hit often means a foothold you did not know about. Read InitiatingProcessFileName on every one of these.

Scheduled task created by a script host DeviceProcessEventsT1053.005Medium

A task created by a script interpreter rather than an installer or an administrator's console is persistence being set up by a payload.

DeviceProcessEvents | where Timestamp > ago(1d) | where FileName =~ "schtasks.exe" and ProcessCommandLine has "/create" | where InitiatingProcessFileName in~ ("cmd.exe", "powershell.exe", "wscript.exe", "cscript.exe", "mshta.exe") | project Timestamp, DeviceName, AccountName, ProcessCommandLine, InitiatingProcessFileName
Service with a binary in a user-writable path DeviceRegistryEventsT1543.003Medium

Services run as SYSTEM. A service binary in Temp or AppData is a privilege escalation and persistence path in one.

DeviceRegistryEvents | where Timestamp > ago(1d) | where RegistryKey has @"\Services\" and RegistryValueName == "ImagePath" | where RegistryValueData has_any (@"\temp\", @"\tmp\", @"\appdata\", @"\users\public\") | project Timestamp, DeviceName, InitiatingProcessAccountName, RegistryKey, RegistryValueData
Run key written DeviceRegistryEventsT1547.001Medium

Run and RunOnce start a program at logon. Read the value data: the path and the process that wrote it.

DeviceRegistryEvents | where Timestamp > ago(7d) | where RegistryKey has_any (@"CurrentVersion\Run", @"CurrentVersion\RunOnce") | where ActionType in ("RegistryValueSet", "RegistryKeyCreated") | project Timestamp, DeviceName, InitiatingProcessAccountName, RegistryKey, RegistryValueName, RegistryValueData, InitiatingProcessFileName
WMI permanent event subscription DeviceEventsT1546.003High

A filter bound to a consumer runs code when an event fires, with no file in any autostart folder. It is rare enough to treat every hit as high confidence.

DeviceEvents | where Timestamp > ago(1d) | where ActionType == "WmiBindEventFilterToConsumer" | project Timestamp, DeviceName, AccountName, ActionType, InitiatingProcessFileName, AdditionalFields
File dropped in a startup folder DeviceFileEventsT1547.001Medium

Anything in a Startup folder runs at logon. Shortcuts and scripts written there by a browser or script host are the shape to look for.

DeviceFileEvents | where Timestamp > ago(7d) | where FolderPath has @"Start Menu\Programs\Startup" | project Timestamp, DeviceName, InitiatingProcessAccountName, FileName, FolderPath, InitiatingProcessFileName
New secret or certificate on an app or service principal AuditLogsT1098.001High

An added credential lets whoever holds it sign in as the application, with its permissions and without a user. Compare every row with a change you know about.

AuditLogs | where TimeGenerated > ago(7d) | where OperationName has_any ("Add service principal credentials", "Certificates and secrets management") | project TimeGenerated, OperationName, Actor = tostring(InitiatedBy.user.userPrincipalName), App = tostring(TargetResources[0].displayName), Result
Mailbox permission granted to another account OfficeActivityT1098.002Medium

Full Access or Send As on someone else's mailbox survives a password reset of the owner. Executives and finance staff are the mailboxes to watch.

OfficeActivity | where TimeGenerated > ago(7d) | where Operation in ("Add-MailboxPermission", "Add-RecipientPermission", "Set-MailboxFolderPermission") | project TimeGenerated, UserId, Operation, Parameters, ClientIP
Local account created on a device DeviceEventsT1136.001Medium

A new local account is a way back in that domain controls do not see. Outside imaging and provisioning, ask who and why.

DeviceEvents | where Timestamp > ago(7d) | where ActionType == "UserAccountCreated" | project Timestamp, DeviceName, AccountName, InitiatingProcessAccountName, InitiatingProcessFileName
Cloud account created and given a role within a day AuditLogsT1136.003High

An account created and promoted in the same day is the shape of an attacker giving themselves a durable, privileged identity.

let created = AuditLogs | where TimeGenerated > ago(7d) | where OperationName == "Add user" | project Created = TimeGenerated, User = tostring(TargetResources[0].userPrincipalName); AuditLogs | where TimeGenerated > ago(7d) | where OperationName == "Add member to role" | extend User = tostring(TargetResources[0].userPrincipalName) | join kind=inner created on User | where TimeGenerated between (Created .. Created + 1d) | project Created, RoleAdded = TimeGenerated, User, AddedBy = tostring(InitiatedBy.user.userPrincipalName)
Web server process starting a shell DeviceProcessEventsT1505.003High

A web server has no reason to start cmd.exe or whoami.exe. This is the classic signature of a web shell, and it is high confidence.

DeviceProcessEvents | where Timestamp > ago(7d) | where InitiatingProcessFileName in~ ("w3wp.exe", "httpd.exe", "tomcat.exe", "nginx.exe", "php-cgi.exe") | where FileName in~ ("cmd.exe", "powershell.exe", "pwsh.exe", "whoami.exe", "net.exe") | project Timestamp, DeviceName, AccountName, FileName, ProcessCommandLine
AWS access key created for another user AWSCloudTrailT1098.001High

An access key created by one identity for another is a common way to persist with long-lived credentials that the victim user never sees.

AWSCloudTrail | where TimeGenerated > ago(30d) | where EventName == "CreateAccessKey" | extend ForUser = tostring(parse_json(RequestParameters).userName) | where isnotempty(ForUser) and ForUser != UserIdentityUserName | project TimeGenerated, UserIdentityArn, ForUser, SourceIpAddress
Tuning: Run keys and startup folders change constantly as software installs and updates. Persistence written into a user-writable path by powershell.exe or wscript.exe is the shape to look for; a vendor installer writing to Program Files is not.

Privilege Escalation 4

Privilege escalation is the attacker gaining rights they did not have: a seat in a privileged group, a directory or cloud role, or control of a Group Policy object that runs code on every machine it applies to. Each of these changes has an owner in your organization, so every hit needs one answer: was this a change someone asked for?

Member added to Domain Admins, Enterprise Admins or Schema Admins SecurityEventT1098High

Membership in these groups is control of the domain. Every addition should match a change record; additions to Schema Admins almost never should.

SecurityEvent | where TimeGenerated > ago(7d) | where EventID in (4728, 4732, 4756) | where TargetUserName in ("Domain Admins", "Enterprise Admins", "Schema Admins", "Administrators") | project TimeGenerated, Computer, Group = TargetUserName, MemberName, AddedBy = SubjectUserName
Entra role assigned AuditLogsT1098.003High

The role name comes from the change's modified properties. Global Administrator, Privileged Role Administrator and Application Administrator are the assignments to read first.

AuditLogs | where TimeGenerated > ago(7d) | where OperationName in ("Add member to role", "Add eligible member to role") | extend Role = tostring(TargetResources[0].modifiedProperties[1].newValue) | project TimeGenerated, OperationName, Role, User = tostring(TargetResources[0].userPrincipalName), AddedBy = tostring(InitiatedBy.user.userPrincipalName)
Azure role assignment created AzureActivityT1098.003Medium

Owner or User Access Administrator on a subscription is control of everything in it. Read Properties for the role and the scope.

AzureActivity | where TimeGenerated > ago(7d) | where OperationNameValue =~ "MICROSOFT.AUTHORIZATION/ROLEASSIGNMENTS/WRITE" | where ActivityStatusValue in ("Success", "Succeeded") | project TimeGenerated, Caller, CallerIpAddress, _ResourceId, Properties
Group Policy object changed SecurityEventT1484.001Medium

A changed GPO can run code on every machine it applies to. This needs a SACL on the Policies container so 5136 is logged.

SecurityEvent | where TimeGenerated > ago(7d) | where EventID == 5136 | where EventData has "groupPolicyContainer" | project TimeGenerated, Computer, SubjectUserName, ObjectName
Tuning: Role and group changes are high confidence when you compare them with your change records. Privileged Identity Management activations land in the same audit logs as eligible role assignments; separate the two before alerting.

Credential Access 15

Once an attacker holds valid credentials, the rest of the intrusion looks like ordinary sign-ins, so these target the theft itself. The endpoint half watches the dumping tools; the cloud half watches spraying, a new authentication method and an application granted access to mail and files.

LSASS dump through comsvcs.dll MiniDump DeviceProcessEventsT1003.001High

comsvcs.dll exports a MiniDump function that writes a process's memory to disk. Used against lsass.exe, it is credential theft with a built-in Windows DLL.

DeviceProcessEvents | where Timestamp > ago(1d) | where FileName =~ "rundll32.exe" | where ProcessCommandLine has "comsvcs" and ProcessCommandLine has "MiniDump" | project Timestamp, DeviceName, AccountName, FileName, ProcessCommandLine, InitiatingProcessFileName
LSASS dump through ProcDump DeviceProcessEventsT1003.001High

ProcDump is a legitimate Sysinternals tool, and -ma on lsass writes its full memory, credentials included.

DeviceProcessEvents | where Timestamp > ago(1d) | where FileName in~ ("procdump.exe", "procdump64.exe") | where ProcessCommandLine has_any ("lsass", "-ma") | project Timestamp, DeviceName, AccountName, FileName, ProcessCommandLine
SAM, SYSTEM or SECURITY hive saved with reg.exe DeviceProcessEventsT1003.002High

Saving these hives gives an attacker local account hashes and cached secrets to extract offline.

DeviceProcessEvents | where Timestamp > ago(1d) | where FileName =~ "reg.exe" | where ProcessCommandLine has "save" and ProcessCommandLine has_any ("sam", "system", "security") | project Timestamp, DeviceName, AccountName, ProcessCommandLine, InitiatingProcessFileName
Searching files for passwords DeviceProcessEventsT1552.001Medium

Scripts, configuration files and shares often hold credentials. Recursive searches for the word password are someone looking for them.

DeviceProcessEvents | where Timestamp > ago(7d) | where ProcessCommandLine has_any ("findstr /si password", "dir /s *pass*", "dir /s *cred*", "Get-ChildItem -Recurse *password*") | project Timestamp, DeviceName, AccountName, ProcessCommandLine, InitiatingProcessFileName
Kerberoasting tools on the command line DeviceProcessEventsT1558.003High

This catches the tooling by name. The SecurityEvent 4769 query in Credential Access catches the tickets whatever the tool is called.

DeviceProcessEvents | where Timestamp > ago(7d) | where ProcessCommandLine has_any ("Invoke-Kerberoast", "Get-SPNUsers", "kerberoast") | project Timestamp, DeviceName, AccountName, ProcessCommandLine
Security info registered from a new address SigninLogsAuditLogsT1556.006High

An attacker who has a password registers their own MFA method to keep access. Registration from an address the user has never signed in from is the tell.

let Known = SigninLogs | where TimeGenerated between (ago(30d) .. ago(1d)) | where ResultType == "0" | distinct UserPrincipalName, IPAddress; AuditLogs | where TimeGenerated > ago(1d) | where OperationName == "User registered security info" | extend UserPrincipalName = tostring(InitiatedBy.user.userPrincipalName), IPAddress = tostring(InitiatedBy.user.ipAddress) | join kind=leftanti Known on UserPrincipalName, IPAddress | project TimeGenerated, UserPrincipalName, IPAddress, Result
Password spray SigninLogsT1110.003Medium

Error 50126 is a bad username or password. Many accounts failing in the same ten minutes is one source trying a common password everywhere.

SigninLogs | where TimeGenerated > ago(1d) | where ResultType == "50126" // invalid username or password | summarize Failures = count(), Accounts = dcount(UserPrincipalName), SourceIPs = dcount(IPAddress) by bin(TimeGenerated, 10m) | where Failures > 20 and Accounts > 5
Consent granted to an application that reads mail or files AuditLogsT1528High

A consent grant gives an application access that a password reset does not end. Mail and file permissions are what consent phishing asks for.

AuditLogs | where TimeGenerated > ago(7d) | where OperationName == "Consent to application" | extend AppName = tostring(TargetResources[0].displayName), Permissions = tostring(TargetResources[0].modifiedProperties) | where Permissions has_any ("Mail.Read", "Mail.ReadWrite", "Files.ReadWrite.All", "User.ReadWrite.All") | project TimeGenerated, UserPrincipalName = tostring(InitiatedBy.user.userPrincipalName), AppName, Permissions
MFA fatigue: repeated MFA denials, then a success SigninLogsT1621High

Result code 500121 is a failed strong-authentication step. Several in an hour followed by a success is a user approving a prompt to make them stop.

SigninLogs | where TimeGenerated > ago(1d) | summarize Denied = countif(ResultType == "500121"), Succeeded = countif(ResultType == "0") by UserPrincipalName, bin(TimeGenerated, 1h) | where Denied >= 5 and Succeeded > 0
Kerberoasting: RC4 service tickets for many services SecurityEventT1558.003High

Requesting RC4 tickets for user-account services gives an attacker hashes to crack offline. Computer accounts end in $ and are filtered out.

SecurityEvent | where TimeGenerated > ago(1d) | where EventID == 4769 | parse EventData with * 'TicketEncryptionType">' Enc '<' * | parse EventData with * 'ServiceName">' Svc '<' * | where Enc == "0x17" and not(Svc endswith "$") | summarize Services = dcount(Svc) by TargetUserName, IpAddress | where Services >= 5
AS-REP roasting: TGTs without pre-authentication SecurityEventT1558.004High

Pre-authentication type 0 means the ticket was issued without proving the password first, which is what AS-REP roasting needs. Fix the account setting as well as alerting.

SecurityEvent | where TimeGenerated > ago(7d) | where EventID == 4768 | parse EventData with * 'PreAuthType">' PreAuth '<' * | where PreAuth == "0" | summarize Tickets = count() by TargetUserName, IpAddress
DCSync: replication rights used outside a domain controller SecurityEventT1003.006High

These three GUIDs are the replication rights. A user account exercising them is pulling password hashes from a domain controller.

let repl = dynamic([ "1131f6aa-9c07-11d1-f79f-00c04fc2dcd2", "1131f6ad-9c07-11d1-f79f-00c04fc2dcd2", "89e95b76-444d-4c62-991a-0facbeda640c"]); SecurityEvent | where TimeGenerated > ago(7d) | where EventID == 4662 and Properties has_any (repl) | where not(SubjectUserName endswith "$") | project TimeGenerated, Computer, SubjectUserName, SubjectDomainName
NTDS.dit copied with ntdsutil or a shadow copy DeviceProcessEventsT1003.003High

NTDS.dit holds every domain password hash. Copying it out of a shadow copy or with ntdsutil ifm is how attackers take the whole domain offline.

DeviceProcessEvents | where Timestamp > ago(7d) | where (FileName =~ "ntdsutil.exe" and ProcessCommandLine has "ifm") or (ProcessCommandLine has "ntds.dit" and ProcessCommandLine has_any ("copy", "HarddiskVolumeShadowCopy")) | project Timestamp, DeviceName, AccountName, ProcessCommandLine
Password spray seen by Defender for Identity IdentityLogonEventsT1110.003Medium

Defender for Identity sees authentication on the domain controllers, so this catches sprays against on-premises accounts that SigninLogs never sees.

IdentityLogonEvents | where Timestamp > ago(1d) | where ActionType == "LogonFailed" | summarize Accounts = dcount(AccountUpn), Failures = count() by IPAddress, bin(Timestamp, 30m) | where Accounts >= 10
Key Vault secrets read in bulk AzureDiagnosticsT1555.006Medium

Applications read the few secrets they need. One caller reading many distinct secrets in a day is someone harvesting the vault. Needs Key Vault diagnostic logs sent to the workspace.

AzureDiagnostics | where TimeGenerated > ago(1d) | where ResourceProvider == "MICROSOFT.KEYVAULT" | where OperationName == "SecretGet" | summarize Secrets = dcount(id_s), Reads = count() by CallerIPAddress, identity_claim_appid_g, Resource | where Secrets >= 10
Tuning: The LSASS and SAM queries are high confidence and still not free of false positives: some EDR, backup and crash-handling tools read LSASS or save hives. Exclude the known callers by signer or path; do not suppress the rule.

Stealth 6

ATT&CK 19 splits the old Defense Evasion tactic in two. Stealth is the attacker hiding in plain sight: a system binary name in the wrong folder, a path excluded from scanning, a command line encoded so nobody reads it, a signed binary running remote script.

System binary running from the wrong folder DeviceProcessEventsT1036.005High

A file called svchost.exe outside System32 is not svchost. Masquerading as a system process is one of the most reliable signals on the page.

DeviceProcessEvents | where Timestamp > ago(7d) | where FileName in~ ("svchost.exe", "csrss.exe", "lsass.exe", "services.exe") | where not(FolderPath has @"C:\Windows\System32" or FolderPath has @"C:\Windows\SysWOW64") | project Timestamp, DeviceName, FileName, FolderPath, SHA256
Microsoft Defender exclusion added DeviceRegistryEventsT1564.012High

An exclusion is a folder, process or extension Defender will not scan. Attackers add one and drop their tools into it.

DeviceRegistryEvents | where Timestamp > ago(7d) | where RegistryKey has @"Windows Defender\Exclusions" | project Timestamp, DeviceName, InitiatingProcessAccountName, RegistryKey, RegistryValueName, RegistryValueData, InitiatingProcessFileName
Encoded PowerShell from an unusual parent DeviceProcessEventsT1027.010Medium

Encoding hides a command from a casual reader. Baseline which management tools legitimately run encoded commands, then read the rest.

DeviceProcessEvents | where Timestamp > ago(1d) | where FileName in~ ("powershell.exe", "pwsh.exe") | where ProcessCommandLine has_any ("-enc", "-EncodedCommand") | where InitiatingProcessFileName !in~ ("svchost.exe", "services.exe") | project Timestamp, DeviceName, AccountName, ProcessCommandLine, InitiatingProcessFileName
MSHTA running remote or inline script DeviceProcessEventsT1218.005High

mshta.exe runs HTML applications, including script fetched from a URL. Legitimate use is rare in most estates.

DeviceProcessEvents | where Timestamp > ago(7d) | where FileName =~ "mshta.exe" | where ProcessCommandLine has_any ("http://", "https://", "javascript:", "vbscript:") | project Timestamp, DeviceName, AccountName, ProcessCommandLine, InitiatingProcessFileName
Inbox rule that marks mail read and moves it out of sight OfficeActivityT1564.008High

Marking mail read and moving it to RSS, Archive or Conversation History is how business email compromise hides the replies from the real owner.

OfficeActivity | where TimeGenerated > ago(7d) | where Operation in ("New-InboxRule", "Set-InboxRule") | where Parameters has "MarkAsRead" and Parameters has_any ("RSS", "Archive", "Conversation History", "DeleteMessage") | project TimeGenerated, UserId, Parameters, ClientIP
Rundll32 loading a DLL from a user-writable folder DeviceProcessEventsT1218.011Medium

Rundll32 runs exports from any DLL, so a DLL in AppData or Temp run this way is a payload using a signed Windows binary to start.

DeviceProcessEvents | where Timestamp > ago(7d) | where FileName =~ "rundll32.exe" | where ProcessCommandLine has_any (@"\AppData\", @"\Temp\", @"\Users\Public\", @"\ProgramData\") | project Timestamp, DeviceName, AccountName, ProcessCommandLine, InitiatingProcessFileName
Tuning: Masquerading and Defender exclusions are high confidence because legitimate software rarely needs either. Encoded PowerShell is common in management tooling, so baseline the parents that legitimately run it before alerting.

Defense Impairment 7

Defense Impairment is the other half of the old Defense Evasion: the attacker switching off what would see them. AMSI, ETW and the event logs feed every other rule on this page, so a hit here means the rest of the page may already be blind on that host.

AMSI bypass strings on the command line DeviceProcessEventsT1685Medium

AMSI lets security products scan scripts as they run. These strings are the well-known ways to switch it off from inside PowerShell.

DeviceProcessEvents | where Timestamp > ago(1d) | where ProcessCommandLine has_any ("AmsiScanBuffer", "amsiInitFailed", "AmsiUtils", "amsi.dll") | project Timestamp, DeviceName, AccountName, FileName, ProcessCommandLine
ETW trace session stopped or a provider removed DeviceProcessEventsT1685High

Event Tracing for Windows feeds endpoint sensors. Stopping a session or removing a provider blinds them.

DeviceProcessEvents | where Timestamp > ago(1d) | where ProcessCommandLine has_any ("logman stop", "logman delete", "Remove-EtwTraceProvider", "Set-EtwTraceProvider") | project Timestamp, DeviceName, AccountName, ProcessCommandLine
Event log cleared DeviceProcessEventsT1685.005High

Clearing a log removes the record of what came before. On Windows it also produces 1102 or 104, which survive in your SIEM even when the log does not.

DeviceProcessEvents | where Timestamp > ago(7d) | where ProcessCommandLine has_any ("wevtutil cl", "Clear-EventLog", "Remove-EventLog") | project Timestamp, DeviceName, AccountName, ProcessCommandLine
Defender real-time protection turned off with PowerShell DeviceProcessEventsT1685High

Turning off real-time or behavior monitoring is a common step before a payload is dropped. Tamper protection blocks it; a row here may mean it is off.

DeviceProcessEvents | where Timestamp > ago(7d) | where ProcessCommandLine has "Set-MpPreference" | where ProcessCommandLine has_any ("DisableRealtimeMonitoring", "DisableBehaviorMonitoring", "DisableIOAVProtection") | project Timestamp, DeviceName, AccountName, ProcessCommandLine
Audit policy switched off with auditpol DeviceProcessEventsT1685.001High

Clearing or disabling audit subcategories stops the Security log recording what comes next. Expect a 4719 on the host as well.

DeviceProcessEvents | where Timestamp > ago(7d) | where FileName =~ "auditpol.exe" | where ProcessCommandLine has_any ("/clear", "/remove", "success:disable", "failure:disable") | project Timestamp, DeviceName, AccountName, ProcessCommandLine
Azure diagnostic setting deleted AzureActivityT1685.002High

Diagnostic settings are what send resource logs to your workspace. Deleting one blinds every rule that reads those logs.

AzureActivity | where TimeGenerated > ago(30d) | where OperationNameValue =~ "MICROSOFT.INSIGHTS/DIAGNOSTICSETTINGS/DELETE" | project TimeGenerated, Caller, CallerIpAddress, _ResourceId
AWS CloudTrail stopped or changed AWSCloudTrailT1685.002High

StopLogging and DeleteTrail end the record; UpdateTrail and PutEventSelectors can narrow it quietly. Any of them outside a change is an incident.

AWSCloudTrail | where TimeGenerated > ago(30d) | where EventName in ("StopLogging", "DeleteTrail", "UpdateTrail", "PutEventSelectors") | project TimeGenerated, EventName, UserIdentityArn, SourceIpAddress, RequestParameters
Tuning: These are late indicators. By the time an attacker clears logs or blinds AMSI, they are established. Treat a hit as an active incident, and check the host's telemetry with the monitoring queries below.

Discovery 5

Discovery is the reconnaissance after landing on a host. Any one of these commands is ordinary, because administrators run them too, so both queries count: several different recon commands from one account in a short window is the pattern.

Burst of recon commands DeviceProcessEventsT1087Medium

whoami, ipconfig and net are ordinary one at a time. Four different ones from one account in ten minutes is someone getting their bearings.

DeviceProcessEvents | where Timestamp > ago(7d) | where FileName in~ ("whoami.exe", "hostname.exe", "ipconfig.exe", "net.exe", "systeminfo.exe", "tasklist.exe") | summarize CommandCount = dcount(FileName), Commands = make_set(FileName) by DeviceName, AccountName, bin(Timestamp, 10m) | where CommandCount >= 4
Active Directory enumeration DeviceProcessEventsT1087.002Medium

Listing domain controllers, Domain Admins and every computer is the map an attacker needs for the next step.

DeviceProcessEvents | where Timestamp > ago(7d) | where ProcessCommandLine has_any ("nltest /dclist", "net group \"domain admins\"", "dsquery", "Get-ADUser", "Get-ADComputer") | where AccountName !endswith "$" | summarize Commands = make_set(ProcessCommandLine), Count = count() by DeviceName, AccountName, bin(Timestamp, 1h) | where Count > 3
Domain trust enumeration DeviceProcessEventsT1482Medium

Listing trusts tells an attacker where else they can go. Administrators rarely run these commands from workstations.

DeviceProcessEvents | where Timestamp > ago(7d) | where ProcessCommandLine has_any ("nltest /domain_trusts", "nltest /trusted_domains", "Get-ADTrust", "Get-DomainTrust") | project Timestamp, DeviceName, AccountName, ProcessCommandLine
One device connecting to many hosts on the same port DeviceNetworkEventsT1046Medium

Fifty hosts on one port in ten minutes is a scan: 445, 3389 and 5985 are the ports that lead to lateral movement.

DeviceNetworkEvents | where Timestamp > ago(1d) | where ActionType in ("ConnectionSuccess", "ConnectionFailed", "ConnectionAttempt") | summarize Hosts = dcount(RemoteIP) by DeviceName, RemotePort, bin(Timestamp, 10m) | where Hosts >= 50
AWS enumeration: one key calling many List and Describe APIs AWSCloudTrailT1580Medium

Tools that map an AWS account call dozens of read-only APIs in minutes. A human in the console does not.

AWSCloudTrail | where TimeGenerated > ago(1d) | where EventName startswith "List" or EventName startswith "Describe" | summarize Apis = dcount(EventName), Calls = count() by UserIdentityAccessKeyId, SourceIpAddress, bin(TimeGenerated, 1h) | where Apis >= 30
Tuning: Do not alert on a single discovery command. Raise the thresholds until your own administrators and monitoring scripts stop appearing, then alert on what is left.

Lateral Movement 7

Lateral movement is the intrusion spreading from the first host, and every new host widens the incident. Follow RemoteIP and the account across DeviceLogonEvents: that is where the path from host to host assembles.

PsExec service on the target DeviceProcessEventsT1570High

PsExec installs PSEXESVC on the target to run the command. The same shape appears with tools that copy it.

DeviceProcessEvents | where Timestamp > ago(1d) | where FileName =~ "psexesvc.exe" or (FileName =~ "services.exe" and ProcessCommandLine has "PSEXESVC") | project Timestamp, DeviceName, AccountName, FileName, ProcessCommandLine
Pass the hash: NTLM NewCredentials logon DeviceLogonEventsT1550.002High

A NewCredentials logon over NTLM from a process other than Windows itself is how pass-the-hash tools present a stolen hash.

DeviceLogonEvents | where Timestamp > ago(1d) | where LogonType == "NewCredentials" | where Protocol == "NTLM" | where InitiatingProcessFileName !in ("services.exe", "lsass.exe") | project Timestamp, DeviceName, AccountName, RemoteIP, Protocol, InitiatingProcessFileName
Executable or script copied to an admin share DeviceFileEventsT1021.002Medium

Copying a binary to C$ or ADMIN$ is the first half of most remote execution. Read what ran on the target next.

DeviceFileEvents | where Timestamp > ago(7d) | where FolderPath has_any (@"\ADMIN$\", @"\C$\") | where FileName matches regex @"(?i)\.(exe|dll|bat|ps1)$" | project Timestamp, DeviceName, InitiatingProcessAccountName, FileName, FolderPath, RequestSourceIP
RDP logons by people DeviceLogonEventsT1021.001Medium

Every interactive remote logon by a person. Compare the source addresses with the jump hosts your administrators use.

DeviceLogonEvents | where Timestamp > ago(1d) | where LogonType == "RemoteInteractive" | where AccountName !endswith "$" | project Timestamp, DeviceName, AccountName, RemoteIP, RemoteDeviceName
One session used from two countries SigninLogsT1550.004High

A session ID that appears from two countries means the session token was copied. That is the signature of adversary-in-the-middle phishing, which MFA does not stop.

SigninLogs | where TimeGenerated > ago(1d) | where ResultType == "0" and isnotempty(SessionId) | summarize Countries = dcount(Location), IPs = make_set(IPAddress, 10), Apps = make_set(AppDisplayName, 10) by SessionId, UserPrincipalName | where Countries > 1
PowerShell remoting into a host DeviceProcessEventsT1021.006Medium

wsmprovhost.exe hosts inbound PowerShell remoting sessions, so what it starts is what a remote user ran on this host.

DeviceProcessEvents | where Timestamp > ago(7d) | where InitiatingProcessFileName =~ "wsmprovhost.exe" | project Timestamp, DeviceName, AccountName, FileName, ProcessCommandLine
DCOM: a process started by MMC20 over the network DeviceProcessEventsT1021.003Medium

The MMC20.Application DCOM object can run commands remotely; mmc.exe with -Embedding starting a shell is that technique.

DeviceProcessEvents | where Timestamp > ago(7d) | where InitiatingProcessFileName =~ "mmc.exe" and InitiatingProcessCommandLine has "-Embedding" | project Timestamp, DeviceName, AccountName, FileName, ProcessCommandLine
Tuning: Administration produces the same artifacts. The pass-the-hash query is the strongest here; the RDP and admin-share queries need a list of who normally administers what before an alert means anything.

Collection 5

Collection is the attacker gathering what they came for, just before taking it. On the endpoint that is data staged into an archive; in Exchange Online it is an inbox rule that hides or forwards mail.

Archive created with a compression tool DeviceProcessEventsT1560.001Medium

Attackers compress what they collect before taking it. An archive on a host that also shows discovery is staging.

DeviceProcessEvents | where Timestamp > ago(7d) | where FileName in~ ("7z.exe", "7za.exe", "rar.exe", "winrar.exe") or (FileName =~ "powershell.exe" and ProcessCommandLine has "Compress-Archive") | project Timestamp, DeviceName, AccountName, FileName, ProcessCommandLine
Inbox rule that deletes, forwards or moves mail OfficeActivityT1114.003High

Rules that forward or hide mail are a staple of business email compromise. Read the folder and the conditions.

OfficeActivity | where TimeGenerated > ago(7d) | where Operation in ("New-InboxRule", "Set-InboxRule") | where Parameters has_any ("DeleteMessage", "ForwardTo", "RedirectTo", "MoveToFolder") | project TimeGenerated, UserId, Operation, Parameters, ClientIP
Bulk download from SharePoint or OneDrive CloudAppEventsT1213.002Medium

A hundred distinct files in an hour is more than reading. Check whether the account also changed sharing or synced to an unmanaged device.

CloudAppEvents | where Timestamp > ago(7d) | where ActionType in ("FileDownloaded", "FileSyncDownloadedFull") | summarize Files = dcount(ObjectName), Events = count() by AccountDisplayName, IPAddress, bin(Timestamp, 1h) | where Files >= 100
Mailbox forwarding set to an outside address OfficeActivityT1114.003High

Mailbox-level forwarding sends a copy of every message elsewhere and does not show as an inbox rule. Outbound spam filter policy can block external forwarding.

OfficeActivity | where TimeGenerated > ago(7d) | where Operation == "Set-Mailbox" | where Parameters has_any ("ForwardingSmtpAddress", "ForwardingAddress") | project TimeGenerated, UserId, Parameters, ClientIP
Content search or export started OfficeActivityT1114.002Medium

eDiscovery can search and export every mailbox in the tenant. Searches by anyone outside your legal or compliance team are a collection step.

OfficeActivity | where TimeGenerated > ago(7d) | where Operation in ("New-ComplianceSearch", "Start-ComplianceSearch", "New-ComplianceSearchAction") | project TimeGenerated, UserId, Operation, Parameters, ClientIP
Tuning: Malicious inbox rules have a recognizable shape: forwarding outside the organization, or moving mail with finance keywords to a folder nobody opens. Archive creation matters most on a host that also shows discovery or credential access.

Command and Control 6

Command and control is the channel an attacker uses to work a foothold, so a hit means an active compromise. The first query catches tools pulled onto a host with built-in Windows binaries; the second measures how regular a host's connections to one address are.

Download with certutil, bitsadmin or mshta DeviceProcessEventsT1105Medium

Built-in binaries that can fetch a URL let an attacker bring tools in without a browser. certutil -urlcache is the classic example.

DeviceProcessEvents | where Timestamp > ago(1d) | where FileName in~ ("certutil.exe", "bitsadmin.exe", "mshta.exe") | where ProcessCommandLine has_any ("http://", "https://", "urlcache", "transfer", "download") | project Timestamp, DeviceName, AccountName, FileName, ProcessCommandLine
Beaconing: connections at regular intervals DeviceNetworkEventsT1071.001Medium

Implants call home on a schedule. A low ratio of spread to average gap means the connections are close to clockwork.

DeviceNetworkEvents | where Timestamp > ago(7d) | where ActionType == "ConnectionSuccess" and RemoteIPType == "Public" | sort by DeviceName asc, RemoteIP asc, Timestamp asc | extend Gap = iff(prev(DeviceName) == DeviceName and prev(RemoteIP) == RemoteIP, datetime_diff('second', Timestamp, prev(Timestamp)), long(null)) | where isnotnull(Gap) | summarize Connections = count(), MeanGap = avg(Gap), GapStdev = stdev(Gap) by DeviceName, RemoteIP | where Connections > 50 | extend Jitter = GapStdev / MeanGap // near 0 means clockwork | order by Jitter asc
Remote access software running DeviceProcessEventsT1219.002Medium

Legitimate remote support tools are a favored way to keep access, because they are signed and expected. Compare against the tools your support team actually uses.

DeviceProcessEvents | where Timestamp > ago(7d) | where FileName in~ ("anydesk.exe", "teamviewer.exe", "screenconnect.exe", "rustdesk.exe", "atera_agent.exe", "splashtop.exe", "netsupport.exe") | summarize FirstSeen = min(Timestamp), Devices = dcount(DeviceName) by FileName, AccountName | order by FirstSeen desc
Tunnel services such as ngrok and Cloudflare quick tunnels DeviceNetworkEventsT1572High

Tunnel services expose an internal port to the internet through an outbound connection, which firewalls usually allow.

DeviceNetworkEvents | where Timestamp > ago(7d) | where RemoteUrl has_any ("ngrok.io", "ngrok-free.app", "trycloudflare.com") | project Timestamp, DeviceName, InitiatingProcessFileName, RemoteUrl, RemoteIP
Long DNS names: a sign of tunneling or generated domains DnsEventsT1071.004Low

Data tunneled over DNS is encoded into long subdomains. Group by the parent domain: many long, unique names under one domain is the pattern.

DnsEvents | where TimeGenerated > ago(1d) | where strlen(Name) > 60 | summarize Queries = count(), Names = dcount(Name) by ClientIP, Domain = strcat_array(array_slice(split(Name, "."), -2, -1), ".") | where Names > 20
Connections to addresses in your threat intelligence ThreatIntelIndicatorsDeviceNetworkEventsT1071.001High

Only as good as the feed. Expire old indicators, and treat a hit on shared hosting or a CDN with suspicion of the indicator, not the host.

let bad = ThreatIntelIndicators | where TimeGenerated > ago(30d) | where IsActive == true and ObservableKey == "ipv4-addr:value" | project RemoteIP = ObservableValue | distinct RemoteIP; DeviceNetworkEvents | where Timestamp > ago(1d) | where RemoteIP in (bad) | project Timestamp, DeviceName, InitiatingProcessFileName, RemoteIP, RemotePort
Tuning: Jitter, randomized call-home timing, defeats interval analysis, and most current frameworks turn it on by default. A hit is valuable; no hit is no assurance. Pair it with how rare the destination is across your estate.

Exfiltration 4

Exfiltration is data leaving, the outcome most incidents turn on, and the hardest to separate from normal traffic by volume alone. Defender XDR's network table records connections without byte counts, so this one reads your firewall's logs.

Large uploads to one outside address CommonSecurityLogT1048.002Low

Volume alone is weak evidence. Combine it with rarity: an address no other host talks to, receiving gigabytes, after collection on the same host.

CommonSecurityLog | where TimeGenerated > ago(7d) | where DestinationPort in (443, 8443) | where not(ipv4_is_private(DestinationIP)) | summarize Sent = sum(SentBytes), Connections = count() by SourceIP, DestinationIP | where Sent > 50000000 | order by Sent desc
Rclone or a similar sync tool copying data out DeviceProcessEventsT1567.002High

Rclone is a common exfiltration tool in ransomware intrusions because it copies to almost any cloud storage service.

DeviceProcessEvents | where Timestamp > ago(7d) | where FileName in~ ("rclone.exe", "megacmd.exe") or ProcessCommandLine has_any ("rclone copy", "rclone sync") | project Timestamp, DeviceName, AccountName, ProcessCommandLine
Anonymous sharing link created OfficeActivityT1567Medium

An anonymous link lets anyone with the URL open the file. Many organizations disable them; where they are allowed, watch who creates them and for what.

OfficeActivity | where TimeGenerated > ago(7d) | where Operation in ("AnonymousLinkCreated", "AnonymousLinkUsed") | summarize Links = count(), Files = make_set(SourceFileName, 20) by UserId, Operation
AWS snapshot shared with another account AWSCloudTrailT1537High

Sharing a disk or database snapshot with another account copies the data out without moving a byte through your network.

AWSCloudTrail | where TimeGenerated > ago(30d) | where EventName in ("ModifySnapshotAttribute", "ModifyDBSnapshotAttribute") | where RequestParameters has "add" | project TimeGenerated, EventName, UserIdentityArn, SourceIpAddress, RequestParameters
Tuning: Cloud sync, backups and updates move large volumes every day. Use this as a correlation input: a large upload matters when it follows collection on the same host, or goes to a destination nothing else in your network talks to.

Impact 5

Impact is the attacker acting on the objective: encrypting, destroying, stopping services or spending your cloud budget. These are the latest indicators on the page, and the most expensive to miss by minutes, so they belong in near-real-time rules where the platform allows it.

Shadow copies, backups or boot recovery disabled DeviceProcessEventsT1490High

Deleting shadow copies and disabling recovery usually comes minutes before encryption. Treat a hit as an incident in progress.

DeviceProcessEvents | where Timestamp > ago(7d) | where (FileName =~ "vssadmin.exe" and ProcessCommandLine has "delete") or (FileName =~ "wmic.exe" and ProcessCommandLine has "shadowcopy") or (FileName =~ "wbadmin.exe" and ProcessCommandLine has "delete") or (FileName =~ "bcdedit.exe" and ProcessCommandLine has "recoveryenabled") | project Timestamp, DeviceName, AccountName, ProcessCommandLine
Hundreds of files renamed by one process in minutes DeviceFileEventsT1486High

Encryption renames files as it goes. The extension list shows whether it is a new, unfamiliar extension appearing on everything.

DeviceFileEvents | where Timestamp > ago(1d) | where ActionType == "FileRenamed" | summarize Renamed = count(), Extensions = make_set( tostring(parse_path(FileName).Extension), 10) by DeviceName, InitiatingProcessFileName, bin(Timestamp, 5m) | where Renamed >= 200
Security and backup services stopped DeviceProcessEventsT1489Medium

Stopping SQL, backup and security services frees locked files for encryption and removes the tools that would stop it.

DeviceProcessEvents | where Timestamp > ago(7d) | where FileName in~ ("net.exe", "net1.exe", "sc.exe", "taskkill.exe") | where ProcessCommandLine has_any ("stop", "config", "/im") | where ProcessCommandLine has_any ("vss", "sql", "backup", "veeam", "sophos", "defend", "sense") | project Timestamp, DeviceName, AccountName, ProcessCommandLine
Azure resources deleted in bulk AzureActivityT1485Medium

Mass deletion is destruction or a ransom demand in the cloud. Check the caller against your automation accounts.

AzureActivity | where TimeGenerated > ago(1d) | where OperationNameValue endswith "/DELETE" | where ActivityStatusValue in ("Success", "Succeeded") | summarize Deleted = count(), Types = make_set(ResourceProviderValue, 10) by Caller, bin(TimeGenerated, 1h) | where Deleted >= 20
AWS instances launched in bulk (resource hijacking) AWSCloudTrailT1496Medium

Many instances launched at once, often in unused regions, is the shape of cryptocurrency mining on a stolen key.

AWSCloudTrail | where TimeGenerated > ago(1d) | where EventName == "RunInstances" and isempty(ErrorCode) | summarize Launches = count(), Regions = make_set(AWSRegion) by UserIdentityArn, SourceIpAddress, bin(TimeGenerated, 1h) | where Launches >= 10
Tuning: Backup software deletes shadow copies, and deployment tools stop services, so exclude them by signer and path rather than by name. The rename threshold depends on the estate: measure your busiest file server first.

Monitoring 4

Health checks, not detections. A device that stopped reporting, a sensor that is not healthy, an attack surface reduction rule left in audit: each is a blind spot every other query on this page shares. Run them on a schedule.

Devices that stopped reporting DeviceInfoHealth

A device that went quiet is invisible to every other query here. It may be off, or its sensor may have been stopped.

DeviceInfo | where Timestamp > ago(30d) | summarize LastSeen = max(Timestamp) by DeviceId, DeviceName, OSPlatform | where LastSeen < ago(7d) | extend DaysSilent = datetime_diff('day', now(), LastSeen) | order by DaysSilent desc
Sensors that are not healthy DeviceInfoHealth

A sensor that is onboarded but not active sends nothing. Fix these before trusting an empty result anywhere else.

DeviceInfo | where Timestamp > ago(1d) | summarize arg_max(Timestamp, *) by DeviceId | where SensorHealthState != "Active" or OnboardingStatus != "Onboarded" | project DeviceName, OSPlatform, SensorHealthState, OnboardingStatus
Attack surface reduction events by rule DeviceEventsHealth

Rules left in audit block nothing. The audited count is what enforcement would have stopped.

DeviceEvents | where Timestamp > ago(30d) | where ActionType startswith "Asr" | summarize Audited = countif(ActionType endswith "Audited"), Blocked = countif(ActionType endswith "Blocked") by ActionType | order by Audited desc
Tables that stopped receiving data SigninLogsAuditLogsOfficeActivitySecurityEventHealth

A table that went quiet makes every rule reading it silently pass. Add the tables your rules depend on.

union withsource=Table SigninLogs, AuditLogs, OfficeActivity, SecurityEvent | where TimeGenerated > ago(30d) | summarize LastRecord = max(TimeGenerated) by Table | extend HoursSilent = datetime_diff('hour', now(), LastRecord) | order by HoursSilent desc

Part two: the operators

The detections above are built from a handful of operators. This part takes them one at a time, each with a security query, for when you are adapting a detection or writing your own.

Every query has the same shape

A query is a table followed by operators joined with pipes, each one taking the rows the last produced. Write it in the order of the question: which table, which period, which rows, what to measure, grouped by what, in what order. Run it after each line, so you see what each step kept.

SigninLogs | where TimeGenerated > ago(7d) // the table, then its time column | where ResultType != "0" // the rows the question is about | summarize Failures = count(), // the measure Accounts = dcount(UserPrincipalName) by IPAddress // the grouping | top 5 by Failures desc // the order and the cut
Time columnWhere
TimestampDefender XDR advanced hunting tables: DeviceProcessEvents, EmailEvents, IdentityLogonEvents and the rest
TimeGeneratedMicrosoft Sentinel tables: SigninLogs, AuditLogs, OfficeActivity, SecurityEvent, Syslog

Filter on time first, on the table's own time column. Microsoft's guidance is to apply datetime predicates immediately after the table reference, because the time index lets the engine skip whole shards of data before it reads anything else.

Filtering: which operator matches what

KQL splits text into terms, runs of letters and digits, and indexes terms of three or more characters. has matches a whole term and can use that index; contains matches any substring and has to scan. The choice changes the answer, not only the speed.

DeviceProcessEvents | where Timestamp > ago(30d) | where FileName in~ ("powershell.exe", "pwsh.exe") | summarize Rows = count(), HasEnc = countif(ProcessCommandLine has "enc"), ContainsEnc = countif(ProcessCommandLine contains "enc")

has "enc" finds the command lines carrying -enc as a flag. contains "enc" also finds every command line with those three letters inside a longer word, so it returns far more rows. Read the two counts side by side before choosing.

OperatorMatchesCase
==, !=The whole value exactlySensitive
=~, !~The whole valueInsensitive
in, in~Any value in a listin sensitive, in~ insensitive
has, !hasA whole term inside the valueInsensitive (has_cs sensitive)
has_any, has_allAny or all of several termsInsensitive
containsAny substring, scanning every valueInsensitive (contains_cs sensitive)
startswith, endswithThe start or end of the valueInsensitive
matches regexA regular expressionAs the pattern says
between (a .. b)A range, both ends includedNumbers, dates, times
ipv4_is_in_range()An address inside a CIDR rangeAddresses
Prefer the case-sensitive operator when the data allows it. Microsoft's performance guidance is == over =~ and in over in~ where you know the case. A negative filter such as !has or != also keeps the rows where the column is empty, so count the empties before trusting what a negative filter left.

Every string operator, and which ones use the index

Kusto builds a term index of every term three characters or more, and the has family of operators uses it. A term is a run of letters and digits, so in C:\Windows\System32\cmd.exe the terms are C, Windows, System32, cmd and exe. contains, startswith, endswith and regular expressions look at raw characters instead, which is why they are slower on large tables and why they can match where has does not.

OperatorTrue whenCase-sensitiveUses the term index
==EqualsYesYes
!=Not equalsYesYes
=~EqualsNoYes
!~Not equalsNoYes
hasRight side is a whole term in the leftNoYes
!hasRight side is not a whole termNoYes
has_csWhole termYesYes
hasprefixA term starts with the right sideNoYes
hassuffixA term ends with the right sideNoYes
has_anyAny of the listed termsNoYes
has_allAll of the listed termsNoYes
containsRight side appears anywhere, as a substringNoNo, scans
contains_csSubstringYesNo, scans
startswithThe value starts with the right sideNoNo
endswithThe value ends with the right sideNoNo
inEquals one of the listed valuesYesYes
in~Equals one of the listed valuesNoYes
matches regexThe value matches a regular expression (RE2 syntax)As writtenNo

Every operator has a negated form with ! in front, and most have a _cs case-sensitive form. Microsoft's performance guidance: use has rather than contains when looking for whole terms, and the case-sensitive form when two operators would do the same job.

DeviceProcessEvents | where Timestamp > ago(7d) | where FileName in~ ("powershell.exe", "pwsh.exe") | summarize Rows = count(), HasPrefixDown = countif(ProcessCommandLine hasprefix "download"), HasDownloadString = countif(ProcessCommandLine has "DownloadString"), ContainsDown = countif(ProcessCommandLine contains "download")

hasprefix "download" catches DownloadString, DownloadFile and DownloadData as terms; has "DownloadString" catches one; contains "download" also catches every path and URL with those letters inside a longer word. Three counts from one pass tell you which filter you actually want.

A term shorter than three characters falls back to a scan. has "ps" cannot use the index. Search for the longer term (powershell, pwsh) or accept the cost.

Shaping a result someone can read

extend adds a computed column to every row. case tests its conditions in order and returns the first that is true, with the last value catching everything else. Read what lands in "other" before dismissing it.

SigninLogs | where TimeGenerated > ago(30d) | where ResultType != "0" | extend Kind = case( ResultType == "50126", "wrong password", ResultType in ("50074", "50076"), "second factor", ResultType == "50053", "locked", ResultType == "53003", "Conditional Access", "other") | summarize Failures = count() by Kind | order by Failures desc
OperatorUse it to
extendAdd a computed column, keeping the rest
projectKeep only the named columns, in that order, renaming with =
project-away, project-renameDrop or rename columns without listing the others
case(), iff()Label rows by a rule
order by, top N bySort, or sort and keep the first N
distinctOne row per distinct combination of the named columns
format_datetime(), bin()Present a time, or round it down to a period

Scalar functions, by family

A scalar function turns one value into another inside extend, where or project. The families below cover almost everything a security query needs.

Date and time

FunctionUse it to
ago(7d), now()Anchor a window to the time the query runs
bin(TimeGenerated, 1h), bin_at()Round down to a bucket, for counting per period
startofday(), startofweek()Align to calendar boundaries
datetime_diff("minute", a, b)The gap between two times in a unit
datetime_add("day", 1, t)Move a time by an amount
hourofday(), dayofweek()Out-of-hours and weekend activity
format_datetime(t, "yyyy-MM-dd HH:mm")A readable time in a report
todatetime()Turn text from JSON or a log line into a datetime
SigninLogs | where TimeGenerated > ago(30d) | where ResultType == "0" | extend Hour = hourofday(TimeGenerated), Day = dayofweek(TimeGenerated) | where Hour < 6 or Hour > 21 or Day in (0d, 6d) | summarize OutOfHours = count(), First = min(TimeGenerated) by UserPrincipalName | order by OutOfHours desc

dayofweek returns a timespan from Sunday, so Sunday is 0d and Saturday is 6d. Set the hours to your own working day; this assumes UTC.

Strings, paths and URLs

FunctionUse it to
extract(regex, group, text)Pull one value out with a regular expression
extract_all(regex, text)Pull every match into an array
split(text, "\\")Break a path or list into an array
parse_path(path)DirectoryPath, Filename and Extension of a Windows or Unix path
parse_url(url)Scheme, Host, Port, Path and the query parameters of a URL
tolower(), trim(), replace_string()Normalize before comparing
strlen(), countof(), indexof(), substring()Measure and cut text
base64_decode_tostring(), url_decode()Read encoded payloads
hash_sha256()A stable key from a long value
EmailUrlInfo | where Timestamp > ago(7d) | extend U = parse_url(Url) | extend Host = tostring(U.Host), Path = tostring(U.Path) | summarize Messages = dcount(NetworkMessageId), Paths = dcount(Path) by Host | order by Messages desc
DeviceProcessEvents | where Timestamp > ago(7d) | extend Folder = tostring(parse_path(FolderPath).DirectoryPath) | where Folder has_any (@"\AppData\Local\Temp", @"\Downloads") | summarize Runs = count(), Devices = dcount(DeviceName) by FileName | order by Devices asc

Dynamic values: JSON and arrays

Function or operatorUse it to
parse_json(text), todynamic()Turn JSON text into a value you can address with dots and brackets
mv-expandOne row per element of an array
mv-applyFilter or summarize inside each row's array without exploding the table
bag_unpackTurn the keys of an object into columns
array_length(), set_difference(), set_intersect()Count and compare arrays
AuditLogs | where TimeGenerated > ago(7d) | mv-apply T = TargetResources on ( where tostring(T.type) == "User" | project Target = tostring(T.userPrincipalName)) | summarize Changes = count(), Ops = make_set(OperationName, 10) by Target | order by Changes desc

mv-apply keeps one row per audit event and reaches into its TargetResources array for the user. mv-expand would turn a three-target event into three rows, and every count after it would be three times too high.

IP addresses

FunctionUse it to
ipv4_is_private(ip)Separate internal from public addresses
ipv4_is_in_range(ip, "10.0.0.0/8")Test an address against a CIDR range
parse_ipv4(ip)An address as a number, for sorting and ranges
geo_info_from_ip_address(ip)Country, state, city, latitude and longitude for an address
SigninLogs | where TimeGenerated > ago(7d) | where ResultType == "0" and not(ipv4_is_private(IPAddress)) | extend Geo = geo_info_from_ip_address(IPAddress) | summarize SignIns = count(), Countries = make_set(tostring(Geo.country)) by UserPrincipalName | where array_length(Countries) > 1

Conditionals and empty values

FunctionUse it to
iff(cond, a, b)One of two values
case(c1, v1, c2, v2, else)One of several values
coalesce(a, b, c)The first value that is not empty
isempty(), isnotempty(), isnull()Find the rows a filter would silently drop
DeviceLogonEvents | where Timestamp > ago(7d) | extend Kind = case(LogonType == "RemoteInteractive", "RDP", LogonType == "Network", "Network", LogonType == "Interactive", "Console", "Other") | extend Source = iff(isempty(RemoteIP), "local", RemoteIP) | summarize Logons = count() by Kind, Source | order by Logons desc

Aggregation: counting the right thing

summarize returns one row per distinct value of its by columns. Choosing what to count is the analysis: failures per address measures volume, distinct accounts per address measures spread, and a password spray is many accounts with few failures each.

SigninLogs | where TimeGenerated > ago(30d) | where ResultType == "50126" // wrong password | summarize Failures = count(), Accounts = dcount(UserPrincipalName), Users = make_set(UserPrincipalName, 10), Last = max(TimeGenerated) by IPAddress | where Accounts >= 5 | order by Accounts desc
FunctionReturns
count(), countif()Rows, or rows meeting a condition
dcount(), dcountif()Distinct values; distinct counts per group do not add up to a total
make_set(), make_list()The values themselves, as evidence, capped at a size you set
arg_max(), arg_min()The latest or earliest row per group, with the columns you name
min(), max(), avg()Range and mean; read a percentile too when a few values are extreme
percentile(), percentiles()The value below which a share of the group falls
bin()Rows per period when used in by: by bin(TimeGenerated, 1h)

Aggregation functions

FunctionReturnsWatch for
count(), countif(cond)Rows, or rows meeting a conditioncountif lets one pass count several things
dcount(x), dcountif(x, cond)Distinct valuesAn estimate: Microsoft notes it trades accuracy for performance and can vary between runs
make_set(x, n), make_list(x, n)The distinct values, or all values, as an arrayCap the size with n
arg_max(t, *), arg_min(t, *)The whole row with the largest or smallest valueThe latest state of each entity
min(), max(), avg(), sum()The usual statisticsavg of a skewed value hides the outlier
percentile(x, 95), stdev(x)SpreadUse these for "unusually large"
take_any(x)Any one value from the groupNot the first, not the latest
DeviceNetworkEvents | where Timestamp > ago(7d) | where RemoteIPType == "Public" | summarize Connections = count(), Devices = dcount(DeviceName), Processes = dcountif(InitiatingProcessFileName, InitiatingProcessFileName != ""), FirstSeen = min(Timestamp), Latest = arg_max(Timestamp, DeviceName, InitiatingProcessFileName) by RemoteIP | where Devices == 1 | order by FirstSeen desc

An address only one device ever talks to is rare by definition. arg_max carries the device and process of the latest connection alongside the counts, so the row is ready to read.

Joins and unions

The default join is not a SQL inner join. A join with no kind runs as innerunique, which removes duplicate keys on the left side before matching. Name the kind on every join so the reader, and you, know which rows it keeps.

kind=Keeps
innerunique (default)Left rows with a match, left side deduplicated on the key
innerEvery matching pair from both sides
leftouterEvery left row, with right columns empty where nothing matched
leftsemiLeft rows that have a match, left columns only
leftantiLeft rows with no match, left columns only
fullouterEvery row from both sides

The rows an inner join drops

SigninLogs | where TimeGenerated > ago(30d) | where ResultType != "0" | summarize Failures = count() by UserPrincipalName | join kind=leftanti (IdentityInfo | where TimeGenerated > ago(30d) | project UserPrincipalName = AccountUPN) on UserPrincipalName

Failing accounts with no identity record. An inner join to IdentityInfo to add each account's department would quietly remove exactly these rows, and an account the directory does not know about is often the one that matters.

A join bounded in time

SigninLogs | where TimeGenerated > ago(30d) | where ResultType == "0" | project SignedIn = TimeGenerated, UserId = UserPrincipalName, IPAddress | join kind=inner (OfficeActivity | where TimeGenerated > ago(30d) | where Operation == "New-InboxRule" | project RuleAt = TimeGenerated, UserId, ClientIP) on UserId | where RuleAt between (SignedIn .. SignedIn + 1h) | summarize FirstRule = min(RuleAt) by UserId, IPAddress

Join on the account, then keep only the pairs where the inbox rule came within an hour of the sign-in. Without the time bound, every sign-in in the month pairs with every rule.

One question across several tables

union withsource = SourceTable SigninLogs, AADNonInteractiveUserSignInLogs, AADServicePrincipalSignInLogs | where TimeGenerated > ago(30d) | where IPAddress == "185.234.72.18" | summarize Rows = count() by SourceTable

union reads tables as one; withsource names the table each row came from. An address that appears only in the non-interactive or service principal tables is invisible to a query of SigninLogs alone.

Join order and size matter. Microsoft's guidance is to put the table with fewer rows on the left of a join, to use in rather than a left semi join when filtering by one column, and to use lookup instead of join when the right side is small.

Every join kind, lookup and union

join takes a kind, and the default is innerunique: an inner join that first removes duplicate keys from the left side. On security data the left side is usually events, so innerunique silently keeps one event per key and drops the rest. Say kind=inner when you want every match.

kind=Returns
innerunique (default)Matches, after deduplicating the left side on the key
innerEvery matching pair of rows
leftouterEvery left row, with right columns where they match
rightouterEvery right row, with left columns where they match
fullouterEvery row from both sides
leftantiLeft rows with no match: "what is new"
rightantiRight rows with no match
leftsemiLeft rows that have a match, left columns only
rightsemiRight rows that have a match, right columns only
let alerts = AlertEvidence | where Timestamp > ago(7d) | where EntityType == "Machine" | distinct DeviceName, AlertId; DeviceLogonEvents | where Timestamp > ago(7d) | where LogonType == "RemoteInteractive" | join kind=inner alerts on DeviceName | summarize Logons = count(), Alerts = dcount(AlertId) by DeviceName, AccountName

lookup is a join for adding columns from a small table to a large one. Microsoft notes it broadcasts the right side, so the right side must be small: a query fails if it is larger than several tens of megabytes.

SigninLogs | where TimeGenerated > ago(1d) | where ResultType == "0" | lookup kind=leftouter (IdentityInfo | where TimeGenerated > ago(14d) | summarize arg_max(TimeGenerated, Department, JobTitle) by AccountUPN | project UserPrincipalName = AccountUPN, Department, JobTitle) on UserPrincipalName | summarize SignIns = count() by Department, AppDisplayName

union stacks tables. withsource adds a column naming the table each row came from, which turns one query into a check across several sources.

union withsource=Source (SigninLogs | where TimeGenerated > ago(1d) | project TimeGenerated, Account = UserPrincipalName, IPAddress), (AADNonInteractiveUserSignInLogs | where TimeGenerated > ago(1d) | project TimeGenerated, Account = UserPrincipalName, IPAddress) | where IPAddress == "203.0.113.42" | summarize Events = count() by Source, Account

Text, JSON and arrays

Pull a value out of text and decode it

DeviceProcessEvents | where Timestamp > ago(30d) | where ProcessCommandLine has_any ("-enc", "-EncodedCommand") | extend Encoded = extract( @"(?i)\s-e(?:nc|ncodedcommand)?\s+([A-Za-z0-9+/=]{16,})", 1, ProcessCommandLine) | where isnotempty(Encoded) | extend Decoded = replace_regex(base64_decode_tostring(Encoded), @"\x00", "") | project Timestamp, DeviceName, Decoded

extract takes a regular expression and returns one capture group. PowerShell encodes -EncodedCommand as UTF-16LE, so the decoded text carries a null after every character; replace_regex strips them. A command line the pattern does not fit returns empty and is dropped by isnotempty, so count those rows separately.

Read inside nested JSON

AuditLogs | where TimeGenerated > ago(30d) | where OperationName == "Consent to application" | extend App = tostring(TargetResources[0].displayName), Actor = tostring(InitiatedBy.user.userPrincipalName) | mv-expand Prop = TargetResources[0].modifiedProperties | where tostring(Prop.displayName) == "ConsentAction.Permissions" | extend Scopes = tostring(Prop.newValue) | where Scopes has_any ("Mail.Read", "Mail.ReadWrite", "Files.ReadWrite.All") | project TimeGenerated, Actor, App, Scopes

Dot and bracket paths reach into a dynamic column; tostring turns the result into text you can compare. mv-expand turns an array into one row per element, so each modified property can be filtered by its name. Here: who consented to which application, for mail or file scopes.

OperatorUse it to
parse, parse-whereSplit text by its fixed parts; parse-where drops rows that do not fit
extract(), extract_all()Take one or every match of a regular expression
parse_json(), todynamic()Turn JSON text into a value you can navigate
mv-expandOne row per element of an array or bag
mv-applyFilter or aggregate inside each row's array without expanding the table
bag_unpackOne column per key of a property bag

Data types and conversion

Every column has one type, and comparisons between types fail quietly: a long compared with a string matches nothing. The types you meet in security tables:

TypeHoldsTypical columns
stringTextNames, paths, command lines, and many codes such as ResultType
int, longSigned 32-bit and 64-bit integersPorts, counts, EventID
realA 64-bit floating-point numberScores, averages
booltrue or falseIsClickedThrough, IsActive
datetimeAn instant in time, in UTCTimeGenerated, Timestamp
timespanA length of time: 1d, 2h, 30m, 10sThe result of subtracting two datetimes
dynamicAn array, a property bag (JSON object), or any scalarTargetResources, AdditionalFields
guidA 128-bit unique valueObject IDs, correlation IDs

Convert explicitly with tostring(), toint(), tolong(), toreal(), tobool(), todatetime() and totimespan(), and check a value's type with gettype(). Values taken out of a dynamic column stay dynamic until you convert them, which is why so many queries on this page wrap a JSON path in tostring() before comparing or grouping.

SigninLogs | where TimeGenerated > ago(1d) | extend City = tostring(LocationDetails.city), Code = toint(ResultType), T = gettype(LocationDetails) | summarize SignIns = count() by City, Code, T
ResultType is a string in SigninLogs. Compare it with "0", not 0. A failed conversion returns null rather than an error, so toint() on a value that is not a number gives an empty cell, which then drops out of every filter.

Names, lists and data from outside the query

let names a value, a table or a function, ending with a semicolon; the query after it uses the name. A short list of indicators can live in the query as a datatable and join with lookup, which keeps every row of the main table and adds the list's columns where they match.

let Watched = datatable(IPAddress: string, Note: string) [ "193.32.162.89", "spray source, ticket 4512", "185.234.72.18", "token replay, ticket 4519" ]; SigninLogs | where TimeGenerated > ago(30d) | lookup kind=inner Watched on IPAddress | summarize SignIns = count(), Successes = countif(ResultType == "0"), Accounts = dcount(UserPrincipalName) by IPAddress, Note

Successes from an address on the list are the rows to read first: a spray source with a success is a password that worked.

ConstructUse it to
let Name = value;Name a threshold, a list or a result, so the query reads as its intent
let f = (x: string) { ... };Reuse logic as a function inside the query
datatable()Put a small list of values in the query itself
_GetWatchlist('Name')Read a Sentinel watchlist; the indexed column is SearchKey
externaldata()Read a CSV or JSON file from a URL at query time
materialize()Compute a let result once when the query uses it more than once

Watchlists, threat intelligence and reusable functions

A watchlist is a table you upload to Sentinel. Microsoft's guidance is to read it with _GetWatchlist('name') and to join on its SearchKey column, which is the column you named as the key when you created it.

let vip = _GetWatchlist("VIP-Users") | project UserPrincipalName = tostring(SearchKey); SigninLogs | where TimeGenerated > ago(1d) | where ResultType == "0" | join kind=inner vip on UserPrincipalName | summarize SignIns = count(), IPs = make_set(IPAddress, 20) by UserPrincipalName

Threat intelligence indicators land in ThreatIntelIndicators, one row per indicator version, with ObservableKey saying what kind of value ObservableValue holds. Keep the active ones and match on the value.

let ti = ThreatIntelIndicators | where TimeGenerated > ago(30d) | where IsActive == true and ObservableKey == "domain-name:value" | project Domain = ObservableValue | distinct Domain; DeviceNetworkEvents | where Timestamp > ago(1d) | where isnotempty(RemoteUrl) | extend Domain = tostring(parse_url(strcat("https://", RemoteUrl)).Host) | where Domain in (ti) | project Timestamp, DeviceName, InitiatingProcessFileName, RemoteUrl

A let statement can define a function with parameters, so one query body serves several windows or accounts. materialize() computes a let value once when you use it more than once, which Microsoft lists as a best practice.

let failures = (lookback: timespan, minimum: int) { SigninLogs | where TimeGenerated > ago(lookback) | where ResultType != "0" | summarize Failures = count() by UserPrincipalName | where Failures >= minimum }; let recent = materialize(failures(1d, 10)); recent | join kind=leftanti (failures(14d, 10) | where UserPrincipalName !in ((recent | project UserPrincipalName))) on UserPrincipalName

externaldata reads a CSV or JSON file from a URL into the query, for a block list that lives outside Sentinel. The platform engine reads only its own hosted files, so this one is checked against the reference only.

Not run on practice data: the platform's KQL engine reads externaldata only from files it hosts.

let blocklist = externaldata(Ip: string) [@"https://example.com/blocklist.csv"] with (format = "csv"); SigninLogs | where TimeGenerated > ago(1d) | where IPAddress in (blocklist)
ASIM parsers. In Sentinel, the Advanced Security Information Model functions (for example _Im_Dns and _Im_NetworkSession) present different vendors' logs under one schema, so one query covers several firewalls or DNS servers. They are workspace functions, not tables.

Time series and the row before

Count every hour, including the empty ones

SigninLogs | where TimeGenerated > ago(30d) | make-series Failures = countif(ResultType != "0") default = 0 on TimeGenerated from ago(30d) to now() step 1h | extend (Flags, Score, Baseline) = series_decompose_anomalies(Failures, 3) | mv-expand Hour = TimeGenerated to typeof(datetime), Failures to typeof(long), Flags to typeof(int) | where Flags == 1 | project Hour, Failures

summarize by bin() leaves out the hours with no rows; make-series keeps them as zeros, which is what a baseline needs. series_decompose_anomalies flags the hours that break the series' own pattern, and mv-expand turns the flagged points back into rows.

Compare a row with the one before it

SigninLogs | where TimeGenerated > ago(30d) | sort by UserPrincipalName asc, TimeGenerated asc | extend PrevUser = prev(UserPrincipalName), PrevResult = prev(ResultType), Seconds = datetime_diff("second", TimeGenerated, prev(TimeGenerated)) | where ResultType == "0" and PrevResult == "50126" and PrevUser == UserPrincipalName and Seconds < 300 | project TimeGenerated, UserPrincipalName, IPAddress, Seconds

Sorting serializes the rows, so prev() and next() can read a neighbor. A success within five minutes of a wrong password for the same account is either a user correcting a typo or a guess that worked; the address tells you which to check first.

Time series, sessions and sequences

make-series builds one array of values per entity across fixed time steps, filling empty steps with a default. The series functions then work on the whole array: decompose it into trend and seasonality, and flag the points that do not fit.

SigninLogs | where TimeGenerated > ago(14d) | where ResultType != "0" | make-series Failures = count() default = 0 on TimeGenerated from ago(14d) to now() step 1h by AppDisplayName | extend (Flags, Score, Baseline) = series_decompose_anomalies(Failures, 2.5) | mv-expand TimeGenerated to typeof(datetime), Failures to typeof(long), Flags to typeof(int) | where Flags == 1

The 2.5 is the anomaly threshold; raise it to see fewer, stronger anomalies. mv-expand turns the arrays back into rows so you can read the hours that were flagged.

row_window_session groups sorted rows into sessions: a new session starts when the gap since the previous row exceeds a limit, the session exceeds a maximum length, or a condition (such as a new account) is true.

DeviceProcessEvents | where Timestamp > ago(1d) | where FileName in~ ("whoami.exe", "net.exe", "nltest.exe", "ipconfig.exe") | sort by DeviceName asc, Timestamp asc | extend Session = row_window_session(Timestamp, 1h, 10m, DeviceName != prev(DeviceName)) | summarize Commands = make_set(FileName), Start = min(Timestamp) by DeviceName, Session | where array_length(Commands) >= 3

scan matches a sequence of steps in order, such as failures followed by a success for the same account. The platform engine does not run it, so this one is checked against Microsoft's reference only.

Not run on practice data: the platform's KQL engine does not support scan. Run it in Sentinel or Azure Data Explorer.

SigninLogs | where TimeGenerated > ago(1d) | sort by UserPrincipalName asc, TimeGenerated asc | scan declare (Failures: long = 0) with ( step failed: ResultType != "0" => Failures = failed.Failures + 1; step success: ResultType == "0" and failed.Failures >= 5; ) | project TimeGenerated, UserPrincipalName, IPAddress

Graphs: questions about connections

SigninLogs | where TimeGenerated > ago(30d) | where ResultType == "0" | project Source = IPAddress, Target = UserPrincipalName | distinct Source, Target | make-graph Source --> Target with_node_id = Name | graph-match (u1)<--(a)-->(u2) where u1.Name < u2.Name and not(ipv4_is_in_any_range(a.Name, dynamic(["203.0.113.0/24", "192.0.2.0/24", "198.51.100.0/24"]))) project Address = a.Name, First = u1.Name, Second = u2.Name

make-graph turns rows into nodes and edges; graph-match finds a pattern in them and returns a table. This pattern is one outside address with successful sign-ins to two different accounts. Replace the ranges with your own corporate egress ranges. For one step a summarize answers the same question; a graph earns its place when the path is longer, such as address to account to application to permission.

Performance and limits

LimitValueWhere
Records returned to the client500,000, and 64 MB in total; more fails with a partial query failureKusto query limits (Log Analytics and Sentinel included)
Scheduled analytics rule query1 to 10,000 characters; no search * or union *Microsoft Sentinel
Scheduled rule frequency and lookback5 minutes to 14 days each; frequency no longer than lookbackMicrosoft Sentinel
Advanced hunting historyUp to 30 days of raw Defender XDR data; longer for Sentinel tables, by their retentionDefender XDR

The habits that keep a query fast, from Microsoft's best practices:

DoInstead ofWhy
Filter on time first, then on the most selective columnFiltering lateLess data reaches every later step
has, has_any, hasprefixcontainsThe term index; contains scans
==, in, has_cs=~, in~, hasMicrosoft: use the case-sensitive form when two operators do the same job
A specific columnsearch * or a whole-row searchScans every column
The smaller table on the left of a joinA large left sideMicrosoft: the table with the fewest rows first
in (subquery) to filter by one columnleftsemi joinMicrosoft lists in instead of a left semi join
lookup for a small right sidejoinlookup broadcasts the right side
materialize() a let you use twiceComputing it twiceMicrosoft lists it as a best practice
project only the columns you need, earlyCarrying every columnSmaller rows through summarize and join

Sentinel and Defender XDR: the same language, different tables

Microsoft Sentinel (Log Analytics)Defender XDR advanced hunting
Time columnTimeGeneratedTimestamp
HistoryYour workspace retentionUp to 30 days of Defender XDR data; Sentinel tables by retention
Identity sign-insSigninLogs, AADNonInteractiveUserSignInLogsEntraIdSignInEvents
EndpointThe Device* tables, if you stream themThe Device* tables
RulesAnalytics rules (scheduled, near-real-time)Custom detection rules

When Defender XDR tables are streamed into Log Analytics, Microsoft notes that Timestamp and TimeGenerated can differ, and that data arriving more than 48 hours late has TimeGenerated set to the time of ingestion. Use Timestamp for when the event happened.

DeviceProcessEvents | where Timestamp > ago(7d) | where FileName =~ "powershell.exe" | summarize Runs = count() by DeviceName | top 10 by Runs

From a query to an analytics rule

A hunting query answers a question once. A scheduled analytics rule asks it every few minutes and raises alerts, so the query needs a few more decisions. The ones Microsoft Sentinel asks for, with the limits its documentation gives:

SettingWhat to decide
Run every and look backBoth from 5 minutes to 14 days; the interval no longer than the lookback. Leave overlap for late-arriving data rather than gaps.
Alert thresholdHow many results it takes to alert. Two failed sign-ins is normal; two hundred is not.
Event groupingOne alert per run (the default), or one alert per result row. A rule can generate up to 150 alerts per run; past that, the 150th summarizes the rest.
Entity mappingWhich columns are the account, host, IP address, file or URL, so incidents correlate and the investigation graph works. Project those columns by name.
Custom details and alert detailsExtra columns surfaced on the alert, and an alert title built from the results, so the analyst does not have to open the raw events.
SuppressionStop the rule for up to 24 hours after it alerts, for noisy conditions you will handle in one go.

Worked example: password spray to rule

Start with the question (is anyone spraying passwords at us?), count the raw signal, then shape it into one row per attacking address with the entities the rule will map.

let lookback = 1h; let threshold = 10; SigninLogs | where TimeGenerated > ago(lookback) | where ResultType in ("50126", "50053") // bad password, locked out | summarize Accounts = dcount(UserPrincipalName), Failures = count(), Sample = make_set(UserPrincipalName, 10), FirstSeen = min(TimeGenerated), LastSeen = max(TimeGenerated) by IPAddress | where Accounts >= threshold | join kind=leftouter (SigninLogs | where TimeGenerated > ago(lookback) | where ResultType == "0" | summarize Succeeded = make_set(UserPrincipalName, 10) by IPAddress) on IPAddress | project IPAddress, Accounts, Failures, Sample, Succeeded, FirstSeen, LastSeen

Map IPAddress to the IP entity. The Succeeded column turns a spray alert into a compromise alert: any account in it signed in from the spraying address. Run it hourly with a one-hour lookback, raise the threshold until your own authentication servers drop out, and test it by checking that it returns the last spray you know about.

Checking an answer before you report it

Count the rows at every step

let Failing = SigninLogs | where TimeGenerated > ago(30d) | where ResultType != "0" | summarize Failures = count() by UserPrincipalName; let People = IdentityInfo | where TimeGenerated > ago(30d) | project UserPrincipalName = AccountUPN; print Failing = toscalar(Failing | count), Matched = toscalar(Failing | join kind=inner People on UserPrincipalName | count), Unmatched = toscalar(Failing | join kind=leftanti People on UserPrincipalName | count)

Matched and Unmatched must add up to Failing. When they do not, the join multiplied or dropped rows, and the result above it is wrong in a way the result itself will not show.

Prove the data could have answered

DeviceInfo | where Timestamp > ago(7d) | distinct DeviceName | join kind=leftouter (DeviceProcessEvents | where Timestamp > ago(7d) | summarize Processes = count() by DeviceName) on DeviceName | project DeviceName, Processes = coalesce(Processes, 0) | order by Processes asc

Every device that checked in, with how many process events it sent. A device at zero cannot return a hit from any process query, so "no results" on that device is a telemetry gap, not a clean bill.

Before a query leaves your hands. Run it on a case you know exists and confirm it returns that row. Check the columns it filters are populated for the operation you searched. Check the time column matches the table. A query copied from a blog or written by an AI assistant gets the same checks: it can parse, run and return rows while answering a different question from the one you asked.

Common mistakes and the fix

SymptomCause and fix
A join that returns too few rowsThe default kind is innerunique; set kind=inner.
A count that is three times too highmv-expand multiplied the rows; use mv-apply or count distinct IDs.
A negative filter that keeps blanks!has, != and !in keep empty values; add isnotempty() if you mean it.
has missing a matchThe text is not a separate term (a substring, or under three characters); use contains or hasprefix, knowingly.
An alert that never firesThe rule's lookback is shorter than the ago() in the query, or the table stopped arriving; run the monitoring query.
A time mismatch between tablesDefender tables use Timestamp, Log Analytics tables TimeGenerated; filter each on its own.
dcount numbers that changedcount is an estimate; for exact small counts use count() over distinct.
A query that times outTime filter first, has over contains, smaller table left, project early.
A result cut offMore than 500,000 records or 64 MB returned; summarize instead of returning raw rows.
Case surprises== and in are case-sensitive; =~ and in~ are not.

Quick lookup: the operator for the question

QuestionReach for
Where does this value appear at all?search in (Table1, Table2) "value", then query the column
How many, per what?summarize count(), dcount() by
Several counts in one pass?countif(), dcountif()
The latest state of each device or account?summarize arg_max(Timestamp, *) by DeviceName
What is new this week?join kind=leftanti against a baseline window
Every match, not one per key?join kind=inner
Add columns from a small table?lookup
One question across several tables?union withsource=
Did B happen soon after A?join on the entity, then where B between (A .. A + 1h)
Which value is rare?summarize dcount(DeviceName) by value, order by ascending
What is inside this JSON?parse_json, dot paths, mv-apply
Which part of a path or URL?parse_path, parse_url
Is the address internal, or where is it?ipv4_is_private, ipv4_is_in_range, geo_info_from_ip_address
Out of hours?hourofday, dayofweek
Which hour does not fit?make-series, series_decompose_anomalies
Which commands belong together?row_window_session
A sequence of steps in order?scan
What happened just before?sort, then prev()
Is it on my list?_GetWatchlist, ThreatIntelIndicators, in (subquery)
Use the same logic twice?let functions, materialize()
What connects these?make-graph, graph-match
Is my answer right?count each step, test a known positive

From looking up an operator to writing the query yourself

KQL for Security Analysts teaches KQL from your first query to graph operators and query validation, on a month of Sentinel and Defender XDR data with real attacks in it. Every query runs in your browser and shows what it returned, and every answer comes with what it does not prove.

Read the first module free →

Weekly security engineering insights

Detection techniques, architecture patterns, and operational judgment, every Tuesday.

No spam. Unsubscribe anytime.