Advanced ⏱ 150 min 📋 16 Steps

Deploy and Tune Endpoint Detection Policies

Build a comprehensive, layered detection policy stack in Microsoft Defender for Endpoint. Configure next-generation antivirus, EDR in block mode, custom indicators of compromise, RBAC for SOC tiers, automated investigation levels, web content filtering, device control, tamper protection, network protection, and custom detection rules with KQL.

📋 Overview

About This Lab

Microsoft Defender for Endpoint provides a rich set of configurable detection and response policies that work together as a layered defense stack. This lab covers end-to-end deployment: next-generation antivirus via Intune, EDR in block mode, custom indicators, RBAC, and automated investigation and response (AIR). You will also configure supporting protections: web content filtering, device control for removable media, tamper protection, and network protection. Finally, you will build custom detection rules using KQL and validate the entire policy stack with simulated attacks.

🏢 Enterprise Use Case

Scenario: A global financial services firm operates 15,000 endpoints across North America, Europe, and Asia-Pacific.

The CISO has mandated a unified detection policy framework that balances security coverage with operational stability. SOC Tier 1 analysts need read-only access, Tier 2 analysts need response capabilities, and Tier 3 engineers need full configuration access. Regulatory requirements (PCI-DSS, SOX, GDPR) mandate USB device control, web filtering, and automated investigation documentation.

Success criteria: zero policy gaps across all device groups, RBAC aligned to SOC tiers, automated investigation enabled for high-confidence alerts, and a detection effectiveness dashboard.

🎯 What You Will Learn

  1. How MDE's detection architecture layers next-gen AV, EDR behavioral sensors, and cloud-delivered protection
  2. How to deploy and configure antivirus policies through Microsoft Intune
  3. How to enable EDR in block mode for post-breach detection on devices running third-party AV
  4. How to create custom indicators of compromise for files, IPs, URLs, and certificates
  5. How to implement RBAC with device group scoping for multi-tier SOC operations
  6. How to set automated investigation and response levels per device group
  7. How to build custom detection rules and a detection effectiveness dashboard using KQL

🔑 Why This Matters

Misconfigured detection policies are the leading cause of alert blind spots; organizations frequently deploy MDE without tuning defaults. Layered detection reduces dwell time: next-gen AV catches known threats, EDR catches behavioral anomalies, and custom rules target organization-specific risks. RBAC enforcement ensures least-privilege access, preventing accidental or unauthorized configuration changes in production. Automated investigation accelerates mean time to respond (MTTR) by eliminating manual triage for high-confidence alerts.

⚙️ Prerequisites

  • Licensing: Microsoft Defender for Endpoint Plan 2 (or Microsoft 365 E5 / E5 Security)
  • Intune: Microsoft Intune with endpoint security policy permissions for antivirus and EDR configuration
  • Devices: At least two Windows 10/11 devices onboarded to MDE with healthy sensor status
  • Portal Access: Global Administrator or Security Administrator role in security.microsoft.com
  • RBAC: Azure AD Security groups for SOC Tier 1, Tier 2, and Tier 3 roles
  • Advanced Hunting: Familiarity with KQL syntax for building custom detection rules
  • Network: Outbound HTTPS (443) connectivity to MDE cloud service URLs
  • Prior Labs: Completion of MDE Lab 01 (Onboarding), Lab 02 (ASR Rules), and Lab 03 (Ransomware Investigation) is recommended
⚠️ Important: Policy changes affect all devices in the targeted device groups. Always test new detection policies on a pilot device group before deploying to production. Use Intune scope tags and device group targeting to control rollout.

Step 1 · Review MDE Detection Architecture

Before configuring policies, understand how MDE's detection layers work together. Each layer addresses a different phase of the threat lifecycle.

Detection Layer Stack

  • Next-Generation Antivirus (NGAV): Signature-based and heuristic scanning with cloud-delivered machine learning models for real-time file verdicts
  • Behavioral Sensors: Kernel-level sensors that monitor process creation, registry modifications, network connections, and file system changes in real time
  • EDR (Endpoint Detection and Response): Post-breach detection that records full telemetry and enables advanced hunting, custom detections, and automated investigation
  • Cloud-Delivered Protection: Files are detonated in Microsoft's cloud sandbox for rapid classification; block-at-first-sight stops unknown threats within seconds
  • Custom Indicators: Organization-specific IoCs (file hashes, IPs, URLs, certificates) that extend detection beyond global threat intelligence
  • Attack Surface Reduction (ASR): Pre-breach rules that block common attack techniques before they execute

Verify Current Configuration with PowerShell

# ---------------------------------------------------------
# WHAT: Audit the current Defender AV configuration on a device
# WHY:  Before deploying new detection policies, baseline what's
#       already configured. Inconsistencies across devices indicate
#       policy gaps or conflicting Intune/GPO configurations.
# ---------------------------------------------------------

# Review protection settings
# DisableRealtimeMonitoring: $false = real-time scanning ON (required)
# DisableBehaviorMonitoring: $false = behavior detection ON (required)
# MAPSReporting: 0=Off, 1=Basic, 2=Advanced (target: 2 for full cloud)
# SubmitSamplesConsent: 0=Prompt, 1=Safe, 2=Never, 3=All (target: 3)
# CloudBlockLevel: 0=Default, 2=High, 4=High+, 6=Zero tolerance
# CloudExtendedTimeout: Seconds to wait for cloud verdict (target: 50)
# EnableNetworkProtection: 0=Off, 1=Block, 2=Audit
# EnableControlledFolderAccess: 0=Off, 1=Block, 2=Audit
# PUAProtection: 0=Off, 1=Block, 2=Audit
Get-MpPreference | Select-Object `
    DisableRealtimeMonitoring,
    DisableBehaviorMonitoring,
    MAPSReporting,
    SubmitSamplesConsent,
    CloudBlockLevel,
    CloudExtendedTimeout,
    EnableNetworkProtection,
    EnableControlledFolderAccess,
    PUAProtection

# Check AV engine and signature versions
# WHY: Outdated engines may lack detection capabilities for new threats.
# AMProductVersion = Defender platform version (e.g., 4.18.x)
# AMEngineVersion = AV engine version (updated with platform)
# AntispywareSignatureVersion = signature/definition version
# AntivirusSignatureLastUpdated = should be within last 24 hours
Get-MpComputerStatus | Select-Object `
    AMProductVersion,
    AMEngineVersion,
    AntispywareSignatureVersion,
    AntivirusSignatureLastUpdated,
    RealTimeProtectionEnabled,
    BehaviorMonitorEnabled
💡 Pro Tip: Run the Get-MpPreference command on several devices across different groups. Inconsistencies indicate policy gaps or conflicting Intune configurations. Document baseline settings before making changes.

Step 2 · Configure Next-Generation Antivirus Policies via Intune

Deploy a centrally managed antivirus policy through Microsoft Intune to ensure consistent protection settings across all endpoint groups.

Create an Antivirus Policy in Intune

  1. Navigate to intune.microsoft.com > Endpoint security > Antivirus
  2. Click + Create policy and select Platform: Windows 10, Windows 11, and Windows Server
  3. Select the Microsoft Defender Antivirus profile type
  4. Name the policy (e.g., "MDE-NGAV-Production") and add a description
  5. Configure the following recommended settings:

Recommended NGAV Settings

  • Real-time protection: Enabled
  • Behavior monitoring: Enabled
  • Scan all downloaded files and attachments: Enabled
  • Scan scripts that are used in Microsoft browsers: Enabled
  • Scan network files: Enabled
  • Scan removable drives during full scan: Enabled
  • PUA (Potentially Unwanted Application) protection: Block
  • Action against detected threats: Quarantine for Severe and High; Remove for Medium and Low
  1. Under Assignments, target a pilot device group first
  2. Click Review + Create to deploy the policy
  3. Monitor deployment status under Endpoint security > Antivirus > select the policy > Device status
💡 Pro Tip: Create separate antivirus profiles for servers and workstations. Server workloads may require scan exclusions for SQL, IIS, or Exchange directories to prevent performance degradation.

Step 3 · Enable Cloud-Delivered Protection and Automatic Sample Submission

Cloud-delivered protection sends suspicious files to Microsoft's cloud for detonation and machine learning analysis. Block-at-first-sight stops unknown threats within seconds of first encounter.

Configure Cloud Protection in Intune

  1. In the antivirus policy you created, navigate to Cloud protection settings
  2. Set Cloud-delivered protection level to High+ (the most aggressive level)
  3. Set Cloud extended timeout to 50 seconds (allows more time for cloud analysis)
  4. Set Submit samples consent to Send all samples automatically
  5. Ensure Block at first sight is enabled (requires cloud-delivered protection and automatic sample submission)

Verify Cloud Protection with PowerShell

# ---------------------------------------------------------
# WHAT: Verify and configure cloud-delivered protection settings
# WHY:  Cloud protection sends suspicious files to Microsoft's
#       detonation sandbox for ML analysis. Block-at-first-sight
#       stops zero-day threats within seconds of first encounter.
# ---------------------------------------------------------

# Verify current cloud protection settings
Get-MpPreference | Select-Object `
    MAPSReporting,
    SubmitSamplesConsent,
    CloudBlockLevel,
    CloudExtendedTimeout

# EXPECTED VALUES for maximum protection:
# MAPSReporting          : 2 (Advanced) - sends full file metadata to cloud
# SubmitSamplesConsent   : 3 (Send all samples automatically)
# CloudBlockLevel        : 6 (High+ / Zero Tolerance) - most aggressive blocking
# CloudExtendedTimeout   : 50 (seconds to wait for cloud verdict before allowing)

# Configure directly via PowerShell if Intune policy hasn't applied yet
# NOTE: Intune-managed settings will override these on next policy sync.
Set-MpPreference -MAPSReporting Advanced
Set-MpPreference -SubmitSamplesConsent SendAllSamples
Set-MpPreference -CloudBlockLevel 6
Set-MpPreference -CloudExtendedTimeout 50
⚠️ Important: Some organizations restrict automatic sample submission due to data sensitivity. If your organization handles classified data, set SubmitSamplesConsent to "Send safe samples automatically" and review the implications with your data governance team.

Step 4 · Configure EDR in Block Mode

EDR in block mode allows MDE to take automated blocking and remediation actions on post-breach detections, even when a third-party antivirus is installed. It acts as a safety net when the primary AV misses a threat.

Enable EDR in Block Mode

  1. Navigate to security.microsoft.com > Settings > Endpoints > General > Advanced features
  2. Locate EDR in block mode and toggle it to On
  3. Click Save preferences
  4. Changes apply automatically; no device restart required

How EDR in Block Mode Works

  • When Microsoft Defender Antivirus is the primary AV: EDR block mode provides an additional layer; behavioral detections are automatically remediated
  • When a third-party AV is installed: Microsoft Defender AV runs in passive mode, but EDR block mode can still block and remediate threats detected by EDR behavioral sensors
  • Blocked artifacts appear in the Action center with the source "EDR in block mode"

Query EDR Block Events with KQL

// ---------------------------------------------------------
// WHAT: Find all EDR in block mode remediation actions
// WHY:  EDR block mode acts as a safety net - it blocks threats
//       that the primary AV missed, using behavioral detection.
//       Tracking these events quantifies the value of EDR block mode.
// TABLE: DeviceEvents - ActionType "AntivirusDetection" with
//        IsEdrInBlockMode flag in AdditionalFields.
// KEY FIELDS:
//   ThreatName = the malware family/variant detected post-breach
//   WasRemediated = whether the threat was successfully cleaned
//   IsEdrBlockMode = true when EDR (not AV) triggered the block
// OUTPUT: Threat names ranked by block count - evidence that
//         EDR block mode is catching threats the primary AV missed.
// ---------------------------------------------------------
DeviceEvents
| where Timestamp > ago(30d)
| where ActionType == "AntivirusDetection"
| extend ParsedFields = parse_json(AdditionalFields)
| extend ThreatName = tostring(ParsedFields.ThreatName),
    WasRemediated = tobool(ParsedFields.WasRemediated),
    IsEdrBlockMode = tobool(ParsedFields.IsEdrInBlockMode)
| where IsEdrBlockMode == true
| summarize BlockedCount = count(),
    UniqueThreats = dcount(ThreatName),
    AffectedDevices = dcount(DeviceName)
    by ThreatName, WasRemediated
| sort by BlockedCount desc
💡 Pro Tip: EDR in block mode is especially valuable during antivirus migrations. When transitioning from a third-party AV to Microsoft Defender, EDR block mode provides immediate post-breach coverage while the primary AV transition completes.

Step 5 · Create Custom Indicators of Compromise (IoCs)

Custom indicators extend MDE detection beyond global threat intelligence. Create organization-specific blocks or alerts for known-bad file hashes, IP addresses, URLs, and certificates.

Create File Hash Indicators

  1. Navigate to Settings > Endpoints > Indicators > File hashes
  2. Click + Add item
  3. Enter the SHA-256 hash of the known-malicious file
  4. Set the action: Alert and block (prevents execution and generates an alert)
  5. Set severity, title, and description for SOC context
  6. Optionally scope the indicator to specific device groups
  7. Set an expiration date for time-limited threat campaigns

Create Network Indicators (IPs and URLs)

  1. Navigate to Indicators > IP addresses or URLs/domains
  2. Add the indicator value (e.g., a command-and-control IP or phishing domain)
  3. Set the action: Alert and block, Alert only, or Allowed
  4. For URL indicators, network protection must be enabled on endpoints (Step 12)

Create Certificate Indicators

  1. Navigate to Indicators > Certificates
  2. Enter the certificate thumbprint (SHA-1)
  3. Use certificate indicators to block or alert on binaries signed by compromised or revoked certificates

Query Custom Indicator Hits

// ---------------------------------------------------------
// WHAT: Find all alerts triggered by custom indicators (IoCs)
// WHY:  Measures the effectiveness of your organization-specific
//       threat intelligence - custom file hashes, IPs, URLs, and
//       certificates that you imported into MDE.
// TABLES: AlertInfo (alert metadata) joined with AlertEvidence
//         (files, processes, IPs associated with the alert).
// DETECTION SOURCES:
//   "CustomDetection" = KQL custom detection rules
//   "CustomerTI" = Custom Indicators (file hash, IP, URL, cert)
// OUTPUT: Which indicators are hitting, how often, and severity.
//         Low hit counts may indicate stale IoCs that need removal.
// ---------------------------------------------------------
AlertInfo
| where Timestamp > ago(30d)
| where DetectionSource == "CustomDetection"
    or DetectionSource == "CustomerTI"
| join kind=inner AlertEvidence on AlertId
| summarize HitCount = count(),
    AffectedDevices = dcount(DeviceId),
    IndicatorValues = make_set(FileName)
    by Title, Severity, DetectionSource
| sort by HitCount desc
💡 Pro Tip: Integrate custom indicators with your threat intelligence platform. Use the MDE Indicators API to automate the import of IoCs from STIX/TAXII feeds, MISP, or your internal TI team's watchlists.

Step 6 · Configure Device Groups with Tag-Based Membership

Device groups determine how policies, RBAC permissions, and automated investigation levels are applied. Use tag-based membership for dynamic, scalable grouping.

Create Device Groups

  1. Navigate to Settings > Endpoints > Permissions > Device groups
  2. Click + Add device group
  3. Name the group (e.g., "Finance-Workstations", "IT-Servers", "Executive-Devices")
  4. Set the Automation level (covered in Step 8)
  5. Under Members, select Tag as the membership type
  6. Enter the device tag value (e.g., "Finance", "IT-Servers", "VIP")
  7. Add Azure AD user groups that should have access to this device group
  8. Click Done and repeat for each required group

Apply Tags to Devices

  • Portal: Navigate to the device page > click Manage tags > add the tag
  • Intune: Use device configuration profiles to assign tags via registry keys
  • API: Use the MDE Machine API to programmatically tag devices at scale
  • Group Policy: Set the registry value HKLM\SOFTWARE\Policies\Microsoft\Windows Advanced Threat Protection\DeviceTagging\Group
💡 Pro Tip: Align device group naming with your organizational structure. Finance, HR, Engineering, and IT-Servers groups enable granular policy targeting and simplify RBAC scoping in Step 7.

Step 7 · Implement Role-Based Access Control (RBAC) for SOC Tiers

RBAC ensures that SOC analysts only access the devices and actions appropriate for their tier. This prevents configuration drift and supports audit compliance.

Enable RBAC

  1. Navigate to Settings > Endpoints > Permissions > Roles
  2. Click Turn on roles to activate the RBAC engine
  3. Once activated, only users with assigned roles can access portal features

Create SOC Tier Roles

  • Tier 1 (Triage Analyst): View data, manage alerts, use Live Response (basic). Permissions: View data. Security operations. Assigned device groups: All
  • Tier 2 (Incident Responder): All Tier 1 permissions plus active remediation actions (isolate, collect investigation package, stop and quarantine). Permissions: Active remediation actions. Assigned device groups: All
  • Tier 3 (Security Engineer): All permissions including manage security settings, manage portal system settings, and manage endpoint security policies. Assigned device groups: All

Create a Role

  1. Click + Add role
  2. Enter the role name (e.g., "SOC-Tier1-Triage")
  3. Select the appropriate permissions for the tier
  4. Under Assigned user groups, map to the Azure AD security group (e.g., "SG-SOC-Tier1")
  5. Under Assigned device groups, select which device groups this role can access
  6. Click Save role
⚠️ Important: After enabling RBAC, any user without an assigned role loses portal access. Ensure at least one Global Administrator or Security Administrator retains full access before activation.

Step 8 · Configure Automated Investigation and Response (AIR) Levels

Automated Investigation and Response enables MDE to automatically investigate alerts and remediate threats without analyst intervention. Configure the automation level per device group based on risk tolerance.

Automation Levels

  • Full. remediate threats automatically: All remediation actions execute without approval. Best for standard workstations
  • Semi. require approval for core folders: Actions on system-critical folders require analyst approval; others remediate automatically
  • Semi. require approval for non-temp folders: Actions on non-temporary folders require approval
  • Semi. require approval for any remediation: All remediation actions require analyst approval. Best for executive or VIP devices
  • No automated response: Investigation runs but no actions are taken. Use only for troubleshooting

Set Automation Level per Device Group

  1. Navigate to Settings > Endpoints > Permissions > Device groups
  2. Select the device group to configure
  3. Set the Remediation level to the desired automation level
  4. Recommended mapping: Standard workstations = Full, Servers = Semi (core folders), VIP/Executive = Semi (any remediation)

Query Automated Investigation Results

// ---------------------------------------------------------
// WHAT: Review automated investigation (AIR) outcomes by severity
// WHY:  Measures how effectively AIR is handling alerts without
//       human intervention. A high AutoRemediationRate indicates
//       well-tuned automation; low rates suggest configuration gaps.
// TABLES: AlertInfo joined with AlertEvidence on AlertId.
// KEY FIELDS:
//   AttackTechniques: MITRE ATT&CK techniques (non-empty = mapped)
//   RemediationStatus: "Remediated" | "PendingApproval" | "Failed"
// LOGIC: Calculates auto-remediation rate as a percentage.
//        Target: > 80% for standard workstation device groups.
// OUTPUT: One row per severity level with counts and rates.
//         PendingApproval build-up = need more Tier 2 analysts or
//         adjust automation level to "Full" for that device group.
// ---------------------------------------------------------
AlertInfo
| where Timestamp > ago(30d)
| where isnotempty(AttackTechniques)
| join kind=inner (
    AlertEvidence
    | where Timestamp > ago(30d)
    | where isnotempty(RemediationStatus)
    ) on AlertId
| summarize TotalAlerts = dcount(AlertId),
    AutoRemediated = dcountif(AlertId, RemediationStatus == "Remediated"),
    PendingApproval = dcountif(AlertId, RemediationStatus == "PendingApproval"),
    Failed = dcountif(AlertId, RemediationStatus == "Failed")
    by Severity
| extend AutoRemediationRate = round(100.0 * AutoRemediated / TotalAlerts, 1)
| sort by Severity
💡 Pro Tip: Monitor the Action center daily to review pending approval actions. A build-up of pending actions indicates either overly conservative automation levels or a need for additional Tier 2 analysts to handle the approval queue.

Step 9 · Set Up Web Content Filtering

Web content filtering blocks access to websites based on category, reducing attack surface from drive-by downloads, phishing sites, and malicious content hosting.

Enable Web Content Filtering

  1. Navigate to Settings > Endpoints > General > Advanced features
  2. Ensure Web content filtering is toggled On
  3. Navigate to Settings > Endpoints > Rules > Web content filtering
  4. Click + Add policy
  5. Name the policy (e.g., "WCF-Corporate-Standard")
  6. Select categories to block. Recommended security-focused categories:

Recommended Block Categories

  • Malware: Sites confirmed to host malware
  • Phishing: Sites designed to steal credentials
  • Newly registered domains: Domains registered within the past 30 days (high risk)
  • Parked domains: Domains with no active content (often used for malware staging)
  • Hacking: Sites providing hacking tools, exploits, or instructions
  • Command and control: Known C2 infrastructure
  1. Under scope, select the device groups to target
  2. Click Save to deploy the policy
💡 Pro Tip: Web content filtering requires network protection to be enabled in block mode (Step 12). Without network protection, web content filtering only works on Microsoft Edge. Enabling network protection extends coverage to all browsers and third-party applications.

Step 10 · Configure Device Control (USB and Removable Media Policies)

Device control restricts USB and removable media access to prevent data exfiltration and block USB-based malware delivery. Configure granular policies that allow approved devices while blocking unauthorized ones.

Configure Device Control via Intune

  1. Navigate to intune.microsoft.com > Endpoint security > Attack surface reduction
  2. Click + Create policy > Platform: Windows 10, Windows 11, and Windows Server > Device control
  3. Name the policy (e.g., "DC-Block-Unauthorized-USB")
  4. Configure removable storage access control rules

Recommended Device Control Settings

  • Default enforcement: Deny all removable storage devices
  • Allow list: Create exceptions for approved USB vendor IDs (e.g., corporate-issued encrypted drives)
  • Read-only access: Allow read access but block write operations for specific device groups
  • Audit mode: Log removable media usage without blocking (useful for initial deployment)

PowerShell: Review Device Control Events

# ---------------------------------------------------------
# WHAT: Review device control events for USB/removable media
# WHY:  Device control policies generate events when users connect
#       removable storage devices. Monitoring these events helps
#       validate policy enforcement and detect shadow IT.
# EVENT IDs in the Defender Operational log:
#   1123 = Removable storage BLOCKED (block mode active)
#   1124 = Removable storage AUDITED (audit mode, logged only)
#   1125 = Removable storage policy APPLIED to device
# ---------------------------------------------------------
Get-WinEvent -LogName "Microsoft-Windows-Windows Defender/Operational" |
    Where-Object { $_.Id -in @(1123, 1124, 1125) } |
    Select-Object -First 20 TimeCreated, Id, Message |
    Format-Table -AutoSize

# Event ID 1123: Blocked removable storage event
# Event ID 1124: Audit removable storage event
# Event ID 1125: Removable storage policy applied
⚠️ Important: Deploy device control in audit mode first and review the logs for at least one week. Blocking all USB devices without an allow list can disrupt users who rely on approved peripherals such as keyboards, mice, and headsets.

Step 11 · Enable Tamper Protection

Tamper protection prevents malicious actors or unauthorized users from disabling Microsoft Defender Antivirus, real-time protection, cloud-delivered protection, and other security features.

Enable Tamper Protection

  1. Navigate to security.microsoft.com > Settings > Endpoints > General > Advanced features
  2. Locate Tamper protection and toggle it to On
  3. Click Save preferences
  4. Tamper protection is applied tenant-wide for all onboarded devices

What Tamper Protection Blocks

  • Disabling virus and threat protection
  • Disabling real-time protection
  • Turning off behavior monitoring
  • Disabling cloud-delivered protection (MAPS)
  • Removing security intelligence updates
  • Disabling automatic actions on detected threats

Verify Tamper Protection Status

# ---------------------------------------------------------
# WHAT: Verify tamper protection status on the local device
# WHY:  Tamper protection prevents attackers (and local admins)
#       from disabling Defender AV security features.
#       When active, attempts to disable protections are denied.
# ---------------------------------------------------------

# Check tamper protection and real-time protection status
# IsTamperProtected: True = tamper protection active (security settings locked)
# RealTimeProtectionEnabled: True = file scanning is active
Get-MpComputerStatus | Select-Object IsTamperProtected, RealTimeProtectionEnabled

# Expected output when tamper protection is active:
# IsTamperProtected       : True
# RealTimeProtectionEnabled : True

# TEST: Attempt to disable real-time protection (should FAIL)
# WHY: Validates that tamper protection is actually enforcing.
# EXPECTED: Error "This setting is managed by your administrator"
Set-MpPreference -DisableRealtimeMonitoring $true
# Expected: This setting is managed by your administrator
💡 Pro Tip: When tamper protection is managed through Intune, it applies to the device regardless of local admin access. This is the recommended management method because it prevents local administrators from overriding tenant-level security settings.

Step 12 · Configure Network Protection

Network protection extends SmartScreen protection to all HTTP/HTTPS traffic on the device, blocking outbound connections to malicious or suspicious destinations regardless of the browser or application used.

Enable Network Protection via Intune

  1. Navigate to intune.microsoft.com > Endpoint security > Attack surface reduction
  2. Create a new policy or edit an existing ASR profile
  3. Set Enable network protection to Block mode
  4. Assign the policy to the target device groups

Enable via PowerShell

# ---------------------------------------------------------
# WHAT: Configure and verify network protection
# WHY:  Network protection extends SmartScreen to ALL HTTP/HTTPS
#       traffic (not just Edge). Blocks outbound connections to
#       malicious domains, C2 infrastructure, and phishing sites.
#       Required for web content filtering on non-Edge browsers.
# MITRE: Blocks T1071 (Application Layer Protocol) C2 channels.
# ---------------------------------------------------------

# Enable network protection in block mode (enforced)
# VALUE: Enabled = block malicious connections; AuditMode = log only
Set-MpPreference -EnableNetworkProtection Enabled

# Verify current network protection status
# OUTPUT: 0 = Disabled, 1 = Enabled (Block), 2 = Audit
Get-MpPreference | Select-Object EnableNetworkProtection

# Start in audit mode first (recommended for initial deployment)
# WHY: Logs blocked connections without disrupting users. Review
#      logs for false positives before switching to Block.
Set-MpPreference -EnableNetworkProtection AuditMode

# Test network protection by accessing Microsoft's SmartScreen test URL
# WHY: This URL is safe but classified as malicious for testing.
#      Block mode = browser shows block page; Audit mode = logged only.
Start-Process "https://smartscreentestratings2.net"

Network Protection Dependencies

  • Real-time protection must be enabled
  • Cloud-delivered protection must be enabled
  • Network protection is required for web content filtering to work on non-Microsoft browsers
  • Network protection enables custom URL/IP indicators to block connections at the network level
⚠️ Important: Deploy network protection in audit mode for at least one week before switching to block mode. Review the audit logs to identify any legitimate applications or services that may be blocked by false positives.

Step 13 · Create Custom Detection Rules for Advanced Threats

Custom detection rules use KQL queries to automatically detect suspicious activity and generate alerts or take response actions. Build rules for threats specific to your organization.

Create a Custom Detection Rule

  1. Navigate to security.microsoft.com > Hunting > Custom detection rules
  2. Click + New detection rule
  3. Enter and validate the KQL query in the query editor
  4. Map the query results to entity types (Device, File, User, IP, URL)
  5. Configure the alert details: title, severity, category, MITRE technique
  6. Set the frequency: every 1 hour, 3 hours, 12 hours, or 24 hours
  7. Optionally configure automated response actions (isolate device, quarantine file, restrict app execution)
  8. Click Create to activate the rule

Example: Detect LSASS Credential Access

// ---------------------------------------------------------
// WHAT: Custom detection rule - LSASS credential access
// WHY:  Detects credential dumping tools (Mimikatz, ProcDump,
//       pypykatz) targeting the LSASS process to extract
//       passwords, NTLM hashes, and Kerberos tickets.
// MITRE: T1003.001 (OS Credential Dumping: LSASS Memory)
// DETECTION LOGIC:
//   Matches known credential dumping tool names OR any process
//   whose command line references "lsass" with dump-related keywords.
//   Excludes SYSTEM/LOCAL SERVICE/NETWORK SERVICE accounts as
//   they legitimately interact with LSASS.
// TRUE POSITIVE: Mimikatz, ProcDump with -ma lsass, pypykatz.
// FALSE POSITIVE: Some EDR agents or monitoring tools may access LSASS.
//   Verify InitiatingProcessFileName before adding exclusions.
// FREQUENCY: Every 1 hour for near-real-time detection.
// RESPONSE: Auto-isolate the device and collect investigation package.
// ---------------------------------------------------------
DeviceProcessEvents
| where Timestamp > ago(1h)
| where FileName in~ ("procdump.exe", "procdump64.exe", "mimikatz.exe", "pypykatz.exe")
    or (ProcessCommandLine has "lsass" and ProcessCommandLine has_any ("dump", "minidump", "sekurlsa"))
| where InitiatingProcessAccountName !in ("SYSTEM", "LOCAL SERVICE", "NETWORK SERVICE")
| project Timestamp, DeviceId, DeviceName, FileName,
    ProcessCommandLine, AccountName,
    InitiatingProcessFileName, ReportId

Example: Detect Suspicious PowerShell Execution

// ---------------------------------------------------------
// WHAT: Custom detection rule - Suspicious PowerShell execution
// WHY:  Encoded PowerShell and download cradles are the #1 delivery
//       mechanism for malware payloads, including ransomware,
//       Cobalt Strike beacons, and reverse shells.
// MITRE: T1059.001 (Command and Scripting Interpreter: PowerShell)
//        T1105 (Ingress Tool Transfer) for download behavior.
// DETECTION LOGIC:
//   Matches powershell.exe or pwsh.exe with suspicious command-line
//   patterns: encoded commands (-enc), Base64 decoding, web downloads,
//   or dynamic code execution (IEX/Invoke-Expression).
// EXCLUSIONS:
//   SCCM (CCM) and Intune management agents are excluded because
//   they legitimately use encoded PowerShell for policy delivery.
//   UPDATE THESE EXCLUSIONS for your environment's management tools.
// TRUE POSITIVE: Encoded download cradle from unknown parent process.
// FALSE POSITIVE: IT automation scripts using Invoke-WebRequest.
//   Check InitiatingProcessFileName for context.
// FREQUENCY: Every 1 hour.
// ---------------------------------------------------------
DeviceProcessEvents
| where Timestamp > ago(1h)
| where FileName =~ "powershell.exe" or FileName =~ "pwsh.exe"
| where ProcessCommandLine has_any (
    "-EncodedCommand", "-enc ", "-e ",
    "FromBase64String", "DownloadString",
    "DownloadFile", "Invoke-WebRequest",
    "IEX", "Invoke-Expression"
)
| where ProcessCommandLine !has "Windows\\CCM"    // Exclude SCCM
| where ProcessCommandLine !has "IntuneManagement" // Exclude Intune
| project Timestamp, DeviceId, DeviceName, FileName,
    ProcessCommandLine, AccountName,
    InitiatingProcessFileName, ReportId
💡 Pro Tip: Always include exclusions for known-good processes (SCCM, Intune, monitoring agents) in custom detection rules. Without exclusions, custom rules will generate false positives that erode SOC trust in the detection system.

Step 14 · Build a Detection Effectiveness Dashboard with KQL

Measure the effectiveness of your detection policies by building KQL queries that track coverage, alert volume, auto-remediation rates, and policy gaps across device groups.

Detection Coverage Analysis

// ---------------------------------------------------------
// WHAT: Detection coverage dashboard - alerts by source and severity
// WHY:  Measures which detection layers are generating alerts.
//       Low counts from a specific DetectionSource may indicate
//       policy gaps (e.g., custom rules not triggering).
// DetectionSource values: "WindowsDefenderAv", "EDR", "CustomDetection",
//   "CustomerTI", "SmartScreen", "AntimalwareScanInterface".
// CriticalPercent: High % = mature detections catching real threats.
//                  Low % = mostly informational noise.
// ---------------------------------------------------------
AlertInfo
| where Timestamp > ago(30d)
| summarize AlertCount = count(),
    UniqueAlerts = dcount(Title),
    CriticalCount = countif(Severity == "High" or Severity == "Critical"),
    AutoResolved = countif(ServiceSource == "Automated investigation")
    by DetectionSource
| extend CriticalPercent = round(100.0 * CriticalCount / AlertCount, 1)
| sort by AlertCount desc

// ---------------------------------------------------------
// WHAT: Detection coverage by MITRE ATT&CK tactic
// WHY:  Identifies which kill chain phases your detections cover.
//       Gaps in specific tactics (e.g., no Persistence detections)
//       indicate you need additional custom rules for those techniques.
// LOGIC: mv-expand unpacks the AttackTechniques JSON array so each
//        technique gets its own row for accurate counting.
// ---------------------------------------------------------
AlertInfo
| where Timestamp > ago(30d)
| where isnotempty(AttackTechniques)
| mv-expand tactic = parse_json(AttackTechniques)
| summarize AlertCount = count(),
    UniqueDevices = dcount(AlertId)
    by tostring(tactic)
| sort by AlertCount desc

Device Group Policy Compliance

// ---------------------------------------------------------
// WHAT: Identify devices missing key security configurations
// WHY:  Devices with protection features disabled are the most
//       vulnerable nodes in your fleet. This query uses TVM
//       (Threat & Vulnerability Management) assessments to find gaps.
// TABLE: DeviceTvmSecureConfigurationAssessment
// ConfigurationId reference (security posture checks):
//   scid-2010 = Real-time protection enabled
//   scid-2011 = PUA (Potentially Unwanted App) protection enabled
//   scid-2012 = Cloud-delivered protection enabled
//   scid-2013 = Tamper protection enabled
//   scid-91   = Network protection enabled
//   scid-92   = Controlled folder access enabled
// LOGIC: IsApplicable=1 means the check applies to this device.
//        IsCompliant=0 means the device FAILS the check.
//        MissingCount = how many checks this device fails.
// OUTPUT: Devices sorted by most missing configs - remediate top entries first.
// ---------------------------------------------------------
DeviceTvmSecureConfigurationAssessment
| where ConfigurationId in (
    "scid-2010",  // Real-time protection
    "scid-2011",  // PUA protection
    "scid-2012",  // Cloud-delivered protection
    "scid-2013",  // Tamper protection
    "scid-91",    // Network protection
    "scid-92"     // Controlled folder access
)
| where IsApplicable == 1
| where IsCompliant == 0
| summarize MissingConfigs = make_set(ConfigurationId),
    MissingCount = count()
    by DeviceId, DeviceName
| sort by MissingCount desc

Custom Indicator Effectiveness

// ---------------------------------------------------------
// WHAT: Track custom indicator (IoC) hit rates over time
// WHY:  A daily trend of IoC hits shows whether your threat
//       intelligence is actively protecting against current threats.
//       Flat-line = IoCs may be stale and need refreshing.
//       Spike = active campaign targeting your organization.
// DetectionSource "CustomerTI" = Custom Indicators you imported.
// OUTPUT: Time chart for executive reporting.
// ---------------------------------------------------------
AlertInfo
| where Timestamp > ago(30d)
| where DetectionSource == "CustomerTI"
| summarize DailyHits = count() by bin(Timestamp, 1d)
| render timechart

// ---------------------------------------------------------
// WHAT: Top triggered custom indicators by alert title
// WHY:  Identifies which specific IoCs (file hashes, IPs, URLs)
//       are most actively matched. High-hit indicators confirm
//       your TI is relevant. Zero-hit indicators should be reviewed
//       for removal to keep the indicator list manageable.
// ---------------------------------------------------------
AlertInfo
| where Timestamp > ago(30d)
| where DetectionSource == "CustomerTI"
| summarize HitCount = count(),
    AffectedDevices = dcount(AlertId)
    by Title, Severity
| sort by HitCount desc
💡 Pro Tip: Schedule these KQL queries as custom detection rules with "Informational" severity to generate weekly dashboard reports automatically. Export the results to Power BI for executive-level detection coverage reporting.

Step 15 · Test Detection Coverage with Simulated Attacks

Validate that your detection policies catch real-world attack techniques by running safe simulations on your test devices. Each test below includes the exact script to run and the expected outcome to verify.

Test 1: Next-Gen AV Detection

# ---------------------------------------------------------
# WHAT: Standard MDE detection test command (safe, no actual malware)
# WHY:  Validates that the NGAV detection layer is operational.
#       The command simulates a download-and-execute pattern that
#       MDE's behavioral engine is designed to detect.
# DETECTION: Triggers "Microsoft Defender for Endpoint test alert"
#            within 15-30 minutes in the Defender portal.
# NOTE: Connects to localhost (127.0.0.1) only - completely safe.
# ---------------------------------------------------------
powershell.exe -NoExit -ExecutionPolicy Bypass -WindowStyle Hidden `
  $ErrorActionPreference='silentlycontinue'; `
  (New-Object System.Net.WebClient).DownloadFile( `
  'http://127.0.0.1/1.exe','C:\test-WDATP-test\invoice.exe'); `
  Start-Process 'C:\test-WDATP-test\invoice.exe'

# Verify: An alert should appear in the portal within 15-30 minutes

Test 2: Network Protection Block

# ---------------------------------------------------------
# WHAT: Test network protection by accessing the SmartScreen test URL
# WHY:  Validates that network protection blocks connections to
#       known-malicious URLs across ALL browsers, not just Edge.
#       The test URL is safe but classified as malicious by SmartScreen.
# EXPECTED (Block mode): Browser shows a block/warning page.
# EXPECTED (Audit mode): No block, but Event ID 1125 is logged.
# ---------------------------------------------------------
Start-Process "https://smartscreentestratings2.net"

# Verify block was recorded in the Defender event log
# Event ID 1125 = network protection triggered (block or audit)
Get-WinEvent -LogName "Microsoft-Windows-Windows Defender/Operational" |
    Where-Object { $_.Id -eq 1125 } |
    Select-Object -First 5 TimeCreated, Message

Test 3: Custom Detection Rule Trigger

# ---------------------------------------------------------
# WHAT: Test the custom PowerShell detection rule from Step 13
# WHY:  Validates that your KQL-based custom detection rule actually
#       triggers when an encoded PowerShell command is executed.
# HOW:  Creates a Base64-encoded 'Write-Host "Detection test"' command
#       and runs it via -EncodedCommand, which matches the detection
#       rule's "-EncodedCommand" pattern.
# EXPECTED: Custom detection rule fires an alert within 1-3 hours
#           (based on the rule's configured frequency).
# VERIFY: Hunting > Custom detection rules > select rule > Last run results
# ---------------------------------------------------------
$command = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes('Write-Host "Detection test"'))
powershell.exe -EncodedCommand $command

# Verify: Your custom detection rule should trigger an alert
# Check: Hunting > Custom detection rules > select rule > Last run results

Test Validation Checklist

  • NGAV detection test: alert generated within 30 minutes
  • Network protection: test URL blocked in all browsers
  • Web content filtering: blocked category sites show a block page
  • Custom detection rule: KQL rule triggers an alert on the test activity
  • Tamper protection: local commands to disable Defender are rejected
  • Device control: unauthorized USB device is blocked or audited
  • EDR in block mode: post-breach behavioral detection is logged
⚠️ Important: Always run detection tests on pilot or evaluation devices, not production endpoints. Document test results and compare against expected outcomes to identify any policy gaps or misconfigurations.

Step 16 · Document and Validate the Complete Policy Stack

Create a comprehensive policy documentation artifact that records every detection policy, its configuration, target scope, and validation status. This document serves as both an operational reference and an audit artifact.

Policy Stack Documentation Template

  • 1. Next-Generation Antivirus: Policy name, targeted groups, real-time protection status, PUA mode, scan schedules, exclusions
  • 2. Cloud-Delivered Protection: Cloud block level, extended timeout, sample submission consent, block-at-first-sight status
  • 3. EDR in Block Mode: Enabled/disabled, applicable device groups, third-party AV coexistence status
  • 4. Custom Indicators: Total count by type (file, IP, URL, certificate), action distribution (block, alert, allow), expiration policies
  • 5. Device Groups: Group names, membership criteria, tag values, assigned automation levels
  • 6. RBAC Roles: Role names, permission sets, assigned Azure AD groups, device group scoping
  • 7. Automated Investigation: Automation levels per device group, pending action queue statistics
  • 8. Web Content Filtering: Blocked categories, targeted device groups, exception domains
  • 9. Device Control: Default enforcement, allow-listed vendor IDs, audit vs. block mode
  • 10. Tamper Protection: Tenant-wide status, management method (Intune or portal)
  • 11. Network Protection: Block vs. audit mode, targeted device groups, exclusions
  • 12. Custom Detection Rules: Rule count, frequency, automated response actions, false positive rate

Export Policy Configuration with PowerShell

# ---------------------------------------------------------
# WHAT: Export the complete Defender configuration from a device
# WHY:  Creates a comprehensive policy report for documentation,
#       compliance audits, and baseline comparison across devices.
#       Run on devices from each device group to verify consistency.
# OUTPUT: CSV file at C:\Temp\MDE-PolicyReport-.csv
# ---------------------------------------------------------

# Collect all relevant Defender preferences and status
$config = Get-MpPreference
$status = Get-MpComputerStatus

# Build a structured report object with key policy settings
$report = [PSCustomObject]@{
    DeviceName               = $env:COMPUTERNAME
    RealTimeProtection       = $status.RealTimeProtectionEnabled
    BehaviorMonitoring       = $status.BehaviorMonitorEnabled
    TamperProtection         = $status.IsTamperProtected
    CloudProtectionLevel     = $config.CloudBlockLevel        # 0-6 scale
    CloudExtendedTimeout     = $config.CloudExtendedTimeout   # seconds
    MAPSReporting            = $config.MAPSReporting          # 0-2
    SampleSubmission         = $config.SubmitSamplesConsent   # 0-3
    NetworkProtection        = $config.EnableNetworkProtection # 0=Off,1=Block,2=Audit
    ControlledFolderAccess   = $config.EnableControlledFolderAccess
    PUAProtection            = $config.PUAProtection          # 0=Off,1=Block,2=Audit
    AntivirusVersion         = $status.AMProductVersion
    SignatureVersion         = $status.AntispywareSignatureVersion
    LastSignatureUpdate      = $status.AntivirusSignatureLastUpdated
}

# Display the report in the console
$report | Format-List

# Export to CSV for audit documentation and cross-device comparison
$report | Export-Csv -Path "C:\Temp\MDE-PolicyReport-$env:COMPUTERNAME.csv" -NoTypeInformation
Write-Host "Policy report exported to C:\Temp\MDE-PolicyReport-$env:COMPUTERNAME.csv"

Validation Checklist

  • All device groups have an assigned automation level
  • RBAC roles are mapped to Azure AD groups with correct permissions
  • Cloud-delivered protection is set to High+ across all device groups
  • Tamper protection is enabled tenant-wide
  • Network protection is in block mode on all workstation groups
  • Web content filtering covers all security-relevant categories
  • Device control is active with an approved USB allow list
  • Custom detection rules have zero false positive alerts in the past 7 days
  • Detection test results match expected outcomes for all policy layers
  • Policy documentation is reviewed and approved by the security engineering lead
💡 Pro Tip: Schedule quarterly policy reviews to keep your detection stack current. Threat landscapes evolve, new MITRE techniques emerge, and organizational changes introduce new device types. A living policy document ensures your detection coverage never falls behind.

Summary

What You Accomplished

  • Reviewed MDE's layered detection architecture: NGAV, behavioral sensors, EDR, cloud protection, custom indicators, and ASR
  • Deployed next-generation antivirus policies through Microsoft Intune with recommended settings
  • Enabled cloud-delivered protection with High+ block level, extended timeout, and automatic sample submission
  • Configured EDR in block mode for post-breach detection and automated remediation
  • Created custom indicators of compromise for files, IPs, URLs, and certificates
  • Built tag-based device groups for granular policy targeting
  • Implemented RBAC with three SOC tiers: triage, incident response, and security engineering
  • Configured automated investigation and response levels per device group
  • Deployed web content filtering with security-focused category blocks
  • Set up device control policies for USB and removable media
  • Enabled tamper protection tenant-wide and verified its enforcement
  • Configured network protection in block mode for all-browser coverage
  • Built custom detection rules for LSASS access and suspicious PowerShell execution
  • Created a detection effectiveness dashboard with KQL queries
  • Validated the complete policy stack with simulated attack tests
  • Documented the full policy configuration for operational and audit use

Cost Considerations

  • All features covered in this lab require MDE Plan 2 (included in Microsoft 365 E5 or available standalone)
  • Intune endpoint security policies require an Intune license (included in Microsoft 365 E3/E5)
  • Custom detection rules run at scheduled intervals and consume tenant-level compute; there are no per-query charges
  • Advanced hunting data retention is 30 days by default; forwarding to Microsoft Sentinel for longer retention incurs data ingestion costs

Cleanup (Lab Environment Only)

  • Remove test custom detection rules to avoid false positive alert noise
  • Delete test custom indicators (file hashes, IPs, URLs) that were created for validation
  • Resolve any test alerts and incidents generated during the simulation steps
  • Remove simulation artifacts from test devices (C:\test-WDATP-test, C:\MDE-Lab-Simulation folders)
  • Revert any device control policies from block to audit mode if they impact lab users

Next Steps

  • Integrate MDE alerts and incidents with Microsoft Sentinel for cross-product SIEM correlation
  • Build Sentinel playbooks that automatically enrich MDE alerts with threat intelligence lookups
  • Deploy Microsoft Defender for Cloud to extend detection coverage to cloud workloads and containers
  • Explore Security Copilot for AI-assisted alert triage and KQL query generation

📚 Documentation Resources

ResourceDescription
Configure endpoints onboarding to Microsoft Defender for EndpointOverview of onboarding methods for Windows, macOS, and Linux endpoints
Automated investigation and response in Microsoft Defender for EndpointConfigure automated investigation levels and remediation actions
Role-based access control for Microsoft Defender for EndpointSet up RBAC with device group scoping for multi-tier SOC teams
EDR in block modeEnable post-breach blocking even with third-party antivirus installed
Manage indicatorsCreate custom indicators for files, IPs, URLs, and certificates
Web content filteringBlock access to websites by category using web content filtering
Device control in Microsoft Defender for EndpointManage removable media and USB device access policies
Protect security settings with tamper protectionPrevent unauthorized changes to Defender Antivirus security settings
Network protectionBlock outbound connections to malicious domains and IP addresses
Custom detection rulesBuild KQL-based detection rules for organization-specific threats
← Previous Lab Next Lab →