#!/usr/bin/env python3 """Start the existing W32Time once after review; lost replies use readback only. This bootstrap never changes service configuration, NTP, policy, ACLs or RMM components. A running W32Time is not evidence of a qualified/trusted clock. """ import argparse import hashlib import json import os from pathlib import Path import re import stat import uuid import client_bootstrap as cb import system_helper_bootstrap as helper import transport_acceptance as source_stage STATE = cb.EVIDENCE / 'time-service-start' CONTEXT = cb.EVIDENCE / 'time-service-start-context/888b18b8-da7e-4b9f-9e36-32a23f2ff973/before.json' require = cb.contract.require SCRIPT = r'''$ErrorActionPreference='Stop' $p=$global:RmmTimeServiceStartPayload if(!$p-or[guid]::ParseExact($p.id,'D').ToString()-cne$p.id-or$p.action-notin@('state','start','readback')){throw 'Fixed time-service case'} foreach($name in @('agent_sha256','helper_sha256','config_sha256','policy_sha256','pin_sha256')){if($p.$name-notmatch'^[a-f0-9]{64}$'){throw 'Exact retained component pins'}} $boot='C:\ProgramData\RustDiscoveryBootstrap';$folder=Join-Path $boot ('time-service-'+$p.id);$active=Join-Path $boot 'w32time-start-once.json' function HashBytes([byte[]]$bytes){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash($bytes))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}} function JsonHash($value){return HashBytes ([Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 24 -Compress)))} function CheckControl($path,[bool]$directory){ $item=Get-Item -LiteralPath $path -Force if($item.PSIsContainer-ne$directory-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Fixed private bootstrap path'} $acl=Get-Acl -LiteralPath $path if($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')-or!$acl.Access.Count){throw 'Bootstrap owner/DACL'} foreach($r in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Bootstrap controller only'}} } function WriteNew($path,$value){$bytes=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 24 -Compress));$file=[IO.File]::Open($path,'CreateNew','Write','Read');try{$file.Write($bytes,0,$bytes.Length);$file.Flush($true)}finally{$file.Dispose()};CheckControl $path $false} function FileMeta($path,[bool]$hash){ $item=Get-Item -LiteralPath $path -Force;if($item.PSIsContainer-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Regular original component'} $parent=$item.Directory;while($null-ne$parent){if($parent.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Original ancestor reparse'};$parent=$parent.Parent} $acl=Get-Acl -LiteralPath $path return [ordered]@{length=$item.Length;created_filetime=$item.CreationTimeUtc.ToFileTimeUtc().ToString();written_filetime=$item.LastWriteTimeUtc.ToFileTimeUtc().ToString();owner_sid=$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value;acl_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes($acl.Sddl)));sha256=if($hash){(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}else{$null}} } function ServiceState($name){ $service=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") -OperationTimeoutSec 10 if(!$service){throw 'Existing fixed service required'} $security=& "$env:WINDIR\System32\sc.exe" sdshow $name;if($LASTEXITCODE-ne0){throw 'Read service security'} $sidtype=& "$env:WINDIR\System32\sc.exe" qsidtype $name;if($LASTEXITCODE-ne0){throw 'Read service SID type'} $definition=[ordered]@{account=$service.StartName;start_mode=$service.StartMode;image_path=$service.PathName;service_type=$service.ServiceType;security_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes(($security-join "`n").Trim())));sid_type_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes(($sidtype-join "`n").Trim())))} return [ordered]@{name=$name;state=$service.State;pid=$service.ProcessId;definition=$definition} } function TimeConfigHash{ # Selected stable configuration only. Normal synchronization may update other # runtime registry state; neither values nor NTP hostnames leave this function. $specs=@( @('SYSTEM\CurrentControlSet\Services\W32Time',@('Start','DelayedAutoStart','ImagePath','ObjectName','Type')), @('SYSTEM\CurrentControlSet\Services\W32Time\Parameters',@('Type','NtpServer','ServiceDll','ServiceMain')), @('SYSTEM\CurrentControlSet\Services\W32Time\Config',@('AnnounceFlags','MinPollInterval','MaxPollInterval','MaxNegPhaseCorrection','MaxPosPhaseCorrection','UpdateInterval','FrequencyCorrectRate','PhaseCorrectRate','LocalClockDispersion')), @('SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient',@('Enabled','InputProvider','DllName','SpecialPollInterval')), @('SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer',@('Enabled','InputProvider','DllName')), @('SOFTWARE\Policies\Microsoft\W32Time\Parameters',@('Type','NtpServer')), @('SOFTWARE\Policies\Microsoft\W32Time\Config',@('AnnounceFlags','MinPollInterval','MaxPollInterval','MaxNegPhaseCorrection','MaxPosPhaseCorrection','UpdateInterval')), @('SOFTWARE\Policies\Microsoft\W32Time\TimeProviders\NtpClient',@('Enabled','InputProvider','DllName','SpecialPollInterval')), @('SOFTWARE\Policies\Microsoft\W32Time\TimeProviders\NtpServer',@('Enabled','InputProvider','DllName'))) $entries=@();foreach($spec in $specs){$path='Registry::HKEY_LOCAL_MACHINE\'+$spec[0];$exists=Test-Path -LiteralPath $path;$values=@() if($exists){$key=Get-Item -LiteralPath $path;try{foreach($name in $spec[1]){if($key.GetValueNames()-ccontains$name){$values+=,[ordered]@{name=$name;kind=$key.GetValueKind($name).ToString();value=$key.GetValue($name,$null,[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)}}}}finally{$key.Close()}} $entries+=,[ordered]@{path=$spec[0];exists=$exists;values=$values} };return JsonHash $entries } function Snapshot{ $rmm=@();foreach($pair in @(@('RmmDiscoveryWindows','C:\Program Files\RustDiscovery\rmm-agent-windows.exe',$p.agent_sha256),@('RmmDiscoverySystemHelper','C:\Program Files\RustDiscovery\rmm-helper-windows.exe',$p.helper_sha256))){ $service=ServiceState $pair[0];if($service.state-cne'Running'-or$service.pid-le0){throw 'Retain both running RMM components'} $proc=[Diagnostics.Process]::GetProcessById([int]$service.pid);try{$birth=$proc.StartTime.ToUniversalTime().ToFileTimeUtc().ToString();$image=$proc.MainModule.FileName}finally{$proc.Dispose()} if(![string]::Equals($image,$pair[1],[StringComparison]::OrdinalIgnoreCase)){throw 'Actual retained RMM image'} $binary=FileMeta $pair[1] $true;if($binary.sha256-cne$pair[2]){throw 'Independently pinned RMM binary'} $rmm+=,[ordered]@{service=$service;process_birth_filetime=$birth;binary=$binary} } $files=[ordered]@{};foreach($pair in @(@('config','C:\ProgramData\RustDiscovery\config.json',$p.config_sha256),@('helper_settings','C:\ProgramData\RustDiscoverySystem\helper.json',$p.policy_sha256),@('agent_pin','C:\ProgramData\RustDiscoverySystem\agent-pin.json',$p.pin_sha256))){$value=FileMeta $pair[1] $true;if($value.sha256-cne$pair[2]){throw 'Retained original config/pins'};$files[$pair[0]]=$value} foreach($pair in @(@('ca','C:\ProgramData\RustDiscovery\server-ca.pem'),@('identity','C:\ProgramData\RustDiscovery\state\identity.json'),@('certificate','C:\ProgramData\RustDiscovery\state\device.pem'))){$files[$pair[0]]=FileMeta $pair[1] $true} $files['private_key_metadata_only']=FileMeta 'C:\ProgramData\RustDiscovery\state\device.key' $false $cfg=Get-Content -LiteralPath 'C:\ProgramData\RustDiscovery\config.json' -Raw|ConvertFrom-Json if(($cfg.PSObject.Properties.Name-ccontains'enable_jobs')-and$cfg.enable_jobs-ne$false){throw 'No RMM jobs enabled'} if(($cfg.PSObject.Properties.Name-ccontains'job_binding_file')-and$null-ne$cfg.job_binding_file){throw 'No new job binding'} $policy=Get-Content -LiteralPath 'C:\ProgramData\RustDiscoverySystem\helper.json' -Raw|ConvertFrom-Json if($policy.enable_effects-ne$false-or$policy.allow_reboot-ne$false-or@($policy.allowed_services).Count-ne0){throw 'Closed original helper policy'} return [ordered]@{rmm=$rmm;original_files=$files;time_service=(ServiceState 'W32Time');selected_time_config_sha256=(TimeConfigHash);time_config_coverage='fixed_service_NTP_and_policy_configuration_values_only'} } function BaselineHash($snapshot){return JsonHash ([ordered]@{rmm=$snapshot.rmm;original_files=$snapshot.original_files;time_definition=$snapshot.time_service.definition;selected_time_config_sha256=$snapshot.selected_time_config_sha256})} function Preserved($before,$after){ if((JsonHash $before.rmm)-cne(JsonHash $after.rmm)-or(JsonHash $before.original_files)-cne(JsonHash $after.original_files)){throw 'RMM components or original config/PKI metadata changed'} if((JsonHash $before.time_service.definition)-cne(JsonHash $after.time_service.definition)-or$before.selected_time_config_sha256-cne$after.selected_time_config_sha256){throw 'Service configuration/security or selected NTP/policy values changed'} } CheckControl $boot $true if($p.action-ceq'state'){$snapshot=Snapshot;@{id=$p.id;snapshot=$snapshot;baseline_sha256=(BaselineHash $snapshot);read_only=$true;no_jobs=$true;clock_trust_assessed=$false}|ConvertTo-Json -Depth 24 -Compress;return} if($p.expected_sha256-notmatch'^[a-f0-9]{64}$'-or$p.baseline_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Retained reviewed case hashes'} if($p.action-ceq'readback'){ if(!(Test-Path -LiteralPath $folder)){@{id=$p.id;entered=$false;readback_only=$true;start_repeated=$false;current=(Snapshot);clock_trust_assessed=$false}|ConvertTo-Json -Depth 24 -Compress;return} CheckControl $folder $true;CheckControl (Join-Path $folder 'intent.json') $false $intent=Get-Content -LiteralPath (Join-Path $folder 'intent.json') -Raw|ConvertFrom-Json if($intent.id-cne$p.id-or$intent.expected_sha256-cne$p.expected_sha256){throw 'Exact retained time-service intent'} $after=Snapshot;Preserved $intent.before $after $receipt=Join-Path $folder 'result.json';$result=$null;if(Test-Path -LiteralPath $receipt){CheckControl $receipt $false;$result=Get-Content -LiteralPath $receipt -Raw|ConvertFrom-Json} @{id=$p.id;entered=$true;readback_only=$true;start_repeated=$false;original_result=$result;start_intent_exists=(Test-Path -LiteralPath (Join-Path $folder 'start-intent.json'));current=$after;preserved=$true;clock_trust_assessed=$false}|ConvertTo-Json -Depth 24 -Compress;return } if((Test-Path -LiteralPath $folder)-or(Test-Path -LiteralPath $active)){throw 'Existing start case: readback only, never repeat start'} $before=Snapshot if((BaselineHash $before)-cne$p.baseline_sha256){throw 'Exact reviewed baseline changed; do not rebase'} if($before.time_service.state-notin@('Stopped','Running')){throw 'Pending or unknown time-service state: no start'} if($before.time_service.state-ceq'Stopped'){$controller=Get-Service -Name W32Time;try{if(@($controller.ServicesDependedOn).Count-ne0-or$controller.Status-ne[ServiceProcess.ServiceControllerStatus]::Stopped){throw 'No implicit dependency starts or changed service state'}}finally{$controller.Dispose()}} New-Item -ItemType Directory -Path $folder|Out-Null;CheckControl $folder $true WriteNew (Join-Path $folder 'intent.json') @{id=$p.id;expected_sha256=$p.expected_sha256;before=$before;create_only=$true;clock_trust_assessed=$false} if($before.time_service.state-ceq'Running'){ $after=Snapshot;Preserved $before $after $result=@{id=$p.id;status='already_running';start_called=$false;already_running_read_only=$true;preserved=$true;clock_trust_assessed=$false;no_jobs=$true} WriteNew (Join-Path $folder 'result.json') $result;$result|ConvertTo-Json -Compress;return } # Durable local and global admission precede the one exact SCM start. Nothing # catches/retries the start; an incomplete receipt can only be read back. WriteNew $active @{id=$p.id;expected_sha256=$p.expected_sha256;service='W32Time';create_only=$true} WriteNew (Join-Path $folder 'start-intent.json') @{id=$p.id;service='W32Time';start_reserved=$true;observed_at=[DateTime]::UtcNow.ToString('o')} Start-Service -Name W32Time $service=Get-Service -Name W32Time $service.WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running,[TimeSpan]::FromSeconds(20)) $after=Snapshot;Preserved $before $after if($after.time_service.state-cne'Running'){throw 'No running-state confirmation'} $result=@{id=$p.id;status='started';start_called=$true;preserved=$true;clock_trust_assessed=$false;no_jobs=$true;after=$after} WriteNew (Join-Path $folder 'result.json') $result;$result|ConvertTo-Json -Depth 24 -Compress ''' PREPARE = source_stage.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', 'TimeServiceStart.ps1') LAUNCH = source_stage.LAUNCH_SCRIPT.replace('TransportAcceptance.ps1', 'TimeServiceStart.ps1').replace('RmmTransportPayload', 'RmmTimeServiceStartPayload') def digest(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def save(folder, name, value): return helper.store(folder, name, value) def preserve_failure(folder): path = cb.EVIDENCE / 'bootstrap-private-last-error.json' if not path.exists(): return fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) with os.fdopen(fd, 'rb') as source: info = os.fstat(source.fileno()) require(stat.S_ISREG(info.st_mode) and info.st_uid == os.getuid() and info.st_mode & 0o077 == 0 and info.st_size <= 4 * 1024 * 1024, 'private original bootstrap failure') raw = source.read() target = folder / ('retained-bootstrap-error-' + hashlib.sha256(raw).hexdigest() + '.json') if not target.exists(): fd = os.open(target, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) with os.fdopen(fd, 'wb') as output: output.write(raw); output.flush(); os.fsync(output.fileno()) def remote(folder, payload): preserve_failure(folder) try: return cb.powershell(LAUNCH, {'sha256': hashlib.sha256(SCRIPT.encode()).hexdigest(), 'payload': payload}, timeout=100, remote_signed=True) finally: preserve_failure(folder) def prepare(pins): require(all(re.fullmatch('[0-9a-f]{64}', value) for value in pins.values()), 'independently known retained hashes') helper.private_dir(STATE); ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700) source_sha = hashlib.sha256(SCRIPT.encode()).hexdigest() payload = dict(id=ident, **pins) save(folder, 'intent.json', {'schema_version': 1, 'type': 'rmm.windows.time-service-start', 'payload': payload, 'source_file_sha256': digest(__file__), 'script_sha256': source_sha, 'closed_central_before': {'path': str(CONTEXT), 'sha256': digest(CONTEXT)}}) source = folder / 'TimeServiceStart.ps1' fd = os.open(source, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) with os.fdopen(fd, 'wb') as output: output.write(SCRIPT.encode()); output.flush(); os.fsync(output.fileno()) preserve_failure(folder) try: helper.transfer(source, 'TimeServiceStart.ps1', source_sha, PREPARE) before = remote(folder, dict(payload, action='state')) finally: preserve_failure(folder) require(before.get('read_only') is True and before.get('clock_trust_assessed') is False, 'actual readonly baseline') save(folder, 'before.json', before) print(json.dumps({'case_id': ident, 'prepared': True, 'time_state': before['snapshot']['time_service']['state'], 'clock_trust_assessed': False, 'start_executed': False})) def run(ident, action): require(str(uuid.UUID(ident)) == ident, 'exact existing case UUID') folder = STATE / ident; intent = cb.contract.protected_json(folder / 'intent.json') require(intent['source_file_sha256'] == digest(__file__) and intent['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest(), 'same reviewed source; no case rebase') baseline = cb.contract.protected_json(folder / 'before.json')['snapshot'] # Powershell creates its canonical baseline hash during state. It is sent # back verbatim rather than approximating ConvertTo-Json in Python. payload = dict(intent['payload'], action=action, baseline_sha256=cb.contract.protected_json(folder / 'before.json')['baseline_sha256'], expected_sha256=hashlib.sha256(json.dumps(intent['payload'], sort_keys=True, separators=(',', ':')).encode()).hexdigest()) require(baseline is not None and digest(CONTEXT) == intent['closed_central_before']['sha256'], 'retained actual baseline and closed central context') if action == 'start': save(folder, 'start-attempt.json', {'case_id': ident, 'once': True, 'lost_reply_readback_only': True}) result = remote(folder, payload) save(folder, ('result.json' if action == 'start' else 'readback-' + str(uuid.uuid4()) + '.json'), result) original = result.get('original_result') or result current = result.get('current') or result.get('after') print(json.dumps({'case_id': ident, 'status': original.get('status', 'unconfirmed'), 'running': current['time_service']['state'] == 'Running' if current else original.get('status') == 'already_running', 'preserved': result.get('preserved', False), 'readback_only': result.get('readback_only', False), 'clock_trust_assessed': False})) def main(): parser = argparse.ArgumentParser(description=__doc__); parser.add_argument('action', choices=['prepare', 'start', 'readback']); parser.add_argument('--id') for name in ['agent', 'helper', 'config', 'policy', 'pin']: parser.add_argument('--' + name + '-sha256') args = parser.parse_args() if args.action == 'prepare': pins = {name + '_sha256': getattr(args, name + '_sha256') for name in ['agent', 'helper', 'config', 'policy', 'pin']} require(all(isinstance(value, str) for value in pins.values()), 'all five independent hashes required'); prepare(pins) else: require(args.id is not None, 'explicit retained case required'); run(args.id, args.action) if __name__ == '__main__': main()