# ============================================================================== # NetworkChaos.psm1 - Safe Program-Targeted Network Interruption with Fail-Closed Watchdog # ============================================================================== $RulePrefix = "ClassNotify-Chaos-" $WatchdogTaskName = "ClassNotifyChaos-NetWatchdog" function Clear-AllTestFirewallRules { [CmdletBinding()] param() # 1. Unregister watchdog task if present try { $task = Get-ScheduledTask -TaskName $WatchdogTaskName -ErrorAction SilentlyContinue if ($task) { Unregister-ScheduledTask -TaskName $WatchdogTaskName -Confirm:$false -ErrorAction SilentlyContinue | Out-Null Write-Verbose "[NetworkChaos] Watchdog scheduled task removed." } } catch {} # 2. Remove all firewall rules matching prefix try { $rules = netsh advfirewall firewall show rule name=all | Select-String "Rule Name:\s+($RulePrefix.*)" foreach ($r in $rules) { $rName = $r.Matches[0].Groups[1].Value.Trim() netsh advfirewall firewall delete rule name="$rName" | Out-Null Write-Verbose "[NetworkChaos] Deleted firewall rule: $rName" } } catch { Write-Warning "[NetworkChaos] Cleanup error: $($_.Exception.Message)" } } function Get-ClassNotifyServiceExePath { $proc = Get-Process -Name "ClassNotify.Service" -ErrorAction SilentlyContinue | Select-Object -First 1 if ($proc -and $proc.Path -and (Test-Path $proc.Path)) { return $proc.Path } $defaultPaths = @( "C:\Program Files\ClassNotify\ClassNotify.Service.exe", "C:\Program Files\ClassNotify\Service\ClassNotify.Service.exe", "C:\Program Files (x86)\ClassNotify\ClassNotify.Service.exe", "$env:LOCALAPPDATA\Programs\ClassNotify\ClassNotify.Service.exe" ) foreach ($p in $defaultPaths) { if (Test-Path $p) { return $p } } return $null } function Set-ClassNotifyNetworkBlock { [CmdletBinding()] param( [string]$SessionId = "default", [int]$AutoRevertSeconds = 180, [string]$TargetServiceExe = $null, [switch]$SimulateWatchdogFailure ) Clear-AllTestFirewallRules $ruleName = "${RulePrefix}${SessionId}" # Blocker 3 Fix: If target program cannot be located, fail closed! No 5000/5001 fallback! if (-not $TargetServiceExe) { $TargetServiceExe = Get-ClassNotifyServiceExePath } if (-not $TargetServiceExe -or -not (Test-Path $TargetServiceExe)) { throw "TargetServiceExecutableNotFound: Cannot block network without valid program path. Fallback ports are strictly forbidden." } # Blocker 2 Fix: Fail-Closed Watchdog Verification # Watchdog MUST be armed and verified via Get-ScheduledTask before adding ANY firewall rule! $watchdogArmed = $false if (-not $SimulateWatchdogFailure) { try { $triggerTime = (Get-Date).AddSeconds($AutoRevertSeconds) $action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-NoProfile -ExecutionPolicy Bypass -Command `"netsh advfirewall firewall delete rule name='$ruleName'`"" $trigger = New-ScheduledTaskTrigger -Once -At $triggerTime $principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest Register-ScheduledTask -TaskName $WatchdogTaskName -Action $action -Trigger $trigger -Principal $principal -Force -ErrorAction Stop | Out-Null $task = Get-ScheduledTask -TaskName $WatchdogTaskName -ErrorAction Stop if ($task) { $watchdogArmed = $true } } catch { $watchdogArmed = $false } } if (-not $watchdogArmed) { # Fail closed: Do NOT create firewall rule! Clear-AllTestFirewallRules throw "NetworkChaosSafetyWatchdogNotArmed: Scheduled task watchdog registration failed or was rejected. Aborting network chaos with 0 firewall rules." } # Secondary in-process timer backup $timerCmd = "Start-Sleep -Seconds $AutoRevertSeconds; netsh advfirewall firewall delete rule name=`"$ruleName`"" Start-Process -FilePath "powershell.exe" -ArgumentList "-NoProfile", "-WindowStyle", "Hidden", "-Command", $timerCmd -WindowStyle Hidden -ErrorAction SilentlyContinue | Out-Null # Add Firewall outbound block rule targeted strictly at the program executable Write-Host "[NetworkChaos] Blocking outbound traffic specifically for program: $TargetServiceExe" -ForegroundColor Yellow netsh advfirewall firewall add rule name="$ruleName" dir=out action=block program="$TargetServiceExe" enable=yes | Out-Null return $ruleName } function Remove-ClassNotifyNetworkBlock { [CmdletBinding()] param() Clear-AllTestFirewallRules Write-Host "[NetworkChaos] Network block removed and durable watchdogs disarmed." -ForegroundColor Green } function Test-ServiceSignalRConnected { [CmdletBinding()] param( [string]$RemoteAddress = "auto" ) try { $svc = Get-Process -Name "ClassNotify.Service" -ErrorAction SilentlyContinue | Select-Object -First 1 if (-not $svc) { return $false } # 1. Primary: Check health_status.json for authoritative application-level SignalR handshake $hsFile = "C:\ProgramData\ClassNotify\health_status.json" if (Test-Path $hsFile) { $hs = Get-Content $hsFile -Raw -ErrorAction SilentlyContinue | ConvertFrom-Json if ($hs -and $hs.SignalROk) { $hsDate = [DateTime]::UtcNow if ($hs.CheckedAtUtc -and [DateTime]::TryParse($hs.CheckedAtUtc, [ref]$hsDate)) { if (([DateTime]::UtcNow - $hsDate).TotalSeconds -lt 30) { return $true } } elseif ($hs.Timestamp -and [DateTime]::TryParse($hs.Timestamp, [ref]$hsDate)) { if (([DateTime]::UtcNow - $hsDate).TotalSeconds -lt 30) { return $true } } else { return $true } } } # 2. Secondary: Inspect OS TCP table $conns = @(Get-NetTCPConnection -OwningProcess $svc.Id -ErrorAction SilentlyContinue | Where-Object { $_.State -eq "Established" }) if ($RemoteAddress -and $RemoteAddress -ne "auto") { $matched = $conns | Where-Object { $_.RemoteAddress -eq $RemoteAddress } if ($matched.Count -gt 0) { return $true } } else { # Any established connection to port 443, 80, 5000, 5001 or non-local $matched = $conns | Where-Object { $_.RemotePort -in @(443, 80, 5000, 5001) -or $_.RemoteAddress -ne "127.0.0.1" } if ($matched.Count -gt 0) { return $true } } return $false } catch { return $false } } function Test-EndpointReachable { [CmdletBinding()] param( [string]$TestUrl = "http://127.0.0.1:5000/api/health", [int]$TimeoutSeconds = 3 ) try { $resp = Invoke-WebRequest -Uri $TestUrl -TimeoutSec $TimeoutSeconds -UseBasicParsing -ErrorAction Stop return ($resp.StatusCode -ge 200 -and $resp.StatusCode -lt 400) } catch { return $false } } function Invoke-NetworkChaosCycle { [CmdletBinding()] param( [int]$BlockDurationSeconds = 15, [int]$MaxAllowedRecoverySeconds = 45, [string]$HealthCheckUrl = "http://127.0.0.1:5000/api/health", [string]$SessionId = "chaos", [string]$TargetServiceExe = $null, [string]$RemoteAddress = "auto" ) $result = [PSCustomObject]@{ TimestampUtc = (Get-Date).ToUniversalTime().ToString("o") DurationSeconds = $BlockDurationSeconds BeforeConnected = $false DuringBlocked = $false AfterRecovered = $false RecoveryDurationSeconds = 0 ChaosEffective = $false Error = $null } $isUsingSignalR = $false $svcProc = Get-Process -Name "ClassNotify.Service" -ErrorAction SilentlyContinue | Select-Object -First 1 if ($svcProc -and (Test-ServiceSignalRConnected)) { $isUsingSignalR = $true } # Step 1: Prove connectivity BEFORE injection if ($isUsingSignalR) { $result.BeforeConnected = Test-ServiceSignalRConnected } else { $result.BeforeConnected = Test-EndpointReachable -TestUrl $HealthCheckUrl } try { # Step 2: Install block rule (Fail-closed watchdog enforced) Set-ClassNotifyNetworkBlock -SessionId $SessionId -AutoRevertSeconds ($BlockDurationSeconds + 60) -TargetServiceExe $TargetServiceExe # Step 3: Prove connectivity is BLOCKED during injection $connectedDuring = $false if ($isUsingSignalR) { $swDuring = [System.Diagnostics.Stopwatch]::StartNew() while ($swDuring.Elapsed.TotalSeconds -lt 8) { Start-Sleep -Seconds 1 if (-not (Test-ServiceSignalRConnected)) { break } } $connectedDuring = Test-ServiceSignalRConnected } else { Start-Sleep -Seconds 2 $connectedDuring = Test-EndpointReachable -TestUrl $HealthCheckUrl -TimeoutSeconds 2 } $result.DuringBlocked = (-not $connectedDuring) if ($connectedDuring) { Write-Warning "[NetworkChaos] Injection verification failed: traffic was not blocked!" $result.Error = "ChaosInjectionIneffective: Target remained connected during block rule." } # Sleep remainder of block duration if ($BlockDurationSeconds -gt 8) { Start-Sleep -Seconds ($BlockDurationSeconds - 8) } # Step 4: Remove rule $sw = [System.Diagnostics.Stopwatch]::StartNew() Remove-ClassNotifyNetworkBlock # Step 5: Prove connectivity RECOVERS after unblock $recovered = $false while ($sw.Elapsed.TotalSeconds -lt $MaxAllowedRecoverySeconds) { if ($isUsingSignalR) { if (Test-ServiceSignalRConnected) { $recovered = $true break } } else { if (Test-EndpointReachable -TestUrl $HealthCheckUrl) { $recovered = $true break } } Start-Sleep -Milliseconds 500 } $result.RecoveryDurationSeconds = [math]::Round($sw.Elapsed.TotalSeconds, 2) $result.AfterRecovered = $recovered # Complete Self-Proof: connected -> disconnected -> connected $result.ChaosEffective = ($result.BeforeConnected -and $result.DuringBlocked -and $result.AfterRecovered) if (-not $recovered) { $result.Error = "Connection failed to recover within ${MaxAllowedRecoverySeconds}s after rule removal" } } catch { $result.Error = $_.Exception.Message Remove-ClassNotifyNetworkBlock } return $result } Export-ModuleMember -Function Clear-AllTestFirewallRules, Get-ClassNotifyServiceExePath, Set-ClassNotifyNetworkBlock, Remove-ClassNotifyNetworkBlock, Test-EndpointReachable, Test-ServiceSignalRConnected, Invoke-NetworkChaosCycle