diff --git a/deploy/windows/test_time_profile_config.py b/deploy/windows/test_time_profile_config.py new file mode 100644 index 0000000..64032ae --- /dev/null +++ b/deploy/windows/test_time_profile_config.py @@ -0,0 +1,103 @@ +"""Local contract fixtures only; no native qualification or target calls.""" +import base64 +import copy +import json +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +import time_profile_config as t +from vm_mvp_acceptance import GuardError + + +def fixture(): + binding = {'tenant_id':'11111111-1111-4111-8111-111111111111', + 'agent_id':'22222222-2222-4222-8222-222222222222', + 'asset_id':'33333333-3333-4333-8333-333333333333', + 'enrollment_generation':1,'assignment_version':1,'public_key_hex':'11'*32} + public = {'public-binding.json':binding,'qualified-time-public-key.json':{ + 'key_generation':1,'server_instance':'44444444-4444-4444-8444-444444444444', + 'key_id':'local_fixture_only','public_key_hex':'22'*32},'public-platform.json':{'fixture_only':True}} + agent_sid = 'S-1-5-80-1-2-3-4-5';helper_sid = 'S-1-5-80-1-2-3-4-6' + result = {'id':'55555555-5555-4555-8555-555555555555','verified':True,'completed':True, + 'no_jobs':True,'windows_jobs_enabled':False,'helper_effects_enabled':False, + 'clock_adapter_qualified':False,'private_key_read':False} + native = dict(agent_id=binding['agent_id'],asset_id=binding['asset_id'], + binary_sha256=t.IMAGES['agent'],helper_sha256=t.IMAGES['system_helper'], + policy_sha256='a'*64,pin_sha256='b'*64,files={}) + for role, service, kernel, label, user, image in ( + ('agent','service','agent_kernel','agent','S-1-5-19','rmm-agent-windows.exe'), + ('system_helper','helper_service','helper_kernel','helper','S-1-5-18','rmm-helper-windows.exe')): + native[service] = dict(state='Running',pid=42,creation_filetime='123',owner_sid=user) + native[kernel] = dict(pid=42,creation_filetime='123',owner_sid=user,service_sid=agent_sid if role=='agent' else helper_sid, + kernel_handle_bound=True,service_sid_enabled=True, + image='C:\\Program Files\\RustDiscovery\\'+image) + native['files'][label] = dict(file_id='a'*32,sha256=t.IMAGES[role]) + result['native'] = native + settings = dict(binding=binding,enable_effects=False,agent=dict(service_sid=agent_sid),helper=dict(service_sid=helper_sid)) + payload = dict(new_agent=t.IMAGES['agent'],new_helper=t.IMAGES['system_helper'], + new_policy='a'*64,new_pin='b'*64,qualification_sha256=t.LINK_RECEIPT, + manifest_sha256=t.LINK_RECEIPT,settings_base64=base64.b64encode(t.canonical(settings)).decode()) + return public,result,payload,{'local-service':{'fixture_only':True},'system':{'fixture_only':True}} + + +class PublicProfileContract(unittest.TestCase): + def setUp(self): + self.values = fixture() + self.pair = patch.object(t,'PAIR_ID',self.values[1]['id']);self.pair.start();self.addCleanup(self.pair.stop) + + def render(self, values=None): + return t.produce(*(values or self.values),'c'*64,'d'*64)[0] + + def test_v2_fixture_links_both_exact_roles_without_runtime_success(self): + items = self.render();config=json.loads(items['time-attestation.json']) + self.assertEqual(config['schema_version'],2) + self.assertNotIn('base_error_ns',config) + for role in config['trusted_os_active_guest']['qualifications']: + raw=items[role['role']+'-qualification.json'];value=json.loads(raw) + self.assertEqual(t.sha(raw),role['qualification_sha256']) + self.assertFalse(value['signed_runtime_verified']);self.assertFalse(value['physical_calibration_claimed']) + self.assertEqual(value['source_sha256'],t.SOURCE_SHA if role['role']=='agent' else t.ORIGINAL_SOURCE_SHA) + + def test_missing_or_not_completed_actual_pair_is_denied(self): + for field in ('verified','completed','no_jobs'): + values=copy.deepcopy(self.values);values[1].pop(field) + with self.assertRaises(GuardError):self.render(values) + + def test_wrong_kernel_birth_account_sid_image_or_fileid_is_denied(self): + for field,value in [('creation_filetime','124'),('owner_sid','S-1-5-18'), + ('service_sid_enabled',False),('kernel_handle_bound',False), + ('service_sid','S-1-5-18'),('image','C:\\wrong.exe')]: + values=copy.deepcopy(self.values);values[1]['native']['agent_kernel'][field]=value + with self.assertRaises(GuardError):self.render(values) + values=copy.deepcopy(self.values);values[1]['native']['files']['agent']['file_id']='bad' + with self.assertRaises(GuardError):self.render(values) + + def test_image_build_policy_and_identity_drift_is_denied(self): + for field in ('new_agent','new_helper','new_policy','new_pin','qualification_sha256','manifest_sha256'): + values=copy.deepcopy(self.values);values[2][field]='0'*64 + with self.assertRaises(GuardError):self.render(values) + values=copy.deepcopy(self.values);values[0]['public-binding.json']['agent_id']='99999999-9999-4999-8999-999999999999' + with self.assertRaises(GuardError):self.render(values) + + def test_no_actual_pair_pins_blocks_before_creating_any_case(self): + with tempfile.TemporaryDirectory() as root, patch.object(t,'STATE',Path(root)/'absent'),patch.object(t,'PAIR_ID',None): + with self.assertRaises(GuardError):t.prepare() + self.assertFalse(t.STATE.exists()) + + def test_bounded_nofollow_read_duplicate_json_and_createonce(self): + with tempfile.TemporaryDirectory() as root: + path=Path(root)/'value.json';t.write(path,b'{"a":1}\n') + self.assertEqual(t.read(path)[1],{'a':1}) + with self.assertRaises(FileExistsError):t.write(path,b'{}') + with self.assertRaises(GuardError):t.read(path,'0'*64) + link=Path(root)/'link';link.symlink_to(path) + with self.assertRaises(OSError):t.read(link) + bad=Path(root)/'duplicate.json';t.write(bad,b'{"a":1,"a":2}') + with self.assertRaises(GuardError):t.read(bad) + with self.assertRaises(GuardError):t.read(path,limit=1) + + +if __name__ == '__main__': + unittest.main() diff --git a/deploy/windows/time_profile_config.py b/deploy/windows/time_profile_config.py new file mode 100644 index 0000000..1d5e815 --- /dev/null +++ b/deploy/windows/time_profile_config.py @@ -0,0 +1,509 @@ +#!/usr/bin/env python3 +"""First public V2 time pin for one actual qualified Windows product pair. + +prepare/guards are local only. No target operation happens on import. +Missing native product-role/readback evidence blocks preparation; diagnostics +are never relabelled as calibrated product clocks or signed runtime success. +""" +import argparse +import base64 +import copy +import hashlib +import json +import os +from pathlib import Path +import re +import stat +import uuid + +import system_pipe_upgrade as prior +import signed_clock_capture_acceptance as raw_capture + +ROOT = Path(__file__).resolve().parents[2] +CLOCK = ROOT.parent / 'rust-discovery-signed-clock' +MAIN = ROOT.parent / 'rust-discovery' +STATE = ROOT / 'devstate/windows-time-profile-config' +PUBLIC = CLOCK / 'devstate/windows-time-profile-public-preparation/c3077acf-12da-410e-9f55-e75a1cd0a75f' +PAIR_ID = None # Root binds the actual new single passive pair case after qualification. +PAIR_RESULT_SHA = None +PAIR_INTENT_SHA = None +PAIR_ROOT = CLOCK / 'devstate/windows-signed-clock/passive-pair-upgrade' +SOURCE_CASE = CLOCK / 'devstate/windows-signed-clock/trusted-os-qualification-c4679433-b632-4d6e-8668-f0f2fb54a542' +LINK_CASE = MAIN / 'devstate/windows-client/operator-window-20261115/observed-agent-build' +ORIGINAL_SOURCE_SHA = 'd8594c1eba2c2cc5d5fde4a462b2110aa2e7e64081452b742c4ed81a2cfb477d' +SOURCE_SHA = '342494c4f9e7eca439c059745591a8e907026da20f56b223fcb0eb0707aa6d82' +SOURCE_RECEIPT = '96b05fe13f4d459b4b3ef78292beea33827b1ea47293ffb5921c685940e82a4d' +LINK_RECEIPT = 'f04024f78c2f11f5c66bbdf9278467f5bcc50da5c2bd7336623851bca42dd446' +LINK_INPUTS = '11717fab51bd1d6bf103b1821cc1e2a84699f46cac21f2cc614acf4b68381fa4' +ORIGINAL_LINK_RECEIPT = '04ed34e6e850aca77c1fd4677ddb271f7ccd9492a97f5d4e00ead4c1f032f29d' +NATIVE_RESULTS = { + 'linux': ('84592e7a-6554-4a7d-a73f-2bdebdb9e9a8', '150954b0ab290d8e9fbda5616f6df071168efd88a9f1d8b48b2bd8a5f5de7c20'), + 'windows': ('44059065-c17e-43c3-86aa-d4d131454ccb', 'b235bdd444c112ff91cbc5f160d39d69ef79fb419b9b2ab7ccdcec06009d5c6b')} +ORIGINAL_IMAGES = {'agent': '26dc9d2f6928c5a41050ac9324e041c065e7a9ae52324416f3bb6222c002ae6b', + 'system_helper': '59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e'} +IMAGES = {'agent': '0549d9ebea73cff996938f859b92192cc333de194128d7c6859a3f1d2e85893c', + 'system_helper': ORIGINAL_IMAGES['system_helper']} +ASSUMPTION = 'active_guest_no_pause_save_restore_snapshot_migration_host_suspend' +PUBLIC_SHAS = {'qualified-time-public-key.json': 'c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2', + 'public-platform.json': '94ae865e0e3449f6901f4d5f593aacbd5829b06340e296e19e6f0159a157cba3', + 'public-binding.json': '9239ee9f4142735867e77451478bf309fbf449d730a0ede6c958bc8018830dde', + 'input-provenance.json': '1c0db66cd0692024f68bddd71949692d274380a86e4b880fea0756479ceb5d0c', + 'receipt.json': '97e4db147f31f3cff134d2bc596d7d73ea5330b8b5a87971f215bb03a9751391'} +RAW = CLOCK / 'devstate/windows-signed-clock-capture-completion/ccba6d8f-c58f-4d2d-a51c-1efb3bfbabdf' +RAW_RECEIPTS = {'local-service': '10dd411be265d018489bf9477747ce2d5846ac04128f583425aec4b3c9d5252b', + 'system': '7409309ea6d586566373f570d6950c60ce2597cf939f261e6d2ea4def004a22f'} +require = prior.require + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + +def canonical(value): + return (json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False) + '\n').encode() + +def strict_object(items): + value = {} + for key, item in items: + require(key not in value, 'duplicate public JSON field') + value[key] = item + return value + +def read(path, expected=None, limit=2*1024*1024, decode=True, public=False): + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + with os.fdopen(fd, 'rb') as stream: + before = os.fstat(stream.fileno()) + modes = (0o600,0o644,0o664) if public and expected is not None else (0o600,) + require(stat.S_ISREG(before.st_mode) and before.st_uid == os.getuid() and before.st_nlink == 1 + and stat.S_IMODE(before.st_mode) in modes and 0 < before.st_size <= limit, + 'private bounded actual public evidence') + raw = stream.read(limit + 1); after = os.fstat(stream.fileno()) + require((before.st_dev,before.st_ino,before.st_size,before.st_mtime_ns,before.st_ctime_ns) + == (after.st_dev,after.st_ino,after.st_size,after.st_mtime_ns,after.st_ctime_ns) + and len(raw) == before.st_size and (expected is None or sha(raw) == expected), + 'unchanged independently pinned public evidence') + return raw, json.loads(raw, object_pairs_hook=strict_object) if decode else None + +def write(path, raw): + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd,'wb') as stream: + stream.write(raw); stream.flush(); os.fsync(stream.fileno()) + fd = os.open(path.parent,os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: os.fsync(fd) + finally: os.close(fd) + +def public_inputs(): + values = {name: read(PUBLIC/name,digest)[1] for name,digest in PUBLIC_SHAS.items()} + pin, platform, binding = (values[n] for n in ('qualified-time-public-key.json','public-platform.json','public-binding.json')) + require(set(pin) == {'algorithm','schema_version','key_generation','key_id','server_instance','public_key_hex'} + and pin['algorithm'] == 'Ed25519' and pin['schema_version'] == 1 + and type(pin['key_generation']) is int and pin['key_generation'] > 0 + and re.fullmatch('[A-Za-z0-9_-]{1,64}',pin['key_id']) + and re.fullmatch('[a-f0-9]{64}',pin['public_key_hex']), 'actual separate public time key') + require(str(uuid.UUID(pin['server_instance'])) == pin['server_instance'] and uuid.UUID(pin['server_instance']).int > 0, + 'actual server instance') + require(set(binding) == {'tenant_id','asset_id','agent_id','enrollment_generation','assignment_version','public_key_hex'} + and all(str(uuid.UUID(binding[k])) == binding[k] and uuid.UUID(binding[k]).int > 0 for k in ('tenant_id','asset_id','agent_id')) + and type(binding['enrollment_generation']) is int and binding['enrollment_generation'] == 1 + and type(binding['assignment_version']) is int and binding['assignment_version'] == 1 + and bytes.fromhex(pin['public_key_hex']) != bytes.fromhex(binding['public_key_hex']), 'unchanged actual identity and distinct time/job keys') + require(platform['schema'] == 1 and platform['hypervisor'] == 'kvm' and platform['state'] == 'running' + and platform['domain_uuid'] == '1ec0d319-24bc-4953-a6b2-52b85449be07' + and platform['has_genid'] is False + and {'name':'hypervclock','present':'yes'} in platform['timers'], 'actual selectively observed active KVM platform') + provenance = values['input-provenance.json'] + require(provenance['candidate_images'] == ORIGINAL_IMAGES and provenance['operating_assumption'] == ASSUMPTION + and provenance['platform'] == 'kvm_qemu_hypervclock' and provenance['roles_qualified'] is False + and provenance['time_config_created'] is False and provenance['target_called'] is False, + 'original incomplete public preparation stays incomplete and unchanged') + return values + +def source_inputs(): + _, source = read(SOURCE_CASE/'receipt.json',SOURCE_RECEIPT) + read(SOURCE_CASE/'source/crates/agent-windows/src/signed_clock.rs',ORIGINAL_SOURCE_SHA,decode=False) + _, link = read(LINK_CASE/'receipt.json',LINK_RECEIPT) + _, inputs = read(LINK_CASE/'source-inputs.json',LINK_INPUTS) + require(len(inputs) == 202 and len({item['path'] for item in inputs}) == 202, + 'exact updated source input set') + clock = [item for item in inputs if item['path'] == 'crates/agent-windows/src/signed_clock.rs'] + require(len(clock) == 1 and clock[0]['sha256'] == SOURCE_SHA, 'same qualified V2 clock source') + read(LINK_CASE/'source/crates/agent-windows/src/signed_clock.rs',SOURCE_SHA,decode=False) + original_path = CLOCK/'devstate/windows-signed-clock/trusted-os-candidate-link-542cbf43-afb2-4994-b141-06e003e5e2e8' + _, original = read(original_path/'receipt.json',ORIGINAL_LINK_RECEIPT) + require(source['source_sha256'] == original['source_sha256'] == ORIGINAL_SOURCE_SHA + and source['input_count'] == link['input_count'] == 202 + and source['inputs_sha256'] == original['inputs_sha256'] + and original['source_receipt_sha256'] == SOURCE_RECEIPT + and link['source_receipt_sha256'] == ORIGINAL_LINK_RECEIPT + and link['source_inputs_sha256'] == LINK_INPUTS + and source['inputs_verified_before_after'] is True and link['source_verified_before_after'] is True + and source['checks']['linux_signed_clock_guards']['passed'] == 8 + and link['link_exit'] == 0 and link['original_helper_sha256'] == IMAGES['system_helper'] + and link['target'] == 'x86_64-pc-windows-gnu' and link['patches'] == ['656102b','cc82124'], + 'actual fixed V2 source and linked product pair, no runtime success inferred') + for artifact, role in ((link['artifacts']['rmm-agent-windows.exe'],'agent'), + (original['artifacts']['rmm-helper-windows.exe'],'system_helper')): + require(artifact['sha256'] == IMAGES[role] and artifact['machine'] == 'PE_AMD64', 'same actual linked role image') + for platform in ('linux','windows'): + case, binary_sha = NATIVE_RESULTS[platform] + _, result = read(LINK_CASE.parent/case/'result.json',link[platform+'_result_sha256'],public=True) + output = result['stdout'] if platform == 'linux' else '\n'.join(result['lines']) + names = re.findall(r'^test (signed_clock::tests::[a-z_]+) \.\.\. ok$', output, re.MULTILINE) + expected = set(source['checks']['linux_signed_clock_guards']['selected']) | { + 'signed_clock::tests::passive_sampling_requires_a_profile_and_uses_heartbeat_cadence'} + require(result['test_binary_sha256'] == binary_sha + and result['exit' if platform=='linux' else 'exit_code'] == 0 + and len(names) == 9 and set(names) == expected + and '9 passed; 0 failed; 0 ignored' in output, 'same-source actual native nine guards') + return source,link + +def raw_inputs(): + require(sha(Path(raw_capture.__file__).read_bytes()) == + 'dd6c575a119751429448e40e6f306cf79efa3a86c49bf2cd32a7783937177770', + 'unchanged original raw-role decoder') + records = {} + for role, digest in RAW_RECEIPTS.items(): + _, receipt = read(RAW/('start-'+role+'-receipt.json'),digest) + raw_link = receipt['raw_reply'] + require(raw_link['filename'] == 'start-'+role+'-reply.json', 'fixed original raw role namespace') + _, reply = read(RAW/raw_link['filename'],raw_link['sha256']) + require(receipt['calibrated'] is False and receipt['clock_authority'] is False + and reply['calibrated'] is False and reply['clock_authority'] is False, + 'raw probe is never a product calibration') + for key in ('native_witness','server_witness','preservation'): + item = receipt[key] + require(Path(item['filename']).name == item['filename'], 'fixed sibling evidence leaf') + read(RAW/item['filename'],item['sha256']) + raw_capture.validate_role(role,reply['roles'][role],'efd17b43-7e04-49a7-9bd4-862d13365eec') + records[role] = {'receipt_sha256':digest,'probe_image_sha256':raw_capture.EXE_SHA, + 'raw_report_sha256':reply['roles'][role]['raw_report_sha256']} + return records + +def validate_pair(result, intent): + require(result.get('id') == PAIR_ID and result.get('verified') is True and result.get('completed') is True + and result.get('no_jobs') is True and result.get('windows_jobs_enabled') is False + and result.get('helper_effects_enabled') is False and result.get('clock_adapter_qualified') is False + and result.get('private_key_read') is False, 'actual completed passive pair required; no missing or dummy result') + payload = intent.get('payload',intent) + require(payload['new_agent'] == IMAGES['agent'] and payload['new_helper'] == IMAGES['system_helper'] + and payload['qualification_sha256'] == LINK_RECEIPT and payload['manifest_sha256'] == LINK_RECEIPT, + 'actual exact V2 pair source chain') + native = result['native'] + require(native['binary_sha256'] == IMAGES['agent'] and native['helper_sha256'] == IMAGES['system_helper'] + and native['policy_sha256'] == payload['new_policy'] and native['pin_sha256'] == payload['new_pin'], 'complete native image/pin pair') + qualifications = [] + for role,service,kernel,label,user in [('agent','service','agent_kernel','agent','S-1-5-19'),('system_helper','helper_service','helper_kernel','helper','S-1-5-18')]: + s,k,f = native[service],native[kernel],native['files'][label] + require(s['state'] == 'Running' and type(s['pid']) is int and s['pid'] > 0 + and k['pid'] == s['pid'] and k['creation_filetime'] == s['creation_filetime'] + and k['owner_sid'] == s['owner_sid'] == user and k['service_sid_enabled'] is True + and k['kernel_handle_bound'] is True and f['sha256'] == IMAGES[role] + and k['image'] == ('C:\\Program Files\\RustDiscovery\\rmm-agent-windows.exe' if role=='agent' + else 'C:\\Program Files\\RustDiscovery\\rmm-helper-windows.exe') + and re.fullmatch(r'S-1-5-80-(?:[0-9]+-){4}[0-9]+',k['service_sid']) + and re.fullmatch('[0-9]+',k['creation_filetime']) and re.fullmatch('[a-f0-9]{32}',f['file_id']), + 'actual SCM/kernel account, enabled service SID, birth and image FileID') + qualifications.append({'role':role,'binary_sha256':IMAGES[role],'service':copy.deepcopy(s), + 'kernel':copy.deepcopy(k),'image_file':copy.deepcopy(f)}) + return native,payload,qualifications + +def produce(public, pair_result, pair_intent, raw, result_sha, intent_sha): + native,payload,roles = validate_pair(pair_result,pair_intent) + binding = public['public-binding.json']; pin=public['qualified-time-public-key.json'] + require(native['agent_id'] == binding['agent_id'] and native['asset_id'] == binding['asset_id'], 'same actual device binding') + settings = json.loads(base64.b64decode(payload['settings_base64'],validate=True),object_pairs_hook=strict_object) + require(settings['binding'] == binding and settings['enable_effects'] is False + and settings['agent']['service_sid'] == roles[0]['kernel']['service_sid'] + and settings['helper']['service_sid'] == roles[1]['kernel']['service_sid'] + and settings['agent']['service_sid'] != settings['helper']['service_sid'], 'actual reciprocal settings and distinct service roles') + platform = {'profile':'rmm.windows.trusted-os.platform-provenance.v1','operating_assumption':ASSUMPTION, + 'platform':'kvm_qemu_hypervclock','public_platform_sha256':PUBLIC_SHAS['public-platform.json'], + 'original_public_preparation_sha256':PUBLIC_SHAS['input-provenance.json'], + 'source_sha256':SOURCE_SHA,'source_receipt_sha256':SOURCE_RECEIPT, + 'product_pair_receipt_sha256':LINK_RECEIPT,'pair_result_sha256':result_sha, + 'pair_intent_sha256':intent_sha,'independent_physical_calibration_claimed':False} + items={'platform-provenance.json':canonical(platform),'public-platform.json':canonical(public['public-platform.json'])} + # The original platform file is separately retained below using its actual + # bytes; this canonical descriptive copy is never mislabelled as its hash. + references=[] + for role in roles: + role.update(profile='rmm.windows.trusted-os.product-role-prerequisite.v1',pair_case_id=PAIR_ID, + pair_result_sha256=result_sha,pair_intent_sha256=intent_sha, + source_sha256=SOURCE_SHA if role['role']=='agent' else ORIGINAL_SOURCE_SHA, + original_source_receipt_sha256=SOURCE_RECEIPT,product_pair_receipt_sha256=LINK_RECEIPT, + platform_provenance_sha256=sha(items['platform-provenance.json']), + raw_capture=raw['local-service' if role['role']=='agent' else 'system'], + signed_runtime_verified=False,physical_calibration_claimed=False) + name=role['role']+'-qualification.json';items[name]=canonical(role) + references.append({'role':role['role'],'binary_sha256':role['binary_sha256'],'qualification_sha256':sha(items[name])}) + value={'schema_version':2,'key_generation':pin['key_generation'],'server_instance':pin['server_instance'], + 'binding':binding,'public_keys_hex':{pin['key_id']:pin['public_key_hex']}, + 'trusted_os_active_guest':{'operating_assumption':ASSUMPTION,'platform':'kvm_qemu_hypervclock', + 'platform_provenance_sha256':sha(items['platform-provenance.json']),'qualifications':references}} + items['time-attestation.json']=canonical(value) + require(len(items['time-attestation.json'])<=16384, 'real bounded public V2 configuration') + return items,native,payload + +# Controller and transport are defined below; no remote action on import. + +HEADER = r''' +$ErrorActionPreference='Stop';$request=$global:RmmTimeProfilePayload +if(!$request-or$request.action-isnot[string]-or$request.action-cnotin@('install','read')-or[guid]::ParseExact($request.id,'D').ToString()-cne$request.id-or$request.profile-cne'rmm.windows.initial-public-time-profile.v2'){throw 'Exact initial time-profile operation'} +$p=$request.pair_payload +$boot='C:\ProgramData\RustDiscoveryBootstrap';$folder=Join-Path $boot ('time-profile-'+$request.id) +$agentRoot='C:\ProgramData\RustDiscovery';$agentState=Join-Path $agentRoot 'state';$helperRoot='C:\ProgramData\RustDiscoverySystem';$helperState=Join-Path $helperRoot 'state' +$config=Join-Path $agentRoot 'config.json';$settings=Join-Path $helperRoot 'helper.json';$pin=Join-Path $helperRoot 'agent-pin.json' +$agentBinary='C:\Program Files\RustDiscovery\rmm-agent-windows.exe';$helperBinary='C:\Program Files\RustDiscovery\rmm-helper-windows.exe' +$agentName='RmmDiscoveryWindows';$helperName='RmmDiscoverySystemHelper';$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 +$helperSid=(New-Object Security.Principal.NTAccount('NT SERVICE',$helperName)).Translate([Security.Principal.SecurityIdentifier]).Value +$target=Join-Path $helperRoot 'time-attestation.json';$active=Join-Path $boot 'time-profile-initial-active.json' +''' + +BODY = r''' +function ReadAcl($path,[bool]$directory){ + Check $path $directory;$acl=Get-Acl -LiteralPath $path + if($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value-cnotin@($sys,$admin)){throw 'Public pin owner must remain SYSTEM/Administrators'} + $seen=@{};foreach($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){ + $id=$rule.IdentityReference.Value;$rights=[int64]$rule.FileSystemRights + if($rule.AccessControlType-cne'Allow'-or$id-cnotin@($sys,$admin,$agentSid,$helperSid)-or($id-cnotin@($sys,$admin)-and($rights-band(-bnot 0x1200a9))-ne0)){throw 'Only exact native reader rights, no foreign writer'} + $seen[$id]=$true + };foreach($id in @($sys,$admin)){if(!$seen[$id]){throw 'Privileged public-pin role missing'}} + return $acl +} +function GrantRootReaders{ + $acl=ReadAcl $helperRoot $true + foreach($id in @($agentSid,$helperSid)){ + $present=$false;foreach($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($rule.IdentityReference.Value-ceq$id-and([int64]$rule.FileSystemRights-band0x1200a9)-eq0x1200a9){$present=$true}} + if(!$present){$acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($id)),[Security.AccessControl.FileSystemRights]0x1200a9,'None','None','Allow')))} + } + # This-folder-only ACEs: do not expose state/PKI/ledger/intent descendants. + Set-Acl -LiteralPath $helperRoot -AclObject $acl;$null=ReadAcl $helperRoot $true +} +function SetPinAcl($path){ + $acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm(('O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;'+$agentSid+')(A;;0x1200a9;;;'+$helperSid+')')) + Set-Acl -LiteralPath $path -AclObject $acl;$null=ReadAcl $path $false +} +function NewPrivateCase{ + [RmmTimeProfileCase]::CreatePrivateOnce($folder);CheckControl $folder $true +} +function FileVolume($path){ + $handle=[RmmPipeNative]::CreateFile($path,0x80,7,[IntPtr]::Zero,3,0x2200000,[IntPtr]::Zero) + try{if($handle.IsInvalid){throw 'Protected directory identity handle'};$id=New-Object RmmPipeNative+FileId;if(![RmmPipeNative]::GetFileInformationByHandleEx($handle,18,[ref]$id,24)){throw 'Protected directory volume'};return $id.Volume.ToString([Globalization.CultureInfo]::InvariantCulture)}finally{$handle.Dispose()} +} +function SameLive($before,$after){ + Preserved $before $after $false + foreach($field in @('files','service','helper_service','agent_kernel','helper_kernel')){if(!(JsonEqual $before.$field $after.$field)){throw 'Same original data/PKI/FileIDs/services/process generations required'}} +} +function ConfigBytes{ + $bytes=[Convert]::FromBase64String($request.config_base64) + if($bytes.Length-gt16384-or$bytes.Length-lt1-or(BytesHash $bytes)-cne$request.config_sha256){throw 'Fixed complete public config bytes'} + $value=[Text.Encoding]::UTF8.GetString($bytes)|ConvertFrom-Json + if($value.schema_version-ne2-or$value.key_generation-ne$request.key_generation-or$value.server_instance-cne$request.server_instance-or!(JsonEqual $value.binding $request.binding)-or$value.trusted_os_active_guest.operating_assumption-cne'active_guest_no_pause_save_restore_snapshot_migration_host_suspend'-or$value.trusted_os_active_guest.platform-cne'kvm_qemu_hypervclock'-or@($value.trusted_os_active_guest.qualifications).Count-ne2-or$value.trusted_os_active_guest.qualifications[0].role-cne'agent'-or$value.trusted_os_active_guest.qualifications[0].binary_sha256-cne$p.new_agent-or$value.trusted_os_active_guest.qualifications[1].role-cne'system_helper'-or$value.trusted_os_active_guest.qualifications[1].binary_sha256-cne$p.new_helper){throw 'Closed real schema2/profile/role binding'} + return ,$bytes +} +CheckControl $boot $true +if($PSCommandPath-cne(Join-Path (Join-Path $boot $request.script_sha256) 'InstallPublicTimeProfile.ps1')-or(Hash $PSCommandPath)-cne$request.script_sha256){throw 'Exact reviewed public-pin controller'} +CheckControl $PSCommandPath $false +$expected=$request.expected_native +$before=ActualState $true;SameLive $expected $before +if($before.agent_kernel.service_sid-cne$agentSid-or$before.helper_kernel.service_sid-cne$helperSid){throw 'Same actual qualified service SIDs'} +$null=ReadAcl $helperRoot $true +if($request.action-ceq'read'){ + $records=[ordered]@{};if(Test-Path -LiteralPath $folder){CheckControl $folder $true;foreach($name in @('intent.json','directory-acl-intent.json','directory-acl-done.json','publish-intent.json','result.json')){$path=Join-Path $folder $name;$records[$name]=$null;if(Test-Path -LiteralPath $path){CheckControl $path $false;if((Get-Item -LiteralPath $path -Force).Length-gt2097152){throw 'Bounded original public-pin history'};$records[$name]=Get-Content -LiteralPath $path -Raw|ConvertFrom-Json}}} + if($records['intent.json']){foreach($field in $request.PSObject.Properties.Name){if($field-cne'action'-and!(JsonEqual $records['intent.json'].request.$field $request.$field)){throw 'Same original public-pin intent only'}}} + $activeRecord=$null;if(Test-Path -LiteralPath $active){CheckControl $active $false;if((Get-Item -LiteralPath $active -Force).Length-gt8192){throw 'Bounded public-pin active marker'};$activeRecord=Get-Content -LiteralPath $active -Raw|ConvertFrom-Json;if($activeRecord.id-cne$request.id-or$activeRecord.config_sha256-cne$request.config_sha256-or$activeRecord.script_sha256-cne$request.script_sha256){throw 'Another initial public-pin case; no adoption'}} + $current=$null;if(Test-Path -LiteralPath $target){$null=ReadAcl $target $false;$current=FileIdentity $target;if($current.sha256-cne$request.config_sha256){throw 'Unexpected existing configuration; no adoption'}} + @{id=$request.id;read_only=$true;records=$records;active=$activeRecord;configuration=$current;native=$before;root_sddl=(Get-Acl -LiteralPath $helperRoot).Sddl;clock_runtime_qualified=$false;no_jobs=$true}|ConvertTo-Json -Depth 50 -Compress;exit0 +} +if($request.action-cne'install'){throw 'Exact install action only'} +if((Test-Path -LiteralPath $target)-or(Test-Path -LiteralPath $folder)-or(Test-Path -LiteralPath $active)){throw 'Existing initial time profile or partial attempt: original read only'} +$bytes=ConfigBytes +$rootSddl=(Get-Acl -LiteralPath $helperRoot).Sddl +$heldAgent=[RmmPipeNative]::Open([int]$before.service.pid);$heldHelper=[RmmPipeNative]::Open([int]$before.helper_service.pid) +try{ + $null=Kernel 'agent' $before.service $heldAgent;$null=Kernel 'helper' $before.helper_service $heldHelper + NewPrivateCase + WriteNew (Join-Path $folder 'intent.json') @{id=$request.id;request=$request;before=$before;original_root_sddl=$rootSddl;no_retry=$true} + WriteNew $active @{id=$request.id;config_sha256=$request.config_sha256;script_sha256=$request.script_sha256;no_retry=$true} + foreach($item in $request.provenance.PSObject.Properties){if($item.Name-cnotmatch'^(platform-provenance|public-platform|original-public-platform|agent-qualification|system_helper-qualification|qualified-time-public-key|public-binding)\.json$'){throw 'Closed public provenance leaves'};$raw=[Convert]::FromBase64String($item.Value);if($raw.Length-gt65536){throw 'Bounded public provenance'};WriteBytes (Join-Path $folder $item.Name) $raw} + $staged=Join-Path $folder 'time-attestation.candidate.json';WriteBytes $staged $bytes;SetPinAcl $staged + if((FileIdentity $staged).sha256-cne$request.config_sha256-or(FileVolume $folder)-cne(FileVolume $helperRoot)){throw 'Verified complete same-volume public pin'} + SameLive $before (ActualState $true) + if((Get-Acl -LiteralPath $helperRoot).Sddl-cne$rootSddl){throw 'Immediate directory ACL CAS'} + WriteNew (Join-Path $folder 'directory-acl-intent.json') @{old_sddl=$rootSddl;readers=@($agentSid,$helperSid);this_folder_only=$true} + GrantRootReaders + WriteNew (Join-Path $folder 'directory-acl-done.json') @{sddl=(Get-Acl -LiteralPath $helperRoot).Sddl} + SameLive $before (ActualState $true) + $null=Kernel 'agent' $before.service $heldAgent;$null=Kernel 'helper' $before.helper_service $heldHelper + if(Test-Path -LiteralPath $target){throw 'Target appeared before no-overwrite publication'} + $stagedId=FileIdentity $staged + WriteNew (Join-Path $folder 'publish-intent.json') @{config_sha256=$request.config_sha256;staged=$stagedId;create_once=$true} + [IO.File]::Move($staged,$target) + $null=ReadAcl $target $false;$published=FileIdentity $target + if(!(JsonEqual $published $stagedId)){throw 'Exact same file identity/hash/ACL after publication'} + $after=ActualState $true;SameLive $before $after + $null=Kernel 'agent' $before.service $heldAgent;$null=Kernel 'helper' $before.helper_service $heldHelper + $result=@{id=$request.id;installed=$true;configuration=$published;native=$after;original_root_sddl=$rootSddl;root_sddl=(Get-Acl -LiteralPath $helperRoot).Sddl;no_jobs=$true;clock_runtime_qualified=$false;services_changed=$false;private_key_read=$false} + WriteNew (Join-Path $folder 'result.json') $result;$result|ConvertTo-Json -Depth 50 -Compress +}finally{$heldAgent.Dispose();$heldHelper.Dispose()} +'''.replace('exit0','exit 0') + + +def controller(): + """Reuse only existing read-only witnesses, not any old phase/repair code.""" + require(sha(Path(prior.__file__).read_bytes()) == 'e466576673a0e5c332cfc1613ae88a62f5b526015ced76b1d22473e292a995e0' + and sha(Path(prior.u.__file__).read_bytes()) == 'f8dc1c8fbc064e253b1fbe130fb628afef58cf45c2bafb6837d6716125b42d38', 'unchanged reviewed original readonly witness sources') + source = prior.u.SCRIPT + # Every selected section ends at the next named function. No StartOnce, + # StopPinned, Swap, Backup, original phase, or old payload dispatch is copied. + names = ['Check','BytesHash','Hash','AclHash','CheckControl','Service','Probe','Diagnostic','RawAgentProbe','EmptyIntentStore','State','Preserved'] + functions=[] + for name in names: + start=source.index('function '+name+'(') if 'function '+name+'(' in source else source.index('function '+name+'{') + end=source.find('\nfunction ',start+1) + require(end>start, 'closed existing readonly witness boundary') + functions.append(source[start:end]) + # File writers are new, closed by the controller's fixed namespace only. + writers=r'''function WriteBytes($path,[byte[]]$bytes){$file=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$file.Write($bytes,0,$bytes.Length);$file.Flush($true)}finally{$file.Dispose()}} +function WriteNew($path,$value){WriteBytes $path ([Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 50 -Compress)))}''' + return HEADER+'\n'+STRUCTURAL+'\n'+'\n'.join(functions)+'\n'+prior.NATIVE+'\n'+CASE_NATIVE+'\n'+writers+'\n'+BODY + +# Same reviewed structural comparison as e6debe5; member order is not identity. +STRUCTURAL = r'''function CanonicalStateValue($value,[int]$depth=0){ + if($depth-gt40){throw 'Bounded state comparison depth'} + if($null-eq$value){return $null} + if($value-is[Collections.IDictionary]){$result=[ordered]@{};foreach($key in @($value.Keys|Sort-Object -CaseSensitive)){if($key-isnot[string]-or$result.Contains($key)){throw 'Nonunique state object key'};$result[$key]=CanonicalStateValue $value[$key] ($depth+1)};return $result} + if($value-is[pscustomobject]){$result=[ordered]@{};foreach($property in @($value.PSObject.Properties|Sort-Object -Property Name -CaseSensitive)){if($property.Name-isnot[string]-or$result.Contains($property.Name)){throw 'Nonunique state object key'};$result[$property.Name]=CanonicalStateValue $property.Value ($depth+1)};return $result} + if($value-is[Collections.IEnumerable]-and$value-isnot[string]){$result=New-Object 'Collections.Generic.List[object]';foreach($item in $value){$result.Add((CanonicalStateValue $item ($depth+1)))};return ,$result.ToArray()} + return $value +} +function JsonEqual($a,$b){return((ConvertTo-Json -InputObject (CanonicalStateValue $a) -Depth 40 -Compress)-ceq(ConvertTo-Json -InputObject (CanonicalStateValue $b) -Depth 40 -Compress))}''' +CASE_NATIVE = r'''Add-Type -TypeDefinition @' +using System; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Security.AccessControl; +public static class RmmTimeProfileCase { + [StructLayout(LayoutKind.Sequential)] struct Attributes {public int Length;public IntPtr Descriptor;public int Inherit;} + [DllImport("kernel32.dll",EntryPoint="CreateDirectoryW",ExactSpelling=true,CharSet=CharSet.Unicode,SetLastError=true)] + [return:MarshalAs(UnmanagedType.Bool)] static extern bool CreateDirectory(string path,ref Attributes security); + public static void CreatePrivateOnce(string path){ + RawSecurityDescriptor sd=new RawSecurityDescriptor("O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)"); + byte[] raw=new byte[sd.BinaryLength];sd.GetBinaryForm(raw,0);GCHandle pin=GCHandle.Alloc(raw,GCHandleType.Pinned); + try{Attributes attributes=new Attributes{Length=Marshal.SizeOf(typeof(Attributes)),Descriptor=pin.AddrOfPinnedObject(),Inherit=0}; + if(!CreateDirectory(path,ref attributes))throw new Win32Exception(Marshal.GetLastWin32Error(),"TIME_PROFILE_PRIVATE_CREATE_ONCE"); + }finally{pin.Free();} + } +} +'@''' + +LAUNCH = r'''$ErrorActionPreference='Stop';$request=([Console]::In.ReadLine()|ConvertFrom-Json) +if(!$request-or$request.action-isnot[string]-or$request.action-cnotin@('install','read')-or$request.script_sha256-cnotmatch'^[a-f0-9]{64}$'){throw 'Fixed public-pin launch'} +$script=Join-Path (Join-Path 'C:\ProgramData\RustDiscoveryBootstrap' $request.script_sha256) 'InstallPublicTimeProfile.ps1' +$item=Get-Item -LiteralPath $script -Force;if($item.PSIsContainer-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)-or$item.Length-gt100000-or(Get-FileHash -LiteralPath $script -Algorithm SHA256).Hash.ToLowerInvariant()-cne$request.script_sha256){throw 'Exact bounded immutable time-pin script'} +$acl=Get-Acl -LiteralPath $script;if($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value-cnotin@('S-1-5-18','S-1-5-32-544')){throw 'Private launch owner'} +foreach($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($rule.AccessControlType-cne'Allow'-or$rule.IdentityReference.Value-cnotin@('S-1-5-18','S-1-5-32-544')){throw 'Private launch DACL'}} +$global:RmmTimeProfilePayload=$request;& $script +''' + +def guards(): + script=controller() + for forbidden in ('Stop-Service','Start-Service','Restart-Computer','Set-Date','AdjustTokenPrivileges', + 'function Swap','function Backup','function StartOnce','CreateService(', 'DeleteService('): + require(forbidden not in script, 'no service/clock/job effect imported') + require("$request.action-cnotin@('install','read')" in script + and "if($request.action-cne'install')" in script + and '[IO.File]::Move($staged,$target)' in script + and script.index("'publish-intent.json') @") < script.index('[IO.File]::Move($staged,$target)') + and 'This-folder-only ACEs' in script and '0x1200a9' in script + and 'CreatePrivateOnce' in script, 'closed create-once public-pin effects') + return script + +def prepare(): + # All prerequisites are checked BEFORE creating a local installation case. + # Source/link/role constants deliberately remain unset until actual evidence. + require(PAIR_ID is not None and str(uuid.UUID(PAIR_ID)) == PAIR_ID + and all(isinstance(value,str) and re.fullmatch('[a-f0-9]{64}',value) + for value in (PAIR_RESULT_SHA,PAIR_INTENT_SHA)), + 'actual completed new pair and independently pinned role readback required') + public=public_inputs(); source_inputs(); raw=raw_inputs() + pair=PAIR_ROOT/PAIR_ID + result_raw,result=read(pair/'result.json',PAIR_RESULT_SHA) + intent_path=pair/'intent.json' + if not intent_path.exists(): intent_path=pair/'bound-payload.json' + intent_raw,intent=read(intent_path,PAIR_INTENT_SHA) + items,native,payload=produce(public,result,intent,raw,sha(result_raw),sha(intent_raw)) + items['original-public-platform.json']=read(PUBLIC/'public-platform.json',PUBLIC_SHAS['public-platform.json'])[0] + for name in ('qualified-time-public-key.json','public-binding.json'): + items[name]=read(PUBLIC/name,PUBLIC_SHAS[name])[0] + script=guards().encode(); ident=str(uuid.uuid4()); script_sha=sha(script) + keep=('old_agent','old_helper','new_agent','new_helper','old_policy','old_pin','new_policy','new_pin', + 'config_sha256','probe_sha256','system_probe_sha256','intent_leaves') + public_payload={key:payload[key] for key in keep} + request={'profile':'rmm.windows.initial-public-time-profile.v2','id':ident,'action':'read', + 'script_sha256':script_sha,'config_sha256':sha(items['time-attestation.json']), + 'config_base64':base64.b64encode(items.pop('time-attestation.json')).decode(), + 'pair_payload':public_payload,'expected_native':native,'binding':public['public-binding.json'], + 'key_generation':public['qualified-time-public-key.json']['key_generation'], + 'server_instance':public['qualified-time-public-key.json']['server_instance'], + 'provenance':{name:base64.b64encode(value).decode() for name,value in items.items()}} + # Existing transport passes the payload on stdin, not on the command line. + require(len(canonical(request))<=128*1024,'bounded public bootstrap request') + STATE.mkdir(mode=0o700,parents=True,exist_ok=True);ident_dir=STATE/ident;ident_dir.mkdir(mode=0o700) + write(ident_dir/'InstallPublicTimeProfile.ps1',script) + write(ident_dir/'time-attestation.json',base64.b64decode(request['config_base64'],validate=True)) + for name,value in items.items(): write(ident_dir/name,value) + manifest={'profile':request['profile'],'id':ident,'generator_sha256':sha(Path(__file__).read_bytes()), + 'script_sha256':script_sha,'request':request,'pair_result_sha256':sha(result_raw), + 'pair_intent_sha256':sha(intent_raw),'source_receipt_sha256':SOURCE_RECEIPT, + 'product_link_receipt_sha256':LINK_RECEIPT,'target_called':False,'clock_runtime_qualified':False, + 'files':{name:{'sha256':sha(value),'bytes':len(value)} for name,value in items.items()}} + write(ident_dir/'manifest.json',canonical(manifest)) + print(json.dumps({'id':ident,'prepared_locally':True,'target_called':False, + 'config_sha256':request['config_sha256'],'manifest_sha256':sha(canonical(manifest))})) + +def load_case(ident): + require(str(uuid.UUID(ident))==ident and uuid.UUID(ident).version==4,'canonical original time-pin case') + folder=STATE/ident; _,manifest=read(folder/'manifest.json') + require(manifest['id']==ident and manifest['generator_sha256']==sha(Path(__file__).read_bytes()) + and manifest['script_sha256']==sha(guards().encode()),'same exact reviewed operator and case') + require(read(folder/'InstallPublicTimeProfile.ps1',decode=False)[0]==guards().encode(), 'same controller bytes') + request=manifest['request'];read(folder/'time-attestation.json',request['config_sha256']) + for name,item in manifest['files'].items(): read(folder/name,item['sha256']) + return folder,manifest + +def target(action,ident): + """Only Root invokes these explicit phases after independent review.""" + folder,manifest=load_case(ident) + require(action in ('stage','install','read'),'closed public-pin phase') + if action!='read': + write(folder/(action+'-attempt.json'),canonical({'id':ident,'action':action,'once':True,'lost_reply_read_original_case_only':True})) + access=raw_capture.CaptureAccess(MAIN) + if action=='stage': + path=folder/'InstallPublicTimeProfile.ps1';digest=manifest['script_sha256'] + stage=prior.u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1',path.name) + observed=access.powershell(stage,{'sha256':digest}) + if not observed['already_uploaded']: + import subprocess + config=prior.cb.contract.protected_json(MAIN/'credentials/windows-dev-access.json') + prefix=config['ssh_prefix'];args=['sftp']+[p for p in prefix[1:-1] if p!='-T']+['-b','-',prefix[-1]] + remote='/C:/ProgramData/RustDiscoveryBootstrap/'+digest+'/'+path.name + reply=subprocess.run(args,input=('put '+json.dumps(str(path.resolve()))+' '+json.dumps(remote)+'\n').encode(),capture_output=True,timeout=60) + write(folder/'stage-transport.json',canonical({'returncode':reply.returncode,'stdout_b64':base64.b64encode(reply.stdout).decode(),'stderr_b64':base64.b64encode(reply.stderr).decode()})) + require(reply.returncode==0,'once-only fixed script transfer; lost reply read only') + observed=access.powershell(stage,{'sha256':digest}) + require(observed['already_uploaded'] is True and observed['sha256']==digest,'exact staged public-pin controller') + result={'id':ident,'staged':True,'script_sha256':digest,'configuration_installed':False} + else: + request=copy.deepcopy(manifest['request']);request['action']=action + result=access.powershell(LAUNCH,request,timeout=120) + require(result['id']==ident and result.get('no_jobs') is True and result.get('clock_runtime_qualified') is False, + 'same native public-pin result, never clock readiness') + output=folder/((action+'-'+str(uuid.uuid4()) if action=='read' else action)+'-reply.json') + write(output,canonical(result)) + print(json.dumps({'id':ident,'action':action,'reply_sha256':sha(canonical(result)),'clock_runtime_qualified':False})) + +if __name__=='__main__': + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('guards','prepare','stage','install','read'));parser.add_argument('--case');arguments=parser.parse_args() + if arguments.action=='guards': guards();print('PASS closed public-profile source guards; no target action') + elif arguments.action=='prepare': prepare() + else: target(arguments.action,arguments.case) diff --git a/docs/windows-time-profile-config.md b/docs/windows-time-profile-config.md new file mode 100644 index 0000000..6bfe782 --- /dev/null +++ b/docs/windows-time-profile-config.md @@ -0,0 +1,120 @@ +# Erste öffentliche Windows-Zeitkonfiguration V2 + +Stand 2026-11-15: `deploy/windows/time_profile_config.py` bereitet den eng +begrenzten Bootstrap einer ersten `time-attestation.json` vor. Die tatsächliche +Paarwartung und neue Rollenbelege fehlen noch. Deshalb sind `PAIR_ID`, +`PAIR_RESULT_SHA` und `PAIR_INTENT_SHA` absichtlich nicht gesetzt. `prepare` +verweigert **vor** dem Anlegen eines lokalen Falls. Es wurde keine Konfiguration +auf der VM angelegt, kein Dienst geändert und kein Job erzeugt. + +Der Operator prüft die unveränderten öffentlichen Vorbereitungsbelege +`c3077acf-12da-410e-9f55-e75a1cd0a75f`, deren getrennten Ed25519-Zeitschlüssel, +Gerätebindung und tatsächlich gelesene KVM-Plattform. Die ursprüngliche +Vorbereitung bleibt mit `roles_qualified=false` unverändert. Die akzeptierte +Betriebsannahme ist ausdrücklich +`active_guest_no_pause_save_restore_snapshot_migration_host_suspend`; das ist +keine physikalische Kalibrierung und keine automatische Überwachung dieser +Betriebsannahme. + +Der neue Agent ist an SHA256 +`0549d9ebea73cff996938f859b92192cc333de194128d7c6859a3f1d2e85893c` +und Buildreceipt `f04024f78c2f11f5c66bbdf9278467f5bcc50da5c2bd7336623851bca42dd446` +gebunden. Seine 202 Quellinputs sind durch `11717fab…` fixiert; das tatsächlich +erweiterte Zeitmodul hat SHA256 `342494c4…`. Gegen die ursprüngliche Quelle +`d8594c1e…` kamen die passive Sampling-Auswahl und deren neunte Prüfung hinzu. +Der Helper bleibt `59675a3c…`, aus dem ursprünglichen Linkbeleg `04ed34e6…` +und Quellbeleg `96b05fe1…`. Diese unterschiedlichen Provenienzen werden nicht +gleichgesetzt. Der tatsächliche neue Paar-Payload verwendet für +`qualification_sha256` und `manifest_sha256` jeweils den neuen Beleg `f04024f7…`; +der alte Helper-Quellbeleg ist kein Ersatz dafür. + +Bevor ein Fall erstellt werden kann, müssen ein abgeschlossener passiver +Paarwechsel und unabhängig fixierte Originalbelege vorliegen. Für beide Rollen +werden SCM-Status, PID, Kernel-Prozessgeburt, tatsächliches Konto, aktivierte +Service-SID, gehaltener Prozesshandle, Imagepfad, Imagehash und native FileID +verknüpft. Die alten numerischen 601-Proben bleiben ausdrücklich rohe +Voraussetzungsbelege; sie qualifizieren kein Produktimage. Der Producer erzeugt +öffentliche Rollen- und Plattformbelege und daraus das vorhandene strikte +V2-Format mit genau beiden Rollen. Er behauptet weder signierte Laufzeitprüfung +noch physikalische Genauigkeit. Fehlende oder widersprüchliche Belege sperren. + +## Geplanter Ablauf nach neuem realem Paar-Readback + +Die folgenden Phasen sind **vorbereitet, nicht auf dem Ziel ausgeführt**: + +1. Root bestätigt Original-Paarfall und Originalbeleg-Hashes; diese werden als + konkrete Quellenkonstanten gebunden und nochmals geprüft. +2. `prepare` liest ausschließlich öffentliche lokale Belege und erzeugt einen + privaten, einmaligen Fall. `stage --case ` überträgt ausschließlich den + fixierten Controller über den bestehenden bestätigten SSH-Transport. +3. `install --case ` darf genau eine bisher fehlende feste öffentliche Datei + veröffentlichen. Bereits vorhandene Datei, aktiver Marker oder Teilfall + verweigern einen neuen Installationsversuch. Ein verlorener Antwortweg führt + ausschließlich zu `read --case `, nicht zu Wiederholung oder Rollback. +4. Root liest den ursprünglichen Fall separat und prüft danach die echten + passiven Agent-/Helper-Zeitbelege. Eine erfolgreiche Veröffentlichung allein + setzt `clock_runtime_qualified` ausdrücklich nicht auf true. + +## Begrenzte Wirkung und Erhaltungsnachweis + +Der Controller verwendet ausschließlich die vorhandenen lesenden SCM-, +Kernel-, FileID-, PKI-Metadaten- und Journalzeugen. Er importiert keine alten +Stop-/Start-/Swap-/Repair-Phasen. Die aktuelle Prozessgeneration, beide Images, +vier Code-/Policydateien, Konfiguration, Geräteidentität, Zertifikat, +Schlüsselmetadaten, Telemetrieidentität, Sequenzmonotonie und leere +Job-/Helper-Intents werden vor, während und nach der Veröffentlichung geprüft. +Der private Schlüssel wird weder gelesen noch gehasht. + +Eine neue private Bootstrap-Falldirectory wird nativ exklusiv mit geschützter +SYSTEM-/Administrators-DACL angelegt. Alle Originalmarker werden create-only +geschrieben und geflusht. Nur der öffentliche Helper-Stamm erhält bei Bedarf +fehlende `0x001200a9`-Leserechte für beide **Service-SIDs**, ausschließlich für +diesen Ordner, ohne Vererbung auf State/PKI/Ledger. Fremde oder weiter gehende +Service-Rechte werden verweigert. Die Kandidatdatei erhält vor Veröffentlichung +SYSTEM/Administrators-Vollzugriff und dieselben begrenzten Leser. Die feste +Zieldatei wird nach durablem Publish-Intent mit einem gleichvolumigen, +überschreibungsfreien Move veröffentlicht; anschließend müssen FileID, Hash +und DACL unverändert sein. Keine allgemeine Stromausfall-Atomizität wird daraus +abgeleitet. Teilzustände bleiben im Originalfall lesbar, ohne automatische +Reparatur oder Rechte-Rücksetzung. + +## Laden und tatsächliche Grenzen + +Das vorhandene `signed_clock::native::SignedClock::open` lädt bei jedem Öffnen +geschützte Settings, beweist den eigenen Dienstprozess und öffnet den festen +Stamm sowie die maximal 16384 Byte große Datei über `PinnedFile`. Besitzer +müssen SYSTEM/Administrators bleiben; zusätzliche Leser dürfen nur die +festgelegte Lesemaske besitzen. Beide Images müssen zu den Settings passen. +Die Prüfung bindet Dateiinhalt und FileID; spätere Rechecks öffnen denselben +Namen erneut und verwerfen Austausch oder Änderungen. Fehlerhaft beobachtete +Konfigurationen oder fehlgeschlagene Reads stellen alte Autorität nicht wieder +her; geänderte Bytes derselben Generation gelten als Fork. + +Im neuen Agenten versucht die passive Heartbeat-Schleife das Setup bei bisher +fehlendem Profil erneut. Ein erster Pin benötigt daher nach Quellenvertrag +keinen Dienstneustart. Das ist **noch kein VM-Nachweis**. Der Agent schreibt erst +nach tatsächlich erfolgreichem `complete` pro Verbindung öffentliche historische +`agent-time-sample.json` und `helper-time-sample.json` in sein bestehendes +geschütztes State-Verzeichnis. Der Helper-State bleibt unverändert. Root muss +diese Originalbelege noch für die tatsächlich installierten Rollen und +Konfigurationsbytes prüfen. Ein Statusfile ersetzt kein aktuelles Job-Startgate. + +## Tatsächlich lokal ausgeführt + +- Python-Syntaxprüfung und geschlossene Sourceguards: PASS. +- Sechs lokale Vertragsfälle: PASS. Sie prüfen die reinen Referenzbytes, + fehlende Paarbelege, falsche Rollen/Images/Geburt/SID/FileID/Policy/Identität, + create-only, begrenztes Lesen, Symlink- und Duplicate-JSON-Verweigerung. + Positive In-Memory-Fixtures sind ausdrücklich keine native Qualifikation. +- Beide erzeugten PowerShell-ASTs mit vorhandenem lokalem Parser: PASS. +- Die festgehaltenen öffentlichen Eingänge, rohen Rollenbelege und realen + Quell-/Buildbelege werden vom Operator lokal erfolgreich gelesen. Die durch + Root tatsächlich ausgeführten neun Linux- und neun Windows-Zeitmodulprüfungen + sind über deren Originalbeleg-Hashes und exakte Testnamen angebunden. +- `prepare` ohne reale Paarbelege: erwartete Verweigerung ohne angelegten Fall. + +Nicht ausgeführt: Übertragung, ACL-Änderung, Konfigurationsinstallation, +Produktdienst-Laden/Reopen auf der VM, signierte passive Laufzeitabnahme, +WebUI-Genehmigung oder RMM-Job. Nach Notebook-Suspend fehlt aktuell der +antwortende SSH-Transport; der vorbereitete Paarfall `570c7a86…` hat keine +neuen Rollenbelege und darf nicht als abgeschlossener Wechsel verwendet werden.