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 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.
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, InitiatingProcessFileNameTwo 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 > 1Legacy 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, ClientAppUsedIdentity 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, ConditionalAccessStatusIsClickedThrough 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, IPAddressDisk 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, DeliveryLocationThe 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, RecipientAccountIdExecution 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.
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 descHidden 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,
InitiatingProcessFileNameWmiPrvSE.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 < 5Run 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, ActivityStatusValueA 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, InitiatingProcessFileNamesc \\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, ProcessCommandLinePersistence 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.
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,
InitiatingProcessFileNameServices 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, RegistryValueDataRun 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, InitiatingProcessFileNameA 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, AdditionalFieldsAnything 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, InitiatingProcessFileNameAn 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), ResultFull 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, ClientIPA 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, InitiatingProcessFileNameAn 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)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, ProcessCommandLineAn 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, SourceIpAddressPrivilege 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?
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 = SubjectUserNameThe 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)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, PropertiesA 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, ObjectNameCredential 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.
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, InitiatingProcessFileNameProcDump 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, ProcessCommandLineSaving 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,
InitiatingProcessFileNameScripts, 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,
InitiatingProcessFileNameThis 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, ProcessCommandLineAn 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, ResultError 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 > 5A 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, PermissionsResult 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 > 0Requesting 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 >= 5Pre-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, IpAddressThese 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, SubjectDomainNameNTDS.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, ProcessCommandLineDefender 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 >= 10Applications 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 >= 10Stealth 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.
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, SHA256An 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, InitiatingProcessFileNameEncoding 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,
InitiatingProcessFileNamemshta.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,
InitiatingProcessFileNameMarking 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, ClientIPRundll32 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,
InitiatingProcessFileNameDefense 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 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, ProcessCommandLineEvent 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, ProcessCommandLineClearing 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, ProcessCommandLineTurning 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, ProcessCommandLineClearing 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, ProcessCommandLineDiagnostic 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, _ResourceIdStopLogging 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,
RequestParametersDiscovery 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.
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 >= 4Listing 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 > 3Listing 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, ProcessCommandLineFifty 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 >= 50Tools 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 >= 30Lateral 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 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, ProcessCommandLineA 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,
InitiatingProcessFileNameCopying 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, RequestSourceIPEvery 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, RemoteDeviceNameA 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 > 1wsmprovhost.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, ProcessCommandLineThe 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, ProcessCommandLineCollection 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.
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, ProcessCommandLineRules 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, ClientIPA 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 >= 100Mailbox-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, ClientIPeDiscovery 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, ClientIPCommand 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.
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, ProcessCommandLineImplants 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 ascLegitimate 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 descTunnel 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,
RemoteIPData 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 > 20Only 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,
RemotePortExfiltration 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.
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 descRclone 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, ProcessCommandLineAn 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, OperationSharing 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,
RequestParametersImpact 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.
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, ProcessCommandLineEncryption 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 >= 200Stopping 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, ProcessCommandLineMass 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 >= 20Many 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 >= 10Monitoring 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.
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 descA 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, OnboardingStatusRules 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 descA 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 descPart 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 column | Where |
|---|---|
| Timestamp | Defender XDR advanced hunting tables: DeviceProcessEvents, EmailEvents, IdentityLogonEvents and the rest |
| TimeGenerated | Microsoft 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.
| Operator | Matches | Case |
|---|---|---|
| ==, != | The whole value exactly | Sensitive |
| =~, !~ | The whole value | Insensitive |
| in, in~ | Any value in a list | in sensitive, in~ insensitive |
| has, !has | A whole term inside the value | Insensitive (has_cs sensitive) |
| has_any, has_all | Any or all of several terms | Insensitive |
| contains | Any substring, scanning every value | Insensitive (contains_cs sensitive) |
| startswith, endswith | The start or end of the value | Insensitive |
| matches regex | A regular expression | As the pattern says |
| between (a .. b) | A range, both ends included | Numbers, dates, times |
| ipv4_is_in_range() | An address inside a CIDR range | Addresses |
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.
| Operator | True when | Case-sensitive | Uses the term index |
|---|---|---|---|
| == | Equals | Yes | Yes |
| != | Not equals | Yes | Yes |
| =~ | Equals | No | Yes |
| !~ | Not equals | No | Yes |
| has | Right side is a whole term in the left | No | Yes |
| !has | Right side is not a whole term | No | Yes |
| has_cs | Whole term | Yes | Yes |
| hasprefix | A term starts with the right side | No | Yes |
| hassuffix | A term ends with the right side | No | Yes |
| has_any | Any of the listed terms | No | Yes |
| has_all | All of the listed terms | No | Yes |
| contains | Right side appears anywhere, as a substring | No | No, scans |
| contains_cs | Substring | Yes | No, scans |
| startswith | The value starts with the right side | No | No |
| endswith | The value ends with the right side | No | No |
| in | Equals one of the listed values | Yes | Yes |
| in~ | Equals one of the listed values | No | Yes |
| matches regex | The value matches a regular expression (RE2 syntax) | As written | No |
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.
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| Operator | Use it to |
|---|---|
| extend | Add a computed column, keeping the rest |
| project | Keep only the named columns, in that order, renaming with = |
| project-away, project-rename | Drop or rename columns without listing the others |
| case(), iff() | Label rows by a rule |
| order by, top N by | Sort, or sort and keep the first N |
| distinct | One 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
| Function | Use 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 descdayofweek 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
| Function | Use 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 descDeviceProcessEvents
| 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 ascDynamic values: JSON and arrays
| Function or operator | Use it to |
|---|---|
| parse_json(text), todynamic() | Turn JSON text into a value you can address with dots and brackets |
| mv-expand | One row per element of an array |
| mv-apply | Filter or summarize inside each row's array without exploding the table |
| bag_unpack | Turn 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 descmv-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
| Function | Use 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) > 1Conditionals and empty values
| Function | Use 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 descAggregation: 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| Function | Returns |
|---|---|
| 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
| Function | Returns | Watch for |
|---|---|---|
| count(), countif(cond) | Rows, or rows meeting a condition | countif lets one pass count several things |
| dcount(x), dcountif(x, cond) | Distinct values | An 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 array | Cap the size with n |
| arg_max(t, *), arg_min(t, *) | The whole row with the largest or smallest value | The latest state of each entity |
| min(), max(), avg(), sum() | The usual statistics | avg of a skewed value hides the outlier |
| percentile(x, 95), stdev(x) | Spread | Use these for "unusually large" |
| take_any(x) | Any one value from the group | Not 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 descAn 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 |
| inner | Every matching pair from both sides |
| leftouter | Every left row, with right columns empty where nothing matched |
| leftsemi | Left rows that have a match, left columns only |
| leftanti | Left rows with no match, left columns only |
| fullouter | Every 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 UserPrincipalNameFailing 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, IPAddressJoin 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 SourceTableunion 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.
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 |
| inner | Every matching pair of rows |
| leftouter | Every left row, with right columns where they match |
| rightouter | Every right row, with left columns where they match |
| fullouter | Every row from both sides |
| leftanti | Left rows with no match: "what is new" |
| rightanti | Right rows with no match |
| leftsemi | Left rows that have a match, left columns only |
| rightsemi | Right 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, AccountNamelookup 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, AppDisplayNameunion 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, AccountText, 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, Decodedextract 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, ScopesDot 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.
| Operator | Use it to |
|---|---|
| parse, parse-where | Split 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-expand | One row per element of an array or bag |
| mv-apply | Filter or aggregate inside each row's array without expanding the table |
| bag_unpack | One 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:
| Type | Holds | Typical columns |
|---|---|---|
| string | Text | Names, paths, command lines, and many codes such as ResultType |
| int, long | Signed 32-bit and 64-bit integers | Ports, counts, EventID |
| real | A 64-bit floating-point number | Scores, averages |
| bool | true or false | IsClickedThrough, IsActive |
| datetime | An instant in time, in UTC | TimeGenerated, Timestamp |
| timespan | A length of time: 1d, 2h, 30m, 10s | The result of subtracting two datetimes |
| dynamic | An array, a property bag (JSON object), or any scalar | TargetResources, AdditionalFields |
| guid | A 128-bit unique value | Object 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, TNames, 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, NoteSuccesses from an address on the list are the rows to read first: a spray source with a success is a password that worked.
| Construct | Use 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 UserPrincipalNameThreat 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, RemoteUrlA 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 UserPrincipalNameexternaldata 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)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, Failuressummarize 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, SecondsSorting 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 == 1The 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) >= 3scan 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, IPAddressGraphs: 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.Namemake-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
| Limit | Value | Where |
|---|---|---|
| Records returned to the client | 500,000, and 64 MB in total; more fails with a partial query failure | Kusto query limits (Log Analytics and Sentinel included) |
| Scheduled analytics rule query | 1 to 10,000 characters; no search * or union * | Microsoft Sentinel |
| Scheduled rule frequency and lookback | 5 minutes to 14 days each; frequency no longer than lookback | Microsoft Sentinel |
| Advanced hunting history | Up to 30 days of raw Defender XDR data; longer for Sentinel tables, by their retention | Defender XDR |
The habits that keep a query fast, from Microsoft's best practices:
| Do | Instead of | Why |
|---|---|---|
| Filter on time first, then on the most selective column | Filtering late | Less data reaches every later step |
| has, has_any, hasprefix | contains | The term index; contains scans |
| ==, in, has_cs | =~, in~, has | Microsoft: use the case-sensitive form when two operators do the same job |
| A specific column | search * or a whole-row search | Scans every column |
| The smaller table on the left of a join | A large left side | Microsoft: the table with the fewest rows first |
| in (subquery) to filter by one column | leftsemi join | Microsoft lists in instead of a left semi join |
| lookup for a small right side | join | lookup broadcasts the right side |
| materialize() a let you use twice | Computing it twice | Microsoft lists it as a best practice |
| project only the columns you need, early | Carrying every column | Smaller rows through summarize and join |
Sentinel and Defender XDR: the same language, different tables
| Microsoft Sentinel (Log Analytics) | Defender XDR advanced hunting | |
|---|---|---|
| Time column | TimeGenerated | Timestamp |
| History | Your workspace retention | Up to 30 days of Defender XDR data; Sentinel tables by retention |
| Identity sign-ins | SigninLogs, AADNonInteractiveUserSignInLogs | EntraIdSignInEvents |
| Endpoint | The Device* tables, if you stream them | The Device* tables |
| Rules | Analytics 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 RunsFrom 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:
| Setting | What to decide |
|---|---|
| Run every and look back | Both from 5 minutes to 14 days; the interval no longer than the lookback. Leave overlap for late-arriving data rather than gaps. |
| Alert threshold | How many results it takes to alert. Two failed sign-ins is normal; two hundred is not. |
| Event grouping | One 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 mapping | Which 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 details | Extra columns surfaced on the alert, and an alert title built from the results, so the analyst does not have to open the raw events. |
| Suppression | Stop 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,
LastSeenMap 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 ascEvery 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.
Common mistakes and the fix
| Symptom | Cause and fix |
|---|---|
| A join that returns too few rows | The default kind is innerunique; set kind=inner. |
| A count that is three times too high | mv-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 match | The text is not a separate term (a substring, or under three characters); use contains or hasprefix, knowingly. |
| An alert that never fires | The rule's lookback is shorter than the ago() in the query, or the table stopped arriving; run the monitoring query. |
| A time mismatch between tables | Defender tables use Timestamp, Log Analytics tables TimeGenerated; filter each on its own. |
| dcount numbers that change | dcount is an estimate; for exact small counts use count() over distinct. |
| A query that times out | Time filter first, has over contains, smaller table left, project early. |
| A result cut off | More 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
| Question | Reach 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.