220 lines
14 KiB
Python
220 lines
14 KiB
Python
#!/usr/bin/env python3
|
|
"""Activate the already native-qualified passive Windows automatic transport.
|
|
|
|
Only the existing service configuration changes. Historical acceptance reports
|
|
remain immutable. Ambiguous replies permit readback or explicit restoration of
|
|
that same transition, never a repeated enter or automatic re-enrollment.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import os
|
|
from pathlib import Path
|
|
import uuid
|
|
|
|
import auto_transport_acceptance as auto
|
|
|
|
base = auto.base
|
|
require = base.require
|
|
STATE = base.cb.EVIDENCE/'auto-default'
|
|
CURRENT = base.cb.EVIDENCE/'current-transport.json'
|
|
|
|
# Independent re-derivation from the immutable, hash-pinned original bytes.
|
|
# No private identity/key bytes leave the guest. A missing entered receipt after
|
|
# a lost reply remains missing; current state and fresh contacts prove activation.
|
|
READ_TRANSITION = r'''
|
|
$ErrorActionPreference='Stop'
|
|
$p=([Console]::In.ReadLine() | ConvertFrom-Json)
|
|
if ([string]([guid]$p.id) -cne $p.id) {throw 'Fixed transition ID'}
|
|
$folder='C:\ProgramData\RustDiscoveryBootstrap\transport-'+$p.id
|
|
$allowed=@('S-1-5-18','S-1-5-32-544')
|
|
foreach($path in @($folder,(Join-Path $folder 'manifest.json'),(Join-Path $folder 'config-original.bin'))) {
|
|
$item=Get-Item -LiteralPath $path -Force
|
|
if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or (!$item.PSIsContainer -and $item.Length -gt 32768)) {throw 'Bounded fixed transition metadata'}
|
|
$acl=Get-Acl -LiteralPath $path
|
|
if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -notin $allowed) {throw 'Bootstrap metadata owner'}
|
|
$rules=@($acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]))
|
|
if (!$rules.Count) {throw 'Missing restrictive DACL'}
|
|
foreach($r in $rules) {if ($r.AccessControlType -ne 'Allow' -or $r.IdentityReference.Value -notin $allowed) {throw 'Bootstrap metadata DACL'}}
|
|
}
|
|
function Digest([byte[]]$bytes) {
|
|
$sha=[Security.Cryptography.SHA256]::Create()
|
|
try {return ([BitConverter]::ToString($sha.ComputeHash($bytes))).Replace('-','').ToLowerInvariant()} finally {$sha.Dispose()}
|
|
}
|
|
$manifest=Get-Content -LiteralPath (Join-Path $folder 'manifest.json') -Raw | ConvertFrom-Json
|
|
$original=[IO.File]::ReadAllBytes((Join-Path $folder 'config-original.bin'))
|
|
$originalHash=Digest $original
|
|
if ($manifest.id -cne $p.id -or $manifest.mode -cne 'auto' -or $originalHash -cne 'ad396dfafe1d9764eb9840185d1e167d06e018799d6786218691e600a33ff589' -or $manifest.original_config_sha256 -cne $originalHash) {throw 'Qualified original transition binding'}
|
|
$text=[Text.Encoding]::UTF8.GetString($original)
|
|
$re=New-Object Text.RegularExpressions.Regex('("transport"\s*:\s*)"wss"')
|
|
if ($re.Matches($text).Count -ne 1) {throw 'Single original WSS field'}
|
|
$selected=[Text.Encoding]::UTF8.GetBytes($re.Replace($text,'${1}"auto"',1));$selectedHash=Digest $selected
|
|
if ($manifest.selected_config_sha256 -cne $selectedHash) {throw 'Independently derived automatic configuration'}
|
|
[pscustomobject]@{id=$manifest.id;mode=$manifest.mode;original_config_sha256=$originalHash;expected_auto_config_sha256=$selectedHash;original_acl_sha256=(Digest ([Text.Encoding]::UTF8.GetBytes($manifest.original_sddl)));before=$manifest.before;entered_receipt_present=(Test-Path -LiteralPath (Join-Path $folder 'receipt-entered.json'));read_only=$true} | ConvertTo-Json -Depth 12 -Compress
|
|
'''
|
|
|
|
|
|
def reference(path):
|
|
path = Path(path)
|
|
return dict(path=str(path.resolve()),sha256=hashlib.sha256(path.read_bytes()).hexdigest())
|
|
|
|
|
|
def prior_result(ident):
|
|
path = auto.STATE/str(uuid.UUID(ident))/'result.json'
|
|
report = base.cb.contract.protected_json(path)
|
|
require(report['verified'] is True and report['case'] == 'automatic_fallback'
|
|
and report['no_jobs_or_approvals'] is True and report['no_reboot'] is True
|
|
and report['final_native']['agent_id'] == base.AGENT
|
|
and report['final_native']['asset_id'] == base.ASSET
|
|
and report['final_native']['transport'] == 'wss'
|
|
and report['final_native']['config_sha256'] == base.ORIGINAL_CONFIG
|
|
and report['counts']['windows'] == dict(jobs=0,outbox=0,permits=0,unresolved=0)
|
|
and auto.flags_disabled(report['server']), 'finished native fallback and original WSS restoration required')
|
|
return report,path
|
|
|
|
|
|
def transition(ident):
|
|
return base.cb.powershell(READ_TRANSITION,dict(id=ident))
|
|
|
|
|
|
def publish_current(folder, mode, report_name):
|
|
report_path = folder/report_name
|
|
report = base.cb.contract.protected_json(report_path)
|
|
native = report['native']
|
|
require(mode in ('auto','wss') and report['verified'] is True and native['transport'] == mode,
|
|
'only a verified actual transport state may become current')
|
|
value = dict(schema_version=1,type='rmm.windows.current-transport',case_id=folder.name,
|
|
agent_id=base.AGENT,asset_id=base.ASSET,binary_sha256=base.BINARY,
|
|
transport=mode,config_sha256=native['config_sha256'],evidence=reference(report_path))
|
|
if CURRENT.exists():
|
|
previous = base.cb.contract.protected_json(CURRENT)
|
|
if previous == value:return
|
|
require(previous.get('type') == value['type'] and previous['agent_id'] == base.AGENT
|
|
and previous['asset_id'] == base.ASSET
|
|
and (previous['case_id'] == folder.name or previous['transport'] == 'wss'), 'preserve any other current activation')
|
|
backup = folder/('current-index-before-'+mode+'.json')
|
|
if not backup.exists():base.save(folder,backup.name,previous)
|
|
temporary = CURRENT.with_name('.current-transport-'+str(uuid.uuid4())+'.json')
|
|
base.cb.contract.write_private(temporary,value)
|
|
os.replace(temporary,CURRENT)
|
|
|
|
|
|
def finish(ident):
|
|
folder = STATE/str(uuid.UUID(ident));intent = base.cb.contract.protected_json(folder/'intent.json')
|
|
before = base.cb.contract.protected_json(folder/'before.json')
|
|
require(intent['case'] == 'activate_automatic_transport' and intent['id'] == ident
|
|
and intent['source_sha256'] == hashlib.sha256(base.SCRIPT.encode()).hexdigest(), 'same fixed configuration activation')
|
|
require(not (folder/'explicit-restore-intent.json').exists() and not (folder/'restore-result.json').exists(),
|
|
'an explicit restoration is not a new automatic activation; never republish historical auto evidence')
|
|
completed = folder/'result.json'
|
|
if completed.exists():
|
|
recorded = base.cb.contract.protected_json(completed)
|
|
require(recorded['verified'] is True, 'preserve completed activation')
|
|
current = base.remote(ident,'state',mode='auto',source_sha256=intent['source_sha256'])
|
|
base.preserved(before['native'],current)
|
|
require(current['transport'] == 'auto' and current['config_sha256'] == recorded['native']['config_sha256']
|
|
and current['config_acl_sha256'] == before['native']['config_acl_sha256']
|
|
and current['service_state'] == 'Running' and current['process_owner_sid'] == 'S-1-5-19'
|
|
and auto.status() == before['server'] and auto.scopes() == before['counts'],
|
|
'completed historical activation must still match actual current config and closed server state')
|
|
publish_current(folder,'auto','result.json')
|
|
print('Retained completed automatic Windows transport activation '+ident)
|
|
return
|
|
derived = transition(ident)
|
|
require(derived['id'] == ident and derived['mode'] == 'auto' and derived['read_only'] is True
|
|
and derived['original_config_sha256'] == base.ORIGINAL_CONFIG
|
|
and derived['original_acl_sha256'] == before['native']['config_acl_sha256'], 'same preserved native transition and independently derived configuration')
|
|
base.preserved(before['native'],derived['before'])
|
|
current = base.remote(ident,'state',mode='auto',source_sha256=intent['source_sha256'])
|
|
base.preserved(before['native'],current)
|
|
require(current['transport'] == 'auto' and current['config_sha256'] == derived['expected_auto_config_sha256']
|
|
and current['config_acl_sha256'] == before['native']['config_acl_sha256']
|
|
and current['service_state'] == 'Running' and current['process_owner_sid'] == 'S-1-5-19', 'actual already activated automatic config; no repeated enter or service start')
|
|
online = base.wait_mode(ident,'wss',base.cb.contract.timestamp(intent['started_at']),before['central']['device'])
|
|
native = base.remote(ident,'state',mode='auto',source_sha256=intent['source_sha256']);base.preserved(before['native'],native)
|
|
require(native['transport'] == 'auto' and native['config_sha256'] == derived['expected_auto_config_sha256']
|
|
and native['config_acl_sha256'] == before['native']['config_acl_sha256']
|
|
and native['journal']['pending_inventory_events'] == 0 and native['journal']['sequence'] > before['native']['journal']['sequence'],
|
|
'two actual preferred-WSS contacts with retained journal and concrete ACK')
|
|
flags = auto.status(); counts = auto.scopes(); inventory = base.read_device()
|
|
require(auto.flags_disabled(flags) and flags == before['server'] and counts == before['counts'],
|
|
'no server mutation, transport fault, new job or grant on either target')
|
|
base.save(folder,'result.json',dict(verified=True,completed=True,case=intent['case'],id=ident,
|
|
native=native,online=online,transition=derived,inventory=inventory,server=flags,counts=counts,
|
|
no_jobs_or_approvals=True,no_reboot=True,permanent_transport='auto',
|
|
qualification=intent['qualification']))
|
|
publish_current(folder,'auto','result.json')
|
|
print('PASS permanent passive Windows auto transport: actual preferred WSS/heartbeats/ACK, retained identity/ACLs, no server changes or jobs')
|
|
|
|
|
|
def start(qualified_case):
|
|
os.umask(0o077);STATE.mkdir(mode=0o700,parents=True,exist_ok=True)
|
|
qualified,path = prior_result(qualified_case)
|
|
if CURRENT.exists():
|
|
previous = base.cb.contract.protected_json(CURRENT)
|
|
require(previous['transport'] == 'wss', 'already active automatic transport; inspect current index, never enter again')
|
|
ident = str(uuid.uuid4());folder = STATE/ident;folder.mkdir(mode=0o700)
|
|
source = hashlib.sha256(base.SCRIPT.encode()).hexdigest()
|
|
intent = dict(id=ident,case='activate_automatic_transport',mode='auto',started_at=base.cb.contract.now().isoformat(),
|
|
source_sha256=source,qualification=reference(path),no_jobs=True,no_reboot=True)
|
|
base.save(folder,'intent.json',intent)
|
|
native = base.remote(ident,'state',mode='auto',source_sha256=source)
|
|
base.preserved(qualified['final_native'],native)
|
|
central = auto.observe(ident);flags = auto.status();counts = auto.scopes()
|
|
require(native['transport'] == 'wss' and native['config_sha256'] == base.ORIGINAL_CONFIG
|
|
and native['journal']['pending_inventory_events'] == 0 and native['service_state'] == 'Running'
|
|
and auto.flags_disabled(flags) and counts == qualified['counts'], 'known settled original WSS configuration and closed fault hooks')
|
|
base.save(folder,'before.json',dict(native=native,central=central,server=flags,counts=counts))
|
|
base.save(folder,'enter-intent.json',base.payload(ident,'enter','auto'))
|
|
try:
|
|
entered = base.remote(ident,'enter',mode='auto',source_sha256=source)
|
|
base.save(folder,'entered.json',entered)
|
|
except Exception as error:
|
|
base.save(folder,'enter-reply-incomplete.json',dict(error_class=type(error).__name__,same_case_preserved=True,
|
|
continuation='finish reads actual state; restore explicitly restores the same original config'))
|
|
raise
|
|
print('Activated Windows automatic transport case '+ident,flush=True)
|
|
finish(ident)
|
|
|
|
|
|
def restore(ident):
|
|
folder = STATE/str(uuid.UUID(ident));intent = base.cb.contract.protected_json(folder/'intent.json')
|
|
before = base.cb.contract.protected_json(folder/'before.json')
|
|
require(auto.scopes() == before['counts'], 'unchanged target job state before explicit restoration')
|
|
base.fixed_intent(folder,'explicit-restore-intent.json',dict(id=ident,expected_original_config_sha256=base.ORIGINAL_CONFIG))
|
|
current = base.remote(ident,'state',mode='auto',source_sha256=intent['source_sha256']);base.preserved(before['native'],current)
|
|
if not (current['transport'] == 'wss' and current['config_sha256'] == base.ORIGINAL_CONFIG
|
|
and current['config_acl_sha256'] == before['native']['config_acl_sha256'] and current['service_state'] == 'Running'):
|
|
value = base.remote(ident,'restore',mode='auto',source_sha256=intent['source_sha256'])
|
|
base.save(folder,'explicit-restored-'+str(uuid.uuid4())+'.json',value)
|
|
online = base.wait_mode(ident,'wss',base.cb.contract.now(),before['central']['device'])
|
|
native = base.remote(ident,'state',mode='auto',source_sha256=intent['source_sha256']);base.preserved(before['native'],native)
|
|
require(native['transport'] == 'wss' and native['config_sha256'] == base.ORIGINAL_CONFIG
|
|
and native['config_acl_sha256'] == before['native']['config_acl_sha256'] and native['journal']['pending_inventory_events'] == 0,
|
|
'same original config bytes/ACL and concrete inventory ACK')
|
|
result = folder/'restore-result.json'
|
|
if not result.exists():base.save(folder,result.name,dict(verified=True,id=ident,native=native,online=online,no_jobs=True,no_reboot=True))
|
|
publish_current(folder,'wss',result.name)
|
|
print('PASS explicit restoration of original Windows WSS configuration; activation evidence retained')
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('action',choices=('start','finish','restore'))
|
|
parser.add_argument('--qualified-auto-case');parser.add_argument('--id')
|
|
args = parser.parse_args()
|
|
if args.action == 'start':
|
|
require(args.qualified_auto_case and not args.id, 'one finished native fallback qualification required')
|
|
start(args.qualified_auto_case)
|
|
else:
|
|
require(args.id and not args.qualified_auto_case, 'same retained activation ID required')
|
|
{'finish':finish,'restore':restore}[args.action](args.id)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
main()
|
|
except Exception as error:
|
|
message = str(error)
|
|
print('WINDOWS_AUTO_ACTIVATION_INCOMPLETE:'+(message if isinstance(error,base.cb.contract.GuardError) else type(error).__name__))
|
|
raise SystemExit(2) from None
|