In this module

AD6.5 Evidence Preservation Basics

5-6 hours · Module 6 · Free
Operational Objective
When you respond to an incident, your first instinct is to contain — revoke sessions, reset passwords, delete malicious inbox rules. But every containment action potentially destroys evidence. Revoking a session terminates the attacker's connection, but it also removes the active session data. Deleting an inbox rule removes the persistence mechanism, but you lose the rule's creation timestamp, conditions, and destination address. Resetting a password invalidates the credential, but also clears sign-in failure patterns. Evidence preservation means capturing the state BEFORE you take action — screenshots, exports, and logs that document what the attacker did, when, and how. This evidence serves three purposes: management reporting (what happened and what was the impact), compliance documentation (GDPR breach assessment), and law enforcement (if financial fraud occurred). This subsection teaches you what to capture, when to capture it, and how to capture it without delaying the containment response.
Deliverable: An evidence preservation checklist that takes 5 minutes to execute before containment — capturing sign-in data, inbox rules, and mailbox audit logs before they're modified by the response.
Estimated completion: 25 minutes
EVIDENCE PRESERVATION — CAPTURE BEFORE CONTAINMENT BEFORE CONTAINMENT (5 min) 1. Screenshot inbox rules (before deleting) 2. Export sign-in log to CSV 3. Screenshot MFA methods (before removing) 4. Note timestamp of each action Then execute containment DURING CONTAINMENT Record every action with timestamp "09:16 — Sessions revoked" "09:17 — Password reset" "09:19 — MFA method removed" Action log = timeline evidence AFTER CONTAINMENT Export mailbox audit log Export message trace (forwarded emails) Save all evidence to secure folder Hash files for integrity (optional) Evidence package complete

Figure AD6.5 — Evidence preservation happens in three phases: before containment (capture current state), during containment (record every action), after containment (export comprehensive logs). The 5-minute pre-containment capture doesn't delay the response — it protects the evidence.

The 5-minute pre-containment capture

Before executing AD6.2, run this evidence preservation script. It takes 5 minutes and captures the three most critical evidence sources:

param([string]$User)

$timestamp = Get-Date -Format "yyyyMMdd-HHmm"
$evidenceDir = "C:\Evidence\$($User.Split('@')[0])-$timestamp"
New-Item -Path $evidenceDir -ItemType Directory -Force | Out-Null

Write-Host "=== EVIDENCE PRESERVATION ===" -ForegroundColor Cyan
Write-Host "User: $User"
Write-Host "Evidence directory: $evidenceDir"
Write-Host "Timestamp: $timestamp"

# 1. Export sign-in log
Write-Host "`nExporting sign-in logs..." -ForegroundColor Yellow
Connect-MgGraph -Scopes "AuditLog.Read.All" -NoWelcome
$weekAgo = (Get-Date).AddDays(-14).ToString("yyyy-MM-ddTHH:mm:ssZ")
Get-MgAuditLogSignIn -Filter "userPrincipalName eq '$User' and createdDateTime ge $weekAgo" -All |
    Select-Object CreatedDateTime, UserPrincipalName, AppDisplayName,
        IpAddress, @{N="City";E={$_.Location.City}},
        @{N="Country";E={$_.Location.CountryOrRegion}},
        @{N="OS";E={$_.DeviceDetail.OperatingSystem}},
        @{N="Browser";E={$_.DeviceDetail.Browser}},
        @{N="MFA";E={$_.MfaDetail.AuthMethod}},
        @{N="CAStatus";E={$_.ConditionalAccessStatus}},
        @{N="RiskLevel";E={$_.RiskLevelDuringSignIn}},
        @{N="ErrorCode";E={$_.Status.ErrorCode}} |
    Export-Csv -Path "$evidenceDir\SignInLogs.csv" -NoTypeInformation
Write-Host "Sign-in logs exported"

# 2. Export inbox rules (BEFORE deleting them)
Write-Host "`nExporting inbox rules..." -ForegroundColor Yellow
Connect-ExchangeOnline -ShowBanner:$false
Get-InboxRule -Mailbox $User | Select-Object Name, Enabled, Priority,
    ForwardTo, ForwardAsAttachmentTo, RedirectTo, DeleteMessage,
    MoveToFolder, SubjectContainsWords, BodyContainsWords,
    @{N="Created";E={$_.WhenCreated}} |
    Export-Csv -Path "$evidenceDir\InboxRules.csv" -NoTypeInformation
Write-Host "Inbox rules exported"

# 3. Export MFA methods (BEFORE removing suspicious ones)
Write-Host "`nExporting MFA methods..." -ForegroundColor Yellow
Get-MgUserAuthenticationMethod -UserId $User | ForEach-Object {
    $type = $_.AdditionalProperties["@odata.type"]
    [PSCustomObject]@{
        Type = $type
        Id = $_.Id
    }
} | Export-Csv -Path "$evidenceDir\MFAMethods.csv" -NoTypeInformation
Write-Host "MFA methods exported"

Write-Host "`n=== EVIDENCE PRESERVED ===" -ForegroundColor Green
Write-Host "Files saved to: $evidenceDir"
Write-Host "NOW proceed with AD6.2 containment procedure"

Save this as C:\SecurityScripts\Preserve-Evidence.ps1. When a compromise is confirmed, run this script FIRST, then proceed with AD6.2.

The principle: disable, don't delete during containment. Disable inbox rules before deleting them. Record MFA methods before removing them. Export sign-in data before revoking sessions. The evidence directory contains the pre-containment state — proving what the attacker configured and when.

After containment: comprehensive export

After the account is secured, export additional evidence that provides the full picture:

# Mailbox audit log — shows all attacker activity in the mailbox
Search-UnifiedAuditLog -StartDate (Get-Date).AddDays(-14) -EndDate (Get-Date) `
    -UserIds $User -ResultSize 5000 |
    Export-Csv -Path "$evidenceDir\MailboxAuditLog.csv" -NoTypeInformation

# Message trace — shows emails sent/received during compromise
Get-MessageTrace -SenderAddress $User `
    -StartDate (Get-Date).AddDays(-14) -EndDate (Get-Date) |
    Export-Csv -Path "$evidenceDir\SentMessages.csv" -NoTypeInformation

Get-MessageTrace -RecipientAddress $User `
    -StartDate (Get-Date).AddDays(-14) -EndDate (Get-Date) |
    Export-Csv -Path "$evidenceDir\ReceivedMessages.csv" -NoTypeInformation

The evidence directory now contains: sign-in logs (where and when the attacker signed in), inbox rules (what persistence the attacker created), MFA methods (what devices the attacker registered), mailbox audit log (what the attacker did in the mailbox), sent messages (what the attacker sent from the mailbox), and received messages (what the attacker could read). This evidence package supports management reporting, GDPR assessment, and law enforcement referral.

Exporting from the Defender portal

The Defender portal provides its own evidence export for incidents. Navigate to the incident → Evidence and response tab → Export. This produces a CSV containing all artifacts associated with the incident: alerts, entities, files, URLs, emails, and processes. Save this alongside your PowerShell exports — it provides Microsoft's perspective on the incident alongside your investigation data.

Additionally, screenshot the Attack story tab for the incident report. The visual timeline provided by Defender tells the story more effectively than a CSV — include it in your incident report's timeline section. Use the Windows Snipping Tool (Win+Shift+S) to capture the full attack story, including the timeline, entities, and alert sequence.

Evidence integrity basics

For most IT administrator-level incidents (credential compromise, phishing, BEC), the evidence you collect serves management reporting and GDPR assessment — not criminal prosecution. Formal forensic standards (chain of custody forms, cryptographic hashing of every file, write-blocking) are not required for these purposes.

However, two simple integrity practices make your evidence more credible:

Timestamped evidence directory. The directory name includes the timestamp of when you collected the evidence (e.g., rwilliams-20260414-0915). This establishes when the evidence was captured relative to the incident timeline.

Read-only after collection. After exporting all evidence, set the evidence directory to read-only:

$evidenceDir = "C:\Evidence\rwilliams-20260414-0915"
Get-ChildItem -Path $evidenceDir -Recurse | Set-ItemProperty -Name IsReadOnly -Value $true
Set-ItemProperty -Path $evidenceDir -Name Attributes -Value "ReadOnly"
Write-Host "Evidence directory set to read-only"

This prevents accidental modification. If anyone asks "was this evidence modified after collection?", the read-only attribute and the unmodified file timestamps demonstrate it wasn't.

For incidents that may involve law enforcement (BEC with financial loss, ransomware with data theft), consult with your legal counsel about formal evidence handling requirements before providing evidence to authorities. They may advise engaging a forensic specialist who can provide evidence with formal chain of custody documentation.

What NOT to preserve

Don't waste time preserving evidence that's already preserved by Microsoft. The Defender portal retains incident data for 180 days. Sign-in logs are retained for 30 days (90 days with Entra ID P1/P2). Mailbox audit logs are retained for 90 days. These are your backup — if you miss something in your initial export, you can go back and retrieve it within the retention window.

What you DO need to preserve: anything that might be MODIFIED by your response actions. Inbox rules (deleted during containment), MFA methods (removed during cleanup), and the current sign-in session details (terminated by session revocation). These are the artifacts that change or disappear when you take action — and they're the ones your pre-containment script captures.

Evidence retention

Store the evidence directory on a secure network share or a dedicated folder that's backed up. Don't store it on the compromised user's OneDrive. Set a retention period: keep evidence for 12 months minimum (GDPR investigations can extend beyond the standard audit log retention). After 12 months, review whether the evidence is still needed (ongoing legal proceedings, insurance claims) before deleting.

Evidence checklist per incident type

Different incidents require different evidence. Use these checklists alongside the pre-containment script:

Compromised account evidence:

  • Sign-in logs (14 days) — exported by the pre-containment script
  • Inbox rules — exported by the pre-containment script
  • MFA methods — exported by the pre-containment script
  • Mailbox audit log — what the attacker did in the mailbox (exported post-containment)
  • Sent messages — what the attacker sent from the mailbox
  • OAuth consents — apps the attacker authorized
  • Screenshots of the Defender incident attack story and timeline

Phishing click evidence:

  • The phishing email (if still in quarantine — export as .eml from the Defender portal)
  • URL click trace showing when the click occurred and whether it was blocked
  • Safe Links analysis of the URL (verdict, classification time, detonation results)
  • Message trace showing all recipients of the phishing email
  • Screenshot of the phishing page (if still active — use the URL detonation in Defender)

BEC evidence (in addition to compromised account):

  • Forwarded email list (message trace filtered by the forwarding destination)
  • Content of forwarded emails (if accessible — determines data exposure)
  • Sent items during the compromise period (attacker-sent fraud emails)
  • Screenshots of the inbox rules showing financial keyword conditions

Hashing evidence files for integrity

If the incident may involve law enforcement or legal proceedings, hash the evidence files to prove they haven't been modified after collection:

# Hash all files in the evidence directory
$evidenceDir = "C:\Evidence\r.williams-20260414-0915"
Get-ChildItem -Path $evidenceDir -File | ForEach-Object {
    $hash = Get-FileHash -Path $_.FullName -Algorithm SHA256
    Write-Host "$($_.Name): $($hash.Hash)"
    [PSCustomObject]@{
        FileName = $_.Name
        SHA256 = $hash.Hash
        CollectedAt = $_.LastWriteTime
        Size = $_.Length
    }
} | Export-Csv -Path "$evidenceDir\EvidenceHashes.csv" -NoTypeInformation
Write-Host "Hash manifest saved to EvidenceHashes.csv"

The hash manifest proves that the evidence files are identical to what was collected. If the sign-in log CSV shows the attacker's IP and timestamps, the SHA256 hash proves the file hasn't been tampered with since collection. This level of integrity isn't required for most incidents (management reporting, GDPR assessment) but becomes important if the incident leads to legal action, insurance claims, or law enforcement investigation.

Evidence folder structure

Organise evidence consistently across incidents:

C:\Evidence\
├── r.williams-20260414-0915\
│   ├── PreContainment\
│   │   ├── SignInLogs.csv
│   │   ├── InboxRules.csv
│   │   └── MFAMethods.csv
│   ├── PostContainment\
│   │   ├── MailboxAuditLog.csv
│   │   ├── SentMessages.csv
│   │   └── ReceivedMessages.csv
│   ├── Screenshots\
│   │   ├── DefenderIncident.png
│   │   ├── AttackStory.png
│   │   └── InboxRulesPortal.png
│   ├── EvidenceHashes.csv
│   └── IncidentReport.md

Every incident gets a folder named {user}-{date}-{time}. Inside: PreContainment (captured before response actions), PostContainment (captured after containment), Screenshots (portal evidence), and the incident report. The hash manifest covers all files. This structure is self-documenting — anyone opening the folder understands what it contains without explanation.

What NOT to preserve

Don't collect evidence that doesn't serve the investigation or that creates unnecessary risk:

Don't export the full mailbox. You don't need every email the user ever received. Export the mailbox audit log (which shows what the attacker accessed) and the message trace (which shows what was sent and received during the compromise period). The full mailbox is thousands of emails that are mostly irrelevant and create a data handling burden.

Don't screenshot the user's password. The temporary password from the reset should be communicated to the user and then forgotten. Don't include it in evidence files — if the evidence folder is accessed by someone else, the temporary password could be misused.

Don't store evidence on shared drives accessible to the compromised user. The user's OneDrive, their team's SharePoint, or a shared network drive they have access to are not appropriate evidence storage locations. Use a location that only IT/security staff can access.

Compliance Myth: "Evidence preservation is only needed for large incidents that involve law enforcement"
Evidence preservation is needed for every incident — not just the ones involving law enforcement. Your manager's first question after a credential compromise is "what did the attacker access?" Without the sign-in log export, you can't answer that question because the default sign-in log retention is 30 days. Your GDPR assessment requires knowing which personal data was accessed — without the mailbox audit log export, you can't determine what emails the attacker read. Your quarterly report needs the incident timeline — without the action log, you're reconstructing from memory weeks later. The 5-minute pre-containment capture is for every incident, every time. It's the cheapest insurance you'll ever buy.
Decision point

You've confirmed a credential compromise at 09:15. The attacker is actively reading emails right now. Your evidence preservation script takes 5 minutes. Should you run the evidence script first, or jump straight to containment?

Option A: Contain immediately — every minute the attacker is active increases the damage. Skip evidence preservation.

Option B: Run the evidence preservation script (5 minutes), then contain. The 5 minutes of continued attacker access is a trade-off for having complete evidence. The attacker has already been active for hours (the compromise happened overnight) — 5 additional minutes doesn't significantly increase the damage, but losing the evidence creates a permanent gap in your investigation and reporting.

The correct answer is Option B for most scenarios. The attacker has been active since 02:00 — 5 additional minutes at 09:15 adds minimal incremental risk compared to the evidence you preserve. The exception: if you observe active data exfiltration in real-time (bulk downloads happening right now) or ransomware activity (files being encrypted), contain immediately and accept the evidence gap. For the typical BEC scenario (attacker reading emails and creating forwarding rules), the 5-minute preservation is worth the trade-off.

Try it: Test the evidence preservation script

Run Preserve-Evidence.ps1 against a test user account. Verify that the evidence directory is created with three CSV files: SignInLogs.csv, InboxRules.csv, and MFAMethods.csv.

Open each file and verify the data is populated: sign-in entries with timestamps and IPs, inbox rule configurations, and MFA method types and IDs. If any file is empty, check the PowerShell module connections (Microsoft.Graph and ExchangeOnlineManagement).

Practice the full sequence: evidence preservation → AD6.2 containment → post-containment export. Time the entire process from script start to last export. Your target: evidence preservation in 5 minutes, containment in 10 minutes, post-containment export in 5 minutes — total 20 minutes from confirmation to complete evidence-preserved containment.

You discover a malicious inbox rule that forwards "payment" emails to an external address. What do you do with the rule?
Delete it immediately — stop the forwarding as fast as possible — Deleting destroys evidence. The rule's creation timestamp, conditions, and destination address are evidence of the attacker's activity.
Export the rule details (Get-InboxRule → CSV), then DISABLE the rule (Set-InboxRule -Enabled $false) to stop forwarding while preserving the evidence. Delete the rule only after the evidence is secured and the incident is fully documented — Correct. Disabling stops the forwarding immediately (same effect as deletion for containment) but preserves the rule as evidence. The rule's conditions, destination address, and creation timestamp prove what the attacker configured and when.
Leave it active and monitor what gets forwarded — Leaving the rule active means the attacker continues receiving forwarded financial emails. Disable it immediately after capturing the evidence.
Take a screenshot and delete it — A screenshot is better than nothing, but a CSV export with full rule details is more comprehensive and machine-readable for later analysis.

You're reading the free modules of M365 Security: From Admin to Defender

The full course continues with advanced topics, production detection rules, worked investigation scenarios, and deployable artifacts.

View Pricing See Full Syllabus