#!/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)