# ============================================================================== # ChaosAgent.ps1 - Autonomous Local Chaos Execution & Telemetry Agent # Implements Safe Startup Invariant & Active Interactive-Session Awareness. # ============================================================================== param( [switch]$Daemon, [string]$HarnessDir = "C:\ProgramData\ClassNotify-TestHarness", [string]$ServerBaseUrl = "http://127.0.0.1:5000" ) $ErrorActionPreference = "Continue" $moduleDir = Join-Path $HarnessDir "modules" if (-not (Test-Path $moduleDir)) { $scriptRoot = $PSScriptRoot if (-not $scriptRoot) { $scriptRoot = Get-Location } $moduleDir = Join-Path $scriptRoot "modules" } Import-Module (Join-Path $moduleDir "NetworkChaos.psm1") -Force Import-Module (Join-Path $moduleDir "ProcessChaos.psm1") -Force Import-Module (Join-Path $moduleDir "Performance.psm1") -Force Import-Module (Join-Path $moduleDir "UpdateChaos.psm1") -Force # ============================================================================== # SAFE STARTUP INVARIANT: Clean up stale firewall rules FIRST on every launch # ============================================================================== Clear-AllTestFirewallRules $stateDir = Join-Path $HarnessDir "state" $logsDir = Join-Path $HarnessDir "logs" $metricsFile = Join-Path $logsDir "metrics.jsonl" $checkpointFile = Join-Path $stateDir "reboot-checkpoint.json" $taskFile = Join-Path $stateDir "active-task.json" $resultFile = Join-Path $stateDir "task-result.json" foreach ($d in @($stateDir, $logsDir)) { if (-not (Test-Path $d)) { New-Item -ItemType Directory -Path $d -Force | Out-Null } } function Test-InteractiveSessionActive { # Check 1: query session / quser for an explicitly 'Active' user session try { $q = quser 2>$null if ($q) { foreach ($line in $q) { if ($line -match "(?i)\bActive\b" -and $line -notmatch "(?i)\bservices\b") { return $true } } } } catch {} # Check 2: Fallback check for explorer.exe running in SessionId > 0 $explorers = Get-Process -Name "explorer" -ErrorAction SilentlyContinue if (-not $explorers) { return $false } foreach ($exp in $explorers) { if ($exp.SessionId -gt 0) { return $true } } return $false } # 1. Boot-Recovery Checkpoint Handler if (Test-Path $checkpointFile) { try { $cp = Get-Content -Path $checkpointFile -Raw | ConvertFrom-Json Write-Host "[ChaosAgent] Found active reboot checkpoint from session $($cp.SessionId)..." -ForegroundColor Yellow # 1A. Service & Boot Recovery Check (Valid in Session 0) $sw = [System.Diagnostics.Stopwatch]::StartNew() $maxWait = 60 $serviceRecovered = $false while ($sw.Elapsed.TotalSeconds -lt $maxWait) { Start-Sleep -Seconds 2 $st = Get-ClientProcessStatus if ($st.ServiceRunning) { $serviceRecovered = $true break } } # 1B. Interactive Desktop Awareness Check (WPF GUI requires interactive session) $hasInteractiveSession = Test-InteractiveSessionActive $wpfStatus = if ($hasInteractiveSession) { $st = Get-ClientProcessStatus if ($st.WpfRunning) { "Recovered" } else { "PendingRelaunch" } } else { "WaitingForInteractiveSession" } $res = [PSCustomObject]@{ SessionId = $cp.SessionId RebootType = $cp.RebootType ServiceReady = $serviceRecovered InteractiveClientReady = ($wpfStatus -eq "Recovered") WpfStatus = $wpfStatus DurationSeconds = [math]::Round($sw.Elapsed.TotalSeconds, 2) CompletedAtUtc = (Get-Date).ToUniversalTime().ToString("o") } Set-Content -Path (Join-Path $stateDir "reboot-result.json") -Value ($res | ConvertTo-Json -Depth 4) -Force Remove-Item -Path $checkpointFile -Force Write-Host "[ChaosAgent] Post-reboot recovery verified! (ServiceReady: $serviceRecovered, WpfStatus: $wpfStatus)" -ForegroundColor Green } catch { Write-Warning "[ChaosAgent] Error processing reboot checkpoint: $($_.Exception.Message)" } } # 2. Main Agent Execution Loop Write-Host "[ChaosAgent] Starting active listener daemon on Client PC..." -ForegroundColor Cyan $sampleTicker = 0 while ($true) { Start-Sleep -Seconds 1 $sampleTicker++ # Sample performance metrics every 5 seconds if ($sampleTicker -ge 5) { $sampleTicker = 0 try { $samples = Sample-ClientPerformanceMetrics -Stage "Active" foreach ($s in $samples) { Add-Content -Path $metricsFile -Value ($s | ConvertTo-Json -Compress) } } catch {} } # Check for active dispatched tasks if (Test-Path $taskFile) { try { $task = Get-Content -Path $taskFile -Raw | ConvertFrom-Json Remove-Item -Path $taskFile -Force # Consume task Write-Host "[ChaosAgent] Executing command: $($task.Action)..." -ForegroundColor Yellow $output = switch ($task.Action) { "KillWpf" { # Interactive Session Guard: If no interactive desktop exists, mark WaitingForInteractiveSession if (-not (Test-InteractiveSessionActive)) { [PSCustomObject]@{ TimestampUtc = (Get-Date).ToUniversalTime().ToString("o") Target = "WPF" Status = "WaitingForInteractiveSession" Message = "Cannot execute WPF GUI chaos in Session 0 without active interactive desktop." RecoveredSuccessfully = $false } } else { $sec = if ($null -ne $task.MaxAllowedRecoverySec) { [int]$task.MaxAllowedRecoverySec } else { 15 } Kill-WpfClientAndMeasureRecovery -MaxAllowedRecoverySeconds $sec } } "KillService" { $sec = if ($null -ne $task.MaxAllowedRecoverySec) { [int]$task.MaxAllowedRecoverySec } else { 75 } Kill-WindowsServiceAndMeasureRecovery -MaxAllowedRecoverySeconds $sec } "NetworkDrop" { $sec = if ($null -ne $task.DurationSec) { [int]$task.DurationSec } else { 15 } $sId = if ($null -ne $task.SessionId) { $task.SessionId } else { "chaos" } Invoke-NetworkChaosCycle -BlockDurationSeconds $sec -MaxAllowedRecoverySeconds 30 -SessionId $sId -TargetServiceExe $task.TargetServiceExe } "ArmRebootCheckpoint" { Set-Content -Path $checkpointFile -Value ($task | ConvertTo-Json -Depth 4) -Force [PSCustomObject]@{ Status = "CheckpointArmed" } } "Status" { [PSCustomObject]@{ InteractiveSessionActive = (Test-InteractiveSessionActive) ClientStatus = (Get-ClientProcessStatus) EnvironmentClean = $true } } Default { [PSCustomObject]@{ Status = "UnknownAction"; Action = $task.Action } } } Set-Content -Path $resultFile -Value ($output | ConvertTo-Json -Depth 4) -Force } catch { Write-Warning "[ChaosAgent] Task execution error: $($_.Exception.Message)" } } if (-not $Daemon) { break # Single pass if not daemon } }