#!/usr/bin/env python3 """Create-once passive SYSTEM helper bootstrap. Never creates or approves a job. Deployment order: accepted feature-agent upgrade first, this helper second. The running LocalService agent discovers the protected pin without another restart. Only its own kernel-authenticated Probe can prove the positive pipe exchange. A lost mutation reply permits readback only, never a repeated install/start. """ import argparse import hashlib import json import os from pathlib import Path import re import subprocess import uuid import client_bootstrap as cb import transport_acceptance as base require = cb.contract.require STATE = cb.EVIDENCE / 'system-helper-bootstrap' AGENT_ID = '63ea15b2-0643-403d-b5b4-cba1288dbea3' ASSET_ID = 'a176520e-8a91-4e93-a78b-8e7620f430e0' HELPER_SHA = '921cf1822f128c3e37ca4c0250f08309a14d760453fa3b56a589229c6614353e' UNIT_SHA = 'd98bbd7c96b78f13b3590bc507961821788672326dd2b690050e81e258e64b45' QUALIFICATION = cb.EVIDENCE / 'helper-unit-qualification/38b0fe75-f6a5-4ad3-ab2d-7f3acf7e9cbd/result.json' OWN_SOURCES = { 'crates/agent-windows/src/helper_ipc.rs': '8163e8029b7dfe256d82995036f351c6e241c8e1e184f34129c15ac205052552', 'crates/agent-windows/src/helper_system.rs': '07908fae9f834f9bd728a10885596d2d997d5e26a5712254de35b9e47dfa7226', 'crates/agent-windows/src/bin/rmm-helper-windows.rs': 'e87c39bee18dc9375287e4f490f70d6bbd76629884564f76804f2bd9152358a4', } SCRIPT = r''' $ErrorActionPreference='Stop' $p=$global:RmmSystemHelperPayload if ($null -eq $p -or [string]([guid]$p.id) -cne $p.id -or $p.action -notin @('install','start','readback')) {throw 'Fixed passive helper intent'} foreach($n in @('helper_sha256','agent_sha256','agent_acl_sha256','config_sha256','config_acl_sha256','source_sha256','policy_sha256','pin_sha256')) {if ($p.$n -notmatch '^[0-9a-f]{64}$') {throw 'Exact bootstrap hashes'}} if ($p.helper_sha256 -cne '921cf1822f128c3e37ca4c0250f08309a14d760453fa3b56a589229c6614353e') {throw 'Native-unit-qualified helper only'} $name='RmmDiscoverySystemHelper';$agentName='RmmDiscoveryWindows' $root='C:\ProgramData\RustDiscoverySystem';$state=Join-Path $root 'state' $settingsPath=Join-Path $root 'helper.json';$pinPath=Join-Path $root 'agent-pin.json' $binary='C:\Program Files\RustDiscovery\rmm-helper-windows.exe' $agentBinary='C:\Program Files\RustDiscovery\rmm-agent-windows.exe' $agentConfig='C:\ProgramData\RustDiscovery\config.json' $bootstrap='C:\ProgramData\RustDiscoveryBootstrap' $folder=Join-Path $bootstrap ('system-helper-'+$p.id) $active=Join-Path $bootstrap 'system-helper-active-intent.json' $uploaded=Join-Path (Join-Path $bootstrap $p.helper_sha256) 'rmm-helper-windows.exe' $helperCommand='"C:\Program Files\RustDiscovery\rmm-helper-windows.exe" --service' $agentCommand='"C:\Program Files\RustDiscovery\rmm-agent-windows.exe" --service --config "C:\ProgramData\RustDiscovery\config.json"' $sys='S-1-5-18';$admin='S-1-5-32-544' $agentSid=(New-Object Security.Principal.NTAccount('NT SERVICE',$agentName)).Translate([Security.Principal.SecurityIdentifier]).Value function Sha([byte[]]$data) { $h=[Security.Cryptography.SHA256]::Create() try {return ([BitConverter]::ToString($h.ComputeHash($data))).Replace('-','').ToLowerInvariant()} finally {$h.Dispose()} } function Hash([string]$path) {return (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()} function Sid([string]$name) {return (New-Object Security.Principal.NTAccount('NT SERVICE',$name)).Translate([Security.Principal.SecurityIdentifier]).Value} function Acl-Hash([string]$path) {return Sha ([Text.Encoding]::UTF8.GetBytes((Get-Acl -LiteralPath $path).Sddl))} function Check([string]$path,[bool]$directory,[string[]]$readers,[string[]]$writers) { $item=Get-Item -LiteralPath $path -Force if ($item.PSIsContainer -ne $directory -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {throw 'Protected regular path'} $acl=Get-Acl -LiteralPath $path if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -notin @($sys,$admin)) {throw 'Protected owner'} if ($directory -and !$acl.AreAccessRulesProtected) {throw 'Explicit protected directory DACL required'} $rules=@($acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if (!$rules.Count) {throw 'Empty DACL'} $seen=@{} foreach($r in $rules) { $id=$r.IdentityReference.Value;$rights=[int64]$r.FileSystemRights if ($r.AccessControlType -ne 'Allow') {throw 'Unexpected deny or inherited DACL'} if ($id -in @($sys,$admin)+$writers) {if ($rights -ne 2032127) {throw 'Exact writer rights'}} elseif ($id -in $readers) {if (($rights -band (-bnot 1179817)) -ne 0 -or ($rights -band 131241) -ne 131241) {throw 'Reader must have read-execute only'}} else {throw 'Unlisted principal'} $seen[$id]=$true } foreach($id in @($sys,$admin)+$readers+$writers) {if (!$seen[$id]) {throw 'Missing intended DACL principal'}} } function Protect([string]$path,[bool]$directory,[string[]]$readers,[string[]]$writers) { if ($directory) {$acl=New-Object Security.AccessControl.DirectorySecurity} else {$acl=New-Object Security.AccessControl.FileSecurity} $acl.SetAccessRuleProtection($true,$false);$acl.SetOwner((New-Object Security.Principal.SecurityIdentifier($admin))) $inherit='None';if ($directory) {$inherit='ContainerInherit,ObjectInherit'} foreach($id in @($sys,$admin)+$writers) {$acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($id)),'FullControl',$inherit,'None','Allow')))} foreach($id in $readers) {$acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($id)),'ReadAndExecute',$inherit,'None','Allow')))} Set-Acl -LiteralPath $path -AclObject $acl;Check $path $directory $readers $writers } function Write-New([string]$path,$value) { $bytes=[Text.Encoding]::UTF8.GetBytes(($value | ConvertTo-Json -Depth 24 -Compress)) $f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read) try {$f.Write($bytes,0,$bytes.Length);$f.Flush($true)} finally {$f.Dispose()} } function Agent-State { $service=Get-CimInstance Win32_Service -Filter "Name='RmmDiscoveryWindows'" -OperationTimeoutSec 10 if ($service.State -cne 'Running' -or $service.StartName -cne 'NT AUTHORITY\LocalService' -or $service.PathName -cne $agentCommand -or $service.StartMode -cne 'Auto') {throw 'Original running LocalService agent'} if ((Hash $agentBinary) -cne $p.agent_sha256 -or (Hash $agentConfig) -cne $p.config_sha256 -or (Acl-Hash $agentBinary) -cne $p.agent_acl_sha256 -or (Acl-Hash $agentConfig) -cne $p.config_acl_sha256) {throw 'Current accepted passive feature agent and ACLs'} $cfg=Get-Content -LiteralPath $agentConfig -Raw | ConvertFrom-Json if ((($cfg.PSObject.Properties.Name|Sort-Object)-join ',') -cne 'ca_file,connect_address,enrollment_token_file,server_name,state_directory,transport' -or $cfg.transport -cne 'auto' -or $cfg.server_name -cne 'discovery.ease-technologies.de') {throw 'Unchanged six-field passive auto configuration'} $ident=Get-Content -LiteralPath 'C:\ProgramData\RustDiscovery\state\identity.json' -Raw | ConvertFrom-Json if ($ident.agent_id -cne $p.binding.agent_id -or $ident.asset_id -cne $p.binding.asset_id -or $ident.agent_id -cne '63ea15b2-0643-403d-b5b4-cba1288dbea3' -or $ident.asset_id -cne 'a176520e-8a91-4e93-a78b-8e7620f430e0') {throw 'Original enrolled identity'} $proc=Get-CimInstance Win32_Process -Filter ('ProcessId='+$service.ProcessId) -OperationTimeoutSec 10 $owner=(Invoke-CimMethod -InputObject $proc -MethodName GetOwnerSid -OperationTimeoutSec 10).Sid if ($owner -cne 'S-1-5-19' -or $proc.ExecutablePath -cne $agentBinary) {throw 'Actual agent LocalService process'} return [ordered]@{process_id=$service.ProcessId;creation=$proc.CreationDate.ToUniversalTime().ToString('o');owner_sid=$owner;binary_sha256=(Hash $agentBinary);config_sha256=(Hash $agentConfig);config_acl_sha256=(Acl-Hash $agentConfig);agent_id=$ident.agent_id;asset_id=$ident.asset_id} } function Same-Agent($before,$after) { foreach($field in @('process_id','creation','owner_sid','binary_sha256','config_sha256','config_acl_sha256','agent_id','asset_id')) {if ($before.$field -cne $after.$field) {throw 'No agent restart or identity/configuration mutation allowed'}} } function Peer([string]$service,[string]$sid,[string]$user,[string]$path,[string]$hash) { return [ordered]@{service_name=$service;service_sid=$sid;user_sid=$user;binary=$path;binary_sha256=$hash} } function Configurations([string]$helperSid) { $binding=[ordered]@{tenant_id=$p.binding.tenant_id;asset_id=$p.binding.asset_id;agent_id=$p.binding.agent_id;enrollment_generation=[long]$p.binding.enrollment_generation;assignment_version=[long]$p.binding.assignment_version;public_key_hex=$p.binding.public_key_hex} $agent=Peer $agentName $agentSid 'S-1-5-19' $agentBinary $p.agent_sha256 $helper=Peer $name $helperSid $sys $binary $p.helper_sha256 $settings=[ordered]@{schema_version=1;binding=$binding;agent=$agent;helper=$helper;allowed_services=@();max_runtime_seconds=30;enable_effects=$false;allow_reboot=$false} # JSON.NET/PowerShell may escape strings differently from serde. The policy # hash comes from exact Python canonical settings bytes, verified below. $expected=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($p.settings_base64)) | ConvertFrom-Json $actual=$settings|ConvertTo-Json -Depth 24 -Compress if (($expected|ConvertTo-Json -Depth 24 -Compress) -cne $actual) {throw 'Exact fixed passive public settings'} $settingsBytes=[Convert]::FromBase64String($p.settings_base64) if ((Sha $settingsBytes) -cne $p.policy_sha256) {throw 'Canonical public policy hash'} $pin=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($p.pin_base64)) | ConvertFrom-Json if ($pin.schema_version -ne 1 -or $pin.policy_sha256 -cne $p.policy_sha256 -or ($pin.binding|ConvertTo-Json -Compress) -cne ($binding|ConvertTo-Json -Compress) -or ($pin.agent|ConvertTo-Json -Compress) -cne ($agent|ConvertTo-Json -Compress) -or ($pin.helper|ConvertTo-Json -Compress) -cne ($helper|ConvertTo-Json -Compress)) {throw 'Exact reciprocal public pin'} return $settingsBytes } function Read-Intent { Check $folder $true @() @() $intent=Get-Content -LiteralPath (Join-Path $folder 'intent.json') -Raw | ConvertFrom-Json foreach($field in @('id','helper_sha256','agent_sha256','agent_acl_sha256','config_sha256','config_acl_sha256','source_sha256','policy_sha256','pin_sha256','helper_service_sid','settings_base64','pin_base64')) {if ($intent.payload.$field -cne $p.$field) {throw 'Exact existing passive helper intent'}} $live=Get-Content -LiteralPath $active -Raw | ConvertFrom-Json if ($live.id -cne $p.id) {throw 'Another helper bootstrap is active'} return $intent } function Existing-State($intent) { $agent=Agent-State;Same-Agent $intent.agent $agent $service=Get-CimInstance Win32_Service -Filter "Name='RmmDiscoverySystemHelper'" -OperationTimeoutSec 10 if ($null -eq $service) {return [ordered]@{service_exists=$false;agent=$agent;root_exists=(Test-Path -LiteralPath $root);binary_exists=(Test-Path -LiteralPath $binary);no_jobs=$true;native_pipe_peer_test=$false}} $helperSid=Sid $name if ((Get-ItemPropertyValue -LiteralPath ('HKLM:\SYSTEM\CurrentControlSet\Services\'+$name) -Name ServiceSidType) -ne 1) {throw 'Unrestricted own helper service SID required'} if ($service.StartName -notin @('LocalSystem','NT AUTHORITY\SYSTEM') -or $service.PathName -cne $helperCommand -or $service.StartMode -cne 'Manual' -or $service.ServiceType -cne 'Own Process') {throw 'Fixed SYSTEM own-process service configuration'} Check $root $true @($agentSid,$helperSid) @();Check $state $true @() @($helperSid) foreach($path in @($settingsPath,$pinPath,$binary)) {Check $path $false @($agentSid,$helperSid) @()} if ((Hash $binary) -cne $p.helper_sha256 -or (Hash $settingsPath) -cne $p.policy_sha256 -or (Hash $pinPath) -cne $p.pin_sha256) {throw 'Exact retained helper image and public policy'} [void](Configurations $helperSid) $owner=$null if ($service.State -eq 'Running') { $proc=Get-CimInstance Win32_Process -Filter ('ProcessId='+$service.ProcessId) -OperationTimeoutSec 10 $owner=(Invoke-CimMethod -InputObject $proc -MethodName GetOwnerSid -OperationTimeoutSec 10).Sid if ($owner -cne $sys -or $proc.ExecutablePath -cne $binary) {throw 'Actual own SYSTEM helper process'} } $ledger=Join-Path $state 'ledger.sqlite';$lock=Join-Path $state 'executor.lock' foreach($path in @($ledger,$lock)) {if (Test-Path -LiteralPath $path) {Check $path $false @() @($helperSid)}} $probePath='C:\ProgramData\RustDiscovery\state\helper-probe.json';$probe=$null if (Test-Path -LiteralPath $probePath) { $item=Get-Item -LiteralPath $probePath -Force if ($item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or $item.Length -gt 8192) {throw 'Bounded current agent IPC witness'} $acl=Get-Acl -LiteralPath $probePath if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -notin @($sys,$admin,'S-1-5-19',$agentSid)) {throw 'Own agent IPC witness owner'} foreach($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) {if ($rule.AccessControlType -ne 'Allow' -or $rule.IdentityReference.Value -notin @($sys,$admin,'S-1-5-19',$agentSid)) {throw 'Own agent IPC witness DACL'}} $probe=Get-Content -LiteralPath $probePath -Raw | ConvertFrom-Json } return [ordered]@{service_exists=$true;service_state=$service.State;process_id=$service.ProcessId;owner_sid=$owner;helper_service_sid=$helperSid;helper_sha256=(Hash $binary);policy_sha256=(Hash $settingsPath);pin_sha256=(Hash $pinPath);agent=$agent;enable_effects=$false;allow_reboot=$false;allowed_services=@();ledger_exists=(Test-Path -LiteralPath $ledger);executor_lock_exists=(Test-Path -LiteralPath $lock);private_state_acl_sha256=(Acl-Hash $state);agent_probe=$probe;no_jobs=$true;native_system_service_running=($service.State -eq 'Running');native_pipe_peer_test=$false;clock_adapter_qualified=$false} } Check $bootstrap $true @() @() if ($p.binding.agent_id -cne '63ea15b2-0643-403d-b5b4-cba1288dbea3' -or $p.binding.asset_id -cne 'a176520e-8a91-4e93-a78b-8e7620f430e0' -or $p.binding.public_key_hex -notmatch '^[0-9a-f]{64}$' -or $p.binding.enrollment_generation -ne 1 -or $p.binding.assignment_version -le 0) {throw 'Public signing binding, never private enrollment material'} if ($p.action -eq 'readback') { $intent=Read-Intent;Existing-State $intent | ConvertTo-Json -Depth 24 -Compress;exit 0 } if ($p.action -eq 'install') { if ((Test-Path -LiteralPath $folder) -or (Test-Path -LiteralPath $active) -or (Test-Path -LiteralPath $root) -or (Test-Path -LiteralPath $binary) -or $null -ne (Get-Service -Name $name -ErrorAction SilentlyContinue)) {throw 'Unknown existing helper state: readback only, never adopt or reset a ledger'} Check 'C:\Program Files\RustDiscovery' $true @($agentSid) @() $before=Agent-State Check $uploaded $false @() @() if ((Hash $uploaded) -cne $p.helper_sha256) {throw 'Exact qualified upload'} # SID derivation is deterministic even before CreateService; no service effects # are needed to prepare reciprocal configuration. $helperSid=$p.helper_service_sid if ($helperSid -notmatch '^S-1-5-80-([0-9]+-){4}[0-9]+$') {throw 'Fixed deterministic helper service SID'} $settingsBytes=Configurations $helperSid New-Item -ItemType Directory -Path $folder | Out-Null;Protect $folder $true @() @() Write-New $active @{id=$p.id;source_sha256=$p.source_sha256;no_jobs=$true} Write-New (Join-Path $folder 'intent.json') @{payload=$p;agent=$before;no_jobs=$true} Write-New (Join-Path $folder 'install-attempt.json') @{install_once=$true;no_jobs=$true;enable_effects=$false} # Every mutation follows the retained intent. No existing path is overwritten. New-Item -ItemType Directory -Path $root | Out-Null;Protect $root $true @($agentSid,$helperSid) @() New-Item -ItemType Directory -Path $state | Out-Null;Protect $state $true @() @($helperSid) $source=[IO.File]::Open($uploaded,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::Read) try {$target=[IO.File]::Open($binary,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try {$source.CopyTo($target);$target.Flush($true)} finally {$target.Dispose()}} finally {$source.Dispose()} Protect $binary $false @($agentSid,$helperSid) @() foreach($pair in @(@($settingsPath,$p.settings_base64),@($pinPath,$p.pin_base64))) { $bytes=[Convert]::FromBase64String($pair[1]);$file=[IO.File]::Open($pair[0],[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read) try {$file.Write($bytes,0,$bytes.Length);$file.Flush($true)} finally {$file.Dispose()} Protect $pair[0] $false @($agentSid,$helperSid) @() } New-Service -Name $name -BinaryPathName $helperCommand -DisplayName 'RustDiscovery SYSTEM Helper' -StartupType Manual | Out-Null $sc=Join-Path $env:WINDIR 'System32\sc.exe' & $sc sidtype $name unrestricted | Out-Null;if ($LASTEXITCODE -ne 0) {throw 'Own helper service SID'} if ((Sid $name) -cne $helperSid) {throw 'Actual SCM service SID differs from pin'} $after=Existing-State @{agent=$before} if ($after.service_state -cne 'Stopped' -or $after.ledger_exists -or $after.executor_lock_exists) {throw 'Installed but deliberately not yet started'} Write-New (Join-Path $folder 'installed.json') $after $after|ConvertTo-Json -Depth 24 -Compress;exit 0 } $intent=Read-Intent if (!(Test-Path -LiteralPath (Join-Path $folder 'installed.json'))) {throw 'Complete exact installation receipt required'} $before=Existing-State $intent if ($before.service_state -cne 'Stopped' -or $before.ledger_exists -or $before.executor_lock_exists) {throw 'First passive start only; preserve any existing state'} # Never replay Start-Service after a timeout/lost reply or service failure. Write-New (Join-Path $folder 'start-attempt.json') @{start_once=$true;no_jobs=$true;enable_effects=$false;allow_reboot=$false} Start-Service -Name $name (Get-Service -Name $name).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running,[TimeSpan]::FromSeconds(20)) $after=Existing-State $intent if ($after.service_state -cne 'Running' -or !$after.ledger_exists -or !$after.executor_lock_exists) {throw 'Running own SYSTEM service with retained private ledger/lock required'} Write-New (Join-Path $folder 'started.json') $after $after|ConvertTo-Json -Depth 24 -Compress ''' PREPARE = base.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', 'SystemHelperBootstrap.ps1') LAUNCH = base.LAUNCH_SCRIPT.replace('TransportAcceptance.ps1', 'SystemHelperBootstrap.ps1').replace('RmmTransportPayload', 'RmmSystemHelperPayload') UPLOAD_PREPARE = base.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', 'rmm-helper-windows.exe') def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def canonical(value): return json.dumps(value, ensure_ascii=False, separators=(',', ':')).encode() def store(folder, name, value): path = folder / name fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) with os.fdopen(fd, 'wb') as out: out.write(json.dumps(value, indent=2).encode());out.flush();os.fsync(out.fileno()) return path def private_dir(path): path.mkdir(mode=0o700, parents=True, exist_ok=True) require(not path.is_symlink() and path.stat().st_mode & 0o077 == 0, 'private bootstrap evidence directory') def service_sid(name): # MS-LSAT 3.1.1.1.2 Configurable Translation Database: # https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-lsat/252cb6b0-2edc-4403-9d75-5b2786ba859e # SERVICE SID: SHA-1 of uppercase UTF-16LE service name, five # little-endian 32-bit subauthorities. Native LookupAccountName verifies it. import struct digest = hashlib.sha1(name.upper().encode('utf-16le')).digest() return 'S-1-5-80-' + '-'.join(str(n) for n in struct.unpack('<5I', digest)) def qualified_helper(artifact): proof = cb.contract.protected_json(QUALIFICATION) require(proof.get('verified') is True and proof.get('passed') == 21 and proof.get('binary_sha256') == UNIT_SHA and proof.get('no_jobs') is True and proof.get('native_system_helper_service_test') is False and proof.get('native_pipe_peer_test') is False, 'actual 21-unit qualification, no invented service/pipe proof') require(sha(artifact) == HELPER_SHA, 'exact associated deployable helper artifact; unit executable is different') for path, digest in OWN_SOURCES.items(): require(proof['source_files'].get(path) == digest and sha(cb.ROOT / path) == digest, 'qualified helper codec/SCM sources unchanged') return {'path': str(QUALIFICATION), 'sha256': sha(QUALIFICATION), 'unit_binary_sha256': UNIT_SHA, 'helper_binary_sha256': HELPER_SHA} def current_runtime(): index_path = cb.EVIDENCE / 'current-runtime.json' index = cb.contract.protected_json(index_path) require(index.get('type') == 'rmm.windows.current-runtime' and index.get('schema_version') == 1 and index.get('agent_id') == AGENT_ID and index.get('asset_id') == ASSET_ID and index.get('transport') == 'auto' and index.get('windows_jobs_enabled') is False and index.get('clock_adapter_qualified') is False, 'accepted retained passive runtime index') evidence = Path(index['evidence']['path']).resolve() require(evidence.is_relative_to(cb.EVIDENCE.resolve()) and sha(evidence) == index['evidence']['sha256'], 'exact current-runtime evidence') result = cb.contract.protected_json(evidence) require(result.get('verified') is True and result.get('completed') is True and result.get('restored') is False and result.get('no_jobs') is True, 'actual accepted current runtime') require(index.get('system_helper_client_feature') is True and result.get('system_helper_client_feature') is True, 'accepted optional IPC client must precede helper install; old passive f64 is not an IPC client') native = result['native'] require(native['binary_sha256'] == index['binary_sha256'] and re.fullmatch('[0-9a-f]{64}', native['config_sha256']), 'actual current binary/configuration association') return index, {'path': str(index_path), 'sha256': sha(index_path), 'evidence': index['evidence']}, native def binding_file(path): value = cb.contract.protected_json(path) fields = ('tenant_id','asset_id','agent_id','enrollment_generation','assignment_version','public_key_hex') require(set(value) == set(fields) and value['agent_id'] == AGENT_ID and value['asset_id'] == ASSET_ID and value['enrollment_generation'] == 1 and type(value['assignment_version']) is int and value['assignment_version'] > 0 and re.fullmatch('[0-9a-f]{64}', value['public_key_hex']), 'public signing binding, never tokens or private keys') require(str(uuid.UUID(value['tenant_id'])) == value['tenant_id'] and uuid.UUID(value['tenant_id']).int != 0, 'explicit tenant binding') return {field:value[field] for field in fields} def configurations(binding, agent_sha): helper_sid = service_sid('RmmDiscoverySystemHelper') agent = dict(service_name='RmmDiscoveryWindows',service_sid=service_sid('RmmDiscoveryWindows'),user_sid='S-1-5-19',binary=r'C:\Program Files\RustDiscovery\rmm-agent-windows.exe',binary_sha256=agent_sha) helper = dict(service_name='RmmDiscoverySystemHelper',service_sid=helper_sid,user_sid='S-1-5-18',binary=r'C:\Program Files\RustDiscovery\rmm-helper-windows.exe',binary_sha256=HELPER_SHA) settings = dict(schema_version=1,binding=binding,agent=agent,helper=helper,allowed_services=[],max_runtime_seconds=30,enable_effects=False,allow_reboot=False) raw = canonical(settings);policy = hashlib.sha256(raw).hexdigest() pin = dict(schema_version=1,binding=binding,policy_sha256=policy,agent=agent,helper=helper) return raw, canonical(pin), helper_sid, policy def transfer(path, name, digest, preparation): status = cb.powershell(preparation, {'sha256':digest}) if not status['already_uploaded']: prefix = cb.contract.protected_json(cb.ROOT / 'credentials/windows-dev-access.json')['ssh_prefix'] args = ['sftp'] + [part for part in prefix[1:-1] if part != '-T'] + ['-b','-',prefix[-1]] target = '/C:/ProgramData/RustDiscoveryBootstrap/' + digest + '/' + name result = subprocess.run(args,input=('put '+json.dumps(str(path.resolve()))+' '+json.dumps(target)+'\n').encode(),capture_output=True,timeout=120) require(result.returncode == 0, 'fixed bootstrap SFTP failed') require(cb.powershell(preparation, {'sha256':digest})['already_uploaded'], 'exact immutable staged artifact') return digest def prepare(artifact, binding_path): # All inputs checked and durable locally before the first remote mutation. qualification = qualified_helper(artifact) index, runtime, native = current_runtime() binding = binding_file(binding_path) raw, pin, helper_sid, policy = configurations(binding, index['binary_sha256']) import base64 ident = str(uuid.uuid4());private_dir(STATE);folder = STATE / ident;folder.mkdir(mode=0o700) source_sha = hashlib.sha256(SCRIPT.encode()).hexdigest() payload = dict(id=ident,helper_sha256=HELPER_SHA,agent_sha256=index['binary_sha256'],agent_acl_sha256=native['binary_acl_sha256'],config_sha256=native['config_sha256'],config_acl_sha256=native['config_acl_sha256'],source_sha256=source_sha,binding=binding,helper_service_sid=helper_sid,policy_sha256=policy,pin_sha256=hashlib.sha256(pin).hexdigest(),settings_base64=base64.b64encode(raw).decode(),pin_base64=base64.b64encode(pin).decode()) store(folder,'intent.json',dict(schema_version=1,type='rmm.windows.passive-system-helper',payload=payload,qualification=qualification,current_runtime=runtime,source_file_sha256=sha(__file__),no_jobs=True,helper_enable_effects=False,allow_reboot=False)) source = folder / 'SystemHelperBootstrap.ps1' fd = os.open(source, os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW, 0o600) with os.fdopen(fd,'wb') as out:out.write(SCRIPT.encode());out.flush();os.fsync(out.fileno()) store(folder,'upload-attempt.json',{'helper_sha256':HELPER_SHA,'source_sha256':source_sha}) transfer(artifact, 'rmm-helper-windows.exe', HELPER_SHA, UPLOAD_PREPARE) transfer(source, 'SystemHelperBootstrap.ps1', source_sha, PREPARE) store(folder,'prepared.json',{'prepared':True,'source_sha256':source_sha,'helper_sha256':HELPER_SHA,'no_service_changes':True}) return {'case_id':ident,'prepared':True,'no_service_changes':True} def run(ident, action): require(str(uuid.UUID(ident)) == ident, 'canonical bootstrap case') folder = STATE / ident intent = cb.contract.protected_json(folder / 'intent.json') require(intent['source_file_sha256'] == sha(__file__) and intent['payload']['source_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest(), 'exact prepared runner/source; never silently rebase case') require(cb.contract.protected_json(folder / 'prepared.json')['prepared'] is True, 'completed source/artifact upload') index_path = Path(intent['current_runtime']['path']) require(sha(index_path) == intent['current_runtime']['sha256'], 'accepted runtime index unchanged during bootstrap') payload = dict(intent['payload'], action='readback' if action == 'verify-peer' else action) if action not in ('readback','verify-peer'): store(folder, action+'-attempt.json', {'action_once':action,'source_sha256':payload['source_sha256'],'no_jobs':True}) else: # Immutable readbacks can be repeated safely with fresh evidence UUIDs. store(folder,'readback-intent-'+str(uuid.uuid4())+'.json',{'read_only':True,'no_jobs':True}) result = cb.powershell(LAUNCH, {'sha256':payload['source_sha256'],'payload':payload}, timeout=90, remote_signed=True) store(folder,action+'-result-'+str(uuid.uuid4())+'.json',result) if action == 'verify-peer': verify_peer(result, payload) receipt={'verified':True,'case_id':ident,'native_system_helper_service_test':True,'native_pipe_peer_test':True,'source':'actual_local_service_runtime','agent_process_id':result['agent']['process_id'],'helper_process_id':result['process_id'],'challenge':result['agent_probe']['challenge'],'policy_sha256':payload['policy_sha256'],'helper_sha256':HELPER_SHA,'clock_adapter_qualified':False,'system_capability_advertised':False,'no_jobs':True,'native':result} store(folder,'peer-verified-'+str(uuid.uuid4())+'.json',receipt) return receipt return {'case_id':ident,'action':action,'native':result,'no_jobs':True,'native_pipe_peer_test':False} def verify_peer(result, payload): """The SSH caller only reads a fresh receipt written by the real service. PeerProof/require_self inside the accepted Agent SDK and helper bind kernel pipe PIDs, SCM PIDs, users/service SIDs, creation/aliveness and pinned images. An Admin process that directly opens the pipe cannot emit this success. """ from datetime import datetime, timezone require(result.get('native_system_service_running') is True and result.get('owner_sid') == 'S-1-5-18' and result.get('enable_effects') is False and result.get('allow_reboot') is False and result.get('allowed_services') == [] and result.get('ledger_exists') is True and result.get('executor_lock_exists') is True, 'actual passive SYSTEM helper with private persistent files') probe=result.get('agent_probe') or {} require(probe.get('schema_version') == 1 and probe.get('source') == 'actual_local_service_runtime' and probe.get('agent_process_id') == result['agent']['process_id'] and probe.get('agent_service') == 'RmmDiscoveryWindows' and probe.get('agent_id') == AGENT_ID and probe.get('asset_id') == ASSET_ID, 'actual current LocalService agent wrote the pipe receipt') require(probe.get('authenticated_pipe_exchange') is True and probe.get('client_service_pid_verified_by_helper') is True and probe.get('verified_helper_user_sid') == 'S-1-5-18' and probe.get('verified_helper_service_sid') == payload['helper_service_sid'] and probe.get('helper_binary_sha256') == HELPER_SHA and probe.get('policy_sha256') == payload['policy_sha256'], 'reciprocal exact role/image/policy pipe proof') require(probe.get('helper_clock_qualified') is False and probe.get('helper_ready') is False and probe.get('system_capability_advertised') is False and probe.get('no_jobs') is True, 'pipe connectivity cannot open the clock or a job capability') observed=datetime.fromisoformat(probe['observed_at'].replace('Z','+00:00')) # Freshness here is only acceptance telemetry, never a trusted job clock. require(0 <= (datetime.now(timezone.utc)-observed).total_seconds() <= 90, 'fresh actual agent receipt; wait for normal periodic probe') require(str(uuid.UUID(probe['challenge'])) == probe['challenge'], 'actual challenge UUID') for name in ('ledger_file_id','executor_lock_file_id'): value=probe.get(name) or {} require(type(value.get('volume_serial')) is int and value['volume_serial'] > 0 and isinstance(value.get('file_id'),list) and len(value['file_id']) == 16 and all(type(n) is int and 0 <= n <= 255 for n in value['file_id']) and any(value['file_id']), 'actual helper-held private Windows file identity') def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('action',choices=['prepare','install','start','readback','verify-peer']) parser.add_argument('--artifact',type=Path) parser.add_argument('--public-binding',type=Path) parser.add_argument('--case') args=parser.parse_args() if args.action == 'prepare': require(args.artifact is not None and args.public_binding is not None, 'prepare requires exact artifact and protected PUBLIC binding') result=prepare(args.artifact,args.public_binding) else: require(args.case is not None, 'explicit existing bootstrap case required') result=run(args.case,args.action) print(json.dumps(result)) if __name__ == '__main__': main()