254 lines
17 KiB
Python
254 lines
17 KiB
Python
#!/usr/bin/env python3
|
|
"""Fixed original-case completion/capture operator; no automatic next action.
|
|
|
|
Each mutation has a create-only local intent. After an uncertain reply use read;
|
|
never repeat a mutation or invent its missing reply, exit proof or outcome.
|
|
"""
|
|
import argparse
|
|
import json
|
|
from pathlib import Path
|
|
import subprocess
|
|
import uuid
|
|
|
|
import signed_clock_capture_acceptance as original
|
|
import signed_clock_capture_completion as completion
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
FOLDER = ROOT / 'devstate/windows-signed-clock-capture-completion/ccba6d8f-c58f-4d2d-a51c-1efb3bfbabdf'
|
|
GENERATOR_SHA = '65dbbd148e4a7d24843167b984c0d3c8ad5a8a065cff7d47dfd5516d9c97cde6'
|
|
ORIGINAL_RUNNER_SHA = 'dd6c575a119751429448e40e6f306cf79efa3a86c49bf2cd32a7783937177770'
|
|
COMPLETE_SHA = 'a36f318fb549071765bd92aa405c2ea3cf16b3696151afe857c4f601e36f624c'
|
|
DELTA_SHA = '2240d7846c82a56e2e13a48bed2c836fae3c836ce89d585c3390540fef76ef14'
|
|
ARTIFACTS = (('SignedClockCaptureCompletion.ps1', COMPLETE_SHA, 16673),
|
|
('SignedClockCaptureDelta.ps1', DELTA_SHA, 23306))
|
|
ACTIONS = ('stage', 'complete', 'read', 'start-local-service', 'start-system',
|
|
'cleanup-local-service', 'cleanup-system')
|
|
require, save, load = original.require, original.save, original.load
|
|
|
|
LAUNCH = r'''$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
|
if(!$p-or$p.id-cne'efd17b43-7e04-49a7-9bd4-862d13365eec'){throw 'Fixed original completion case'}
|
|
if($p.action-ceq'complete'){
|
|
if((($p.PSObject.Properties.Name|Sort-Object)-join',')-cne'action,id,profile,script_sha256'-or$p.profile-cne'rmm.windows.raw-clock.original-completion.v1'-or$p.script_sha256-cne'a36f318fb549071765bd92aa405c2ea3cf16b3696151afe857c4f601e36f624c'){throw 'Fixed completion action'}
|
|
$name='SignedClockCaptureCompletion.ps1';$bytes=16673
|
|
}else{
|
|
if((($p.PSObject.Properties.Name|Sort-Object)-join',')-cne'action,exe_bytes,exe_sha256,id,manifest_sha256,profile,script_sha256'-or$p.action-notin@('read','start-local-service','start-system','cleanup-local-service','cleanup-system')-or$p.profile-cne'rmm.windows.raw-clock.original-delta.v1'-or$p.script_sha256-cne'2240d7846c82a56e2e13a48bed2c836fae3c836ce89d585c3390540fef76ef14'-or$p.exe_sha256-cne'601c27a43fb67c662f926f9dc289a23a5c31c7e27f62901a77fc9ceaafaea7fb'-or$p.exe_bytes-ne8566784-or$p.manifest_sha256-cne'806c062bdd458627cf44ff1ef3f27738e1ebf2f407a96f772223efef267db0b1'){throw 'Fixed delta action'}
|
|
$name='SignedClockCaptureDelta.ps1';$bytes=23306
|
|
}
|
|
$script=Join-Path (Join-Path 'C:\ProgramData\RustDiscoveryBootstrap' $p.script_sha256) $name
|
|
$i=Get-Item -LiteralPath $script -Force;if($i.PSIsContainer-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)-or$i.Length-ne$bytes-or(Get-FileHash -LiteralPath $script -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.script_sha256){throw 'Exact fixed controller bytes'}
|
|
$parent=$i.Directory;while($null-ne$parent){if($parent.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'No controller reparse ancestry'};$parent=$parent.Parent}
|
|
$a=Get-Acl -LiteralPath $script;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Controller owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Nonempty controller DACL'};foreach($r in $rules){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private controller DACL'}}
|
|
if($p.action-ceq'complete'){$global:RmmCaptureCompletionPayload=$p}else{$global:RmmCaptureDeltaPayload=$p}
|
|
& $script
|
|
'''
|
|
|
|
|
|
def verify():
|
|
require(original.sha(ROOT / 'deploy/windows/signed_clock_capture_acceptance.py') == ORIGINAL_RUNNER_SHA
|
|
and original.sha(ROOT / 'deploy/windows/signed_clock_capture_completion.py') == GENERATOR_SHA,
|
|
'reviewed original operator and completion generator unchanged')
|
|
original.private(FOLDER, True)
|
|
manifest = load(FOLDER / 'manifest.json')
|
|
require(manifest['original_case'] == completion.CASE and manifest['generator_sha256'] == GENERATOR_SHA
|
|
and manifest['original_controller_sha256'] == completion.OLD_SCRIPT_SHA
|
|
and manifest['original_manifest_sha256'] == completion.OLD_MANIFEST_SHA
|
|
and manifest['completion'] == dict(sha256=COMPLETE_SHA, bytes=16673,
|
|
profile=completion.COMPLETE_PROFILE)
|
|
and manifest['delta'] == dict(sha256=DELTA_SHA, bytes=23306, profile=completion.DELTA_PROFILE),
|
|
'exact reviewed two-controller package')
|
|
for name, digest, size in ARTIFACTS:
|
|
path = FOLDER / name
|
|
original.private(path)
|
|
require(path.stat().st_size == size and original.sha(path) == digest, 'original exact controller bytes')
|
|
require(original.sha(completion.ORIGINAL / 'manifest.json') == completion.OLD_MANIFEST_SHA
|
|
and original.sha(completion.ORIGINAL / 'SignedClockCaptureAcceptance.ps1') == completion.OLD_SCRIPT_SHA
|
|
and original.sha(completion.REPAIR / 'repair-reply.json') == completion.REPAIR_REPLY_SHA
|
|
and original.sha(completion.REPAIR / 'repair-preservation.json') == completion.REPAIR_PRESERVATION_SHA,
|
|
'original failed setup and actual successful stopped SYSTEM repair')
|
|
|
|
|
|
def payload(action):
|
|
require(action in ACTIONS and action != 'stage', 'fixed code-selected controller action')
|
|
if action == 'complete':
|
|
return dict(id=completion.CASE, profile=completion.COMPLETE_PROFILE,
|
|
action=action, script_sha256=COMPLETE_SHA)
|
|
return dict(id=completion.CASE, profile=completion.DELTA_PROFILE, action=action,
|
|
exe_sha256=completion.EXE_SHA, exe_bytes=completion.EXE_BYTES,
|
|
manifest_sha256=completion.OLD_MANIFEST_SHA, script_sha256=DELTA_SHA)
|
|
|
|
|
|
def stage(access):
|
|
for name, digest, _ in ARTIFACTS:
|
|
require(name in ('SignedClockCaptureCompletion.ps1', 'SignedClockCaptureDelta.ps1'),
|
|
'only literal two new stage names')
|
|
prepare = original.pipe.u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', name)
|
|
observed = access.powershell(prepare, dict(sha256=digest))
|
|
if not observed['already_uploaded']:
|
|
credentials = original.pipe.cb.contract.protected_json(access.root / 'credentials/windows-dev-access.json')
|
|
prefix = credentials['ssh_prefix']
|
|
args = ['sftp'] + [part for part in prefix[1:-1] if part != '-T'] + ['-b', '-', prefix[-1]]
|
|
target = '/C:/ProgramData/RustDiscoveryBootstrap/' + digest + '/' + name
|
|
transferred = subprocess.run(args, input=('put ' + json.dumps(str(FOLDER / name)) + ' '
|
|
+ json.dumps(target) + '\n').encode(), capture_output=True, timeout=60)
|
|
require(transferred.returncode == 0, 'one exact transfer; uncertain reply means original read only')
|
|
observed = access.powershell(prepare, dict(sha256=digest))
|
|
require(observed['already_uploaded'] is True and observed['sha256'] == digest,
|
|
'immutable staged exact controller')
|
|
return dict(staged=True, original_case=completion.CASE,
|
|
completion_sha256=COMPLETE_SHA, delta_sha256=DELTA_SHA)
|
|
|
|
|
|
def linked_receipt(path, action):
|
|
receipt = load(path)
|
|
ident = receipt['operation_id']
|
|
if action == 'read':
|
|
require(ident.startswith('read-') and str(uuid.UUID(ident[5:])) == ident[5:]
|
|
and uuid.UUID(ident[5:]).version == 4, 'canonical unique actual read operation')
|
|
else:
|
|
require(ident == action, 'exact once-only actual mutation operation')
|
|
require(path.parent == FOLDER and path.name == ident + '-receipt.json'
|
|
and receipt['original_case'] == completion.CASE and receipt['action'] == action
|
|
and receipt['read_only'] is (action == 'read')
|
|
and receipt['operator_sha256'] == original.sha(Path(__file__))
|
|
and receipt['completion_sha256'] == COMPLETE_SHA and receipt['delta_sha256'] == DELTA_SHA
|
|
and receipt['calibrated'] is False and receipt['clock_authority'] is False,
|
|
'same original operation/action/operator/controller receipt')
|
|
raw = receipt['raw_reply']
|
|
require(set(raw) == {'filename', 'sha256'} and raw['filename'] == ident + '-reply.json'
|
|
and original.sha(FOLDER / raw['filename']) == raw['sha256'], 'exact original operation raw reply')
|
|
binding = {key: receipt[key] for key in ('original_case', 'action', 'read_only', 'operation_id',
|
|
'raw_reply', 'operator_sha256', 'completion_sha256', 'delta_sha256')}
|
|
witnesses = {}
|
|
for field, suffix in (('server_witness', '-server.json'), ('native_witness', '-native.json'),
|
|
('preservation', '-preservation.json')):
|
|
link = receipt[field]
|
|
require(set(link) == {'filename', 'sha256'} and link['filename'] == ident + suffix
|
|
and original.sha(FOLDER / link['filename']) == link['sha256'],
|
|
'same separately saved operation witness link')
|
|
witness = load(FOLDER / link['filename'])
|
|
require(all(witness[key] == value for key, value in binding.items()),
|
|
'all witness metadata bind same operation/action/read-only/raw reply')
|
|
witnesses[field] = witness
|
|
server, native, preservation = (witnesses[key] for key in ('server_witness', 'native_witness', 'preservation'))
|
|
require(preservation['server_witness'] == receipt['server_witness']
|
|
and preservation['native_witness'] == receipt['native_witness']
|
|
and server['before'] == server['after'] == preservation['server']
|
|
and native['after'] == preservation['native'] and preservation['no_rmm_jobs'] is True
|
|
and preservation['calibrated'] is False and preservation['clock_authority'] is False,
|
|
'actual complete linked server/native preservation format')
|
|
original.preserved(native['before'], native['after'])
|
|
return load(FOLDER / raw['filename'])
|
|
|
|
|
|
def completion_proof():
|
|
reply = linked_receipt(FOLDER / 'complete-receipt.json', 'complete')
|
|
require(reply.get('id') == completion.CASE and reply.get('setup_repair_completed') is True
|
|
and reply.get('original_setup_replayed') is False and reply.get('service_actions') is False
|
|
and reply.get('calibrated') is False and reply.get('clock_authority') is False,
|
|
'actual completed original-case reply; never synthesize missing replies or proof')
|
|
|
|
|
|
def positive_local_service():
|
|
# A fresh linked read may establish an actual saved outcome after a lost
|
|
# reply. Never manufacture the missing start reply, process proof or exit.
|
|
candidates = [FOLDER / 'start-local-service-receipt.json']
|
|
candidates += sorted(FOLDER.glob('read-*-receipt.json'), key=lambda path: path.name)
|
|
for path in candidates:
|
|
if not path.exists():
|
|
continue
|
|
response = linked_receipt(path, 'start-local-service' if path.name.startswith('start-') else 'read')
|
|
value = response.get('roles', {}).get('local-service')
|
|
if value is None or value['markers']['outcome'] is None:
|
|
continue
|
|
original.validate_role('local-service', value, completion.CASE)
|
|
return
|
|
raise RuntimeError('actual successful LocalService capture and exact kernel exit required before SYSTEM start')
|
|
|
|
|
|
def witnesses(access, baseline):
|
|
server, native = original.server_closed(access), original.native_witness(access)
|
|
require(server == baseline['server'], 'original closed server counters and policy unchanged')
|
|
original.preserved(baseline['native'], native)
|
|
return server, native
|
|
|
|
|
|
def run(action):
|
|
verify()
|
|
access = original.CaptureAccess(original.ACCESS_ROOT)
|
|
baseline = load(completion.ORIGINAL / 'baseline.json')
|
|
before_server, before_native = witnesses(access, baseline)
|
|
ident = 'read-' + str(uuid.uuid4()) if action == 'read' else action
|
|
if action != 'read':
|
|
if action != 'stage':
|
|
staged = load(FOLDER / 'stage-reply.json')
|
|
require(staged == dict(staged=True, original_case=completion.CASE,
|
|
completion_sha256=COMPLETE_SHA, delta_sha256=DELTA_SHA), 'one completed original stage')
|
|
if action in ('start-local-service', 'start-system', 'cleanup-local-service', 'cleanup-system'):
|
|
completion_proof()
|
|
if action.startswith('start-'):
|
|
require(not any(FOLDER.glob('cleanup-*-attempt.json')), 'cleanup began; no new starts')
|
|
if action == 'start-system':
|
|
positive_local_service()
|
|
require(not (FOLDER / (action + '-reply.json')).exists(), 'no completed mutation replay')
|
|
save(FOLDER / (action + '-attempt.json'), dict(original_case=completion.CASE, action=action,
|
|
once=True, no_retry=True, operator_sha256=original.sha(Path(__file__)),
|
|
completion_sha256=COMPLETE_SHA, delta_sha256=DELTA_SHA))
|
|
else:
|
|
save(FOLDER / (ident + '-intent.json'), dict(original_case=completion.CASE, read_only=True,
|
|
operator_sha256=original.sha(Path(__file__)), controller_sha256=DELTA_SHA))
|
|
response = stage(access) if action == 'stage' else access.powershell(LAUNCH, payload(action), timeout=90)
|
|
raw_path = FOLDER / (ident + '-reply.json')
|
|
save(raw_path, response) # Preserve exact canonical raw response before validation or witnesses.
|
|
raw_link = dict(filename=raw_path.name, sha256=original.sha(raw_path))
|
|
binding = dict(original_case=completion.CASE, action=action, read_only=action == 'read',
|
|
operation_id=ident, raw_reply=raw_link, operator_sha256=original.sha(Path(__file__)),
|
|
completion_sha256=COMPLETE_SHA, delta_sha256=DELTA_SHA)
|
|
after_server, after_native = witnesses(access, baseline)
|
|
require(before_server == after_server, 'server preserved throughout action')
|
|
original.preserved(before_native, after_native)
|
|
server_path, native_path = FOLDER / (ident + '-server.json'), FOLDER / (ident + '-native.json')
|
|
save(server_path, dict(binding, before=before_server, after=after_server))
|
|
save(native_path, dict(binding, before=before_native, after=after_native))
|
|
server_link = dict(filename=server_path.name, sha256=original.sha(server_path))
|
|
native_link = dict(filename=native_path.name, sha256=original.sha(native_path))
|
|
preservation_path = FOLDER / (ident + '-preservation.json')
|
|
save(preservation_path, dict(binding, server=after_server, native=after_native,
|
|
server_witness=server_link, native_witness=native_link,
|
|
no_rmm_jobs=True, calibrated=False, clock_authority=False))
|
|
# No success/complete-role assertion is made before both linked witnesses.
|
|
completed = []
|
|
if action == 'complete':
|
|
require(response.get('id') == completion.CASE and response.get('setup_repair_completed') is True
|
|
and response.get('original_setup_replayed') is False and response.get('service_actions') is False,
|
|
'only own setup completion; no service action')
|
|
if action not in ('stage', 'complete'):
|
|
require(response.get('id') == completion.CASE and response.get('calibrated') is False
|
|
and response.get('clock_authority') is False, 'same non-authoritative original case response')
|
|
if action == 'read':
|
|
require(response.get('read_only') is True, 'actual delta read only')
|
|
for role, value in response.get('roles', {}).items():
|
|
require(role in ('local-service', 'system'), 'fixed own two roles')
|
|
if value['markers']['outcome'] is not None:
|
|
original.validate_role(role, value, completion.CASE)
|
|
completed.append(role)
|
|
if action.startswith('start-'):
|
|
require(action.removeprefix('start-') in completed, 'actual successful own capture, exact kernel exit')
|
|
if action.startswith('cleanup-'):
|
|
role = action.removeprefix('cleanup-')
|
|
value = response['roles'][role]
|
|
require(value['service'] is None and value['markers']['deleted']['service_absent'] is True,
|
|
'actual original stopped fixture removal')
|
|
receipt_path = FOLDER / (ident + '-receipt.json')
|
|
save(receipt_path, dict(binding, server_witness=server_link, native_witness=native_link,
|
|
preservation=dict(filename=preservation_path.name, sha256=original.sha(preservation_path)),
|
|
completed_roles=sorted(completed), calibrated=False, clock_authority=False))
|
|
print(json.dumps(dict(action=action, original_case=completion.CASE,
|
|
completed_roles=sorted(completed), receipt_filename=receipt_path.name,
|
|
receipt_sha256=original.sha(receipt_path), read_only=action == 'read')))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('action', choices=ACTIONS)
|
|
run(parser.parse_args().action)
|