Goal. By the end you can pick the right analytic for a hypothesis (first-seen, rare, outlier, frequency stacking, beacon, sequence, peer comparison or clustering), run it, and say how it could mislead you.
Why it matters#
Most attacker activity does not come with a signature. You find it because it is new, rare, too regular, in an odd order or unlike its neighbours. Each of those ideas is a simple calculation. Each also fails in a predictable way, and a hunter who does not know the failure will either chase noise all day or report "clean" with false confidence.
None of these proves anything bad. An analytic produces leads: things worth a closer look. Investigation produces findings.
What you will learn#
Choosing#
| If your question is | Use | You need |
|---|---|---|
| Has this ever happened before? | First-seen | A history longer than the window you examine |
| What happens almost nowhere? | Rare values, frequency stacking | Many similar systems |
| What is far from normal? | Outliers | A numeric measure and enough history |
| What repeats like a machine? | Beacon analysis | Per-connection timestamps |
| Did these happen in this order? | Sequence | A shared key and trustworthy times |
| Who is unlike their colleagues? | Peer comparison | Meaningful peer groups |
| What groups together, and what is left over? | Clustering | Good features and patience |
The examples use Microsoft Defender XDR tables (KQL, Kusto Query Language) or Splunk's SPL. The ideas carry to any platform. See Detection Engineering stage 4 if the syntax is new.
First-seen#
Compare a recent period with a longer baseline and keep only what is new.
let baseline = DeviceProcessEvents
| where Timestamp between (ago(30d) .. ago(1d))
| distinct FileName, InitiatingProcessFileName;
DeviceProcessEvents
| where Timestamp > ago(1d)
| summarize Hosts = dcount(DeviceName), Example = any(ProcessCommandLine)
by FileName, InitiatingProcessFileName
| join kind=leftanti baseline on FileName, InitiatingProcessFileName
| order by Hosts ascIllustrative: test it in your lab before relying on it.
How it fails. Anything the attacker did before the baseline started counts as normal. Software updates, new starters and new servers flood the results. If the field you compare contains a version number or a random temporary name, everything is new every day. Normalise those first.
Rare values and frequency stacking#
Stacking (also called least-frequency analysis) counts each value across many systems and reads the short tail. If 800 servers run the same ten service programs and one runs an eleventh, look at the eleventh.
index=endpoint EventCode=1 earliest=-7d
| rex field=Image "(?<process>[^\\\\]+)$"
| rex field=ParentImage "(?<parent>[^\\\\]+)$"
| stats dc(host) AS hosts, count, values(CommandLine) AS examples BY parent, process
| where hosts<=2
| sort hosts, countIllustrative: test it in your lab before relying on it.
Count hosts or accounts, not events: one noisy machine can run a rare program a million times.
How it fails. Rare is not bad, and bad is not always rare. Every estate has unique machines and one-off admin scripts. An attacker who has reached most of your hosts is common. An attacker who runs a standard Windows program is common too, which is why you stack combinations (parent and child, path and name, signer and path) and not names alone.
Outliers#
An outlier is a value far from what is usual, such as one account downloading far more files than it normally does. A robust approach uses the median and the median absolute deviation (MAD, the typical distance from the median), because one huge day distorts an average far more than a median.
index=proxy earliest=-30d@d latest=@d
| bin _time span=1d
| stats sum(bytes_out) AS daily BY _time, user
| eventstats median(daily) AS med, count AS days BY user
| eval dev=abs(daily-med)
| eventstats median(dev) AS mad BY user
| where days>=14 AND mad>0 AND daily > med + 6*madIllustrative: test it in your lab before relying on it. The multiplier 6 is a starting guess, not a standard.
How it fails. Seasonal work (month end, backups) looks like theft. A slow thief who stays under the usual variation never appears. Days with no activity are missing from this query, which raises the median. A new account has no history, so decide what happens to it rather than letting the filter drop it unnoticed.
Beacon analysis#
Malware often calls home on a timer. This is beaconing. Measure the gaps between connections from one source to one destination: very similar gaps suggest automation.
DeviceNetworkEvents
| where Timestamp > ago(1d) and RemoteIPType == "Public"
| project Timestamp, DeviceName, InitiatingProcessFileName, Dest = coalesce(RemoteUrl, RemoteIP)
| sort by DeviceName asc, InitiatingProcessFileName asc, Dest asc, Timestamp asc
| extend Gap = iff(DeviceName == prev(DeviceName) and Dest == prev(Dest)
and InitiatingProcessFileName == prev(InitiatingProcessFileName),
datetime_diff('second', Timestamp, prev(Timestamp)), long(null))
| where isnotnull(Gap) and Gap > 0
| summarize Calls = count(), AvgGap = avg(Gap), SdGap = stdev(Gap)
by DeviceName, InitiatingProcessFileName, Dest
| extend Variation = SdGap / AvgGap
| where Calls >= 20 and Variation < 0.2Illustrative: test it in your lab before relying on it. The thresholds 20 and 0.2 are starting guesses.
How it fails. Updaters, telemetry, mail clients and monitoring agents beacon perfectly. Attackers add jitter (random delay), sleep for hours or use a popular cloud service that you will be tempted to exclude. Endpoint tables may sample or aggregate connections, so check what one row means. Full proxy or flow data is better for this.
Sequence#
Some events are dull alone and alarming in order: many failed sign-ins, then a success; a document opens, then a script interpreter starts, then it connects out.
let fails = SigninLogs
| where TimeGenerated > ago(7d) and ResultType == "50126"
| summarize Fails = count(), LastFail = max(TimeGenerated)
by UserPrincipalName, IPAddress, Hour = bin(TimeGenerated, 1h)
| where Fails >= 10;
fails
| join kind=inner (SigninLogs | where TimeGenerated > ago(7d) and ResultType == "0"
| project SuccessTime = TimeGenerated, UserPrincipalName, IPAddress, AppDisplayName)
on UserPrincipalName, IPAddress
| where SuccessTime between (LastFail .. LastFail + 1h)Illustrative: test it in your lab before relying on it. 50126 is Microsoft Entra's code for invalid
credentials.
How it fails. Fixed time buckets split a burst across two hours. Clock differences reorder events. The attacker changes the joining key (a new address for the successful attempt), or one stage is in a log you do not have. Loosen the join once you have run the strict version, and compare.
Peer comparison#
Compare an account or host with others that should behave like it: finance users with finance users, web servers with web servers. A database export by a database administrator is ordinary; the same export by someone in marketing is a lead.
Take a group list (from the directory or an inventory), count the behaviour per member, and show members whose behaviour almost none of their peers share.
How it fails. Directory groups are often out of date or too broad. Small groups make everyone an outlier. If the whole group is compromised or has the same bad habit, nobody stands out.
Clustering#
Clustering lets an algorithm group similar items, such as command lines, so you can review one example per group and the leftovers. Start cheaply: replace numbers, GUIDs and long encoded strings with placeholders, then count the resulting shapes.
index=endpoint EventCode=1 Image="*\\powershell.exe" earliest=-7d
| eval shape=lower(CommandLine)
| eval shape=replace(shape, "[a-z0-9+/=]{40,}", "<blob>")
| eval shape=replace(shape, "\d+", "<n>")
| stats count, dc(host) AS hosts BY shape
| sort hosts, countIllustrative: test it in your lab before relying on it.
Splunk's cluster command and KQL's autocluster plugin, or a notebook with a machine-learning library, go
further.
How it fails. Results depend heavily on which features you chose and on settings you may not understand. A malicious command can sit comfortably inside a large harmless cluster. Treat clusters as a way to read less, not as a verdict.
Using the results#
Keep a short exclusion list as you go, with a reason and an owner for each entry. Never exclude by file name alone, because attackers copy names. Exclude by a combination such as signer, path, parent and host group. And always record what you excluded, because your "clean" result does not cover it.
Do this#
- Stack parent and child processes (3 hours). Use lab data or a public dataset. Review the 20 rarest pairs and label each harmless, unknown or suspicious, with a reason.
- Build a first-seen search (2 hours). Run it with a 7-day and a 30-day baseline and explain the difference.
- Make a beacon (3 hours). In your lab, schedule a script to request
https://example.com/every minute for an hour, then every minute with random delay. See which version your analytic still catches. - Write the failure note (1 hour). For each analytic you used, write one sentence: what it would miss.
Resources#
Free first
- MSTICPy - Microsoft's Python library for hunting in notebooks, including outlier and sequence helpers.
- RITA - open-source beacon and DNS tunnelling analysis over Zeek network logs.
- Kusto Query Language overview - reference for
join,summarizeand the time-series functions. - Splunk SPL search reference -
reference for
stats,eventstats,streamstatsandcluster.
Paid or needs an account
- None needed for this stage.
Checkpoint#
You are ready to move on when you can:
Go deeper (optional)#
- Stage 5 applies these analytics to Windows technique hunts.