Deploy Safe Attachments and Safe Links policies in Microsoft Defender for Office 365 to protect users from malicious file detonation and URL-based attacks across email, Microsoft Teams, SharePoint Online, and OneDrive for Business.
In this hands-on lab you will configure a complete email and collaboration threat protection stack using Microsoft Defender for Office 365. Starting with a review of the MDO protection policies in the Microsoft Defender portal, you will create and deploy Safe Attachments policies with Dynamic Delivery to detonate suspicious files in a sandbox without delaying mail flow, configure Safe Links policies to rewrite and scan URLs at time of click, extend protection to SharePoint Online, OneDrive for Business, and Microsoft Teams, validate your configuration with EICAR test files and test URLs, and set up monitoring dashboards and alerts to track protection effectiveness. By the end of this lab you will have a production-grade MDO deployment actively defending against weaponized attachments and malicious URLs.
Woodgrove Bank is a regional financial institution with 4,200 employees across 35 branch locations. Over the past quarter, Woodgrove Bank's SOC has observed a 340% increase in weaponized email attachments targeting their loan processing and treasury departments. Threat actors are using macro-enabled Excel attachments disguised as wire transfer confirmations and PDF files embedded with exploit kits. Additionally, the security team has identified a surge in credential-harvesting URLs embedded in emails that impersonate internal HR portals and benefits enrollment pages.
The CISO has mandated an immediate deployment of Safe Attachments with Dynamic Delivery to ensure zero-day attachment threats are detonated in a sandbox before reaching user mailboxes, while still delivering the email body promptly. Safe Links must be deployed with time-of-click URL scanning, click-through blocking, and full URL rewriting to prevent users from navigating to known and unknown phishing pages. Protection must also extend to SharePoint and OneDrive to prevent lateral spread of malicious documents shared internally. Success criteria: 100% of inbound attachments scanned, zero click-throughs to known malicious URLs, full visibility into threat metrics within 30 days, and zero disruption to legitimate business email flow.
Email remains the #1 initial access vector in enterprise cyberattacks. According to Microsoft's Digital Defense Report, over 80% of ransomware incidents begin with a phishing email containing either a weaponized attachment or a malicious URL. Traditional signature-based antimalware solutions miss zero-day threats because they rely on known indicators. Safe Attachments addresses this gap by detonating every attachment in a cloud sandbox, observing its behavior, and blocking it if malicious activity is detected. Safe Links complements this by rewriting every URL in inbound email and scanning it at time of click, so even if a URL was benign at delivery time but was later weaponized, the user is still protected. Together, Safe Attachments and Safe Links form the foundation of the Microsoft Defender for Office 365 protection stack. and mastering their configuration is essential for any organization serious about defending against modern email-borne threats.
Before creating any policies, you need to understand the Microsoft Defender for Office 365 protection stack and how Safe Attachments and Safe Links fit into the overall email security pipeline. Every inbound email passes through multiple layers of protection in a specific order.
Microsoft Defender for Office 365 processes email through these layers in order:
Safe Attachments opens every attachment in a cloud-based sandbox (detonation chamber), observes its behavior for malicious activity. such as spawning processes, modifying registry keys, or reaching out to command-and-control servers. and blocks it if threats are detected. The Dynamic Delivery action delivers the email body immediately while the attachment is being scanned, then attaches the clean file once detonation completes.
Organization Safe AttachmentsDynamic Delivery Safe Attachments policy for all users. detonates attachments in sandbox while delivering email body immediatelycontoso.com)secops@contoso.com# WHAT: Create a Safe Attachments policy with Dynamic Delivery action via Exchange Online PowerShell
# WHY: Safe Attachments detonates every inbound attachment in a cloud sandbox to detect zero-day malware.
# Dynamic Delivery delivers the email body immediately while the attachment is being scanned,
# minimizing user disruption (1-2 min attachment delay vs blocking the entire message).
# OUTPUT: SafeAttachmentPolicy and SafeAttachmentRule objects created in Exchange Online
# - Action DynamicDelivery: Email body delivered instantly; attachment arrives after scan completes
# - ActionOnError $true: If scanning service is unavailable, the configured action still applies
# (prevents unscanned attachments from being delivered during outages)
# - Redirect $false: Detected attachments are quarantined (enable redirect in Step 3 for SOC analysis)
# Connect to Exchange Online
Connect-ExchangeOnline -UserPrincipalName admin@contoso.com
# Create Safe Attachments Policy (defines WHAT to do with attachments)
New-SafeAttachmentPolicy -Name "Organization Safe Attachments" `
-Enable $true `
-Action DynamicDelivery `
-ActionOnError $true `
-Redirect $false
# Create Safe Attachments Rule (defines WHO the policy applies to)
# RecipientDomainIs scopes the policy to all users in the specified domain
# Priority 0 = highest priority (processed first if multiple rules exist)
New-SafeAttachmentRule -Name "Organization Safe Attachments Rule" `
-SafeAttachmentPolicy "Organization Safe Attachments" `
-RecipientDomainIs "contoso.com" `
-Priority 0When Safe Attachments detects a malicious file, the attachment is quarantined and (optionally) redirected to a security mailbox for manual investigation. Properly configuring quarantine and redirect settings ensures your SOC team has full visibility into every blocked threat.
secops@contoso.com# WHAT: Enable attachment redirect so detected malicious files are sent to the SOC for forensic analysis
# WHY: When Safe Attachments blocks a malicious attachment, the SOC needs the original file to:
# 1. Extract IOCs (file hashes, embedded URLs, macros)
# 2. Determine if other users received the same attachment
# 3. Update threat intelligence feeds and block lists
# The redirect sends a copy of the quarantined attachment to the specified security mailbox.
# OUTPUT: Policy updated. Verify Redirect=True and RedirectAddress shows your SOC mailbox.
# - ActionOnError $true: If scanning fails, the configured action (block/quarantine) still applies
# This prevents unscanned attachments from being delivered during service outages.
Set-SafeAttachmentPolicy -Identity "Organization Safe Attachments" `
-Redirect $true `
-RedirectAddress "secops@contoso.com" `
-ActionOnError $true
# Verify the updated policy configuration
Get-SafeAttachmentPolicy -Identity "Organization Safe Attachments" |
Format-List Name, Action, Redirect, RedirectAddress, ActionOnError, Enable# List existing quarantine policies
Get-QuarantinePolicy | Select-Object Name, EndUserQuarantinePermissionsValue,
ESNEnabled, OrganizationBrandingEnabled | Format-Table -AutoSize
# View quarantine messages from Safe Attachments detections
Get-QuarantineMessage -StartReceivedDate (Get-Date).AddDays(-7) -EndReceivedDate (Get-Date) |
Where-Object { $_.PolicyType -eq "SafeAttachmentPolicy" } |
Select-Object Subject, SenderAddress, ReceivedTime, ReleaseStatus |
Sort-Object ReceivedTime -DescendingActionOnError parameter is critical. When set to $true, it ensures that if the Safe Attachments scanning service is unavailable (e.g., during a service outage), the configured action (Dynamic Delivery, Block, etc.) is still applied. Without this, attachments would be delivered unscanned during outages. a significant security gap.Safe Links protects users from malicious URLs by rewriting links in inbound email messages and scanning them at time of click. Unlike traditional URL filtering that only checks at delivery time, Safe Links performs real-time URL analysis when the user actually clicks the link. protecting against delayed weaponization attacks where a URL is benign at delivery but later redirected to a phishing or malware page.
Organization Safe LinksTime-of-click URL scanning with click-through blocking for all users across email, Teams, and Office appscontoso.com)# WHAT: Create a Safe Links policy with comprehensive URL scanning across email, Teams, and Office apps
# WHY: Safe Links rewrites URLs in email and scans them at "time of click" - not just at delivery.
# This protects against delayed weaponization attacks where a URL is benign when the email arrives
# but is later redirected to a phishing/malware page. The policy below enables all protective features.
# OUTPUT: SafeLinksPolicy and SafeLinksRule objects created. URLs in email will be rewritten to route
# through Microsoftβs scanning service (safelinks.protection.outlook.com).
# KEY PARAMETERS:
# - AllowClickThrough $false: Users CANNOT bypass the block page (critical for regulated industries)
# - ScanUrls $true: Enables real-time scanning including links to downloadable files
# - DeliverMessageAfterScan $true: Holds email delivery until URL scan completes (prevents race condition)
# - EnableForInternalSenders $true: Scans internal-to-internal emails too (prevents internal phishing)
# - DisableUrlRewrite $false: URLs ARE rewritten (required for time-of-click scanning to work)
# Create Safe Links Policy (defines scanning behavior)
New-SafeLinksPolicy -Name "Organization Safe Links" `
-EnableSafeLinksForEmail $true `
-EnableSafeLinksForTeams $true `
-EnableSafeLinksForOffice $true `
-TrackClicks $true `
-AllowClickThrough $false `
-ScanUrls $true `
-EnableForInternalSenders $true `
-DeliverMessageAfterScan $true `
-DisableUrlRewrite $false
# Create Safe Links Rule (defines WHO the policy applies to)
New-SafeLinksRule -Name "Organization Safe Links Rule" `
-SafeLinksPolicy "Organization Safe Links" `
-RecipientDomainIs "contoso.com" `
-Priority 0$false, users cannot click through the warning page to reach a malicious URL$false, URLs are rewritten to route through the Safe Links scanning serviceAllowClickThrough to $false is critical for enterprise environments. When a user clicks a URL identified as malicious, they see a warning page. if click-through is allowed, they can dismiss the warning and proceed to the malicious site. In regulated industries like financial services and healthcare, always block click-through to enforce compliance.Some legitimate business URLs may be incorrectly flagged or cause issues when rewritten by Safe Links. You can configure a "Do not rewrite" list to exclude specific trusted URLs from Safe Links scanning. Every exception should be documented with a business justification and reviewed quarterly.
# Add trusted URLs to the Safe Links exception list
# Use wildcards carefully. each entry should have a documented business justification
Set-SafeLinksPolicy -Identity "Organization Safe Links" `
-DoNotRewriteUrls @{
Add = "https://banking-partner.woodgrovebank.com/*",
"https://internal-training.contoso.com/*",
"https://approved-vendor-portal.example.com/login"
}
# Verify the exception list
Get-SafeLinksPolicy -Identity "Organization Safe Links" |
Select-Object -ExpandProperty DoNotRewriteUrls
# Review all Safe Links policies and their exception lists
Get-SafeLinksPolicy | ForEach-Object {
Write-Host "Policy: $($_.Name)" -ForegroundColor Cyan
Write-Host "Exceptions:" -ForegroundColor Yellow
$_.DoNotRewriteUrls | ForEach-Object { Write-Host " . $_" }
Write-Host ""
}https://example.com/*), exclude only the specific path needed (https://example.com/specific-app/callback)gmail.com, outlook.com, or yahoo.comSafe Attachments protection extends beyond email to cover files stored in SharePoint Online, OneDrive for Business, and shared in Microsoft Teams. When enabled, files uploaded to these services are scanned for malware. If a malicious file is detected, it is blocked. users cannot open, download, copy, or share the file until it is removed by an administrator. This prevents lateral spread of malware through internal collaboration.
# WHAT: Enable Safe Attachments scanning for SharePoint Online, OneDrive, and Microsoft Teams
# WHY: Without this, malware uploaded to SharePoint/OneDrive can spread through internal sharing
# and Teams file attachments - bypassing email-based Safe Attachments scanning entirely.
# This is a tenant-wide toggle (no per-policy configuration needed).
# OUTPUT: EnableATPForSPOTeamsODB = True | EnableSafeDocs = True | AllowSafeDocsOpen = False
# - EnableATPForSPOTeamsODB: Scans files uploaded to SharePoint/OneDrive/Teams asynchronously
# - EnableSafeDocs: Scans documents opened in Protected View before allowing users to edit
# - AllowSafeDocsOpen $false: Blocks users from exiting Protected View for malicious documents
Set-AtpPolicyForO365 -EnableATPForSPOTeamsODB $true `
-EnableSafeDocs $true `
-AllowSafeDocsOpen $false# Verify the global ATP policy for Office 365
Get-AtpPolicyForO365 | Format-List EnableATPForSPOTeamsODB,
EnableSafeDocs, AllowSafeDocsOpen
# Expected output:
# EnableATPForSPOTeamsODB : True
# EnableSafeDocs : True
# AllowSafeDocsOpen : FalseDisallowInfectedFileDownload parameter set to $true for full protection. Run: Set-SPOTenant -DisallowInfectedFileDownload $trueMicrosoft provides two preset security policy profiles. Standard and Strict. that bundle recommended settings for anti-spam, anti-phishing, anti-malware, Safe Attachments, and Safe Links into a single package. These presets are based on Microsoft's recommended settings and are updated automatically as the threat landscape evolves.
| Setting | Standard | Strict |
|---|---|---|
| Safe Attachments action | Block | Block |
| Safe Attachments quarantine policy | AdminOnlyAccessPolicy | AdminOnlyAccessPolicy |
| Safe Links. rewrite URLs | On | On |
| Safe Links. scan at time of click | On | On |
| Safe Links. allow click-through | Off (blocked) | Off (blocked) |
| Safe Links. scan internal emails | On | On |
| Safe Links. track clicks | On | On |
The EICAR test file is a standardized, non-malicious file used to test antimalware and sandboxing solutions. It contains a specific string that all antimalware vendors recognize as a test indicator. Using EICAR allows you to validate that Safe Attachments is actively scanning and blocking malicious attachments without using actual malware.
X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*eicar-test.txteicar-test.docx or zip it as eicar-test.zip to test different file type handlingtestuser@contoso.com)Safe Attachments EICAR Testeicar-test.txt file# WHAT: Trace the EICAR test message through the Exchange Online mail pipeline
# WHY: After sending the EICAR test file, you need to confirm it was processed by Safe Attachments.
# The message trace shows the delivery status, and the detail trace shows each processing step
# including Safe Attachments scanning, Dynamic Delivery, and quarantine actions.
# OUTPUT:
# 1. Message trace: Shows Received timestamp, sender, subject, and delivery Status
# Status should be "Quarantined" or "FilteredAsSpam" if Safe Attachments blocked the attachment
# 2. Message trace detail: Shows the sequence of processing events (RECEIVE, DELIVER, QUARANTINE)
# Look for the "Advanced Threat Protection" event confirming detonation occurred
# Search for the EICAR test email in the last 2 hours
Get-MessageTrace -RecipientAddress "testuser@contoso.com" `
-StartDate (Get-Date).AddHours(-2) `
-EndDate (Get-Date) |
Where-Object { $_.Subject -like "*EICAR*" } |
Select-Object Received, SenderAddress, Subject, Status, MessageTraceId |
Format-Table -AutoSize
# Get the detailed processing timeline for the EICAR message
# Each event shows what happened at each stage of the mail pipeline
$trace = Get-MessageTrace -RecipientAddress "testuser@contoso.com" `
-StartDate (Get-Date).AddHours(-2) -EndDate (Get-Date) |
Where-Object { $_.Subject -like "*EICAR*" }
Get-MessageTraceDetail -MessageTraceId $trace.MessageTraceId `
-RecipientAddress "testuser@contoso.com" |
Select-Object Date, Event, Action, Detail |
Format-Table -AutoSizeValidating Safe Links protection requires sending an email with test URLs and verifying that time-of-click scanning intercepts malicious links. Microsoft provides specific test URLs and methods to validate Safe Links without using actual phishing infrastructure.
https://www.microsoft.com)https://nam01.safelinks.protection.outlook.com/ or similar)https://test-blocked-url.example.com1 dayAllowClickThrough is set to $false)# Check recent Safe Links URL trace data
Get-SafeLinksDetailReport -StartDate (Get-Date).AddDays(-1) -EndDate (Get-Date) |
Select-Object ClickTime, NetworkMessageId, Url, Action,
UserPrincipalName, IsClickedThrough |
Sort-Object ClickTime -Descending |
Format-Table -AutoSize
# Check the Tenant Allow/Block List for blocked URLs
Get-TenantAllowBlockListItems -ListType Url -Block |
Select-Object Value, Action, ExpirationDate, Notes |
Format-Table -AutoSizeRemove-TenantAllowBlockListItems or set a short expiration when creating the block entry.Now that Safe Attachments and Safe Links are deployed, you need ongoing monitoring to ensure the policies are working effectively and to detect trends in threat activity. Microsoft Defender for Office 365 provides built-in reports, dashboards, and alerting capabilities to track protection metrics.
# Get Safe Attachments report data
Get-MailDetailATPReport -StartDate (Get-Date).AddDays(-30) -EndDate (Get-Date) |
Group-Object -Property Action |
Select-Object Name, Count |
Sort-Object Count -Descending
# Get Safe Links report data
Get-SafeLinksDetailReport -StartDate (Get-Date).AddDays(-30) -EndDate (Get-Date) |
Group-Object -Property Action |
Select-Object Name, Count |
Sort-Object Count -Descending# Get top targeted users by Safe Attachments detections
Get-MailDetailATPReport -StartDate (Get-Date).AddDays(-30) -EndDate (Get-Date) |
Group-Object -Property RecipientAddress |
Select-Object Name, Count |
Sort-Object Count -Descending |
Select-Object -First 10
# Get top clicked URLs from Safe Links
Get-SafeLinksDetailReport -StartDate (Get-Date).AddDays(-30) -EndDate (Get-Date) |
Where-Object { $_.Action -eq "Blocked" } |
Group-Object -Property Url |
Select-Object Name, Count |
Sort-Object Count -Descending |
Select-Object -First 10
# Get daily detection trends
Get-MailDetailATPReport -StartDate (Get-Date).AddDays(-30) -EndDate (Get-Date) |
Group-Object -Property { $_.Date.ToString("yyyy-MM-dd") } |
Select-Object Name, Count |
Sort-Object Namesoc-alerts@contoso.com)Congratulations! In this lab you have deployed a comprehensive email threat protection stack for Woodgrove Bank:
| Resource | Description |
|---|---|
| Safe Attachments overview | How Safe Attachments works, detonation sandbox architecture, and supported file types |
| Configure Safe Attachments policies | Step-by-step guide to creating and managing Safe Attachments policies |
| Safe Links overview | How Safe Links URL scanning works, time-of-click protection, and URL rewriting |
| Configure Safe Links policies | Step-by-step guide to creating and managing Safe Links policies |
| Preset security policies | Standard and Strict protection profiles with recommended settings |
| Recommended settings for EOP and MDO | Microsoft's recommended configuration values for all email protection policies |
| Safe Attachments for SPO, OneDrive, and Teams | How file scanning works for SharePoint, OneDrive, and Teams collaboration |
| EICAR test file guidance | Using the EICAR test file to validate Safe Attachments scanning |