Bind Windows script contexts to the installed signed helper

This commit is contained in:
2026-11-18 11:58:55 +01:00
parent ab20cb0778
commit c692316abe
10 changed files with 345 additions and 14 deletions
+185 -5
View File
@@ -4,6 +4,7 @@
param(
[Parameter(Mandatory)][Uri]$BootstrapBase,
[Security.SecureString]$EnrollmentToken,
[switch]$EnableAdministratorScripts,
[ValidateSet('x86_64-pc-windows-msvc','x86_64-pc-windows-gnu')]
[string]$Platform = 'x86_64-pc-windows-gnu'
)
@@ -66,8 +67,187 @@ function Set-Text([string]$Path, [string]$Value) {
function Get-Hash([string]$Path) {
return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant()
}
# The network process stays LocalService. Only the pinned local helper consumes
# SYSTEM grants. Its private ledger persists across restarts and signed updates.
function Assert-AdminPath([string]$Path, [string]$StopAt) {
$item = Get-Item -LiteralPath $Path -Force
while ($item) {
if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Unexpected reparse point: $($item.FullName)" }
$acl = Get-Acl -LiteralPath $item.FullName
if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -notin @($administrators.Value,$system.Value)) {
throw "Administrator-owned path required: $($item.FullName)"
}
foreach ($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) {
if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -notin @($administrators.Value,$system.Value) -and
([int64]$rule.FileSystemRights -band 0x500d0156)) { throw "Writable installation path: $($item.FullName)" }
}
if ($item.FullName -ieq $StopAt) { return }
$item = if ($item -is [IO.FileInfo]) { $item.Directory } else { $item.Parent }
}
throw 'Path outside the expected installation directory.'
}
function Publish-HelperText([string]$Path, [string]$Text) {
$pending = $Path + '.' + [Guid]::NewGuid()
try {
$f = [IO.File]::Open($pending, 'CreateNew')
try {
$bytes = $utf8.GetBytes($Text)
$f.Write($bytes, 0, $bytes.Length)
$f.Flush($true)
} finally { $f.Dispose() }
$acl = Get-Acl -LiteralPath $pending
$acl.SetOwner($administrators)
Set-Acl -LiteralPath $pending -AclObject $acl
[IO.File]::Move($pending, $Path)
} finally { if (Test-Path -LiteralPath $pending) { Remove-Item -LiteralPath $pending } }
}
function Install-ScriptHelper {
# Enrollment and ordinary updates cannot grant SYSTEM execution. This switch
# is a local administrator's choice for this particular installation.
if (!$EnableAdministratorScripts) { return }
$cfg = Join-Path $data 'config.json'
Assert-AdminPath $cfg $data
$guardPath = Join-Path $data 'release-job.lock'
Assert-AdminPath $guardPath $data
$gate = [IO.File]::Open($guardPath,'Open','ReadWrite','None')
try {
$config = [IO.File]::ReadAllText($cfg) | ConvertFrom-Json
if (!$config.PSObject.Properties['enable_jobs'] -or !$config.enable_jobs) { throw 'Local script execution is disabled.' }
$timePath = Join-Path $data 'job-time.json'
if ($config.localservice_time_policy -ine $timePath) { throw 'Expected the enrolled LocalService time policy.' }
if (($config.PSObject.Properties['windows_echo_probe_only'] -and $config.windows_echo_probe_only) -or
($config.PSObject.Properties['windows_update_helper'] -and $config.windows_update_helper)) {
throw 'The existing restricted execution profile must finish and be closed before provisioning.'
}
$alreadyConfigured = $config.PSObject.Properties['managed_script_helper'] -and $config.managed_script_helper
$records = Join-Path $data 'release-state'
if ((Test-Path (Join-Path $records 'release-transition.json')) -or (Test-Path (Join-Path $data 'release-transition.json'))) {
throw 'Agent update in progress. Retry the installer once it completes.'
}
$record = Join-Path $records 'installed-release.json'
if (!(Test-Path -LiteralPath $record)) { $record = Join-Path $data 'installed-release.json' }
Assert-AdminPath $record $data
$installed = [IO.File]::ReadAllText($record) | ConvertFrom-Json
$release = Get-Id $installed.release_id
$images = Join-Path $app ('releases\' + $release)
$agentExe = Join-Path $images 'rmm-agent-windows.exe'
$helperExe = Join-Path $images 'rmm-helper-windows.exe'
$worker = Join-Path $app 'rmm-updater-windows.exe'
$envelope = Join-Path $images 'envelope.json'
$ring = Join-Path $data 'release-keyring.json'
foreach ($path in @($agentExe,$helperExe,$worker,$envelope)) { Assert-AdminPath $path $app }
foreach ($path in @($ring,$timePath)) { Assert-AdminPath $path $data }
$service = Get-CimInstance Win32_Service -Filter "Name='RmmDiscoveryWindows'"
$pull = Get-CimInstance Win32_Service -Filter "Name='RmmDiscoveryReleasePull'"
if (!$service -or $service.StartName -ine 'NT AUTHORITY\LocalService' -or
$service.PathName -cne ('"' + $agentExe + '" --service --config "' + $cfg + '"') -or
!$pull -or $pull.StartName -ine 'LocalSystem' -or $pull.PathName -cne ('"' + $worker + '" --release-service')) {
throw 'Service registrations do not match the installed release.'
}
$verified = & $worker --verify-bootstrap $ring $envelope $agentExe $helperExe
if ($LASTEXITCODE -ne 0 -or ($verified | ConvertFrom-Json).release_id -cne $release) { throw 'Installed code pair failed signature verification.' }
foreach ($binary in @($worker,$helperExe)) {
$supported = & $binary --managed-script-helper-version
if ($LASTEXITCODE -ne 0 -or $supported -cne 'managed-script-helper/1') { throw 'Update the agent pair and stable updater before enabling administrator scripts.' }
}
$id = [IO.File]::ReadAllText($identity) | ConvertFrom-Json
$policy = [IO.File]::ReadAllText($timePath) | ConvertFrom-Json
if ($policy.tenant_id -cne $installed.tenant_id -or $policy.job_signing_public_key_hex -cnotmatch '^[0-9a-f]{64}$') {
throw 'Enrolled job trust and installed release belong to different configurations.'
}
$binding = [ordered]@{tenant_id=(Get-Id $policy.tenant_id);agent_id=(Get-Id $id.agent_id);asset_id=(Get-Id $id.asset_id)
enrollment_generation=1;assignment_version=1;public_key_hex=$policy.job_signing_public_key_hex}
$helperName = 'RmmDiscoverySystemHelper'
$helperCommand = '"' + $helperExe + '" --service'
$agentSid = [Security.Principal.NTAccount]::new('NT SERVICE',$serviceName).Translate([Security.Principal.SecurityIdentifier])
$root = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscoverySystem'
$stamp = Join-Path $root 'script-helper-enrollment.json'
$owner = [ordered]@{agent_id=$binding.agent_id;asset_id=$binding.asset_id;tenant_id=$binding.tenant_id} | ConvertTo-Json -Compress
$helper = Get-CimInstance Win32_Service -Filter "Name='RmmDiscoverySystemHelper'"
if ($helper -and !$alreadyConfigured -and !(Test-Path -LiteralPath $stamp)) {
throw 'Existing local helper registration must be reconciled before provisioning.'
}
if (!(Test-Path -LiteralPath $root)) {
$stage = Join-Path $data ('script-helper-' + [Guid]::NewGuid())
[void][IO.Directory]::CreateDirectory($stage,(Get-DirectoryAcl $agentSid 'ReadAndExecute'))
try {
Publish-HelperText (Join-Path $stage 'script-helper-enrollment.json') $owner
[IO.Directory]::Move($stage,$root)
} finally { if (Test-Path -LiteralPath $stage) { Remove-Item -LiteralPath $stage -Recurse -Force } }
}
Assert-AdminPath $root $root
if (Test-Path -LiteralPath $stamp) {
Assert-AdminPath $stamp $root
if ([IO.File]::ReadAllText($stamp) -cne $owner) { throw 'Local helper belongs to another enrollment.' }
} elseif (!$alreadyConfigured) { throw 'Existing helper state must be reconciled before migration.' }
if ($helper -and ($helper.StartName -ine 'LocalSystem' -or $helper.PathName -cne $helperCommand)) { throw 'Unexpected local helper registration.' }
if (!$helper) { New-Service -Name $helperName -BinaryPathName $helperCommand -StartupType Manual | Out-Null }
& (Join-Path $env:SystemRoot 'System32\sc.exe') sidtype $helperName unrestricted | Out-Null
if ($LASTEXITCODE -ne 0) { throw 'Could not set the local helper service SID.' }
$inputDto = [ordered]@{binding=$binding;release_id=$release;agent_sha256=(Get-Hash $agentExe)
helper_sha256=(Get-Hash $helperExe);max_runtime_seconds=3600;managed_scripts=$true}
$rendered = ($inputDto | ConvertTo-Json -Depth 6 -Compress) | & $helperExe --prepare-enrolled-windows-update
if ($LASTEXITCODE -ne 0) { throw 'Helper could not bind the signed code pair to the enrollment.' }
$pins = $rendered | ConvertFrom-Json
foreach ($kv in @(@('helper.json',$pins.helper_settings),@('agent-pin.json',$pins.agent_pin))) {
$path = Join-Path $root $kv[0]
if (Test-Path -LiteralPath $path) {
Assert-AdminPath $path $root
if ([IO.File]::ReadAllText($path) -cne $kv[1]) { throw 'An existing helper pin differs from this release or enrollment.' }
} else { Publish-HelperText $path $kv[1] }
}
$private = Join-Path $root 'state'
if (!(Test-Path -LiteralPath $private)) { [void][IO.Directory]::CreateDirectory($private,(Get-DirectoryAcl $null '')) }
Assert-AdminPath $private $root
$intents = Join-Path $root 'agent-intents'
if (!(Test-Path -LiteralPath $intents)) { [void][IO.Directory]::CreateDirectory($intents,(Get-DirectoryAcl $agentSid 'ReadAndExecute')) }
Assert-AdminPath $intents $root
foreach ($leaf in @('system-intents.sqlite','system-intents.sqlite-journal')) {
$path = Join-Path $intents $leaf
if (!(Test-Path -LiteralPath $path)) { [IO.File]::Open($path,'CreateNew').Dispose() }
if ((Get-Item -Force -LiteralPath $path).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Unexpected link in intent journal.' }
if (!$alreadyConfigured) {
$acl = [Security.AccessControl.FileSecurity]::new()
$acl.SetOwner($administrators)
$acl.SetAccessRuleProtection($true,$false)
foreach ($sid in @($system,$administrators)) { $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid,'FullControl','Allow')) }
$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($agentSid,[Security.AccessControl.FileSystemRights]0x12019f,'Allow'))
Set-Acl -LiteralPath $path -AclObject $acl
}
}
if (!$alreadyConfigured) {
Stop-Service $serviceName
$temp = $cfg + '.' + [Guid]::NewGuid()
try {
$config | Add-Member -NotePropertyName managed_script_helper -NotePropertyValue $true -Force
Set-Text $temp ($config | ConvertTo-Json -Depth 12 -Compress)
[IO.File]::Replace($temp,$cfg,[NullString]::Value)
} catch {
Start-Service $serviceName
throw
} finally {
if (Test-Path -LiteralPath $temp) { Remove-Item -LiteralPath $temp }
}
}
try {
Set-Service $helperName -StartupType Automatic
Start-Service $helperName
} finally { Start-Service $serviceName }
} finally { $gate.Dispose() }
}
function Start-ReleaseAfterFirstContact {
$receipt = Join-Path $state 'job-readiness.json'
# A previous installer can have stopped the enrolled agent just before
# committing its helper configuration. Resume the same local enrollment.
if ((Get-Service $serviceName).Status -eq 'Stopped') {
$agent = Get-CimInstance Win32_Service -Filter "Name='RmmDiscoveryWindows'"
if ($agent.StartName -ine 'NT AUTHORITY\LocalService') { throw 'Unexpected enrolled agent identity.' }
Start-Service $serviceName
}
$until = [DateTime]::UtcNow.AddSeconds(120)
while ([DateTime]::UtcNow -lt $until) {
if ((Get-Service $serviceName).Status -ne 'Running') { throw 'Agent stopped before first gateway contact. Inspect the installed service.' }
@@ -76,7 +256,7 @@ function Start-ReleaseAfterFirstContact {
$enrolled = [IO.File]::ReadAllText($identity) | ConvertFrom-Json
$hello = [IO.File]::ReadAllText($receipt) | ConvertFrom-Json
if ($hello.agent_id -ceq $enrolled.agent_id -and $hello.connection_generation -ge 1) {
Start-Service $releaseService
try { Install-ScriptHelper } finally { Start-Service $releaseService }
Remove-Item -LiteralPath $firstContact -Force
return
}
@@ -85,6 +265,9 @@ function Start-ReleaseAfterFirstContact {
}
throw 'First authenticated version report is pending. Rerun the installer to finish with this identity.'
}
$utf8 = New-Object Text.UTF8Encoding($false)
$administrators = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')
$system = [Security.Principal.SecurityIdentifier]::new('S-1-5-18')
$origin = Get-Origin $BootstrapBase
$app = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) 'RustDiscovery'
$data = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscovery'
@@ -95,7 +278,7 @@ $serviceName = 'RmmDiscoveryWindows'
$releaseService = 'RmmDiscoveryReleasePull'
$service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if ($service -and (Test-Path -LiteralPath $identity -PathType Leaf)) {
if (Test-Path -LiteralPath $firstContact -PathType Leaf) { Start-ReleaseAfterFirstContact }
if (Test-Path -LiteralPath $firstContact -PathType Leaf) { Start-ReleaseAfterFirstContact } else { Install-ScriptHelper }
Write-Output "Rust Discovery is already enrolled. Agent service: $($service.Status)."
return
}
@@ -108,9 +291,6 @@ try { $token = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr) }
finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr) }
if ($token -cnotmatch '^[0-9a-f]{64}$') { throw 'Invalid one-time enrollment token.' }
$query = '?platform=' + $platform
$utf8 = New-Object Text.UTF8Encoding($false)
$administrators = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')
$system = [Security.Principal.SecurityIdentifier]::new('S-1-5-18')
$stage = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) ('RustDiscovery-install-' + [Guid]::NewGuid().ToString('N'))
[void][IO.Directory]::CreateDirectory($stage, (Get-DirectoryAcl $null ''))
$madeApp = $false