Skip to content

Tutorials

Your first Microsoft Sentinel analytics rule, step by step

Build a scheduled analytics rule in Microsoft Sentinel from a KQL query: schedule, threshold, entity mapping, incident grouping, testing and tuning.

Published 6 min readReviewed by The Ledger EditorIntermediate

Every SIEM ships with templates, and Microsoft Sentinel has hundreds of them. Sooner or later, though, you will need a detection the templates do not cover: a pattern from an incident you just closed, a risk specific to your environment, a gap a threat report pointed out. Writing that rule well is one of the most useful skills a SOC analyst can build, and in Sentinel it starts with a KQL query you already know how to write.

This tutorial builds one scheduled analytics rule from start to finish: a password spray followed by a successful sign-in from the same IP address. Along the way it covers every setting in the wizard and why it matters.

Before you start

  • A Microsoft Sentinel workspace with the Microsoft Entra ID data connector sending SigninLogs. A trial or lab tenant is fine.
  • The Microsoft Sentinel Contributor role on the workspace, or equivalent.
  • Some sign-in data. In a quiet lab, generate a few failed sign-ins against test accounts so the query has something to find.

Step 1: write and test the query first

Never start in the rule wizard. Start in Advanced hunting (or Logs), and get a query that returns exactly what you want to be alerted on, one row per thing worth investigating:

spray-then-success.kql
let failureThreshold = 10;
let failures = SigninLogs
    | where ResultType in ("50126", "50053")
    | summarize FailedUsers = dcount(UserPrincipalName), FirstFailure = min(TimeGenerated)
        by IPAddress
    | where FailedUsers >= failureThreshold;
SigninLogs
| where ResultType == "0"
| join kind=inner failures on IPAddress
| where TimeGenerated > FirstFailure
| summarize SuccessfulUsers = make_set(UserPrincipalName, 20), LastSuccess = max(TimeGenerated)
    by IPAddress, FailedUsers, FirstFailure
| extend AccountUpn = tostring(SuccessfulUsers[0])

Some notes on the choices:

  • No time filter inside the query. In a scheduled rule, the lookback setting decides how far back the query reads. When you test it in Advanced hunting, pick a time range in the query settings instead.
  • Specific error codes. 50126 is an invalid username or password and 50053 a locked account. Counting every non-zero ResultType would also count MFA prompts and Conditional Access blocks, and flood the rule with noise.
  • One row per attacking IP, with the accounts that succeeded. That shape becomes one alert per IP.
  • A clean column for the account (AccountUpn), because entity mapping needs a single value, not an array.

Run it against the last day or week. If it returns hundreds of rows, the threshold is too low for your environment; if it never returns anything even after your lab test, check the error codes in your own data first.

Step 2: open the wizard

In the Defender portal, go to Investigation & response → Detection → Analytics (in the Azure portal, Microsoft Sentinel → Configuration → Analytics), select Create and then Scheduled query rule.

Step 3: general settings

  • Name: describe the behavior, not the tool: Password spray followed by successful sign-in from the same IP.
  • Description: what the rule detects, why it matters and what the analyst should check first. This text appears in every alert, so write it for the person on shift at 3 a.m.
  • Severity: Medium is a reasonable start. A spray with a success is serious, but the rule will need tuning before it earns High.
  • MITRE ATT&CK: Credential Access, technique T1110.003 Password Spraying. Mapping to MITRE ATT&CK makes coverage reports and triage easier.
  • Status: Enabled.

Step 4: set the rule logic

Paste the query, then configure the parts that turn it into a detection.

Entity mapping

Entity mapping tells Sentinel which columns are users, hosts, IP addresses and so on. It is what links alerts together into incidents, drives automatic enrichment and lets the analyst pivot from the incident page. You can map up to 10 entity types per rule.

  • Account: identifier FullName → AccountUpn.
  • IP: identifier Address → IPAddress.

Custom details and alert details

Custom details surface extra columns directly in the alert, so the analyst does not have to rerun the query. Add FailedUsers and FirstFailure.

Alert details let you build the alert name from the data, for example Password spray from {{IPAddress}} with a successful sign-in. In the Defender portal, the correlation engine names incidents itself and may override a custom alert name, so do not rely on it for anything important.

Query scheduling

  • Run query every: 1 hour.
  • Lookup data from the last: 1 hour.

Both accept values from 5 minutes to 14 days, and the lookback must be at least as long as the interval, or events would fall between runs. Sentinel also runs scheduled rules with a five-minute delay to allow for ingestion latency. A spray that is spread over several hours will not cross the threshold in a one-hour window, so if you expect slow sprays, use a longer lookback, for example run every hour and look back 24 hours, and rely on grouping to avoid duplicate incidents.

Alert threshold and event grouping

  • Generate alert when number of query results is greater than 0. The real threshold already lives in the query.
  • Event grouping: Trigger an alert for each event, so that two attacking IP addresses produce two alerts. A rule can generate up to 150 alerts per run.
  • Suppression: leave it off for now. It stops the rule from running for up to 24 hours after an alert, which is useful for noisy rules but can hide a second attack.

Test with current data

Select Test with current data in the results simulation panel. Sentinel simulates the rule running 50 times over your existing data with the schedule you chose, and shows how many alerts it would have produced. If the graph is full of alerts, go back to the query before you save anything.

Step 5: incident settings

  • Create incidents from alerts triggered by this analytics rule: Enabled. In the Defender portal, leave this on; Defender XDR creates and correlates the incidents.
  • Alert grouping: enable it, and choose Group alerts into a single incident if all the entities match, with a time window of 24 hours. Repeated alerts for the same IP and account are added to one incident instead of opening a new one every hour. The window can be between 5 minutes and 7 days.

Step 6: automated response

Here you attach automation rules, which can assign the incident, change its severity, add a tag or run a playbook when the rule fires. For a first rule, one automation rule that tags the incident identity and assigns it to the identity queue is plenty. Playbooks that disable accounts automatically belong to SOAR work you do after the rule has proven itself, not on day one.

Step 7: review, create and watch it

Select Review and create, wait for Validation passed and create the rule. Then:

  1. Generate a test. In your lab, make ten or more failed sign-ins to different test accounts from one IP, then one successful sign-in from the same IP. Within the hour plus the five-minute delay, you should see an incident.
  2. Check the incident page. The account and IP should appear as entities, the custom details should be visible, and the description should tell the analyst what to do.
  3. Track the results for two weeks. Every false positive is information: a VPN gateway or a proxy that concentrates many users behind one IP, a misconfigured service account retrying old passwords. Exclude what you understand, with a comment explaining why, and nothing more.

Common mistakes

  • Writing the rule in the wizard instead of testing the query first.
  • Lookback shorter than the interval, which leaves gaps between runs.
  • Counting every failed sign-in, including MFA and Conditional Access interruptions, which buries real attacks in noise.
  • No entity mapping, which leaves incidents that cannot be correlated or enriched.
  • Broad exclusions such as whole IP ranges or all service accounts, added in a hurry and never revisited.
  • No owner. Rules break silently when log formats change. Every custom rule needs someone who reviews it.

Why it matters for a SOC analyst

Writing and tuning detection rules is how you stop seeing the same false positive every morning and start catching the attacks your templates miss. It also changes how you triage: once you have built a rule, you read every alert asking what query produced this, and what would make it wrong? That question is the core of good alert triage. Start with one rule, test it, tune it for a few weeks, and then write the next.

Terms in this article

SIEM
A platform that collects logs from across an organization, correlates them and raises alerts, giving the SOC one place to investigate.
KQL
The read-only query language used by Microsoft Sentinel, Defender XDR advanced hunting, Azure Monitor and Azure Data Explorer.
Password spray
An attack that tries a few common passwords against many accounts, staying under lockout limits that per-account guessing would trigger.
MITRE ATT&CK
A free, public knowledge base of adversary tactics and techniques based on real-world observations, used as a common language for attack and defense.
SOAR
Tools that connect security products and run automated playbooks, so routine response steps happen in seconds instead of being done by hand.
False positive
An alert that fires on activity that is not actually malicious, because the detection logic matched something legitimate.
Alert triage
The first quick assessment of a security alert or incident: is it real, how serious is it, and what needs to happen next and how soon.

Last reviewed on by The Ledger Editor, Security Engineer