Skip to main content

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:

IndicatorThresholdDetection source
Antivirus/EDR alertAny confirmed detection (not suspicious/potential)Security console
Process anomalyUnknown process with network connections or child spawningEDR behavioural detection
Command-and-control trafficAny connection to known malicious IP/domainNetwork monitoring, DNS logs
User reportSystem behaving abnormally after opening attachment or visiting websiteService desk
Cryptominer indicatorsCPU sustained above 80% without user activityEndpoint monitoring
Persistence mechanismNew scheduled task, service, or registry run key matching IOC patternsEDR, SIEM correlation
Lateral movement attemptAuthentication attempts from endpoint to multiple systems within 5 minutesSIEM, authentication logs

A single confirmed detection triggers the playbook. Do not wait for multiple indicators when one provides high confidence of infection.

Roles

RoleResponsibilityTypical assigneeBackup
Incident commanderCoordinates response, makes containment decisions, manages communicationsIT manager or security leadSenior system administrator
Technical leadExecutes containment and eradication proceduresSystem administrator or security analystIT support with admin access
Evidence custodianPreserves forensic data, maintains chain of custodySecurity analystIT manager
Communications leadUpdates stakeholders, manages user notificationsIT managerService 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.

  1. 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.

  2. 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 Quarantine

Unmanaged endpoints or EDR unavailable: Disconnect physically or disable the network adapter:

Terminal window
# Windows - disable all network adapters
Get-NetAdapter | Disable-NetAdapter -Confirm:$false
Terminal window
# 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
  1. Terminate the malicious process if still running. Identify the process ID from your EDR console or detection alert:
Terminal window
# Windows
Stop-Process -Id <PID> -Force
Terminal window
# Linux
kill -9 <PID>
  1. Disable the user account associated with the infected endpoint to prevent credential reuse if the malware captured authentication tokens:
Terminal window
# Active Directory
Disable-ADAccount -Identity <username>
Terminal window
# Entra ID via Microsoft Graph
az rest --method PATCH \
--uri "https://graph.microsoft.com/v1.0/users/<user-id>" \
--body '{"accountEnabled": false}'
  1. 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.

  1. 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>*"
  1. 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>
  1. 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_ip

Any additional source IPs indicate other infected endpoints.

  1. 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
  1. 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 |
+---------------+ +-------+
  1. Determine whether a vendor-specific removal tool exists for the identified malware family. Major antivirus vendors publish standalone removal tools for prevalent malware:

    VendorTool repository
    Kasperskyhttps://support.kaspersky.com/viruses/utility
    ESEThttps://www.eset.com/int/support/stand-alone-tools/
    Malwarebyteshttps://www.malwarebytes.com/mwb-download
    MicrosoftWindows Defender Offline, Microsoft Safety Scanner
  2. 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:

Terminal window
# Example: Microsoft Safety Scanner
.\MSERT.exe /F /Q
  1. For unknown malware or when no removal tool exists, perform manual eradication. First, identify and remove persistence mechanisms:

    Windows persistence locations:

Terminal window
# 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:

Terminal window
# 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
  1. Remove identified persistence entries and delete the malware files:
Terminal window
# 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
Terminal window
# Linux - remove cron persistence
crontab -r -u <user>
# Delete malware file
rm -f <malware_path>
  1. Clear cached credentials to prevent reuse of potentially compromised authentication material:
Terminal window
# Windows - clear credential cache
cmdkey /list | ForEach-Object { if ($_ -like "*Target:*") {
cmdkey /delete:($_ -replace ".*Target: ","") }}
# Clear Kerberos tickets
klist purge
  1. Run a full antivirus scan with updated definitions to detect any remaining components:
Terminal window
# Windows Defender
Update-MpSignature
Start-MpScan -ScanType FullScan
  1. 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:
Terminal window
# 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.

  1. 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:
Terminal window
# Windows
Install-WindowsUpdate -AcceptAll -AutoReboot
Terminal window
# Debian/Ubuntu
apt update && apt upgrade -y
# RHEL/CentOS
dnf update -y
  1. 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:
Terminal window
# 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
  1. 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
  1. Re-enable the user account once the endpoint is confirmed clean and credentials are reset:
Terminal window
Enable-ADAccount -Identity <username>
  1. 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
  2. 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.

  1. 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.

  2. Implement specific mitigations based on the identified vector:

    VectorMitigation
    Email attachmentBlock attachment type at mail gateway; implement Safe Attachments sandboxing
    Web downloadBlock executable downloads from uncategorised sites; enable SmartScreen
    Removable mediaRestrict USB storage to authorised devices via device control policy
    Exploit kitPatch the exploited vulnerability; verify web filtering blocks known exploit kit domains
  3. 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
  4. 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.

  5. 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
  6. 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

StakeholderTimingChannelOwnerTemplate reference
Affected userWithin 1 hour of detectionDirect call or messageTechnical leadUser notification below
IT leadershipWithin 2 hoursEmailIncident commanderLeadership update below
All staffOnly if widespread or high-profileOrganisation emailCommunications leadStaff advisory below
Security vendorIf novel malware requiring analysisSupport ticketTechnical leadN/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 network
2. Save any unsaved work to your desktop
3. [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
Terminal window
# Windows evidence collection script (run from admin PowerShell)
$EvidenceDir = "C:\Evidence\$(Get-Date -Format 'yyyyMMdd_HHmmss')"
New-Item -ItemType Directory -Path $EvidenceDir -Force
# Running processes
Get-Process | Select-Object Id, ProcessName, Path, CommandLine |
Export-Csv "$EvidenceDir\processes.csv" -NoTypeInformation
# Network connections
Get-NetTCPConnection | Select-Object LocalAddress, LocalPort, RemoteAddress,
RemotePort, State, OwningProcess |
Export-Csv "$EvidenceDir\connections.csv" -NoTypeInformation
# Scheduled tasks
Get-ScheduledTask | Export-Clixml "$EvidenceDir\scheduled_tasks.xml"
# Registry run keys
reg export "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" `
"$EvidenceDir\hklm_run.reg" /y
reg export "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" `
"$EvidenceDir\hkcu_run.reg" /y
# Event logs
wevtutil epl Security "$EvidenceDir\Security.evtx"
wevtutil epl System "$EvidenceDir\System.evtx"
wevtutil epl Application "$EvidenceDir\Application.evtx"
Terminal window
# Linux evidence collection script (run as root)
EVIDENCE_DIR="/tmp/evidence/$(date +%Y%m%d_%H%M%S)"
mkdir -p "$EVIDENCE_DIR"
# Running processes
ps auxwww > "$EVIDENCE_DIR/processes.txt"
# Network connections
ss -tunap > "$EVIDENCE_DIR/connections.txt"
netstat -tunap > "$EVIDENCE_DIR/netstat.txt" 2>/dev/null
# Cron jobs
for 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/null
done
# Systemd services
systemctl list-unit-files > "$EVIDENCE_DIR/systemd_units.txt"
# Auth logs
cp /var/log/auth.log "$EVIDENCE_DIR/" 2>/dev/null
cp /var/log/secure "$EVIDENCE_DIR/" 2>/dev/null

Network 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:

Terminal window
# 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