Listen to this Post

Introduction:
The modern cybersecurity landscape is a relentless hunt, where defenders must proactively seek out threats before they cause damage. Microsoft Defender for Office 365 offers a powerful, yet often underutilized, capability for this very purpose: custom detection rules. This guide will transform you from a passive alert monitor into an active threat hunter, leveraging Kusto Query Language (KQL) to uncover sophisticated attacks hiding in your email and collaboration data.
Learning Objectives:
- Master the core concepts of KQL to craft precise hunting queries.
- Learn to create and deploy custom detection rules for persistent threat monitoring.
- Develop the skills to analyze query results and respond to advanced email-based threats.
You Should Know:
- The Foundation: Understanding the Unified Audit Log and KQL
To begin hunting, you need access to data. The Unified Audit Log in Microsoft Purview is the treasure trove. Before you can run advanced hunts, you must enable it. Once active, you can query it using KQL from the Microsoft 365 Defender portal.
Step-by-step guide:
- Enable Unified Audit Log: Navigate to the Microsoft Purview compliance portal > Solutions > Audit. Ensure it is turned on. This process can take several hours to complete.
- Access Advanced Hunting: Go to the Microsoft 365 Defender portal (security.microsoft.com) and select “Advanced Hunting” from the left menu.
- Craft a Basic Query: Start with a simple query to understand the data schema. The `EmailEvents` table is a great starting point for Office 365 hunting.
// Basic query to examine recent emails EmailEvents | where Timestamp > ago(7d) | top 100 by Timestamp desc | project Timestamp, SenderFromAddress, RecipientEmailAddress, Subject, ActionType
This query retrieves the 100 most recent email events from the past week, displaying key fields. The `project` operator is used to specify which columns to return, keeping the output clean and focused.
2. Hunting for Phishing: Identifying Suspicious Sender Domains
Attackers often register domains with subtle typos to impersonate legitimate organizations (e.g., micorsoft.com). We can hunt for this using KQL’s string operators.
KQL Snippet:
// Hunt for potential typosquatting sender domains EmailEvents | where Timestamp > ago(1d) | where ActionType has "EmailDelivery" | extend SenderDomain = tostring(split(SenderFromAddress, "@")[bash]) | where SenderDomain contains "micorsoft" or SenderDomain contains "g00gle" or SenderDomain contains "appple" | project Timestamp, SenderFromAddress, SenderDomain, RecipientEmailAddress, Subject
Step-by-step guide:
- The query filters for successfully delivered emails from the last day.
- The `extend` operator creates a new column,
SenderDomain, by splitting the sender’s email address on the “@” symbol and taking the second part. - The `where` clause uses the `contains` operator to look for common misspellings in the domain name. This list should be customized and expanded based on your company’s common correspondents.
- Results are projected for easy analysis. Any hits from this query should be investigated immediately.
3. Detecting Internal Account Compromise with MailForwarding
A common sign of a compromised mailbox is the automatic forwarding of emails to an external address. This can be set by an attacker to exfiltrate data.
KQL Snippet:
// Hunt for mailbox forwarding rules to external domains CloudAppEvents | where Timestamp > ago(7d) | where ActionType == "New-InboxRule" | where RawEventData has "ForwardTo" or RawEventData has "RedirectTo" | extend ForwardTo = tostring(parse_json(RawEventData).Parameters.Value[bash].Address) | where ForwardTo contains "@" | extend ForwardDomain = tostring(split(ForwardTo, "@")[bash]) | where ForwardDomain !endswith "yourcompany.com" // Replace with your actual domain | project Timestamp, AccountDisplayName, ActionType, ForwardTo, IPAddress, Device
Step-by-step guide:
- This query searches the `CloudAppEvents` table for the creation of new inbox rules.
- It filters for rules that contain “ForwardTo” or “RedirectTo” in their configuration.
- It parses the JSON `RawEventData` to extract the target email address.
- A critical step: it checks if the forwarding domain does NOT end with your company’s domain (
!endswith "yourcompany.com"), indicating a potential exfiltration attempt. -
Weaponized Attachments: Hunting for Macro-Enabled and Archive Files
Attackers deliver malware via email attachments, often hiding them within archive files or using macro-enabled documents.
KQL Snippet:
// Hunt for emails with high-risk attachment file types
EmailAttachmentInfo
| where Timestamp > ago(2d)
| where FileType has_any ("docm", "xlsm", "pptm", "zip", "rar", "7z", "js", "vbs", "wsf")
| where FileName !startswith "~" // Filter out temporary files
| join (EmailEvents | where ActionType == "EmailDelivery") on NetworkMessageId
| project Timestamp, Subject, SenderFromAddress, RecipientEmailAddress, FileName, FileType, SHA256
| top 500 by Timestamp desc
Step-by-step guide:
- The query starts in the `EmailAttachmentInfo` table, looking for specific, high-risk file types.
- It filters out temporary files (which often start with “~”) to reduce noise.
- It performs a `join` with the `EmailEvents` table using the `NetworkMessageId` to get details about the email that delivered the attachment.
- The results provide a comprehensive view of who sent and received the potentially malicious file, along with its hash for further investigation.
-
From Hunting to Automated Detection: Creating a Custom Detection Rule
The true power of Advanced Hunting is turning a reactive query into a proactive, automated alert. This is where Custom Detection Rules come in.
Step-by-step guide:
- In the Advanced Hunting page, craft and validate your query (e.g., the typosquatting query from section 2).
2. Click the “Create detection rule” button.
- Define Alert Details: Give the rule a name (e.g., “Potential Typosquatting Domain Detected”), description, and severity level (e.g., Medium or High).
- Set Actions: Configure what happens when the alert triggers. This can include:
Sending an email notification to your SOC.
Running an automated remediation action (if available and appropriate).
5. Scope the Rule: Determine if it applies to all users or a specific group.
6. Review and Create. The rule will now run on a scheduled basis, and any results will generate an alert in the Incidents queue, allowing for swift triage and response.
6. Cloud Hardening: Checking for Risky Mailbox Permissions
Beyond email content, the permissions on mailboxes themselves can be a risk. Overly permissive “Send As” or “Full Access” permissions can be abused.
KQL Snippet:
// Hunt for non-standard mailbox permissions OfficeActivity | where Timestamp > ago(30d) | where Operation == "Add-MailboxPermission" or Operation == "Add-RecipientPermission" | extend Parameters = parse_json(RawEventData).Parameters | extend User = tostring(Parameters.[bash].Value.User) | extend GrantingUser = tostring(Parameters.[bash].Value) | extend Permissions = tostring(Parameters.[bash].Value.AccessRights) | where GrantingUser != "NT AUTHORITY\SELF" and GrantingUser !contains "Admin" // Filter out common self-assignments and admin accounts | project Timestamp, Operation, User, GrantingUser, Permissions, ClientIP
Step-by-step guide:
- This query scans the `OfficeActivity` log for events where mailbox permissions are added.
- It parses the complex `Parameters` JSON to extract the user being granted permissions, the user granting them, and the specific rights.
- The `where` clause filters out common, low-risk events, such as a user granting themselves permissions or actions performed by known admin accounts. This helps focus on anomalous permission changes that could indicate insider threat or lateral movement.
7. API Security: Auditing Mailbox Access via PowerShell
Many attacks leverage PowerShell to interact with Exchange Online remotely. Auditing these actions is crucial for detecting compromise.
KQL Snippet:
// Hunt for suspicious PowerShell-based mailbox access OfficeActivity | where Timestamp > ago(1d) | where OfficeWorkload == "Exchange" | where Operation startswith "New-InboxRule" or Operation startswith "Set-Mailbox" or Operation startswith "Get-Mailbox" | where LogonUserSid != "S-1-5-18" // Filter out system account | project Timestamp, UserId, Operation, ClientIP, LogonUserSid, ObjectId | summarize Count=count() by UserId, Operation, ClientIP, bin(TimeStamp, 1h) | where Count > 5 // Look for bursts of activity
Step-by-step guide:
- This query focuses on `OfficeActivity` from the Exchange workload, specifically targeting PowerShell cmdlets that manipulate or access mailboxes.
- It filters out the default system account to reduce noise.
- The `summarize` operator is used to count the number of times a specific user, from a specific IP, performed a specific operation within a one-hour window.
- Finally, it filters for bursts of activity (e.g.,
Count > 5), which could indicate automated tooling or an attacker conducting reconnaissance.
What Undercode Say:
- Proactivity is Paramount. The shift from monitoring pre-defined alerts to actively writing custom detections represents the evolution from a SOC analyst to a true cyber defender. It closes the gap between a new attack technique and your ability to see it.
- Context is King. A powerful KQL query is useless without the analytical skill to interpret its results. A mail forward to an external domain might be legitimate (e.g., a consultant forwarding work to their personal address), so investigation and correlation with other signals are critical.
The analysis provided by Microsoft’s experts highlights a fundamental truth: the defender’s advantage lies in leveraging their unique knowledge of the environment. While Microsoft provides robust default protections, they cannot know that an attacker is registering a domain that looks like your specific law firm’s partner. Custom detection rules are the mechanism to encode that domain-specific knowledge into your security apparatus, creating a defensive posture that is dynamic, intelligent, and tailored to your actual threat landscape. This moves security from a generic shield to a personalized immune system.
Prediction:
The sophistication of Business Email Compromise (BEC) and supply-chain phishing attacks will continue to escalate, making default security configurations increasingly insufficient. The future of effective defense will belong to organizations that institutionalize threat hunting and codify their intelligence into automated custom detections. We will see a growing “detection-as-code” movement, where KQL and similar languages become core skills for security professionals. Furthermore, AI will augment this process, suggesting hunting hypotheses and auto-generating complex queries, but the human hunter’s intuition and contextual knowledge will remain the irreplaceable core of uncovering the most stealthy and targeted threats.
🎯Let’s Practice For Free:
IT/Security Reporter URL:
Reported By: Monaghadiri Microsoft – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


