Emergency system isolation script for quickly disconnecting compromised systems from the network during security incidents while preserving forensic evidence.

Overview

This script provides rapid network isolation capabilities for systems suspected of compromise during security incidents. It disables network adapters, blocks all network traffic, logs the isolation action, and preserves system state for forensic analysis.

Use Case: Ransomware attacks, malware infections, data breach containment, compromised account incidents, or any security event requiring immediate system isolation.

Platform: Cross-platform (Windows PowerShell and Linux Bash) Requirements: Administrator/root privileges Execution Time: <10 seconds (critical for incident response)

The Script

Windows PowerShell Version

Lang: powershell
  1#
  2# system-isolation.ps1
  3#
  4# Emergency system isolation script for Windows
  5# Disconnects system from network and blocks all traffic while preserving forensic state
  6#
  7# Author: glyph.sh
  8# Usage: Run as Administrator: .\system-isolation.ps1 [options]
  9# Options:
 10#   -Reason "text"       Reason for isolation (required for logging)
 11#   -LogPath "path"      Custom log file path
 12#   -RestorePoint        Create system restore point before isolation
 13#   -Help                Show this help message
 14#
 15# IMPORTANT: DO NOT SHUT DOWN THE SYSTEM - Preserve volatile memory for forensics
 16#
 17
 18#Requires -RunAsAdministrator
 19
 20param(
 21    [Parameter(Mandatory=$true, HelpMessage="Reason for system isolation")]
 22    [string]$Reason,
 23
 24    [Parameter(Mandatory=$false)]
 25    [string]$LogPath = "C:\IsolationLogs\isolation-$(Get-Date -Format 'yyyyMMdd-HHmmss').log",
 26
 27    [Parameter(Mandatory=$false)]
 28    [switch]$RestorePoint,
 29
 30    [Parameter(Mandatory=$false)]
 31    [switch]$Help
 32)
 33
 34# Colors for output
 35$ErrorColor = "Red"
 36$WarningColor = "Yellow"
 37$SuccessColor = "Green"
 38$InfoColor = "Cyan"
 39
 40# Display help
 41if ($Help) {
 42    Write-Host @"
 43System Isolation Script - Windows
 44==================================
 45
 46Usage: .\system-isolation.ps1 -Reason "description" [options]
 47
 48Parameters:
 49  -Reason "text"       Reason for isolation (REQUIRED)
 50  -LogPath "path"      Custom log file path (optional)
 51  -RestorePoint        Create system restore point (optional)
 52  -Help                Show this help message
 53
 54Example:
 55  .\system-isolation.ps1 -Reason "Ransomware detected - Sev1 incident #2024-001"
 56
 57IMPORTANT: This script will immediately disconnect the system from all networks.
 58           Do NOT shut down the system after isolation - preserve memory for forensics.
 59"@
 60    exit 0
 61}
 62
 63# Function to write log entries
 64function Write-Log {
 65    param(
 66        [string]$Message,
 67        [string]$Level = "INFO"
 68    )
 69
 70    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
 71    $logEntry = "[$timestamp] [$Level] $Message"
 72
 73    # Ensure log directory exists
 74    $logDir = Split-Path -Parent $LogPath
 75    if (-not (Test-Path $logDir)) {
 76        New-Item -ItemType Directory -Path $logDir -Force | Out-Null
 77    }
 78
 79    # Write to log file
 80    Add-Content -Path $LogPath -Value $logEntry
 81
 82    # Write to console with color
 83    switch ($Level) {
 84        "ERROR"   { Write-Host $logEntry -ForegroundColor $ErrorColor }
 85        "WARNING" { Write-Host $logEntry -ForegroundColor $WarningColor }
 86        "SUCCESS" { Write-Host $logEntry -ForegroundColor $SuccessColor }
 87        default   { Write-Host $logEntry -ForegroundColor $InfoColor }
 88    }
 89}
 90
 91# Function to capture system state
 92function Capture-SystemState {
 93    Write-Log "Capturing system state for forensics..." "INFO"
 94
 95    try {
 96        # Create forensics directory
 97        $forensicsDir = "C:\Forensics-$(Get-Date -Format 'yyyyMMdd-HHmmss')"
 98        New-Item -ItemType Directory -Path $forensicsDir -Force | Out-Null
 99
100        # Capture network connections BEFORE isolation
101        Write-Log "Capturing active network connections..." "INFO"
102        Get-NetTCPConnection | Where-Object {$_.State -eq "Established"} |
103            Export-Csv "$forensicsDir\network-connections.csv" -NoTypeInformation
104
105        # Capture running processes
106        Write-Log "Capturing running processes..." "INFO"
107        Get-Process | Select-Object ProcessName, Id, Path, StartTime, CPU, WorkingSet |
108            Export-Csv "$forensicsDir\processes.csv" -NoTypeInformation
109
110        # Capture network adapter information
111        Write-Log "Capturing network adapter information..." "INFO"
112        Get-NetAdapter | Select-Object Name, Status, MacAddress, LinkSpeed |
113            Export-Csv "$forensicsDir\network-adapters.csv" -NoTypeInformation
114
115        # Capture routing table
116        Get-NetRoute | Export-Csv "$forensicsDir\routing-table.csv" -NoTypeInformation
117
118        # Capture DNS cache
119        Get-DnsClientCache | Export-Csv "$forensicsDir\dns-cache.csv" -NoTypeInformation
120
121        # Capture firewall rules
122        Get-NetFirewallRule | Select-Object DisplayName, Enabled, Direction, Action |
123            Export-Csv "$forensicsDir\firewall-rules.csv" -NoTypeInformation
124
125        # Capture logged-on users
126        quser 2>$null | Out-File "$forensicsDir\logged-users.txt"
127
128        # Capture system information
129        Get-ComputerInfo | Out-File "$forensicsDir\system-info.txt"
130
131        Write-Log "System state captured to: $forensicsDir" "SUCCESS"
132        return $forensicsDir
133    }
134    catch {
135        Write-Log "Error capturing system state: $_" "ERROR"
136        return $null
137    }
138}
139
140# Function to create restore point
141function Create-RestorePoint {
142    if ($RestorePoint) {
143        Write-Log "Creating system restore point..." "INFO"
144        try {
145            Enable-ComputerRestore -Drive "C:\" -ErrorAction SilentlyContinue
146            Checkpoint-Computer -Description "Pre-Isolation Restore Point" -RestorePointType "MODIFY_SETTINGS"
147            Write-Log "System restore point created" "SUCCESS"
148        }
149        catch {
150            Write-Log "Warning: Could not create restore point: $_" "WARNING"
151        }
152    }
153}
154
155# Function to disable network adapters
156function Disable-NetworkAdapters {
157    Write-Log "Disabling all network adapters..." "INFO"
158
159    try {
160        $adapters = Get-NetAdapter | Where-Object {$_.Status -eq "Up"}
161
162        if ($adapters.Count -eq 0) {
163            Write-Log "No active network adapters found" "WARNING"
164            return
165        }
166
167        foreach ($adapter in $adapters) {
168            Write-Log "Disabling adapter: $($adapter.Name)" "INFO"
169            Disable-NetAdapter -Name $adapter.Name -Confirm:$false -ErrorAction Stop
170            Write-Log "Disabled: $($adapter.Name)" "SUCCESS"
171        }
172
173        Write-Log "All network adapters disabled" "SUCCESS"
174    }
175    catch {
176        Write-Log "Error disabling network adapters: $_" "ERROR"
177        throw
178    }
179}
180
181# Function to block all network traffic with firewall
182function Block-NetworkTraffic {
183    Write-Log "Configuring firewall to block all traffic..." "INFO"
184
185    try {
186        # Block all inbound traffic
187        Write-Log "Blocking all inbound traffic..." "INFO"
188        New-NetFirewallRule -DisplayName "ISOLATION-BLOCK-INBOUND" `
189            -Direction Inbound `
190            -Action Block `
191            -Enabled True `
192            -Profile Any `
193            -Priority 1 `
194            -ErrorAction Stop | Out-Null
195
196        # Block all outbound traffic
197        Write-Log "Blocking all outbound traffic..." "INFO"
198        New-NetFirewallRule -DisplayName "ISOLATION-BLOCK-OUTBOUND" `
199            -Direction Outbound `
200            -Action Block `
201            -Enabled True `
202            -Profile Any `
203            -Priority 1 `
204            -ErrorAction Stop | Out-Null
205
206        # Set default firewall policy to block
207        Set-NetFirewallProfile -Profile Domain,Public,Private -DefaultInboundAction Block -DefaultOutboundAction Block
208
209        Write-Log "Firewall configured to block all traffic" "SUCCESS"
210    }
211    catch {
212        Write-Log "Error configuring firewall: $_" "ERROR"
213        throw
214    }
215}
216
217# Function to disable Windows services that may cause network activity
218function Disable-NetworkServices {
219    Write-Log "Disabling network-related services..." "INFO"
220
221    $servicesToDisable = @(
222        "WinHttpAutoProxySvc",  # WinHTTP Web Proxy Auto-Discovery Service
223        "WebClient",             # WebClient (WebDAV)
224        "RemoteAccess",          # Routing and Remote Access
225        "SharedAccess"           # Internet Connection Sharing
226    )
227
228    foreach ($serviceName in $servicesToDisable) {
229        try {
230            $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
231            if ($service -and $service.Status -eq "Running") {
232                Write-Log "Stopping service: $serviceName" "INFO"
233                Stop-Service -Name $serviceName -Force -ErrorAction SilentlyContinue
234                Set-Service -Name $serviceName -StartupType Disabled -ErrorAction SilentlyContinue
235                Write-Log "Disabled service: $serviceName" "SUCCESS"
236            }
237        }
238        catch {
239            Write-Log "Could not disable service $serviceName : $_" "WARNING"
240        }
241    }
242}
243
244# Function to create isolation marker file
245function Create-IsolationMarker {
246    param([string]$ForensicsDir)
247
248    $markerFile = "C:\SYSTEM_ISOLATED.txt"
249    $markerContent = @"
250========================================
251SYSTEM ISOLATION NOTICE
252========================================
253
254This system has been isolated from the network due to a security incident.
255
256Isolation Time: $(Get-Date -Format "yyyy-MM-dd HH:mm:ss")
257Reason: $Reason
258Forensics Directory: $ForensicsDir
259Log File: $LogPath
260
261DO NOT:
262- Shut down this system (preserves volatile memory)
263- Reconnect to network without IR team approval
264- Delete or modify files
265- Log in with other accounts
266
267NEXT STEPS:
2681. Contact Incident Response Team immediately
2692. Preserve all system state and logs
2703. Await forensic analysis instructions
2714. Document all actions taken
272
273For assistance, contact your Security Operations Center (SOC).
274========================================
275"@
276
277    try {
278        Set-Content -Path $markerFile -Value $markerContent -Force
279        Write-Log "Isolation marker created at: $markerFile" "SUCCESS"
280
281        # Display marker content
282        Write-Host "`n" -NoNewline
283        Write-Host $markerContent -ForegroundColor Yellow
284        Write-Host "`n" -NoNewline
285    }
286    catch {
287        Write-Log "Could not create isolation marker file: $_" "WARNING"
288    }
289}
290
291# Main execution
292function Main {
293    Write-Host "`n========================================" -ForegroundColor Red
294    Write-Host "  EMERGENCY SYSTEM ISOLATION" -ForegroundColor Red
295    Write-Host "========================================`n" -ForegroundColor Red
296
297    Write-Log "========== SYSTEM ISOLATION INITIATED ==========" "INFO"
298    Write-Log "Reason: $Reason" "INFO"
299    Write-Log "Executed by: $env:USERNAME" "INFO"
300    Write-Log "Computer: $env:COMPUTERNAME" "INFO"
301
302    # Step 1: Capture system state BEFORE isolation
303    $forensicsDir = Capture-SystemState
304
305    # Step 2: Create restore point if requested
306    Create-RestorePoint
307
308    # Step 3: Disable network adapters
309    Disable-NetworkAdapters
310
311    # Step 4: Block network traffic with firewall
312    Block-NetworkTraffic
313
314    # Step 5: Disable network services
315    Disable-NetworkServices
316
317    # Step 6: Create isolation marker
318    Create-IsolationMarker -ForensicsDir $forensicsDir
319
320    # Step 7: Final verification
321    Write-Log "Verifying isolation status..." "INFO"
322    $activeAdapters = Get-NetAdapter | Where-Object {$_.Status -eq "Up"}
323    if ($activeAdapters.Count -eq 0) {
324        Write-Log "VERIFICATION: All network adapters are disabled" "SUCCESS"
325    } else {
326        Write-Log "WARNING: Some adapters may still be active!" "ERROR"
327    }
328
329    Write-Log "========== SYSTEM ISOLATION COMPLETE ==========" "SUCCESS"
330    Write-Host "`n========================================" -ForegroundColor Green
331    Write-Host "  SYSTEM SUCCESSFULLY ISOLATED" -ForegroundColor Green
332    Write-Host "========================================`n" -ForegroundColor Green
333
334    Write-Host "Log file: $LogPath" -ForegroundColor Cyan
335    if ($forensicsDir) {
336        Write-Host "Forensics data: $forensicsDir" -ForegroundColor Cyan
337    }
338
339    Write-Host "`nIMPORTANT: Do NOT shut down this system!" -ForegroundColor Yellow
340    Write-Host "Leave system running to preserve volatile memory for forensics.`n" -ForegroundColor Yellow
341}
342
343# Execute main function
344try {
345    Main
346}
347catch {
348    Write-Log "CRITICAL ERROR during isolation: $_" "ERROR"
349    Write-Host "`nCRITICAL ERROR: System may not be fully isolated!" -ForegroundColor Red
350    Write-Host "Manually disconnect network cable or disable Wi-Fi immediately!" -ForegroundColor Red
351    exit 1
352}

Linux Bash Version

Lang: bash
  1#!/bin/bash
  2
  3#
  4# system-isolation.sh
  5#
  6# Emergency system isolation script for Linux
  7# Disconnects system from network and blocks all traffic while preserving forensic state
  8#
  9# Author: glyph.sh
 10# Usage: sudo ./system-isolation.sh -r "reason" [options]
 11# Options:
 12#   -r, --reason TEXT    Reason for isolation (required)
 13#   -l, --logdir PATH    Custom log directory (default: /var/log/isolation)
 14#   -h, --help          Show this help message
 15#
 16# IMPORTANT: DO NOT SHUT DOWN THE SYSTEM - Preserve volatile memory for forensics
 17#
 18
 19set -euo pipefail
 20
 21# Colors for output
 22RED='\033[0;31m'
 23YELLOW='\033[1;33m'
 24GREEN='\033[0;32m'
 25CYAN='\033[0;36m'
 26NC='\033[0m' # No Color
 27
 28# Variables
 29REASON=""
 30LOG_DIR="/var/log/isolation"
 31TIMESTAMP=$(date +"%Y%m%d-%H%M%S")
 32LOG_FILE=""
 33FORENSICS_DIR=""
 34
 35# Parse command line arguments
 36while [[ $# -gt 0 ]]; do
 37    case $1 in
 38        -r|--reason)
 39            REASON="$2"
 40            shift 2
 41            ;;
 42        -l|--logdir)
 43            LOG_DIR="$2"
 44            shift 2
 45            ;;
 46        -h|--help)
 47            cat << EOF
 48System Isolation Script - Linux
 49================================
 50
 51Usage: sudo $0 -r "reason" [options]
 52
 53Parameters:
 54  -r, --reason TEXT    Reason for isolation (REQUIRED)
 55  -l, --logdir PATH    Custom log directory (optional)
 56  -h, --help          Show this help message
 57
 58Example:
 59  sudo $0 -r "Ransomware detected - Sev1 incident #2024-001"
 60
 61IMPORTANT: This script will immediately disconnect the system from all networks.
 62           Do NOT shut down the system after isolation - preserve memory for forensics.
 63EOF
 64            exit 0
 65            ;;
 66        *)
 67            echo "Unknown option: $1"
 68            exit 1
 69            ;;
 70    esac
 71done
 72
 73# Validate required parameters
 74if [[ -z "$REASON" ]]; then
 75    echo -e "${RED}Error: Reason for isolation is required${NC}"
 76    echo "Usage: sudo $0 -r \"reason\" [options]"
 77    exit 1
 78fi
 79
 80# Check if running as root
 81if [[ $EUID -ne 0 ]]; then
 82    echo -e "${RED}Error: This script must be run as root${NC}"
 83    exit 1
 84fi
 85
 86# Initialize logging
 87LOG_FILE="${LOG_DIR}/isolation-${TIMESTAMP}.log"
 88mkdir -p "$LOG_DIR"
 89
 90# Function to write log entries
 91log() {
 92    local level=$1
 93    shift
 94    local message="$@"
 95    local timestamp=$(date +"%Y-%m-%d %H:%M:%S")
 96    local log_entry="[$timestamp] [$level] $message"
 97
 98    echo "$log_entry" >> "$LOG_FILE"
 99
100    case $level in
101        ERROR)
102            echo -e "${RED}${log_entry}${NC}"
103            ;;
104        WARNING)
105            echo -e "${YELLOW}${log_entry}${NC}"
106            ;;
107        SUCCESS)
108            echo -e "${GREEN}${log_entry}${NC}"
109            ;;
110        *)
111            echo -e "${CYAN}${log_entry}${NC}"
112            ;;
113    esac
114}
115
116# Function to capture system state
117capture_system_state() {
118    log "INFO" "Capturing system state for forensics..."
119
120    FORENSICS_DIR="/var/forensics-${TIMESTAMP}"
121    mkdir -p "$FORENSICS_DIR"
122
123    # Capture network connections BEFORE isolation
124    log "INFO" "Capturing active network connections..."
125    ss -tupan > "${FORENSICS_DIR}/network-connections.txt" 2>/dev/null || \
126        netstat -tupan > "${FORENSICS_DIR}/network-connections.txt" 2>/dev/null
127
128    # Capture network interfaces
129    log "INFO" "Capturing network interface information..."
130    ip addr show > "${FORENSICS_DIR}/network-interfaces.txt" 2>/dev/null
131    ip route show > "${FORENSICS_DIR}/routing-table.txt" 2>/dev/null
132
133    # Capture running processes
134    log "INFO" "Capturing running processes..."
135    ps auxf > "${FORENSICS_DIR}/processes.txt"
136
137    # Capture open files
138    lsof > "${FORENSICS_DIR}/open-files.txt" 2>/dev/null || true
139
140    # Capture ARP cache
141    ip neigh show > "${FORENSICS_DIR}/arp-cache.txt" 2>/dev/null || \
142        arp -a > "${FORENSICS_DIR}/arp-cache.txt" 2>/dev/null
143
144    # Capture firewall rules
145    log "INFO" "Capturing firewall rules..."
146    iptables -L -n -v > "${FORENSICS_DIR}/iptables-rules.txt" 2>/dev/null || true
147    ip6tables -L -n -v > "${FORENSICS_DIR}/ip6tables-rules.txt" 2>/dev/null || true
148
149    # Capture logged-in users
150    who > "${FORENSICS_DIR}/logged-users.txt"
151    w > "${FORENSICS_DIR}/user-activity.txt"
152    last -20 > "${FORENSICS_DIR}/recent-logins.txt"
153
154    # Capture system information
155    uname -a > "${FORENSICS_DIR}/system-info.txt"
156    cat /etc/*-release >> "${FORENSICS_DIR}/system-info.txt" 2>/dev/null || true
157
158    # Capture listening ports
159    ss -tulpn > "${FORENSICS_DIR}/listening-ports.txt" 2>/dev/null || \
160        netstat -tulpn > "${FORENSICS_DIR}/listening-ports.txt" 2>/dev/null
161
162    log "SUCCESS" "System state captured to: ${FORENSICS_DIR}"
163}
164
165# Function to disable network interfaces
166disable_network_interfaces() {
167    log "INFO" "Disabling all network interfaces..."
168
169    # Get list of active network interfaces (excluding loopback)
170    local interfaces=$(ip link show | grep -E '^[0-9]+:' | awk -F': ' '{print $2}' | grep -v '^lo$')
171
172    if [[ -z "$interfaces" ]]; then
173        log "WARNING" "No active network interfaces found"
174        return
175    fi
176
177    for interface in $interfaces; do
178        log "INFO" "Disabling interface: ${interface}"
179        ip link set "$interface" down 2>/dev/null || {
180            log "ERROR" "Failed to disable ${interface}"
181            continue
182        }
183        log "SUCCESS" "Disabled: ${interface}"
184    done
185
186    log "SUCCESS" "All network interfaces disabled"
187}
188
189# Function to block all network traffic with iptables
190block_network_traffic() {
191    log "INFO" "Configuring firewall to block all traffic..."
192
193    # Flush existing rules
194    iptables -F
195    iptables -X
196    ip6tables -F 2>/dev/null || true
197    ip6tables -X 2>/dev/null || true
198
199    # Set default policies to DROP
200    log "INFO" "Setting default policy to DROP..."
201    iptables -P INPUT DROP
202    iptables -P FORWARD DROP
203    iptables -P OUTPUT DROP
204
205    ip6tables -P INPUT DROP 2>/dev/null || true
206    ip6tables -P FORWARD DROP 2>/dev/null || true
207    ip6tables -P OUTPUT DROP 2>/dev/null || true
208
209    # Allow loopback (for local processes)
210    iptables -A INPUT -i lo -j ACCEPT
211    iptables -A OUTPUT -o lo -j ACCEPT
212
213    # Block all other traffic
214    iptables -A INPUT -j DROP
215    iptables -A OUTPUT -j DROP
216    iptables -A FORWARD -j DROP
217
218    # Save iptables rules (distribution-specific)
219    if command -v iptables-save &> /dev/null; then
220        iptables-save > "${FORENSICS_DIR}/iptables-isolation.rules" 2>/dev/null || true
221    fi
222
223    log "SUCCESS" "Firewall configured to block all traffic"
224}
225
226# Function to disable network services
227disable_network_services() {
228    log "INFO" "Stopping network-related services..."
229
230    local services=(
231        "networking"
232        "network-manager"
233        "NetworkManager"
234        "systemd-networkd"
235        "wpa_supplicant"
236        "dhcpcd"
237        "sshd"
238        "ssh"
239    )
240
241    for service in "${services[@]}"; do
242        if systemctl is-active --quiet "$service" 2>/dev/null; then
243            log "INFO" "Stopping service: ${service}"
244            systemctl stop "$service" 2>/dev/null || true
245            log "SUCCESS" "Stopped: ${service}"
246        fi
247    done
248}
249
250# Function to create isolation marker
251create_isolation_marker() {
252    local marker_file="/SYSTEM_ISOLATED.txt"
253
254    cat > "$marker_file" << EOF
255========================================
256SYSTEM ISOLATION NOTICE
257========================================
258
259This system has been isolated from the network due to a security incident.
260
261Isolation Time: $(date +"%Y-%m-%d %H:%M:%S")
262Reason: ${REASON}
263Forensics Directory: ${FORENSICS_DIR}
264Log File: ${LOG_FILE}
265
266DO NOT:
267- Shut down this system (preserves volatile memory)
268- Reconnect to network without IR team approval
269- Delete or modify files
270- Log in with other accounts
271
272NEXT STEPS:
2731. Contact Incident Response Team immediately
2742. Preserve all system state and logs
2753. Await forensic analysis instructions
2764. Document all actions taken
277
278For assistance, contact your Security Operations Center (SOC).
279========================================
280EOF
281
282    log "SUCCESS" "Isolation marker created at: ${marker_file}"
283
284    # Display marker content
285    echo ""
286    echo -e "${YELLOW}$(cat $marker_file)${NC}"
287    echo ""
288}
289
290# Function to verify isolation
291verify_isolation() {
292    log "INFO" "Verifying isolation status..."
293
294    local active_interfaces=$(ip link show | grep -E 'state UP' | grep -v 'lo:' | wc -l)
295
296    if [[ $active_interfaces -eq 0 ]]; then
297        log "SUCCESS" "VERIFICATION: All network interfaces are down"
298    else
299        log "WARNING" "WARNING: Some interfaces may still be active!"
300    fi
301
302    # Check iptables
303    local drop_policy=$(iptables -L INPUT -n | grep -c "policy DROP" || echo "0")
304    if [[ $drop_policy -gt 0 ]]; then
305        log "SUCCESS" "VERIFICATION: Firewall is blocking all traffic"
306    else
307        log "WARNING" "WARNING: Firewall may not be blocking traffic!"
308    fi
309}
310
311# Main execution
312main() {
313    echo -e "\n${RED}========================================${NC}"
314    echo -e "${RED}  EMERGENCY SYSTEM ISOLATION${NC}"
315    echo -e "${RED}========================================${NC}\n"
316
317    log "INFO" "========== SYSTEM ISOLATION INITIATED =========="
318    log "INFO" "Reason: ${REASON}"
319    log "INFO" "Executed by: $(whoami)"
320    log "INFO" "Hostname: $(hostname)"
321
322    # Step 1: Capture system state BEFORE isolation
323    capture_system_state
324
325    # Step 2: Disable network interfaces
326    disable_network_interfaces
327
328    # Step 3: Block network traffic with firewall
329    block_network_traffic
330
331    # Step 4: Disable network services
332    disable_network_services
333
334    # Step 5: Create isolation marker
335    create_isolation_marker
336
337    # Step 6: Verify isolation
338    verify_isolation
339
340    log "SUCCESS" "========== SYSTEM ISOLATION COMPLETE =========="
341    echo -e "\n${GREEN}========================================${NC}"
342    echo -e "${GREEN}  SYSTEM SUCCESSFULLY ISOLATED${NC}"
343    echo -e "${GREEN}========================================${NC}\n"
344
345    echo -e "${CYAN}Log file: ${LOG_FILE}${NC}"
346    echo -e "${CYAN}Forensics data: ${FORENSICS_DIR}${NC}"
347
348    echo -e "\n${YELLOW}IMPORTANT: Do NOT shut down this system!${NC}"
349    echo -e "${YELLOW}Leave system running to preserve volatile memory for forensics.${NC}\n"
350}
351
352# Execute main function
353if ! main; then
354    log "ERROR" "CRITICAL ERROR during isolation"
355    echo -e "\n${RED}CRITICAL ERROR: System may not be fully isolated!${NC}"
356    echo -e "${RED}Manually disconnect network cable or disable Wi-Fi immediately!${NC}\n"
357    exit 1
358fi

Usage

Windows Usage

Basic Isolation

Lang: powershell
1# Run as Administrator
2.\system-isolation.ps1 -Reason "Ransomware detected on workstation"

With System Restore Point

Lang: powershell
1.\system-isolation.ps1 -Reason "Suspected data breach - Sev2 incident" -RestorePoint

Custom Log Location

Lang: powershell
1.\system-isolation.ps1 -Reason "Malware infection" -LogPath "D:\Logs\isolation.log"

Linux Usage

Basic Isolation

Lang: bash
1sudo ./system-isolation.sh -r "Ransomware detected on server"

Custom Log Directory

Lang: bash
1sudo ./system-isolation.sh -r "Compromised account activity" -l "/opt/security/logs"

What It Does

1. System State Capture (Pre-Isolation)

Before disconnecting the network, the script captures critical forensic data:

  • Network Connections: Active TCP/UDP connections and their states
  • Process List: All running processes with details
  • Network Configuration: IP addresses, routes, DNS cache
  • Firewall Rules: Current firewall configuration
  • User Activity: Logged-in users and recent logins
  • System Information: OS version, hostname, kernel details

2. Network Adapter Isolation

Immediately disables all network adapters:

  • Windows: Uses Disable-NetAdapter to shut down interfaces
  • Linux: Uses ip link set down to disable interfaces
  • Result: System cannot send or receive network traffic

3. Firewall-Level Blocking

Creates firewall rules to block all traffic as a secondary defense:

  • Windows: Creates high-priority block rules for inbound/outbound traffic
  • Linux: Sets iptables default policy to DROP for all chains
  • Preserves: Loopback interface for local processes

4. Network Service Shutdown

Stops services that might attempt network communication:

  • Windows: WinHTTP, WebClient, Remote Access, ICS
  • Linux: NetworkManager, wpa_supplicant, sshd, dhcpcd

5. Forensic Evidence Preservation

Maintains system in forensically sound state:

  • No Shutdown: Keeps volatile memory intact
  • Timestamped Logs: All actions logged with timestamps
  • Isolation Marker: Creates visible notice file
  • Read-Only Operations: Minimal system modifications

6. Verification

Confirms successful isolation:

  • Checks network adapter status
  • Verifies firewall rules
  • Reports any remaining active connections

Integration with Incident Response

Severity 1 - Critical (Ransomware, Active Breach)

Lang: bash
1# Windows
2.\system-isolation.ps1 -Reason "CRITICAL: Ransomware encryption detected - Incident #2024-001" -RestorePoint
3
4# Linux
5sudo ./system-isolation.sh -r "CRITICAL: Active data exfiltration detected - Incident #2024-001"

Timeline: Execute within 2-5 minutes of detection

Severity 2 - High (Malware, Suspected Compromise)

Lang: bash
1# Windows
2.\system-isolation.ps1 -Reason "HIGH: Malware detected on endpoint - Incident #2024-002"
3
4# Linux
5sudo ./system-isolation.sh -r "HIGH: Unauthorized root access detected - Incident #2024-002"

Timeline: Execute within 15 minutes of detection

Severity 3 - Medium (Single Compromised Account)

Lang: bash
1# May not require full system isolation
2# Consider network ACLs or user account lockout instead

Forensic Considerations

DO NOT After Isolation

  • Shut down the system - Volatile memory (RAM) contains critical evidence
  • Reconnect to network - May allow attacker to regain access
  • Log in with different accounts - May contaminate evidence
  • Delete files or logs - Destroys forensic evidence
  • Run antivirus scans - May modify malware samples

DO After Isolation

  • Document everything - Write down all observed indicators
  • Contact IR team - Notify incident response immediately
  • Preserve logs - Secure all log files created
  • Wait for guidance - Follow forensic analyst instructions
  • Take photos - Document any on-screen messages/errors

Memory Acquisition (Advanced)

For proper forensic analysis, capture memory before any system changes:

Lang: powershell
1# Windows - Using DumpIt or similar tool
2.\DumpIt.exe /O C:\Forensics\memory.dmp
3
4# Linux - Using LiME or dd
5dd if=/dev/mem of=/forensics/memory.dump bs=1M

Post-Isolation Recovery

Investigation Complete - Clean System

Lang: powershell
 1# Windows - Re-enable network
 2Get-NetAdapter | Enable-NetAdapter
 3
 4# Remove isolation firewall rules
 5Remove-NetFirewallRule -DisplayName "ISOLATION-BLOCK-*"
 6
 7# Linux - Re-enable network
 8sudo ip link set eth0 up
 9sudo systemctl start NetworkManager
10
11# Restore iptables
12sudo iptables -P INPUT ACCEPT
13sudo iptables -P OUTPUT ACCEPT

Confirmed Compromise - Rebuild Required

Lang: bash
1# DO NOT restore system to network
2# 1. Wipe and rebuild from clean media
3# 2. Restore data from clean backups
4# 3. Reset all credentials
5# 4. Enhance monitoring before reconnecting

Limitations

  • Not a substitute for physical isolation - If possible, physically disconnect cables
  • Cannot prevent pre-existing persistence - Malware with firmware-level persistence may survive
  • Assumes normal system function - May not work if system is heavily compromised
  • Volatile memory degrades - Memory evidence begins degrading immediately
  • No memory capture - Script does not capture RAM (requires specialized tools)

Automation and Deployment

Deploy to Multiple Systems

Lang: powershell
1# Windows - Copy to all workstations
2$computers = Get-ADComputer -Filter * | Select-Object -ExpandProperty Name
3foreach ($computer in $computers) {
4    Copy-Item .\system-isolation.ps1 \\$computer\C$\Scripts\
5}

EDR Integration

Integrate with endpoint detection tools for automatic isolation:

Lang: powershell
1# Example: CrowdStrike RTR command
2runscript -CloudFile="system-isolation.ps1" -CommandLine="-Reason 'EDR Auto-Isolation - Malware Detected'"

SOAR Playbook Integration

Add as automated response action in Security Orchestration platforms.

Emergency Contact Information

After running this script:

  1. Contact your SOC/IR Team immediately
  2. Report incident ID and reason for isolation
  3. Provide forensics directory location
  4. Do not make changes until instructed

See Also

Download

Lang: bash
1# Windows
2curl -O https://glyph.sh/scripts/system-isolation.ps1
3
4# Linux
5curl -O https://glyph.sh/scripts/system-isolation.sh
6chmod +x system-isolation.sh

Testing the Script

IMPORTANT: Only test in isolated lab environment!

Lang: bash
1# Create test VM snapshot first
2# Run script
3# Verify isolation (ping should fail)
4# Restore VM from snapshot

Never test isolation scripts on production systems without proper authorization and planning.