#!/usr/bin/env python3 """Preserving passive Windows HTTPS acceptance; no RMM jobs or approvals. The protected per-case intent is written before any remote mutation. A lost reply never reruns the transition: use finish or restore for that same case. """ import argparse import hashlib import json import os import subprocess from pathlib import Path import time import uuid import client_bootstrap as cb import cloud_mvp_acceptance as cloud import cloud_transport_acceptance as server_transport require = cb.contract.require STATE = cb.EVIDENCE/'transport' AGENT = '63ea15b2-0643-403d-b5b4-cba1288dbea3' ASSET = 'a176520e-8a91-4e93-a78b-8e7620f430e0' BINARY = '31e360e50b177b4d5729d24e436d4f25aeed7b1a7bd35f2a129841ba1abffd37' ORIGINAL_CONFIG = 'ad396dfafe1d9764eb9840185d1e167d06e018799d6786218691e600a33ff589' PROBE = '760edb21bdcc2ac70695cd1245f8abaa4ea2bd8ebd42cfb3eeb17a1ff39ff4ec' # Only fixed bootstrap resources are read or changed. Private keys never leave # the VM: only their preservation hashes occur in the protected case receipts. SCRIPT = r''' $ErrorActionPreference='Stop' $p=$global:RmmTransportPayload if ($null -eq $p) {throw 'Pinned bootstrap payload required'} if ([string]([guid]$p.id) -cne $p.id -or $p.mode -notin @('https','auto') -or $p.action -notin @('state','enter','restore')) {throw 'Fixed transport action'} foreach($n in @('binary_sha256','config_sha256','probe_sha256')) {if ($p.$n -notmatch '^[0-9a-f]{64}$') {throw 'Qualified hash'}} if ($p.agent_id -cne '63ea15b2-0643-403d-b5b4-cba1288dbea3' -or $p.asset_id -cne 'a176520e-8a91-4e93-a78b-8e7620f430e0') {throw 'Fixed existing Windows identity'} $root='C:\ProgramData\RustDiscovery';$state=Join-Path $root 'state';$cfg=Join-Path $root 'config.json' $exe='C:\Program Files\RustDiscovery\rmm-agent-windows.exe';$name='RmmDiscoveryWindows' $folder='C:\ProgramData\RustDiscoveryBootstrap\transport-'+$p.id $probe='C:\ProgramData\RustDiscoveryBootstrap\'+$p.probe_sha256+'\PassiveStateProbe.exe' $ss=(New-Object Security.Principal.NTAccount('NT SERVICE',$name)).Translate([Security.Principal.SecurityIdentifier]).Value $allowed=@('S-1-5-18','S-1-5-32-544',$ss) function Check-Path([string]$path,[bool]$directory) { $item=Get-Item -LiteralPath $path -Force if ($item.PSIsContainer -ne $directory -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {throw 'Fixed path type'} $acl=Get-Acl -LiteralPath $path $owner=$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value if ($owner -notin $allowed -and ($directory -or $owner -ne 'S-1-5-19')) {throw 'Fixed owner'} $rules=@($acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) if (!$rules.Count) {throw 'Empty DACL'} foreach($r in $rules) {if ($r.AccessControlType -ne 'Allow' -or $r.IdentityReference.Value -notin $allowed) {throw 'Broad DACL'}} } function Hash-Bytes([byte[]]$bytes) { $h=[Security.Cryptography.SHA256]::Create() try {return ([BitConverter]::ToString($h.ComputeHash($bytes))).Replace('-','').ToLowerInvariant()} finally {$h.Dispose()} } function Hash-File([string]$path) {Check-Path $path $false; return (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()} function Write-New([string]$path,[byte[]]$bytes) { $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 Receipt([string]$phase,$value) { Write-New (Join-Path $folder ('receipt-'+$phase+'.json')) ([Text.Encoding]::UTF8.GetBytes(($value | ConvertTo-Json -Depth 12 -Compress))) } function Probe-State { if ((Hash-File $probe) -cne $p.probe_sha256) {throw 'Readonly probe hash'} $si=New-Object Diagnostics.ProcessStartInfo $si.FileName=$probe;$si.UseShellExecute=$false;$si.CreateNoWindow=$true $si.RedirectStandardOutput=$true;$si.RedirectStandardError=$true $proc=New-Object Diagnostics.Process;$proc.StartInfo=$si if (!$proc.Start()) {throw 'Readonly probe start'} try { if (!$proc.WaitForExit(15000)) {$proc.Kill();throw 'Readonly probe timeout'} if ($proc.ExitCode -ne 0) {throw 'Readonly probe failed'} $raw=$proc.StandardOutput.ReadToEnd() if ($raw.Length -gt 4096) {throw 'Readonly probe bound'} return ($raw | ConvertFrom-Json) } finally {$proc.Dispose()} } function Snapshot { foreach($d in @('C:\Program Files\RustDiscovery',$root,$state)) {Check-Path $d $true} Check-Path $cfg $false if ((Get-Item -LiteralPath $cfg).Length -gt 32768) {throw 'Configuration size'} $c=Get-Content -LiteralPath $cfg -Raw | ConvertFrom-Json if ((($c.PSObject.Properties.Name | Sort-Object) -join ',') -cne 'ca_file,connect_address,enrollment_token_file,server_name,state_directory,transport') {throw 'Configuration schema'} if ($c.server_name -cne 'discovery.ease-technologies.de' -or $c.state_directory -cne $state -or $c.ca_file -cne (Join-Path $root 'server-ca.pem') -or $c.enrollment_token_file -cne (Join-Path $state 'enrollment.token')) {throw 'Fixed configuration paths'} if (Test-Path -LiteralPath $c.enrollment_token_file) {throw 'Enrollment must already be completed'} Check-Path (Join-Path $state 'identity.json') $false if ((Get-Item -LiteralPath (Join-Path $state 'identity.json')).Length -gt 32768) {throw 'Identity metadata size'} $identity=Get-Content -LiteralPath (Join-Path $state 'identity.json') -Raw | ConvertFrom-Json if ($identity.agent_id -cne $p.agent_id -or $identity.asset_id -cne $p.asset_id) {throw 'Existing identity mismatch'} $svc=Get-CimInstance Win32_Service -Filter "Name='RmmDiscoveryWindows'" $expected='"C:\Program Files\RustDiscovery\rmm-agent-windows.exe" --service --config "C:\ProgramData\RustDiscovery\config.json"' if ($svc.PathName -cne $expected -or $svc.StartName -cne 'NT AUTHORITY\LocalService' -or $svc.StartMode -ne 'Auto') {throw 'Fixed LocalService deployment'} $owner=$null if ($svc.State -eq 'Running') { $process=Get-CimInstance Win32_Process -Filter ('ProcessId='+$svc.ProcessId) $owner=(Invoke-CimMethod -InputObject $process -MethodName GetOwnerSid).Sid if ($owner -cne 'S-1-5-19') {throw 'Actual LocalService token'} } $hashes=[ordered]@{};$acls=[ordered]@{} foreach($entry in @(@('binary',$exe),@('ca',$c.ca_file),@('identity',(Join-Path $state 'identity.json')),@('certificate',(Join-Path $state 'device.pem')),@('private_key',(Join-Path $state 'device.key')))) { $hashes[$entry[0]]=Hash-File $entry[1] $acls[$entry[0]]=Hash-Bytes ([Text.Encoding]::UTF8.GetBytes((Get-Acl -LiteralPath $entry[1]).Sddl)) } if ($hashes.binary -cne $p.binary_sha256) {throw 'Existing qualified passive binary'} Check-Path $cfg $false;Check-Path (Join-Path $state 'telemetry.sqlite') $false return [pscustomobject]@{agent_id=$identity.agent_id;asset_id=$identity.asset_id;transport=$c.transport;config_sha256=(Hash-File $cfg);config_acl_sha256=(Hash-Bytes ([Text.Encoding]::UTF8.GetBytes((Get-Acl -LiteralPath $cfg).Sddl)));hashes=$hashes;acl_sha256=$acls;service_state=$svc.State;service_identity=$svc.StartName;process_id=$svc.ProcessId;process_owner_sid=$owner;telemetry_creation_ticks=(Get-Item -LiteralPath (Join-Path $state 'telemetry.sqlite')).CreationTimeUtc.Ticks;journal=(Probe-State)} } function Preserved($baseline,$current) { if ($current.agent_id -cne $baseline.agent_id -or $current.asset_id -cne $baseline.asset_id -or $current.telemetry_creation_ticks -ne $baseline.telemetry_creation_ticks -or $current.journal.integrity -cne 'ok' -or $current.journal.agent_id -cne $baseline.agent_id -or $current.journal.sequence -lt $baseline.journal.sequence) {throw 'Preserved journal identity/sequence'} foreach($n in @('binary','ca','identity','certificate','private_key')) {if ($current.hashes.$n -cne $baseline.hashes.$n -or $current.acl_sha256.$n -cne $baseline.acl_sha256.$n) {throw 'Preserved artifact and identity bytes/ACL'}} } function Start-Own { Start-Service -Name $name (Get-Service -Name $name).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running,[TimeSpan]::FromSeconds(20)) } function Stop-Own { Stop-Service -Name $name (Get-Service -Name $name).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped,[TimeSpan]::FromSeconds(20)) } function Replace-Config([byte[]]$bytes,[string]$label,[string]$sddl) { $next=Join-Path $folder ($label+'-next.json');Write-New $next $bytes [IO.File]::Replace($next,$cfg,(Join-Path $folder ($label+'-previous.json'))) $acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm($sddl);Set-Acl -LiteralPath $cfg -AclObject $acl } if ($p.action -eq 'state') {Snapshot | ConvertTo-Json -Depth 12 -Compress;exit 0} try { if ($p.action -eq 'enter') { $before=Snapshot if ($before.service_state -ne 'Running' -or $before.transport -cne 'wss' -or $before.config_sha256 -cne $p.config_sha256 -or $before.journal.integrity -cne 'ok' -or $before.journal.pending_inventory_events -ne 0) {throw 'Settled original WSS state required'} if (Test-Path -LiteralPath $folder) {throw 'Existing native intent; inspect or restore same case'} New-Item -ItemType Directory -Path $folder | Out-Null $acl=New-Object Security.AccessControl.DirectorySecurity;$acl.SetAccessRuleProtection($true,$false) $acl.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544'))) foreach($sid in @('S-1-5-18','S-1-5-32-544')) {$acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'FullControl','ContainerInherit,ObjectInherit','None','Allow')))} Set-Acl -LiteralPath $folder -AclObject $acl $original=[IO.File]::ReadAllBytes($cfg);$sddl=(Get-Acl -LiteralPath $cfg).Sddl $text=[Text.Encoding]::UTF8.GetString($original);$re=New-Object Text.RegularExpressions.Regex('("transport"\s*:\s*)"wss"') if ($re.Matches($text).Count -ne 1) {throw 'Exact original transport field'} $next=[Text.Encoding]::UTF8.GetBytes($re.Replace($text,('${1}"'+$p.mode+'"'),1)) $manifest=[pscustomobject]@{id=$p.id;mode=$p.mode;before=$before;original_config_sha256=(Hash-Bytes $original);selected_config_sha256=(Hash-Bytes $next);original_sddl=$sddl} Write-New (Join-Path $folder 'config-original.bin') $original Write-New (Join-Path $folder 'manifest.json') ([Text.Encoding]::UTF8.GetBytes(($manifest | ConvertTo-Json -Depth 12 -Compress))) Receipt 'prepared' @{stage='prepared';jobs_created=$false;reboot_requested=$false} Stop-Own Preserved $before (Snapshot) Replace-Config $next 'enter' $sddl if ((Hash-File $cfg) -cne $manifest.selected_config_sha256) {throw 'Selected configuration hash'} Start-Own $after=Snapshot;Preserved $before $after Receipt 'entered' @{stage='entered';snapshot=$after;jobs_created=$false;reboot_requested=$false} [pscustomobject]@{entered=$true;snapshot=$after;backup=$folder;config_selected_sha256=$manifest.selected_config_sha256;no_jobs=$true;no_reboot=$true} | ConvertTo-Json -Depth 12 -Compress } else { Check-Path $folder $true $manifest=Get-Content -LiteralPath (Join-Path $folder 'manifest.json') -Raw | ConvertFrom-Json $original=[IO.File]::ReadAllBytes((Join-Path $folder 'config-original.bin')) if ($manifest.id -cne $p.id -or $manifest.mode -cne $p.mode -or (Hash-Bytes $original) -cne $p.config_sha256 -or $manifest.original_config_sha256 -cne $p.config_sha256) {throw 'Exact original native intent'} $current=Snapshot;Preserved $manifest.before $current if ($current.config_sha256 -cne $p.config_sha256) { if ($current.config_sha256 -cne $manifest.selected_config_sha256 -or $current.transport -cne $p.mode) {throw 'Unknown configuration; refuse overwrite'} if ($current.service_state -eq 'Running') {Stop-Own} elseif ($current.service_state -ne 'Stopped') {throw 'Unexpected service state'} Replace-Config $original 'restore' $manifest.original_sddl } if ((Get-Service -Name $name).Status -ne 'Running') {Start-Own} $after=Snapshot;Preserved $manifest.before $after if ($after.config_sha256 -cne $p.config_sha256 -or $after.config_acl_sha256 -cne $manifest.before.config_acl_sha256 -or $after.transport -cne 'wss') {throw 'Original configuration/ACL restoration'} if (!(Test-Path -LiteralPath (Join-Path $folder 'receipt-restored.json'))) {Receipt 'restored' @{stage='restored';snapshot=$after;jobs_created=$false;reboot_requested=$false}} [pscustomobject]@{restored=$true;snapshot=$after;backup=$folder;no_jobs=$true;no_reboot=$true} | ConvertTo-Json -Depth 12 -Compress } } catch { if (Test-Path -LiteralPath $folder) {Receipt ('error-'+[guid]::NewGuid().ToString()) @{stage='incomplete';error_type=$_.Exception.GetType().FullName;line=$_.InvocationInfo.ScriptLineNumber;jobs_created=$false;reboot_requested=$false}} throw } ''' def payload(ident, action, mode='https'): require(str(uuid.UUID(ident)) == ident and action in ('state','enter','restore') and mode in ('https','auto'), 'fixed passive transport action') probe = cb.contract.protected_json(cb.EVIDENCE/'PassiveStateProbe.exe.latest.json') require(probe['sha256'] == PROBE, 'existing qualified readonly probe artifact') return dict(id=ident, action=action, mode=mode, agent_id=AGENT, asset_id=ASSET, binary_sha256=BINARY, config_sha256=ORIGINAL_CONFIG, probe_sha256=probe['sha256']) PREPARE_SCRIPT = r'''$ErrorActionPreference='Stop' $p=([Console]::In.ReadLine() | ConvertFrom-Json) if ($p.sha256 -notmatch '^[0-9a-f]{64}$') {throw 'Fixed script hash'} $root='C:\ProgramData\RustDiscoveryBootstrap' $item=Get-Item -LiteralPath $root -Force if (!$item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {throw 'Bootstrap directory type'} $acl=Get-Acl -LiteralPath $root if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -notin @('S-1-5-18','S-1-5-32-544')) {throw 'Bootstrap owner'} 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 DACL'}} $directory=Join-Path $root $p.sha256 if (!(Test-Path -LiteralPath $directory)) {New-Item -ItemType Directory -Path $directory | Out-Null} $di=Get-Item -LiteralPath $directory -Force if (!$di.PSIsContainer -or ($di.Attributes -band [IO.FileAttributes]::ReparsePoint)) {throw 'Script directory type'} foreach($r in (Get-Acl -LiteralPath $directory).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 'Script directory DACL'}} $script=Join-Path $directory 'TransportAcceptance.ps1' $exists=Test-Path -LiteralPath $script if ($exists -and (Get-FileHash -LiteralPath $script -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.sha256) {throw 'Existing script mismatch'} [pscustomobject]@{already_uploaded=$exists;sha256=$p.sha256} | ConvertTo-Json -Compress ''' LAUNCH_SCRIPT = r'''$ErrorActionPreference='Stop' $p=([Console]::In.ReadLine() | ConvertFrom-Json) if ($p.sha256 -notmatch '^[0-9a-f]{64}$') {throw 'Fixed script hash'} $script='C:\ProgramData\RustDiscoveryBootstrap\'+$p.sha256+'\TransportAcceptance.ps1' $item=Get-Item -LiteralPath $script -Force if ($item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or (Get-FileHash -LiteralPath $script -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.sha256) {throw 'Pinned source script'} $global:RmmTransportPayload=$p.payload & $script ''' def stage_script(): raw = SCRIPT.encode('utf-8'); digest = hashlib.sha256(raw).hexdigest() prepared = cb.powershell(PREPARE_SCRIPT, dict(sha256=digest)) if not prepared['already_uploaded']: directory = cb.EVIDENCE/'transport-source' directory.mkdir(mode=0o700, parents=True, exist_ok=True) source = directory/(digest+'.ps1') if not source.exists(): descriptor = os.open(source, os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW, 0o600) with os.fdopen(descriptor,'wb') as stream: stream.write(raw);stream.flush();os.fsync(stream.fileno()) require(hashlib.sha256(source.read_bytes()).hexdigest() == digest, 'exact bootstrap script bytes') prefix = cb.contract.protected_json(cb.ROOT/'credentials/windows-dev-access.json')['ssh_prefix'] arguments = ['sftp']+[value for value in prefix[1:-1] if value != '-T']+['-b','-',prefix[-1]] target = '/C:/ProgramData/RustDiscoveryBootstrap/'+digest+'/TransportAcceptance.ps1' transferred = subprocess.run(arguments,input=('put '+json.dumps(str(source.resolve()))+' '+json.dumps(target)+'\n').encode(),capture_output=True,timeout=60) require(transferred.returncode == 0, 'pinned bootstrap SFTP transfer failed') verified = cb.powershell(PREPARE_SCRIPT,dict(sha256=digest)) require(verified['already_uploaded'], 'exact staged source missing') return digest def remote(ident, action, mode='https', source_sha256=None): digest = source_sha256 or stage_script() require(digest == hashlib.sha256(SCRIPT.encode('utf-8')).hexdigest(), 'qualified bootstrap source unchanged') # RemoteSigned affects only this trusted bootstrap process, never machine # policy or any RMM job interpreter. Machine/User policy still wins normally. return cb.powershell(LAUNCH_SCRIPT,dict(sha256=digest,payload=payload(ident,action,mode)),timeout=60,remote_signed=True) def save(folder, name, value): cb.contract.write_private(folder/name, value) def gate(): return cloud.bootstrap.rpc('server.conf', cloud.server, dict(kind='gate', tenant_id=cloud.TENANT, agent_id=AGENT)) def observe(ident): return cloud.bootstrap.rpc('server.conf', server_transport.server_evidence, dict(tenant_id=cloud.TENANT, agent_id=AGENT, fault_id=ident)) def preserved(before, after): require(all(before[k] == after[k] for k in ('agent_id','asset_id','hashes','acl_sha256','telemetry_creation_ticks')), 'native identity/artifacts/ACL preservation') require(after['journal']['integrity'] == 'ok' and after['journal']['read_only'] is True and after['journal']['agent_id'] == AGENT and after['journal']['sequence'] >= before['journal']['sequence'], 'same retained journal and monotone sequence') def wait_mode(ident, mode, after, baseline): deadline = time.monotonic()+150 first = None while True: value = observe(ident); device = value['device'] if device and device['transport'] == mode and device['last_contact_at'] and cloud.contract.timestamp(device['last_contact_at']) > after: require(all(device[k] == baseline[k] for k in ('agent_id','asset_id','enrollment_generation','assignment_version','certificate_sha256')), 'same authenticated Windows device') if first is None: first = value elif device['last_contact_at'] != first['device']['last_contact_at']: return dict(first=first,second=value) require(time.monotonic() < deadline, 'two actual fresh transport heartbeats missing') time.sleep(2) def read_device(): device = cloud.Backend().call('inventory.get_device', dict(tenant_id=cloud.TENANT, asset_id=ASSET)) require(device['agent_id'] == AGENT and device['source_id'] == 'windows.base' and set(device['capabilities']) == {'windows.base/1','heartbeat/1'} and device['inventory'] is not None and device['inventory']['root_available_inodes'] is None and device['presence'] == 'online', 'honest existing passive Windows inventory') return device def foreign_denied(): backend = cloud.Backend('b'); values = [] for tenant in (cloud.TENANT,'22222222-2222-4222-8222-222222222222'): backend.sequence += 1 answer = backend.request(dict(jsonrpc='2.0', id=backend.sequence, method='tools/call', params=dict(name='inventory.get_device',arguments=dict(tenant_id=tenant,asset_id=ASSET)))) data = answer.get('data', {}); result = data.get('result', {}) require('error' in data or result.get('isError'), 'foreign Windows device must remain denied') values.append(dict(tenant_id=tenant, denied=True)) return values def fixed_intent(folder, name, value): path = folder/name if path.exists(): require(cb.contract.protected_json(path) == value, 'same retained transition intent') else: save(folder, name, value) def finish(ident): folder = STATE/str(uuid.UUID(ident)); intent = cb.contract.protected_json(folder/'intent.json') require(intent['case'] == 'explicit_https' and intent['id'] == ident, 'same fixed Windows HTTPS case') require(not (folder/'result.json').exists(), 'completed acceptance retained') require(intent['source_sha256'] == hashlib.sha256(SCRIPT.encode('utf-8')).hexdigest(), 'same qualified bootstrap source') before = cb.contract.protected_json(folder/'before.json') accepted = folder/'https-accepted.json' try: if not accepted.exists(): current = remote(ident,'state',source_sha256=intent['source_sha256']); preserved(before['native'], current) require(current['transport'] == 'https', 'resume observes selected HTTPS without repeating transition') online = wait_mode(ident,'https',cloud.contract.timestamp(intent['started_at']),before['central']['device']) save(folder,'https-observed-'+str(uuid.uuid4())+'.json',online) native = remote(ident,'state',source_sha256=intent['source_sha256']);preserved(before['native'],native) require(native['journal']['pending_inventory_events'] == 0 and native['service_state'] == 'Running' and native['process_owner_sid'] == 'S-1-5-19' and native['journal']['sequence'] > before['native']['journal']['sequence'], 'actual concrete inventory ACK, sequence advancement and LocalService') inventory = read_device(); denied = foreign_denied() require(gate() == before['gate'] == dict(jobs=0,outbox=0,permits=0,unresolved=0), 'passive transport creates no jobs/grants') save(folder,'https-accepted.json',dict(verified=True,online=online,native=native,inventory=inventory,foreign_denied=denied)) else: require(cb.contract.protected_json(accepted)['verified'] is True, 'retain successful same-case HTTPS observations') finally: fixed_intent(folder,'restore-intent.json',dict(id=ident,expected_original_config_sha256=ORIGINAL_CONFIG,no_jobs=True)) cleanup_state = remote(ident,'state',source_sha256=intent['source_sha256']) preserved(before['native'],cleanup_state) if (cleanup_state['transport'] == 'wss' and cleanup_state['config_sha256'] == ORIGINAL_CONFIG and cleanup_state['config_acl_sha256'] == before['native']['config_acl_sha256'] and cleanup_state['service_state'] == 'Running'): # A successful restore with a lost reply is observed, not repeated. restored = dict(restored_by_readback=True,snapshot=cleanup_state,no_jobs=True,no_reboot=True) else: restored = remote(ident,'restore',source_sha256=intent['source_sha256']) save(folder,'restored-'+str(uuid.uuid4())+'.json',restored) wss = wait_mode(ident,'wss',cloud.contract.now(),before['central']['device']) require(gate() == before['gate'], 'restoration preserves zero-job gate') restored = remote(ident,'state',source_sha256=intent['source_sha256']);preserved(before['native'],restored) require(restored['config_sha256'] == ORIGINAL_CONFIG and restored['config_acl_sha256'] == before['native']['config_acl_sha256'] and restored['journal']['pending_inventory_events'] == 0, 'exact original WSS configuration/ACL and acknowledged inventory') save(folder,'result.json',dict(verified=True,case='explicit_https',id=ident,https=cb.contract.protected_json(accepted), restored_wss=wss,final_native=restored,gate=gate(),no_jobs_or_approvals=True,no_reboot=True)) print('PASS native Windows HTTPS: same identity/LocalService, two fresh heartbeats, concrete inventory ACK, tenant denial, original WSS config/ACL restored, zero jobs') def start(): os.umask(0o077);STATE.mkdir(mode=0o700,parents=True,exist_ok=True) ident = str(uuid.uuid4()); folder = STATE/ident;folder.mkdir(mode=0o700) source = stage_script() save(folder,'intent.json',dict(id=ident,case='explicit_https',mode='https',started_at=cloud.contract.now().isoformat(),agent_id=AGENT,asset_id=ASSET,no_jobs=True,source_sha256=source)) native = remote(ident,'state');central = observe(ident);device = read_device();counts = gate() require(native['transport'] == 'wss' and native['config_sha256'] == ORIGINAL_CONFIG and native['journal']['pending_inventory_events'] == 0 and native['journal']['integrity'] == 'ok' and counts == dict(jobs=0,outbox=0,permits=0,unresolved=0), 'healthy preserved original passive WSS prerequisite') save(folder,'before.json',dict(native=native,central=central,device=device,gate=counts)) save(folder,'enter-intent.json',payload(ident,'enter')) # On a lost SSH reply the retained intent identifies the only permitted # continuation. Never create a new case or repeat enter as a substitute. entered = remote(ident,'enter',source_sha256=source);save(folder,'entered.json',entered) print('Entered existing Windows HTTPS case '+ident,flush=True) finish(ident) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('action',choices=('start','finish','restore')) parser.add_argument('--id') args = parser.parse_args() if args.action == 'start': require(args.id is None, 'new case ID is generated once');start() else: require(args.id is not None, 'same existing case ID required') if args.action == 'finish':finish(args.id) else: ident = str(uuid.UUID(args.id));folder = STATE/ident intent = cb.contract.protected_json(folder/'intent.json') require(gate() == dict(jobs=0,outbox=0,permits=0,unresolved=0), 'no Windows jobs during operational restore') save(folder,'explicit-restore-intent-'+str(uuid.uuid4())+'.json',dict(id=ident,no_jobs=True)) restored = remote(ident,'restore',source_sha256=intent['source_sha256']);save(folder,'explicit-restored-'+str(uuid.uuid4())+'.json',restored) print('Restored only the original Windows transport config/ACL for '+ident) if __name__ == '__main__': try: main() except Exception as error: message = str(error) print('WINDOWS_TRANSPORT_INCOMPLETE:'+(message if isinstance(error,cb.contract.GuardError) else type(error).__name__)) raise SystemExit(2) from None