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.
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.
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.
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.
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.
MDE uses multiple detection layers to identify ransomware activity. Understanding these layers helps you interpret the alerts and evidence you will encounter.
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.
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"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 GreenThe 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# 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 GreenOnce the simulation triggers alerts, MDE automatically correlates related alerts into an incident. Begin your investigation from the incidents queue.
The device timeline is your primary investigation tool. It shows every process, file, network, and registry event in chronological order on the affected device.
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.
# ---------------------------------------------------------
# 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.exeAn investigation package captures forensic artifacts from the device, including running processes, network connections, scheduled tasks, event logs, and Defender Antivirus logs.
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.
help to see all available 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
libraryUse 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.
# ---------------------------------------------------------
# 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)# ---------------------------------------------------------
# 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# ---------------------------------------------------------
# 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# ---------------------------------------------------------
# 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# ---------------------------------------------------------
# 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"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.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.
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.
// ---------------------------------------------------------
// 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// ---------------------------------------------------------
// 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// ---------------------------------------------------------
// 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 descRansomware operators frequently establish persistence to survive reboots and re-encrypt files. Use KQL to search for common persistence mechanisms across all devices.
// ---------------------------------------------------------
// 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// ---------------------------------------------------------
// 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// ---------------------------------------------------------
// 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 descWith 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.
# ---------------------------------------------------------
# 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"# 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."Once you have confirmed that the threat is fully remediated, release the device from network isolation so the user can resume normal operations.
processes command)connections command)// ---------------------------------------------------------
// 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 descThorough documentation is essential for compliance, lessons learned, and future reference. Create a comprehensive incident report using the evidence gathered during the investigation.
| Resource | Description |
|---|---|
| Investigate incidents in Microsoft Defender for Endpoint | Triage and analyze security incidents using the MDE portal |
| Investigate entities on devices using Live Response | Run remote forensic commands on endpoints via Live Response |
| Take response actions on a device | Isolate, restrict, or scan devices during incident response |
| Collect investigation package from devices | Gather forensic artifacts and diagnostic data from endpoints |
| Take response actions on a file | Quarantine, block, or allow files across your organization |
| Advanced hunting overview | Write KQL queries to proactively hunt for threats across telemetry |
| Protect important folders with controlled folder access | Prevent unauthorized apps from modifying files in protected folders |
| Microsoft Defender for Endpoint documentation | Comprehensive reference for all MDE features and capabilities |