Configuring Custom Detection Rules
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 11 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Lesson: Configuring Custom Detection Rules in Microsoft Defender XDR
Introduction: Why Custom Detections Matter
In the modern cybersecurity landscape, relying solely on out-of-the-box detection logic is rarely sufficient for a mature security operations center (SOC). While Microsoft Defender XDR provides a vast library of pre-configured analytics designed to catch common malware, credential harvesting, and lateral movement, attackers are constantly shifting their techniques. Custom detection rules act as your organization’s bespoke security layer, allowing you to codify your unique threat intelligence and specific business environment requirements into actionable alerts.
When you create a custom detection rule, you are essentially telling the Microsoft Defender system to continuously monitor your environment for specific patterns that are idiosyncratic to your business. Perhaps you have a specific naming convention for privileged accounts, or you want to track the usage of a specific PowerShell script that should never be executed by standard users. By translating these specific requirements into Kusto Query Language (KQL) and wrapping them in detection logic, you transform raw telemetry into high-fidelity signals that your analysts can act upon immediately.
The importance of this capability cannot be overstated. Standard alerts are often noisy because they are designed to be broad enough to catch threats across millions of different organizations. Custom rules, conversely, are narrow and focused. They significantly reduce alert fatigue by filtering out the noise and highlighting the specific activities that represent a genuine risk to your unique infrastructure. This lesson will guide you through the process of architecting, testing, and deploying custom detections that actually improve your security posture.
Not read yet
Understanding the Foundation: KQL and Telemetry
Before you write a single rule, you must understand that custom detections in Microsoft Defender XDR are powered by Kusto Query Language (KQL). KQL is the engine room of the Microsoft Sentinel and Defender ecosystem. It is a powerful, read-only query language that allows you to slice and dice massive datasets with incredible speed. If you are familiar with SQL, you will find some similarities, but KQL is optimized specifically for log analysis and time-series data.
Every custom detection rule starts with a query. This query interrogates the unified data model within Defender XDR. Tables like DeviceProcessEvents, DeviceNetworkEvents, and EmailEvents contain the raw breadcrumbs left by attackers. Your goal is to write a query that identifies a "bad" behavior while minimizing false positives. A well-constructed query in this context typically involves filtering for specific actions, joining data from multiple tables to correlate events, and summarizing data to identify anomalies over a specific time window.
Callout: The Power of KQL vs. Simple Thresholds Many legacy security tools rely on simple threshold-based alerting (e.g., "alert if failed logins > 10"). While useful, this is prone to high false-positive rates. KQL allows for context-aware detection. You can write queries that look for "failed logins" AND "the user is in the Finance group" AND "the source IP is from a known VPN exit node." This context-aware approach is what turns a simple log entry into a meaningful security incident.
Not read yet
Designing Your Custom Detection Rule
When you decide to build a custom rule, you should follow a structured engineering process. Do not simply jump into the console and start typing queries. Instead, approach it like a software development project.
Step 1: Define the Use Case
What is the specific threat you are trying to detect? Vague goals like "detect hackers" will result in poor rules. Instead, aim for specific behaviors. For example: "I want to be alerted if a user in the 'Domain Admins' group launches mimikatz.exe or any process associated with credential dumping."
Step 2: Test the Query in Advanced Hunting
Never create a rule without first running the query in the Advanced Hunting interface. This allows you to see the results in real-time, refine your filters, and ensure the query returns the data you expect without crashing or timing out.
Step 3: Refine for Performance
Microsoft Defender XDR has limits on how long a query can run. If your query is inefficient—for example, by scanning every single process event across your entire global fleet for the last 30 days—it may fail. Use project to select only the columns you need, and use where clauses at the beginning of your query to filter data as early as possible.
Not read yet
Step-by-Step: Creating a Custom Detection Rule
Once your query is finalized and tested, you can turn it into a rule. Follow these steps to ensure the alert is routed correctly and provides enough context for your analysts.
- Navigate to the Portal: Open the Microsoft Defender portal and go to Hunting > Advanced hunting.
- Input your Query: Paste your finalized KQL query into the query window and run it to verify the output.
- Create the Rule: Click on the Create detection rule button in the query toolbar.
- Define Alert Details:
- Alert Name: Choose a descriptive, actionable name. Avoid generic names like "Custom Alert 1." Instead, use "Unauthorized PowerShell Execution by Finance User."
- Severity: Assign a severity level based on your internal incident response policy.
- Category: Select the category that aligns with the MITRE ATT&CK framework if possible.
- Configure Mapping: This is the most critical step. Mapping allows Defender XDR to automatically link the alert to specific entities (Device, User, IP address). If you don't map these fields, your analysts will have to manually search for the device or user involved.
- Set Actions: Choose what happens when the rule triggers. You can configure the rule to automatically isolate a device or disable a user account, though use caution with automated responses.
Warning: Automation Risks Automated responses are powerful, but they can be dangerous. If your custom detection rule has a flaw and triggers a false positive, an automated action (like isolating a CEO's laptop) could cause significant business disruption. Always test your rules in "Log Only" mode for several days before enabling automated remediation.
Not read yet
Practical Examples of Custom Detections
To master this skill, you need to see how common threats are translated into logic. Below are three practical examples covering different aspects of the attack lifecycle.
Example 1: Detecting Malicious PowerShell Usage
Attackers frequently use encoded PowerShell commands to bypass static analysis. We can write a rule to flag any PowerShell execution where the command line contains -enc or -encodedcommand.
DeviceProcessEvents
| where FileName =~ "powershell.exe"
| where ProcessCommandLine has_any ("-enc", "-encodedcommand", "-e", "-en")
| project Timestamp, DeviceName, InitiatingProcessAccountName, ProcessCommandLine
| order by Timestamp desc
Explanation:
- We filter for
powershell.exespecifically. - We check the
ProcessCommandLinefor common flags used to obfuscate commands. - We output the timestamp, device, user, and the actual command line so the analyst can immediately see what was run.
Example 2: Detecting Lateral Movement via SMB
Attackers often use psexec or similar tools to move laterally. A common sign is the creation of a service on a remote machine.
DeviceEvents
| where ActionType == "ServiceInstallation"
| where FileName endswith ".exe"
| extend RemoteComputer = DeviceName
| join kind=inner (
DeviceNetworkEvents
| where ActionType == "ConnectionSuccess"
| where RemotePort == 445
) on DeviceName
| project Timestamp, DeviceName, RemoteIP, FileName
Explanation:
- This query joins
DeviceEvents(service installation) withDeviceNetworkEvents(SMB traffic). - It looks for correlations where a service was installed shortly after an SMB connection was established from a remote IP.
- This is a high-fidelity indicator of potential lateral movement.
Example 3: Detecting Data Exfiltration to Suspicious Domains
If you have a list of known "bad" or "uncategorized" domains, you can alert on any outbound traffic to these destinations.
DeviceNetworkEvents
| where RemoteUrl has_any (".xyz", ".top", ".ru")
| where ActionType == "ConnectionSuccess"
| summarize Count=count() by RemoteUrl, DeviceName
| where Count > 5
Explanation:
- This looks for successful connections to specific TLDs often associated with spam or phishing.
- We use
summarizeto count connections; this helps filter out occasional "noise" and focuses on persistent connections that might indicate a beaconing C2 (Command and Control) channel.
Not read yet
Best Practices for Rule Management
Managing custom rules is not a "set it and forget it" task. An effective security program requires constant curation.
1. Version Control
Treat your KQL queries like source code. Store them in a repository like GitHub or Azure DevOps. This allows you to track changes, revert to previous versions if a rule starts misbehaving, and collaborate with other team members.
2. The "Staging" Workflow
Never deploy a new rule directly into the "Production" category if your organization has a large footprint. Instead, create the rule, monitor the alerts in the Advanced Hunting dashboard for a week, and adjust the filters to remove false positives. Only when you are confident in the signal-to-noise ratio should you promote it to an active alert.
3. Regular Audits
Review your custom detection rules every quarter. If a rule has not fired in six months, it may be obsolete. If a rule is firing 500 times a day, it is likely misconfigured and is currently contributing to analyst burnout.
4. Entity Mapping is Mandatory
As mentioned earlier, always use the Entity Mapping section of the rule creation wizard. If the system knows that DeviceName maps to the "Device" entity and AccountName maps to the "User" entity, it can automatically populate the incident timeline. Without this, your analysts are flying blind.
Tip: Use Comments in KQL KQL supports comments using
//. Use these to explain why you are filtering for a specific process or string. When an analyst looks at the rule six months from now, they will appreciate the context regarding why this detection was created in the first place.
Not read yet
Common Pitfalls and How to Avoid Them
Even experienced security engineers fall into common traps when writing custom detections. Being aware of these will save you hours of troubleshooting.
The "Too Broad" Trap
Beginners often write queries that are too generic. For example, filtering for any process named cmd.exe will generate thousands of alerts in a typical enterprise. Always add context—look for cmd.exe being launched by a web server process, or cmd.exe being launched with unusual arguments.
The "Time Window" Blindness
Microsoft Defender XDR queries have a lookback period. If you are trying to correlate two events that happen 24 hours apart, a simple join might fail if your query scope is too short. Be mindful of the time range you are querying and ensure your logic accounts for the latency between events.
Ignoring Performance Limits
Defender XDR has a maximum execution time for queries. If you join massive tables without filtering them first, you will hit a timeout error. Always filter by time or specific device groups before performing a join operation.
| Pitfall | Consequence | Prevention Strategy |
|---|---|---|
| Overly Broad Filters | Alert Fatigue | Add context (user, process parent, command line) |
| Missing Entity Mapping | Slow Incident Response | Use the Mapping tab in the rule wizard |
| Hardcoding Values | Rigid Rules | Use parameters or lookups for dynamic data |
| Ignoring False Positives | Loss of Trust | Implement a 1-week "Log Only" testing phase |
Not read yet
Advanced Detection Techniques: Using Lookups and External Data
Sometimes, you need to cross-reference your telemetry against external data. For example, you might want to detect if any of your internal devices are communicating with IP addresses found in a threat intelligence feed provided by a third party.
Microsoft Defender XDR allows you to use externaldata in KQL. This is an advanced technique where you can pull in CSV or JSON files from an Azure Blob storage account or other accessible web endpoints.
let ThreatIntel = externaldata(IP:string, Severity:string)
[@"https://your-storage-account.blob.core.windows.net/threatfeeds/ips.csv"]
with (format="csv");
DeviceNetworkEvents
| join kind=inner (ThreatIntel) on $left.RemoteIP == $right.IP
| project Timestamp, DeviceName, RemoteIP, Severity
This allows you to keep your detection logic (the KQL query) static, while the threat intelligence (the list of IPs) is updated dynamically by your threat intel platform. This is the gold standard for maintaining a modern, responsive detection capability.
Not read yet
Integrating with Incident Response
A custom detection rule is only as good as the response it triggers. When designing your rule, think about the "incident" from the analyst's perspective.
When an alert fires, the analyst will land on the Incident page. If your rule is well-designed:
- The Alert Title clearly states the problem.
- The Description explains what to look for (e.g., "Check the parent process to see if this was a scheduled task").
- The Entities (User and Device) are automatically linked, allowing the analyst to click through to the device timeline to see what happened before and after the alert.
If you omit these details, the analyst must manually copy-paste data into other tools, which increases the "Mean Time to Respond" (MTTR). Always write your alert descriptions as if you are leaving a note for a colleague who is working on the case at 3:00 AM.
Best Practices for Alert Severity
A common mistake is marking every custom detection as "High" severity. If everything is high priority, nothing is. Use a tiered approach:
- Informational: Used for hunting and discovery, or rules that are still in the testing phase.
- Low: Used for anomalous behavior that could be malicious but is often legitimate (e.g., a user accessing a new cloud application).
- Medium: Used for suspicious activities that deviate from normal baselines (e.g., unusual PowerShell usage).
- High: Reserved for clear indicators of compromise (e.g., known malware signatures or unauthorized access to domain controllers).
Not read yet
Summary: A Checklist for Success
As you prepare to implement custom detection rules in your own Microsoft Defender XDR environment, keep this checklist handy to ensure you are following industry best practices:
- Codify the logic: Is the query written in KQL and tested in Advanced Hunting?
- Minimize noise: Have you added sufficient filters to avoid false positives?
- Map entities: Are you mapping the device, user, and IP address fields so they appear in the incident view?
- Document the "Why": Have you included comments in your KQL and a clear description in the alert settings?
- Phase the deployment: Is the rule running in "Log Only" mode for at least a few days before being turned into an active alert?
- Assign to a category: Does the rule align with the MITRE ATT&CK framework to help with reporting and gap analysis?
- Schedule reviews: Is there a process to audit these rules every quarter to ensure they are still relevant?
Not read yet
Key Takeaways
- Customization is Essential: Relying solely on default Microsoft detections leaves gaps in your security. Custom rules allow you to build detections tailored to your specific infrastructure, business applications, and threat profile.
- KQL is the Engine: Proficiency in Kusto Query Language is the single most important skill for a security analyst working with Defender XDR. Master the basics of filtering, joining, and summarizing data.
- The Power of Context: The most effective detections are context-aware. They don't just look for an action; they look for the right person performing the wrong action on the wrong machine.
- Staging is Non-Negotiable: Never push a new rule into production without testing it first. Use the "Log Only" approach to observe how the rule behaves against real-world traffic before enabling alerts and automated actions.
- Entity Mapping Saves Time: Always map your query results to system entities (User, Device, IP). This creates the link between raw data and the incident timeline, which is vital for fast, effective incident response.
- Maintain Your Ruleset: A "set it and forget it" approach leads to stale rules and alert fatigue. Treat your detections like software—version them, test them, and retire them when they are no longer useful.
- Collaborate and Document: Security is a team sport. Use comments in your queries and provide clear descriptions in your alert configurations so that other analysts understand the logic and know how to respond to the alerts you create.
By following these principles, you will move beyond simply reacting to alerts and begin proactively hunting and detecting threats that are specific to your environment. This is the difference between a reactive security stance and a resilient, mature security operations center.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
- Creating a Microsoft 365 Tenant
- Creating a Microsoft 365 Tenant Quiz5q
- Implementing and Managing Domains
- Implementing and Managing Domains Quiz5q
- Configuring Organization Settings
- Configuring Organization Settings Quiz5q
- Monitoring Microsoft 365 Service Health
- Monitoring Microsoft 365 Service Health Quiz5q
- Configuring Network Connectivity Insights
- Configuring Network Connectivity Insights Quiz5q
- Managing Software Updates in Microsoft 365
- Managing Software Updates in Microsoft 365 Quiz5q
- Monitoring Microsoft 365 Adoption and Usage
- Monitoring Microsoft 365 Adoption and Usage Quiz5q
- Configuring Microsoft 365 Backup
- Configuring Microsoft 365 Backup Quiz5q
- Creating and Managing Users in Microsoft Entra ID
- Creating and Managing Users in Microsoft Entra ID Quiz5q
- Managing External Users and Guest Access
- Managing External Users and Guest Access Quiz5q
- Creating and Managing Contacts
- Creating and Managing Contacts Quiz5q
- Creating and Managing Microsoft 365 Groups
- Creating and Managing Microsoft 365 Groups Quiz5q
- Managing Shared Mailboxes
- Managing Shared Mailboxes Quiz5q
- Managing Microsoft 365 Licenses
- Managing Microsoft 365 Licenses Quiz5q
- Performing Bulk User Management with PowerShell
- Performing Bulk User Management with PowerShell Quiz5q
- Implementing Group-Based Licensing
- Implementing Group-Based Licensing Quiz5q
- Implementing Roles in Microsoft 365
- Implementing Roles in Microsoft 365 Quiz5q
- Managing Microsoft Entra ID Roles
- Managing Microsoft Entra ID Roles Quiz5q
- Managing Permissions for Microsoft Defender XDR
- Managing Permissions for Microsoft Defender XDR Quiz5q
- Managing Delegation with Administrative Units
- Managing Delegation with Administrative Units Quiz5q
- Managing Roles with Privileged Identity Management
- Managing Roles with Privileged Identity Management Quiz5q
- Managing Microsoft Purview Permissions
- Managing Microsoft Purview Permissions Quiz5q
- Preparing for Identity Synchronization
- Preparing for Identity Synchronization Quiz5q
- Using IdFix for Directory Cleanup
- Using IdFix for Directory Cleanup Quiz5q
- Implementing Microsoft Entra Connect Sync
- Implementing Microsoft Entra Connect Sync Quiz5q
- Implementing Microsoft Entra Cloud Sync
- Implementing Microsoft Entra Cloud Sync Quiz5q
- Monitoring with Microsoft Entra Connect Health
- Monitoring with Microsoft Entra Connect Health Quiz5q
- Troubleshooting Synchronization Issues
- Troubleshooting Synchronization Issues Quiz5q
- Implementing Authentication Methods
- Implementing Authentication Methods Quiz5q
- Implementing Self-Service Password Reset
- Implementing Self-Service Password Reset Quiz5q
- Implementing Microsoft Entra Password Protection
- Implementing Microsoft Entra Password Protection Quiz5q
- Investigating Authentication Issues
- Investigating Authentication Issues Quiz5q
- Configuring Passwordless Authentication
- Configuring Passwordless Authentication Quiz5q
- Planning for Identity Protection
- Planning for Identity Protection Quiz5q
- Implementing Microsoft Entra Identity Protection
- Implementing Microsoft Entra Identity Protection Quiz5q
- Planning Conditional Access Policies
- Planning Conditional Access Policies Quiz5q
- Implementing Conditional Access Policies
- Implementing Conditional Access Policies Quiz5q
- Implementing Multifactor Authentication
- Implementing Multifactor Authentication Quiz5q
- Configuring Named Locations
- Configuring Named Locations Quiz5q
- Understanding Microsoft Security Exposure Management
- Understanding Microsoft Security Exposure Management Quiz5q
- Managing Microsoft Secure Score
- Managing Microsoft Secure Score Quiz5q
- Reviewing and Responding to Incidents
- Reviewing and Responding to Incidents Quiz5q
- Using Advanced Hunting in Defender XDR
- Using Advanced Hunting in Defender XDR Quiz5q
- Reviewing Defender XDR Reports
- Reviewing Defender XDR Reports Quiz5q
- Using Microsoft Defender Threat Intelligence
- Using Microsoft Defender Threat Intelligence Quiz5q
- Configuring Custom Detection Rules
- Configuring Custom Detection Rules Quiz5q
- Implementing Threat Policies in Defender for Office 365
- Implementing Threat Policies in Defender for Office 365 Quiz5q
- Configuring Alert Policies
- Configuring Alert Policies Quiz5q
- Investigating Email and Collaboration Threats
- Investigating Email and Collaboration Threats Quiz5q
- Managing Attack Simulation Training
- Managing Attack Simulation Training Quiz5q
- Managing Restricted Entities
- Managing Restricted Entities Quiz5q
- Onboarding Devices to Defender for Endpoint
- Onboarding Devices to Defender for Endpoint Quiz5q
- Configuring Endpoint Settings
- Configuring Endpoint Settings Quiz5q
- Using Vulnerability Management Dashboard
- Using Vulnerability Management Dashboard Quiz5q
- Responding to Endpoint Vulnerabilities
- Responding to Endpoint Vulnerabilities Quiz5q
- Managing Automated Investigation and Remediation
- Managing Automated Investigation and Remediation Quiz5q
- Configuring App Connector for Microsoft 365
- Configuring App Connector for Microsoft 365 Quiz5q
- Configuring Cloud Apps Policies
- Configuring Cloud Apps Policies Quiz5q
- Interpreting Activity Logs
- Interpreting Activity Logs Quiz5q
- Configuring Cloud App Discovery
- Configuring Cloud App Discovery Quiz5q
- Responding to Cloud App Discovery Issues
- Responding to Cloud App Discovery Issues Quiz5q
- Implementing Sensitive Information Types
- Implementing Sensitive Information Types Quiz5q
- Using Keywords and Regular Expressions
- Using Keywords and Regular Expressions Quiz5q
- Implementing Retention Labels and Policies
- Implementing Retention Labels and Policies Quiz5q
- Implementing Sensitivity Labels and Policies
- Implementing Sensitivity Labels and Policies Quiz5q
- Monitoring Label Usage with Content Explorer
- Monitoring Label Usage with Content Explorer Quiz5q
- Using Activity Explorer and Label Reports
- Using Activity Explorer and Label Reports Quiz5q
- Configuring Auto-Labeling Policies
- Configuring Auto-Labeling Policies Quiz5q
- Configuring DLP Policies for Exchange Online
- Configuring DLP Policies for Exchange Online Quiz5q
- Configuring DLP for SharePoint and OneDrive
- Configuring DLP for SharePoint and OneDrive Quiz5q
- Configuring DLP for Teams and Power BI
- Configuring DLP for Teams and Power BI Quiz5q
- Configuring DLP for Microsoft 365 Copilot
- Configuring DLP for Microsoft 365 Copilot Quiz5q
- Configuring Endpoint DLP
- Configuring Endpoint DLP Quiz5q
- Reviewing DLP Alerts and Events
- Reviewing DLP Alerts and Events Quiz5q
- Responding to DLP Reports
- Responding to DLP Reports Quiz5q
Spend your points to unlock exam-style practice questions
Spend points to unlock MS-102 exam-style practice questions.
Practice for MS-102