Intermediate ⏱ 120 min 📋 15 Steps

Investigate a Simulated Ransomware Attack

Respond to a simulated ransomware incident in Microsoft Defender for Endpoint. Analyze the device timeline, trace the process tree, use Live Response for remote forensics, isolate the compromised device, hunt for lateral movement, remediate the threat, and document findings for an incident report.

📋 Overview

About This Lab

Ransomware remains one of the most destructive cyber threats facing organizations, encrypting critical data and demanding payment for recovery. Microsoft Defender for Endpoint provides deep visibility into the entire attack chain: from initial access through execution, persistence, lateral movement, and impact. This lab walks you through a complete ransomware investigation workflow using MDE's incident queue, device timeline, process tree, Live Response, and advanced hunting. You will practice the end-to-end response lifecycle: detect, investigate, contain, remediate, and document.

🏢 Enterprise Use Case

Scenario: Fabrikam Manufacturing operates 200 Windows workstations across two production facilities and a corporate office.

A SOC analyst receives a high-severity alert indicating ransomware behavior detected on a workstation in the engineering department. The SOC team must trace the full attack chain: how the attacker gained initial access, what processes executed, whether lateral movement occurred, and how many devices are affected. Production systems are at risk; rapid containment is critical to prevent encryption from spreading to file servers and SCADA workstations.

Success criteria: full attack chain documented, affected devices isolated, threat remediated, and an incident report delivered to leadership.

🎯 What You Will Learn

  1. How the ransomware attack lifecycle maps to MITRE ATT&CK tactics
  2. How to trigger and investigate a safe ransomware simulation in MDE
  3. How to use the device timeline and process tree to reconstruct an attack chain
  4. How to collect investigation packages and use Live Response for remote forensics
  5. How to isolate a compromised device and hunt for lateral movement with KQL
  6. How to remediate threats by quarantining files, stopping processes, and removing persistence
  7. How to document findings and produce an incident report

🔑 Why This Matters

The average ransomware attack causes 21 days of downtime and costs organizations millions in recovery, lost revenue, and reputational damage. Speed of investigation directly impacts blast radius: the faster you contain, the fewer systems are encrypted. Regulatory frameworks (NIST, ISO 27001, HIPAA) require documented incident response procedures and post-incident reports. MDE provides the telemetry and response tools needed to investigate and contain ransomware without relying on third-party forensic tools.

⚙️ Prerequisites

  • Licensing: Microsoft Defender for Endpoint Plan 2 (or Microsoft 365 E5 / E5 Security)
  • Devices: At least one Windows 10/11 or Windows Server 2019/2022/2025 device onboarded to MDE with healthy sensor status
  • Portal Access: Security Administrator or Security Operator role in security.microsoft.com
  • Live Response: Live Response must be enabled under Settings > Endpoints > Advanced features
  • Network Isolation: Device isolation capability requires MDE Plan 2 and onboarded devices
  • Advanced Hunting: Familiarity with basic KQL syntax for threat hunting queries
  • Test Device: A dedicated test VM (non-production) for running safe simulations · never use production devices
  • Network: Outbound HTTPS (443) connectivity to MDE cloud service URLs
⚠️ Important: This lab uses safe simulation techniques. Never execute real ransomware or malware on production systems. Use the EICAR test file and safe PowerShell commands provided in Step 3 on a dedicated test device only.

Step 1 · Understand the Ransomware Attack Lifecycle

Before investigating, understand the phases of a typical ransomware attack mapped to MITRE ATT&CK tactics. This knowledge helps you interpret the telemetry you will see in MDE.

Ransomware Kill Chain Phases

  • Initial Access (TA0001): Phishing email with a malicious Office attachment, or exploitation of a public-facing application such as RDP or VPN
  • Execution (TA0002): Malicious macro launches PowerShell or cmd.exe to download and execute the ransomware payload
  • Persistence (TA0003): Scheduled tasks, registry Run keys, or WMI event subscriptions ensure the payload survives reboots
  • Privilege Escalation (TA0004): Credential dumping via LSASS or token manipulation to gain administrative access
  • Lateral Movement (TA0008): PsExec, WMI, or RDP used to spread to other systems on the network
  • Defense Evasion (TA0005): Disabling security tools, deleting shadow copies, clearing event logs
  • Impact (TA0040): File encryption with a ransom note dropped, volume shadow copies deleted via vssadmin
💡 Pro Tip: In the MDE device timeline, each event is tagged with the corresponding MITRE ATT&CK tactic and technique. Use these tags to quickly map timeline events to kill chain phases during your investigation.

Step 2 · Review MDE Ransomware Detection Capabilities

MDE uses multiple detection layers to identify ransomware activity. Understanding these layers helps you interpret the alerts and evidence you will encounter.

Detection Layers

  • Cloud-delivered Protection: Real-time analysis of suspicious files using machine learning models and detonation chambers in the Microsoft cloud
  • Behavioral Monitoring: The MDE sensor monitors process behavior for ransomware patterns such as rapid file modification, encryption of multiple file types, and ransom note creation
  • ASR Rule (C1DB55AB): The "Use advanced protection against ransomware" rule blocks files that resemble ransomware based on file characteristics and reputation
  • Controlled Folder Access: Prevents unauthorized applications from modifying files in protected folders (Documents, Desktop, Pictures)
  • Tamper Protection: Prevents attackers from disabling Defender Antivirus, real-time protection, or cloud-delivered protection
  • Advanced Hunting: Custom KQL queries can detect ransomware behaviors such as shadow copy deletion, mass file renaming, and encryption patterns

Key Alert Categories

  • Ransomware behavior detected: Behavioral detection of encryption patterns
  • Suspicious file encryption activity: Rapid modification of multiple files with new extensions
  • Shadow copy deletion: Execution of vssadmin.exe with delete shadows parameters
  • Suspicious PowerShell activity: Encoded commands, download cradles, or AMSI bypass attempts

Step 3 · Trigger a Safe Ransomware Simulation

Run the following safe simulation scripts on your dedicated test device to generate ransomware-like telemetry in MDE. These scripts use harmless techniques that trigger MDE behavioral detections without causing real damage.

⚠️ Warning: Run these scripts only on a dedicated test device that is onboarded to MDE. Never run simulation scripts on production systems.

Simulation A: MDE Detection Test (Triggers Alert Within 15 min)

This is Microsoft's official detection test command. It creates a harmless test file that triggers an MDE alert to verify your sensor is working correctly.

# ============================================================
# Simulation A: MDE Official Detection Test
# Run this on your TEST device as Administrator
# Expected: Alert "Microsoft Defender for Endpoint test alert"
# appears in the portal within 15-30 minutes
# ============================================================

# Create the test directory
New-Item -Path "C:\test-WDATP-test" -ItemType Directory -Force

# Run the official MDE detection test command
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 by navigating to:
# security.microsoft.com > Incidents & alerts > Alerts queue
# Look for: "Microsoft Defender for Endpoint test alert"

Simulation B: Safe Ransomware Behavior Simulation (Multi-Phase)

This script simulates the full ransomware kill chain using completely harmless operations that MDE's behavioral engine detects as suspicious. It creates dummy files, renames them to mimic encryption, and simulates shadow copy deletion · all without any real damage.

# ============================================================
# Simulation B: Safe Ransomware Kill Chain Simulation
# Run this on your TEST device as Administrator
# This generates MULTIPLE alerts across the kill chain
# ============================================================

# --- Phase 1: Create dummy target files (simulates data staging) ---
$simPath = "C:\MDE-Lab-Simulation"
New-Item -Path $simPath -ItemType Directory -Force
1..20 | ForEach-Object {
    Set-Content -Path "$simPath\document_$_.docx" -Value ("SampleContent_" + (Get-Random))
    Set-Content -Path "$simPath\spreadsheet_$_.xlsx" -Value ("SampleData_" + (Get-Random))
    Set-Content -Path "$simPath\report_$_.pdf" -Value ("SampleReport_" + (Get-Random))
}
Write-Host "[Phase 1] Created 60 dummy files in $simPath" -ForegroundColor Cyan

# --- Phase 2: Simulate rapid file renaming (mimics encryption) ---
# MDE detects rapid mass file renaming as ransomware behavior
Get-ChildItem "$simPath\*" -File | ForEach-Object {
    $newName = $_.BaseName + ".encrypted_sim"
    Rename-Item -Path $_.FullName -NewName $newName -ErrorAction SilentlyContinue
}
Write-Host "[Phase 2] Renamed files to .encrypted_sim (triggers mass rename detection)" -ForegroundColor Yellow

# --- Phase 3: Simulate shadow copy deletion attempt ---
# This command is BLOCKED by MDE but generates a high-severity alert
cmd.exe /c "vssadmin.exe list shadows"
Write-Host "[Phase 3] Queried shadow copies (vssadmin usage triggers alert)" -ForegroundColor Yellow

# --- Phase 4: Simulate suspicious PowerShell download cradle ---
# Connects to localhost only · blocked by MDE behavioral engine
try {
    $wc = New-Object System.Net.WebClient
    $wc.DownloadString("http://127.0.0.1:9999/payload.exe") | Out-Null
} catch { }
Write-Host "[Phase 4] Simulated download cradle (localhost only, triggers alert)" -ForegroundColor Yellow

# --- Phase 5: Create a fake ransom note (triggers alert) ---
$ransomNote = @"
=== THIS IS A SIMULATION ===
This file was created by the LessIT MDE Lab simulation script.
It is designed to trigger a ransom note detection alert in MDE.
No actual encryption occurred. Safe to delete.
=== END SIMULATION ===
"@
Set-Content -Path "$simPath\README_RESTORE_FILES.txt" -Value $ransomNote
Set-Content -Path "C:\Users\Public\Desktop\HOW_TO_DECRYPT.txt" -Value $ransomNote
Write-Host "[Phase 5] Created simulated ransom notes" -ForegroundColor Red

Write-Host "`n[DONE] Simulation complete. Check the MDE portal in 15-30 minutes for alerts." -ForegroundColor Green
Write-Host "Expected alerts:" -ForegroundColor Green
Write-Host " . Suspicious file renaming activity" -ForegroundColor Green
Write-Host " . Ransomware behavior detected" -ForegroundColor Green
Write-Host " . Suspicious PowerShell activity" -ForegroundColor Green
Write-Host " . Potential ransomware note detected" -ForegroundColor Green

Simulation C: EICAR Test File (Antivirus Detection Test)

The EICAR test file is the industry-standard antivirus test. It is completely harmless but is detected by all antivirus engines including Microsoft Defender.

# ============================================================
# Simulation C: EICAR Standard Antivirus Test File
# This is a standard, harmless test file recognized by all AV
# Expected: Immediate Defender AV detection alert
# ============================================================

# Create the EICAR test string and write it to a file
# Defender AV will immediately detect and quarantine this file
$eicarString = 'X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*'
Set-Content -Path "C:\temp\eicar-test.txt" -Value $eicarString -NoNewline

# This should trigger an immediate detection
# Check: security.microsoft.com > Incidents & alerts > Alerts queue

Cleanup After Simulation

# Remove all simulation artifacts from the test device
Remove-Item -Path "C:\MDE-Lab-Simulation" -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -Path "C:\test-WDATP-test" -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -Path "C:\Users\Public\Desktop\HOW_TO_DECRYPT.txt" -Force -ErrorAction SilentlyContinue
Remove-Item -Path "C:\temp\eicar-test.txt" -Force -ErrorAction SilentlyContinue
Write-Host "Simulation artifacts cleaned up." -ForegroundColor Green
✅ Tip: Run Simulation B for the richest investigation experience · it generates multiple correlated alerts that MDE combines into a single incident, giving you a realistic multi-phase ransomware investigation scenario. Alerts typically appear within 15·30 minutes.

Step 4 · Investigate the Alert in the Incidents Queue

Once the simulation triggers alerts, MDE automatically correlates related alerts into an incident. Begin your investigation from the incidents queue.

  1. Navigate to security.microsoft.com > Incidents & alerts > Incidents
  2. Look for a new incident with severity High or Critical containing ransomware-related alerts
  3. Click the incident to open the incident detail page
  4. Review the Attack story tab to see the visual representation of the attack chain
  5. Check the Alerts tab to see all correlated alerts, including process execution, file creation, and behavioral detections
  6. Review the Assets tab to identify all affected devices and user accounts
  7. Check the Evidence and response tab for automatically identified entities: files, processes, IP addresses, and URLs
  8. Assign the incident to yourself and set the status to In progress
💡 Pro Tip: Pay close attention to the incident classification. MDE auto-classifies ransomware incidents and tags them with relevant MITRE ATT&CK techniques. Use the attack story graph to quickly understand the scope before diving into individual alerts.

Step 5 · Analyze the Device Timeline for the Attack Chain

The device timeline is your primary investigation tool. It shows every process, file, network, and registry event in chronological order on the affected device.

  1. From the incident page, click the affected device under the Assets tab
  2. On the device page, select the Timeline tab
  3. Set the time filter to cover the period around the alert (e.g., 1 hour before and after the first alert)
  4. Use the Flags filter to show only flagged/suspicious events for a focused view
  5. Trace the sequence of events: identify the initial process that started the attack chain
  6. Look for key indicators: Office application spawning cmd.exe or PowerShell, script downloads, new executable files created on disk
  7. Note the timestamps, process IDs, and file hashes for each suspicious event
  8. Export the timeline events for inclusion in your incident report

Key Timeline Events to Look For

  • Process creation: Unexpected child processes from Office apps, explorer.exe, or scripting engines
  • File creation: New .exe, .dll, or .bat files in temp directories or user profile folders
  • File modification: Rapid renaming or modification of many files with new extensions (.encrypted, .locked, .crypt)
  • Registry modification: New Run keys, scheduled task registration, or security tool tampering
  • Network connections: Outbound connections to unknown IPs or command-and-control domains

Step 6 · Examine the Process Tree to Trace Execution Flow

The process tree provides a hierarchical view of parent-child process relationships. This helps you understand exactly how the ransomware payload was delivered and executed.

  1. From the device timeline, click on any flagged alert to expand its details
  2. Click Open process tree or navigate to the alert page and select the process tree view
  3. Identify the root process: this is typically the application that was exploited (e.g., WINWORD.EXE, OUTLOOK.EXE)
  4. Trace the child processes: look for cmd.exe, powershell.exe, wscript.exe, or mshta.exe spawned by the root process
  5. Follow the chain down to the ransomware payload: note the file path, hash, and command-line arguments
  6. Check for additional child processes spawned by the payload: vssadmin.exe (shadow copy deletion), bcdedit.exe (boot configuration changes), wbadmin.exe (backup deletion)
  7. Document each node in the process tree with its PID, file hash, command line, and timestamp

Typical Ransomware Process Tree

# ---------------------------------------------------------
# WHAT: Typical ransomware process tree (reference example)
# WHY:  Understanding the parent-child process relationships is
#       essential for tracing how the payload was delivered.
#       Each level maps to a MITRE ATT&CK tactic.
# ---------------------------------------------------------

# Typical ransomware process tree
# MITRE T1566.001 (Phishing → Macro Execution)
WINWORD.EXE (PID 4120)
  # MITRE T1059 (Command and Scripting Interpreter)
  |-- cmd.exe /c powershell -enc [Base64EncodedPayload]
       # MITRE T1059.001 (PowerShell) + T1105 (Ingress Tool Transfer)
       |-- powershell.exe (downloads ransomware.exe)
            # MITRE T1486 (Data Encrypted for Impact)
            |-- ransomware.exe (PID 7742)
                 # MITRE T1490 (Inhibit System Recovery)
                 |-- vssadmin.exe delete shadows /all /quiet
                 # MITRE T1490 (Disable boot recovery)
                 |-- bcdedit.exe /set {default} recoveryenabled no
                 # MITRE T1490 (Delete backup catalog)
                 |-- wbadmin.exe delete catalog -quiet
                 # MITRE T1070.004 (Indicator Removal: File Deletion)
                 |-- cmd.exe /c del /f /q %TEMP%\ransomware.exe

Step 7 · Collect an Investigation Package from the Affected Device

An investigation package captures forensic artifacts from the device, including running processes, network connections, scheduled tasks, event logs, and Defender Antivirus logs.

  1. Navigate to the affected device page in the Defender portal
  2. Click the ... (ellipsis) menu at the top of the device page
  3. Select Collect investigation package
  4. Add a comment explaining the reason: "Ransomware investigation, collecting forensic artifacts"
  5. Click Confirm to initiate the collection
  6. Monitor the Action center for the package collection status (typically 10-30 minutes)
  7. Once complete, download the .zip package from the Action center

Investigation Package Contents

  • Autoruns: Scheduled tasks, Run registry keys, services, and other persistence mechanisms
  • Installed programs: List of installed software with versions
  • Network connections: Active TCP/UDP connections and listening ports
  • Running processes: Full process list with command lines and parent PIDs
  • Security event logs: Windows Security, System, and Application event logs
  • Defender AV logs: Detection history, quarantined items, and protection logs
  • Prefetch files: Evidence of recently executed programs
💡 Pro Tip: Always collect the investigation package before isolating the device. Some collection tasks require network connectivity to upload the package to the cloud.

Step 8 · Use Live Response to Connect to the Device Remotely

Live Response provides a remote shell session to the affected device directly from the Defender portal. This allows you to run forensic commands, collect additional evidence, and perform remediation without needing physical or RDP access.

  1. Verify Live Response is enabled: Settings > Endpoints > Advanced features > Live Response = On
  2. For advanced commands (put file, run script), also enable Live Response for Servers and Live Response unsigned script execution if needed
  3. Navigate to the affected device page and click Initiate Live Response Session
  4. Wait for the session to connect (the device must be online and the MDE sensor must be healthy)
  5. The Live Response console will open with a command prompt in the context of the SYSTEM account
  6. Type help to see all available Live Response commands

Essential Live Response Commands

# ---------------------------------------------------------
# Live Response: Essential forensic commands reference
# These commands run in SYSTEM context on the remote device.
# ---------------------------------------------------------

# List all available Live Response commands
help

# Navigate the file system to inspect suspicious directories
cd C:\Users\
dir

# Download a file from the device for offline analysis
# WHY: Preserves evidence before remediation alters the device state.
getfile C:\Users\Public\ransom_note.txt

# Upload a remediation or forensic script to the device
# NOTE: Scripts must be pre-approved and uploaded to the LR library,
#       or Live Response unsigned script execution must be enabled.
putfile remediation_script.ps1

# Execute an uploaded PowerShell script on the device
run remediation_script.ps1

# Submit a suspicious file to Microsoft's cloud for deep analysis
# OUTPUT: Returns a verdict (malicious/clean) with threat classification.
analyze C:\Temp\suspicious.exe

# Access the pre-uploaded script library for reusable forensic tools
library

Step 9 · Run Forensic Commands via Live Response

Use Live Response commands to gather forensic evidence from the device in real time. Focus on processes, network connections, file system artifacts, and registry keys associated with the ransomware.

Process Analysis

# ---------------------------------------------------------
# Live Response: Process analysis
# WHY: Identify malicious processes still running on the device.
#      Focus on unknown executables, encoded PowerShell, and
#      processes running from Temp, AppData, or Public folders.
# ---------------------------------------------------------

# List all running processes with PID, name, and command line
processes

# Check for suspicious processes by examining command lines
# LOOK FOR: encoded PowerShell (-enc), unknown executables,
#           processes running from Temp, Downloads, or user profile folders.
# MITRE: T1059 (Command and Scripting Interpreter)

Network Connection Analysis

# ---------------------------------------------------------
# Live Response: Network connection analysis
# WHY: Active C2 (command-and-control) connections indicate the
#      attacker still has a foothold on the device.
# MITRE: T1071 (Application Layer Protocol) for C2 communication
# ---------------------------------------------------------

# List all active TCP/UDP connections with remote IP and port
connections

# KEY INDICATORS TO LOOK FOR:
#   - Outbound connections to unknown external IPs (C2 communication)
#   - Connections on unusual ports: 4444 (Metasploit default),
#     8080/8443 (alt HTTP/S), 9001 (Tor), 1337 (common backdoor)
#   - High-frequency connections to a single IP (beaconing pattern)
#   - Connections from suspicious processes like powershell.exe or
#     unknown executables in Temp directories

File System Investigation

# ---------------------------------------------------------
# Live Response: File system investigation
# WHY: Ransomware stages payloads in world-writable directories
#      and drops ransom notes across user profile folders.
# MITRE: T1074 (Data Staged), T1486 (Data Encrypted for Impact)
# ---------------------------------------------------------

# Check common malware staging directories
# WHY: Attackers prefer Temp, Public, and ProgramData because they
#      don't require elevated privileges and are rarely monitored.
dir C:\Temp\
dir C:\Users\Public\
dir C:\ProgramData\
dir %APPDATA%\

# Search for ransom notes (typically .txt files with instructions)
# WHY: Ransom notes confirm encryption occurred and identify the variant.
dir C:\Users\ *.txt /s
dir C:\Users\ README* /s

# Search for files with encryption-related extensions
# WHY: Renamed files (.encrypted, .locked) confirm which data was affected.
dir C:\Users\ *.encrypted /s
dir C:\Users\ *.locked /s

Registry Analysis

# ---------------------------------------------------------
# Live Response: Registry persistence analysis
# WHY: Ransomware operators add Run keys to survive reboots and
#      re-encrypt files if shadow copies are restored.
# MITRE: T1547.001 (Boot or Logon Autostart Execution: Registry Run Keys)
# TRUE POSITIVE: Unknown .exe paths in Temp, AppData, or Public folders.
# FALSE POSITIVE: Legitimate software updaters (Chrome, Teams, etc.).
# ---------------------------------------------------------

# Check current-user Run keys (execute at user logon)
registry HKCU\Software\Microsoft\Windows\CurrentVersion\Run

# Check machine-wide Run keys (execute at system startup)
registry HKLM\Software\Microsoft\Windows\CurrentVersion\Run

# Check RunOnce keys (execute once then auto-delete)
# WHY: Attackers use RunOnce for one-time re-infection after reboot.
registry HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce
registry HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce

PowerShell Forensic Commands

# ---------------------------------------------------------
# Live Response: PowerShell forensic commands
# WHY: Deep-dive forensics to confirm ransomware impact,
#      identify persistence mechanisms, and check for lateral movement.
# NOTE: Prefix with "run PowerShell.exe -Command" in Live Response.
# ---------------------------------------------------------

# Check for shadow copy deletions - STRONG ransomware indicator
# MITRE: T1490 (Inhibit System Recovery)
# WHY: Event ID 8224 in the Application log indicates VSS was terminated.
#      Ransomware deletes shadow copies to prevent file recovery.
run PowerShell.exe -Command "Get-WinEvent -FilterHashtable @{LogName='Application';ID=8224} -MaxEvents 10 | Format-List"

# Verify if any shadow copies still exist (for potential restoration)
# OUTPUT: If empty, all shadow copies were deleted by the attacker.
run PowerShell.exe -Command "vssadmin list shadows"

# List all scheduled tasks in Ready state
# MITRE: T1053.005 (Scheduled Task/Job)
# WHY: Attackers create scheduled tasks for persistence and re-execution.
# LOOK FOR: Tasks with suspicious names, paths to Temp/AppData, or
#           Base64-encoded PowerShell in the task action.
run PowerShell.exe -Command "Get-ScheduledTask | Where-Object {$_.State -eq 'Ready'} | Select-Object TaskName, TaskPath, State | Format-Table -AutoSize"

# Collect recent logon events for lateral movement analysis
# MITRE: T1078 (Valid Accounts) + T1021 (Remote Services)
# Event ID 4624 = Successful logon
# Event ID 4625 = Failed logon (brute force indicator)
# WHY: Type 3 (network) logons from the attacker's compromised account
#      to other servers indicates lateral movement.
run PowerShell.exe -Command "Get-WinEvent -FilterHashtable @{LogName='Security';ID=4624,4625} -MaxEvents 50 | Select-Object TimeCreated, Id, Message | Format-List"
💡 Pro Tip: Use the getfile command to download suspicious files for offline analysis. Combine with the analyze command to submit files to the Microsoft cloud for deep analysis and verdict.

Step 10 · Isolate the Affected Device from the Network

Device isolation is a critical containment action that cuts the device off from the network while maintaining its connection to the MDE cloud service. This prevents the ransomware from spreading to other devices.

  1. Navigate to the affected device page in the Defender portal
  2. Click Isolate device in the response actions at the top of the page
  3. Choose the isolation type: Full (blocks all network traffic except MDE service) or Selective (allows specific Outlook/Teams/Skype connectivity)
  4. Add a comment: "Isolating device due to confirmed ransomware activity. Preventing lateral movement."
  5. Click Confirm to execute the isolation
  6. Monitor the Action center to confirm isolation was applied successfully
  7. Verify isolation status on the device page: a banner will display showing the device is isolated
⚠️ Important: An isolated device can still communicate with the MDE cloud service. You can continue using Live Response and collecting investigation packages on an isolated device. The device will remain isolated until you explicitly release it.

Step 11 · Hunt for Lateral Movement Indicators Using KQL

Once the initial device is contained, determine whether the attacker moved to other systems. Use advanced hunting with KQL to search across all onboarded devices for lateral movement indicators.

Hunt for Ransomware File Modifications

// ---------------------------------------------------------
// WHAT: Hunt for ransomware file encryption across all devices
// WHY:  If the attacker moved laterally, other devices may also
//       have files being renamed with encryption extensions.
//       Rapid file renaming is the #1 behavioral indicator of
//       active ransomware encryption.
// TABLE: DeviceFileEvents - tracks all file system operations.
// DETECTION LOGIC:
//   ActionType == "FileRenamed" + known encryption extensions
//   Threshold: RenamedFileCount > 50 in 24h = strong indicator.
//   Lower counts may be legitimate (e.g., batch file renaming tools).
// TRUE POSITIVE: 100+ files renamed to .encrypted in minutes.
// FALSE POSITIVE: Backup software renaming archive files.
// MITRE: T1486 (Data Encrypted for Impact)
// ---------------------------------------------------------
DeviceFileEvents
| where Timestamp > ago(24h)
| where ActionType == "FileRenamed"
| where FileName endswith ".encrypted"
    or FileName endswith ".locked"
    or FileName endswith ".crypt"
    or FileName endswith ".ransom"
| summarize RenamedFileCount = count(),
    FirstSeen = min(Timestamp),
    LastSeen = max(Timestamp)
    by DeviceId, DeviceName
| where RenamedFileCount > 50
| sort by RenamedFileCount desc

Detect Encryption Behavior Patterns

// ---------------------------------------------------------
// WHAT: Detect mass file modification patterns (encryption velocity)
// WHY:  Ransomware encrypts hundreds of files per minute. Normal
//       user activity rarely modifies 100+ files in a 5-minute window.
// DETECTION LOGIC:
//   bin(Timestamp, 5m) = groups events into 5-minute windows.
//   ModifiedFiles > 100 per window = encryption speed indicator.
//   InitiatingProcessFileName = the encrypting process.
// THRESHOLDS:
//   > 100 files/5min = investigate immediately
//   > 500 files/5min = confirmed active encryption
// FALSE POSITIVE: Software installations, build processes, or
//   large file copy operations. Check InitiatingProcessFileName.
// MITRE: T1486 (Data Encrypted for Impact)
// ---------------------------------------------------------
DeviceFileEvents
| where Timestamp > ago(24h)
| where ActionType in ("FileModified", "FileRenamed", "FileCreated")
| summarize ModifiedFiles = count(),
    UniqueExtensions = dcount(FileName),
    FirstEvent = min(Timestamp),
    LastEvent = max(Timestamp)
    by DeviceId, DeviceName, InitiatingProcessFileName, bin(Timestamp, 5m)
| where ModifiedFiles > 100
| sort by ModifiedFiles desc

Hunt Lateral Movement from the Compromised Device

// ---------------------------------------------------------
// WHAT: Hunt for lateral movement FROM the compromised device
// WHY:  Ransomware operators spread to other systems before encrypting.
//       Detecting lateral movement determines the full blast radius.
// MITRE: T1021 (Remote Services), T1570 (Lateral Tool Transfer)
// ---------------------------------------------------------

// QUERY 1: Find network connections from the compromised device
//   to internal systems on lateral-movement-relevant ports.
// KEY PORTS:
//   445 = SMB (file shares, PsExec lateral movement)
//   135 = RPC (WMI remote execution)
//   139 = NetBIOS Session (legacy SMB)
//   3389 = RDP (Remote Desktop)
//   5985/5986 = WinRM (PowerShell Remoting, Enter-PSSession)
// OUTPUT: TargetDevices = list of internal IPs contacted.
//   Multiple connections to port 445 = likely PsExec/SMB spreading.
let compromisedDevice = "ENGWS-PC01";  // Replace with actual device name
DeviceNetworkEvents
| where Timestamp > ago(24h)
| where DeviceName == compromisedDevice
| where ActionType == "ConnectionSuccess"
| where RemotePort in (445, 135, 139, 3389, 5985, 5986)  // SMB, RPC, RDP, WinRM
| summarize ConnectionCount = count(),
    TargetDevices = make_set(RemoteUrl)
    by RemoteIP, RemotePort
| sort by ConnectionCount desc

// QUERY 2: Detect PsExec, WMI, or PowerShell Remoting commands
// MITRE: T1569.002 (System Services: Service Execution) for PsExec
//        T1047 (Windows Management Instrumentation) for WMI
//        T1021.006 (Remote Services: Windows Remote Management)
// DETECTION LOGIC: Looks for PsExec executables and WMI/PS Remoting cmdlets.
// TRUE POSITIVE: PsExec running from unexpected user accounts or paths.
// FALSE POSITIVE: IT admins using PsExec for legitimate management.
//   Verify AccountName and context before escalating.
DeviceProcessEvents
| where Timestamp > ago(24h)
| where FileName in~ ("psexec.exe", "psexesvc.exe", "wmiprvse.exe")
    or ProcessCommandLine has_any ("wmic", "Invoke-WmiMethod", "Enter-PSSession")
| project Timestamp, DeviceName, FileName, ProcessCommandLine,
    AccountName, InitiatingProcessFileName
| sort by Timestamp desc
💡 Pro Tip: If the lateral movement hunt reveals additional compromised devices, immediately isolate those devices as well. Repeat the investigation steps for each newly discovered affected device.

Step 12 · Check for Persistence Mechanisms

Ransomware operators frequently establish persistence to survive reboots and re-encrypt files. Use KQL to search for common persistence mechanisms across all devices.

Hunt for Registry-Based Persistence

// ---------------------------------------------------------
// WHAT: Hunt for registry-based persistence (Run keys)
// WHY:  Attackers add registry Run keys so their payload
//       re-executes automatically after every reboot.
// MITRE: T1547.001 (Boot or Logon Autostart: Registry Run Keys)
// TABLE: DeviceRegistryEvents - tracks all registry modifications.
// DETECTION LOGIC: New values added to Run/RunOnce/RunServices keys.
// KEY FIELDS:
//   RegistryValueName = the name of the new entry
//   RegistryValueData = the executable path (inspect for suspicious paths)
//   InitiatingProcessFileName = what process created the key
// TRUE POSITIVE: Unknown .exe in Temp, AppData, or Public folders.
// FALSE POSITIVE: Legitimate software installers updating Run keys.
// ---------------------------------------------------------
DeviceRegistryEvents
| where Timestamp > ago(24h)
| where ActionType == "RegistryValueSet"
| where RegistryKey has_any (
    @"CurrentVersion\Run",
    @"CurrentVersion\RunOnce",
    @"CurrentVersion\RunServices"
)
| project Timestamp, DeviceName, RegistryKey, RegistryValueName,
    RegistryValueData, InitiatingProcessFileName,
    InitiatingProcessCommandLine
| sort by Timestamp desc

Hunt for Scheduled Task Persistence

// ---------------------------------------------------------
// WHAT: Hunt for scheduled task persistence
// WHY:  Ransomware operators create scheduled tasks to re-run
//       encryption payloads or maintain backdoor access.
// MITRE: T1053.005 (Scheduled Task/Job: Scheduled Task)
// DETECTION LOGIC: schtasks.exe with /create flag = new task.
// TRUE POSITIVE: Tasks created by unknown processes or with
//   Base64-encoded commands in the task action.
// FALSE POSITIVE: Windows Update, SCCM, or Intune creating tasks.
// ---------------------------------------------------------
DeviceProcessEvents
| where Timestamp > ago(24h)
| where FileName =~ "schtasks.exe"
| where ProcessCommandLine has "/create"
| project Timestamp, DeviceName, ProcessCommandLine,
    AccountName, InitiatingProcessFileName
| sort by Timestamp desc

// ---------------------------------------------------------
// WHAT: Detect WMI event subscription persistence
// WHY:  WMI event subscriptions are a stealthy persistence method.
//       Attackers create __EventFilter + CommandLineEventConsumer
//       pairs that execute code when specific system events occur.
// MITRE: T1546.003 (Event Triggered Execution: WMI Event Subscription)
// TRUE POSITIVE: Any non-admin process creating WMI subscriptions.
// ---------------------------------------------------------
DeviceProcessEvents
| where Timestamp > ago(24h)
| where ProcessCommandLine has_any (
    "EventSubscription",
    "__EventFilter",
    "CommandLineEventConsumer",
    "ActiveScriptEventConsumer"
)
| project Timestamp, DeviceName, FileName,
    ProcessCommandLine, AccountName

Hunt for Shadow Copy Deletion

// ---------------------------------------------------------
// WHAT: Detect shadow copy, backup, and boot recovery tampering
// WHY:  Deleting shadow copies and disabling recovery options
//       is a hallmark of ransomware - it prevents victims from
//       restoring encrypted files without paying the ransom.
// MITRE: T1490 (Inhibit System Recovery)
// DETECTION LOGIC: Known recovery-sabotage binaries with specific
//   command-line arguments:
//   vssadmin "delete shadows" = deletes Volume Shadow Copies
//   wmic "shadowcopy delete" = alternative VSS deletion method
//   bcdedit "recoveryenabled no" = disables Windows Recovery
//   wbadmin "delete catalog" = deletes Windows backup catalogs
// TRUE POSITIVE: Almost always malicious when seen in combination.
// FALSE POSITIVE: Very rare - IT admins may delete old shadow copies
//   during storage cleanup, but combined with bcdedit = malicious.
// ---------------------------------------------------------
DeviceProcessEvents
| where Timestamp > ago(24h)
| where FileName in~ ("vssadmin.exe", "wmic.exe", "bcdedit.exe", "wbadmin.exe")
| where ProcessCommandLine has_any (
    "delete shadows",
    "shadowcopy delete",
    "recoveryenabled no",
    "delete catalog"
)
| project Timestamp, DeviceName, FileName,
    ProcessCommandLine, AccountName,
    InitiatingProcessFileName
| sort by Timestamp desc

Step 13 · Remediate: Quarantine Files, Stop Processes, Remove Persistence

With the attack chain fully documented, perform remediation actions to remove the threat from affected devices. Use a combination of portal actions and Live Response commands.

Portal-Based Remediation

  1. From the incident's Evidence and response tab, select all malicious files identified during the investigation
  2. Click Quarantine file to quarantine each malicious file across all affected devices
  3. Use Stop and quarantine file to simultaneously terminate the running process and quarantine the file
  4. Review the Action center to confirm all quarantine actions completed successfully

Live Response Remediation Commands

# ---------------------------------------------------------
# Live Response: Remediation commands
# WHY: After investigation, remove malicious artifacts from
#      the device before releasing it from isolation.
# NOTE: Run these in the Live Response console.
# ---------------------------------------------------------

# Stop a running malicious process by name
# WHY: Terminates active encryption or C2 communication.
remediate process ransomware.exe

# Delete a malicious file from the file system
# WHY: Prevents re-execution after process termination.
remediate file C:\Temp\ransomware.exe

# Remove a malicious registry Run key used for persistence
# MITRE: T1547.001 - removes the autostart entry.
remediate registry HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v MaliciousEntry

# Remove a scheduled task used for persistence
# MITRE: T1053.005 - unregisters the malicious task.
run PowerShell.exe -Command "Unregister-ScheduledTask -TaskName 'MaliciousTask' -Confirm:$false"

# Run a full Defender AV scan to catch remaining artifacts
# WHY: Ensures no dormant malware files remain on disk.
run PowerShell.exe -Command "Start-MpScan -ScanType FullScan"

# Update signatures first, then run full scan for latest detections
run PowerShell.exe -Command "Update-MpSignature; Start-MpScan -ScanType FullScan"

PowerShell Cleanup Script

# Comprehensive post-ransomware cleanup script
# Run via Live Response: putfile cleanup.ps1, then: run cleanup.ps1

# 1. Stop suspicious processes
$suspiciousProcesses = @("ransomware", "cryptor", "locker")
foreach ($proc in $suspiciousProcesses) {
    Get-Process -Name $proc -ErrorAction SilentlyContinue |
        Stop-Process -Force -ErrorAction SilentlyContinue
    Write-Host "Stopped process: $proc"
}

# 2. Remove known malicious files
$maliciousPaths = @(
    "C:\Temp\ransomware.exe",
    "C:\Users\Public\payload.exe",
    "$env:APPDATA\malware.exe"
)
foreach ($path in $maliciousPaths) {
    if (Test-Path $path) {
        Remove-Item $path -Force
        Write-Host "Removed: $path"
    }
}

# 3. Clean malicious registry Run keys
$runKeyPath = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run"
$suspiciousValues = Get-ItemProperty $runKeyPath -ErrorAction SilentlyContinue |
    Get-Member -MemberType NoteProperty |
    Where-Object { $_.Name -notin @("PSPath","PSParentPath","PSChildName","PSProvider") }

foreach ($val in $suspiciousValues) {
    $valData = (Get-ItemProperty $runKeyPath).$($val.Name)
    if ($valData -match "Temp|Public|AppData.*\.exe") {
        Remove-ItemProperty -Path $runKeyPath -Name $val.Name -Force
        Write-Host "Removed Run key: $($val.Name) = $valData"
    }
}

# 4. Check if shadow copies can be restored
vssadmin list shadows

# 5. Run a full Defender scan
Update-MpSignature
Start-MpScan -ScanType FullScan
Write-Host "Cleanup complete. Full scan initiated."
⚠️ Important: Always verify remediation actions before releasing a device from isolation. Confirm that all malicious processes are stopped, persistence mechanisms are removed, and a full AV scan returns clean results.

Step 14 · Release Device from Isolation After Remediation

Once you have confirmed that the threat is fully remediated, release the device from network isolation so the user can resume normal operations.

Pre-Release Verification Checklist

  • Full antivirus scan completed with zero detections
  • All malicious processes confirmed stopped (check via Live Response processes command)
  • All persistence mechanisms removed (registry Run keys, scheduled tasks, WMI subscriptions)
  • No active outbound connections to suspicious IP addresses (check via Live Response connections command)
  • Malicious files quarantined or deleted from the file system
  • Device timeline shows no new suspicious activity after remediation

Release from Isolation

  1. Navigate to the isolated device page in the Defender portal
  2. Click Release from isolation in the response actions bar
  3. Add a comment: "Remediation verified. Full AV scan clean. Releasing device from isolation."
  4. Click Confirm to release the device
  5. Monitor the device for the next 24-48 hours for any reoccurrence of suspicious activity
  6. Set up a custom detection rule to alert on any file activity from the same malicious hash on any device in the tenant
💡 Pro Tip: After releasing a device from isolation, proactively monitor it using the following KQL query to catch any recurrence within the next 48 hours.
// ---------------------------------------------------------
// WHAT: Monitor a released device for 48 hours post-remediation
// WHY:  Confirms the threat is truly eliminated. Persistent backdoors
//       or scheduled tasks may re-activate after isolation is lifted.
//       This query catches common post-compromise reinfection patterns.
// DETECTION LOGIC: Watches for script interpreters (powershell, cmd,
//   wscript, cscript, mshta) running with suspicious command-line
//   arguments associated with malware behavior:
//   -enc/-encoded = Base64-encoded commands (obfuscation)
//   downloadstring/downloadfile = remote payload download
//   invoke-expression/iex = dynamic code execution
//   bypass = execution policy bypass
//   hidden = hidden window (stealth execution)
// TIME WINDOW: 48 hours - covers two full business days.
// OUTPUT: Any results require immediate re-investigation.
// ---------------------------------------------------------
let releasedDevice = "ENGWS-PC01";  // Replace with actual device name
DeviceProcessEvents
| where Timestamp > ago(48h)
| where DeviceName == releasedDevice
| where FileName in~ ("powershell.exe", "cmd.exe", "wscript.exe", "cscript.exe", "mshta.exe")
| where ProcessCommandLine has_any (
    "-enc", "-encoded", "downloadstring", "downloadfile",
    "invoke-expression", "iex", "bypass", "hidden"
)
| project Timestamp, DeviceName, FileName,
    ProcessCommandLine, AccountName
| sort by Timestamp desc

Step 15 · Document Findings and Create an Incident Report

Thorough documentation is essential for compliance, lessons learned, and future reference. Create a comprehensive incident report using the evidence gathered during the investigation.

Incident Report Structure

  1. Executive Summary: One-paragraph overview covering what happened, when, scope of impact, and resolution status
  2. Timeline of Events: Chronological listing of each phase from initial access through containment and remediation
  3. Attack Chain Analysis: Detailed breakdown of each kill chain phase with MITRE ATT&CK mappings
  4. Affected Assets: List of all compromised devices, user accounts, and data repositories impacted
  5. Indicators of Compromise (IOCs): File hashes (SHA256), IP addresses, domain names, file paths, registry keys
  6. Containment Actions: Isolation timestamps, network controls applied, and scope of containment
  7. Remediation Actions: Files quarantined, processes stopped, persistence removed, AV scan results
  8. Root Cause Analysis: How the attacker gained initial access and what controls failed
  9. Recommendations: Security improvements to prevent recurrence (patch gaps, email filtering, ASR rules, user training)
  10. Appendices: Raw KQL query results, investigation package analysis, process tree screenshots

Update the Incident in the Defender Portal

  1. Navigate back to the incident in the Defender portal
  2. Update the Classification to True positive with the type Ransomware
  3. Update the Status to Resolved
  4. Add a detailed comment summarizing the investigation findings, remediation actions, and IOCs
  5. Tag the incident with relevant labels: "Ransomware", "Contained", "Remediated"

Export Evidence from MDE

  • Export the device timeline as CSV for inclusion in the report
  • Save advanced hunting query results as evidence artifacts
  • Download the investigation package .zip for offline forensic analysis
  • Take screenshots of the incident attack story graph and process tree
  • Export the Action center log showing all response actions taken
💡 Pro Tip: Store incident reports in a central repository (SharePoint, Azure DevOps Wiki, or your ITSM tool). Cross-reference with incident IDs from the Defender portal so future analysts can quickly locate the full investigation details.

Summary

What You Accomplished

  • Learned the ransomware attack lifecycle and how each phase maps to MITRE ATT&CK tactics
  • Reviewed MDE's multi-layered ransomware detection capabilities
  • Triggered a safe ransomware simulation and generated realistic alerts for investigation
  • Investigated alerts from the incidents queue, analyzing attack story, assets, and evidence
  • Used the device timeline and process tree to reconstruct the full attack chain
  • Collected an investigation package with forensic artifacts from the affected device
  • Connected via Live Response and ran forensic commands to gather process, network, file, and registry evidence
  • Isolated the affected device to contain the threat and prevent lateral movement
  • Hunted for lateral movement and persistence mechanisms using KQL advanced hunting queries
  • Remediated the threat by quarantining files, stopping processes, and removing persistence
  • Released the device from isolation after verifying successful remediation
  • Documented all findings and created a structured incident report

Cost Considerations

  • All investigation and response features (timeline, Live Response, isolation, investigation packages) are included with MDE Plan 2
  • MDE Plan 2 is included in Microsoft 365 E5 or available as a standalone license
  • Advanced hunting queries consume tenant-level resources but have no per-query charges
  • If forwarding device events to Microsoft Sentinel, monitor data ingestion costs for high-volume tables like DeviceFileEvents

Cleanup (Lab Environment Only)

  • Resolve any test alerts and incidents created during the simulation
  • Run the cleanup script from Step 3 to remove simulation artifacts from the test device
  • Remove any test files or scripts uploaded via Live Response
  • Clear the test detection events by resolving them as "Informational, expected activity"

Next Steps

  • Next Lab: Build Custom Detection Rules and Automate Response
  • Enable Automated Investigation and Response (AIR) to automatically remediate common ransomware alerts
  • Deploy Controlled Folder Access to protect critical directories from encryption
  • Integrate MDE incidents with Microsoft Sentinel for cross-product correlation and automated playbook response

📚 Documentation Resources

ResourceDescription
Investigate incidents in Microsoft Defender for EndpointTriage and analyze security incidents using the MDE portal
Investigate entities on devices using Live ResponseRun remote forensic commands on endpoints via Live Response
Take response actions on a deviceIsolate, restrict, or scan devices during incident response
Collect investigation package from devicesGather forensic artifacts and diagnostic data from endpoints
Take response actions on a fileQuarantine, block, or allow files across your organization
Advanced hunting overviewWrite KQL queries to proactively hunt for threats across telemetry
Protect important folders with controlled folder accessPrevent unauthorized apps from modifying files in protected folders
Microsoft Defender for Endpoint documentationComprehensive reference for all MDE features and capabilities
← All Labs Next Lab →