#!/usr/bin/env python3 """Once-only public UDS signature fixture; no private signer read or RMM authority.""" import argparse import hashlib import importlib.util import json import os from pathlib import Path import re import stat import subprocess import sys import uuid START_SHA = 'e1458cb3feecd3d3302f2fccaff4850cfc8c403ee3314563f5f641e7c8bdfc39' START_RESULT_SHA = '8fc6ed5193f9802b7686a93523730c7e805595415c8e887552ffcf4224968d4d' CONTAINER_IMAGE = 'sha256:e6f2cff35d0f309acf8433b4f05878ed77092602c5065cc81801177da0bb3a9c' PYTHON_IMAGE_QUALIFIED = True PYTHON_IMAGE_RECEIPT_SHA = '6431222d42559e79e3aff9e074d743431240bfd173591cbd52ad106921c19114' PUBLIC_PIN_SHA = 'c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2' CASE = Path('/var/lib/rmm-time-source-bootstrap/5b358997-3abc-43db-945f-f41855b4e3c0') PHASE = 'broker-signature-acceptance-v1' PROFILE = 'rmm.server-time-broker.unix-signature-acceptance.v1' ENDPOINT = 'https://discovery.ease-technologies.de/agent/v1/time-attestation' CTX_KEYS = ('tenant_id','asset_id','agent_id','enrollment_generation','assignment_generation','connection_generation','windows_boot_id') DOMAIN = b'RMM-TIME-ATTESTATION/v1\0' SPKI = bytes.fromhex('302a300506032b6570032100') CLIENT = r''' import json,os,socket,struct,sys,time,uuid x=json.load(sys.stdin);mode=x['mode'] expected=0 if mode=='root' else 10001 assert os.getuid()==os.geteuid()==expected and os.getgid()==os.getegid()==expected if mode!='root': c={k:x['context'][k] for k in ('tenant_id','asset_id','agent_id','enrollment_generation','assignment_generation','connection_generation','windows_boot_id')} c.update(verifier_incarnation=str(uuid.UUID(bytes=os.getrandom(16),version=4)),role='agent',helper_image_sha256=None,binding_schema=1) nonce=os.getrandom(32);assert len(nonce)==32 request={'version':1,'endpoint':x['endpoint'],'nonce':nonce.hex(),'context':c} raw=json.dumps(request,ensure_ascii=False,separators=(',',':')).encode('utf-8');assert 1<=len(raw)<=8192 s=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM);s.settimeout(1) started=time.monotonic_ns();s.connect('/run/rmm-time-source/broker.sock') peer=struct.unpack('3i',s.getsockopt(socket.SOL_SOCKET,socket.SO_PEERCRED,12)) assert peer[1:]==(0,989) and (peer[0]==0 if mode=='container' else peer[0]==x['broker_pid']) if mode=='root': try: out=s.recv(1);assert out==b'';denial='eof' except ConnectionResetError:denial='reset' result={'mode':mode,'peer':peer,'received_bytes':0,'denial':denial} else: s.sendall(struct.pack('!I',len(raw))+raw) def exact(n): data=b'' while len(data)0,'exact_public_request_context') require(json.dumps(value,ensure_ascii=False,separators=(',',':'))==raw,'rust_canonical_request_bytes') return value def run_client(mode,pid,context): args=['/usr/bin/setpriv','--reuid=10001','--regid=10001','--clear-groups','--no-new-privs','/usr/bin/python3','-I','-c',CLIENT] if mode=='root':args=['/usr/bin/python3','-I','-c',CLIENT] if mode=='container':args=['/usr/bin/docker','run','-i','--rm','--network=none','--read-only','--cap-drop=ALL','--security-opt=no-new-privileges','--user=10001:10001','--pids-limit=16','--memory=128m','--mount=type=bind,src=/run/rmm-time-source,dst=/run/rmm-time-source,readonly','--entrypoint=/usr/bin/python3',CONTAINER_IMAGE,'-I','-c',CLIENT] result=subprocess.run(args,input=encoded(dict(mode=mode,context=context,endpoint=ENDPOINT,broker_pid=pid)),stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=20,check=False,env={'PATH':'/usr/bin:/bin','LC_ALL':'C'}) require(result.returncode==0 and result.stderr==b'' and len(result.stdout)<=32768,'one_fixed_client_failed_no_retry') return json.loads(result.stdout) def verify_reply(proof,pin,phase,mode,value,public,boot,context): require(value['uid']==value['gid']==10001 and value['peer'][1:]==[0,989] and value['elapsed_ns']>0,'actual_client_identity_and_peer') raw=value['request'];rq=request(raw,context);signed=json.loads(value['response']) require(list(signed)==['payload','signature_hex'] and json.dumps(signed,ensure_ascii=False,separators=(',',':'))==value['response'] and type(signed['payload']) is str and re.fullmatch('[0-9a-f]{128}',signed['signature_hex']),'exact_signed_envelope') payload=json.loads(signed['payload']) require(list(payload)==['version','request_sha256','server_instance','server_boot_id','key_id','key_generation','captured_utc_ns','server_error_ns','source_sync_age_ns'] and json.dumps(payload,ensure_ascii=False,separators=(',',':'))==signed['payload'] and payload['version']==1 and payload['request_sha256']==sha(raw.encode()) and payload['server_instance']==public['server_instance'] and payload['server_boot_id']==boot and payload['key_id']==public['key_id'] and payload['key_generation']==public['key_generation'] and type(payload['captured_utc_ns']) is int and 00,'complete_public_evidence_write');view=view[n:] os.fsync(fd) finally:os.close(fd) os.fsync(parent) def main(): parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('command',choices=('host-preflight','host-execute','host-read'));args=parser.parse_args() require(sys.flags.isolated==1 and os.geteuid()==0 and os.uname().machine=='aarch64','isolated_root_fixed_server_only');os.umask(0o077) fixed_inputs();module,bootstrap,pin,guard=load_start() if args.command=='host-read': records={} for name in ('intent.json','before.json','after.json','result.json','failure.json'): try: raw,meta=pin.read_file(CASE/PHASE/name,65536);records[name]=dict(sha256=sha(raw),metadata=meta,record=pin.parsed(raw)) except FileNotFoundError:records[name]=None print(encoded(dict(profile=PROFILE,read_only=True,records=records)).decode(),end='');return case=pin.directory(CASE);phase=-1;proof=process=None try: pin.absence(case,PHASE);proof=module.InstalledProof(bootstrap,pin,guard) own=proof.context.original.hold(Path(__file__),131072);require(own.path.name=='broker_signature_acceptance.py' and own.path.parent.name==sha(own.raw),'held_exact_signature_fixture_source') start=proof.context.original.hold(CASE/module.PHASE/'result.json',65536,expected=START_RESULT_SHA);start_result=pin.parsed(start.raw) require(start_result['effective_unit_qualified'] is True and start_result['start_executed_once'] is True,'original_successful_start') phase_start=pin.directory(CASE/module.PHASE) try:pin.absence(phase_start,'failure.json') finally:os.close(phase_start) state=module.effective(module.typed_snapshot(proof),True);process=module.ProcessProof(proof,state) require(process.expected==start_result['process'] and module.socket_proof(proof,process)==start_result['socket'],'same_original_running_broker_and_listener') before=proof.fresh();require(sha(proof.public.raw)==PUBLIC_PIN_SHA,'actual_fixed_public_time_pin');public=pin.parsed(proof.public.raw);host_ns=os.stat('/proc/self/ns/pid').st_ino if args.command=='host-preflight': print(encoded(dict(profile=PROFILE,read_only=True,qualified_running=True,process=process.expected,socket=start_result['socket'],public_pin_sha256=PUBLIC_PIN_SHA,public_pin=public,signature_query_sent=False,evidence_written=False)).decode(),end='');return # Explicit Root decision: own codec-only CSPRNG fixture identities, # never an enrolled device, current DB generation, mTLS or clock proof. identity=lambda:str(uuid.UUID(bytes=os.getrandom(16),version=4)) context=dict(tenant_id=identity(),asset_id=identity(),agent_id=identity(),enrollment_generation=1,assignment_generation=1,connection_generation=1,windows_boot_id=identity()) os.mkdir(PHASE,0o700,dir_fd=case);os.fsync(case);phase=os.open(PHASE,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=case) bind=dict(profile=PROFILE,case=CASE.name,phase=PHASE,controller_sha256=sha(own.raw),start_controller_sha256=START_SHA,start_result_sha256=START_RESULT_SHA,public_pin_sha256=sha(proof.public.raw),container_image=CONTAINER_IMAGE,python_image_receipt_sha256=PYTHON_IMAGE_RECEIPT_SHA,context=context,context_authority='operator_fixture_csprng_only_not_enrolled_or_mtls') save(pin,phase,'intent.json',dict(bind,once=True,no_retry=True));save(pin,phase,'before.json',dict(bind,witness=before,process=process.expected,socket=start_result['socket'])) save(pin,phase,'public.der',SPKI+bytes.fromhex(public['public_key_hex'])) host=run_client('host',process.pid,context);require(host['peer'][0]==process.pid and host['pid_namespace_inode']==host_ns,'host_client_actual_peer_pid_namespace') positive=verify_reply(proof,pin,phase,'host',host,public,before['observation']['boot_id'],context) denied=run_client('root',process.pid,context);require(denied['uid']==denied['gid']==0 and denied['peer']==[process.pid,0,989] and denied['received_bytes']==0 and denied['denial'] in ('eof','reset'),'root_uid_denied_without_signed_bytes') container=run_client('container',process.pid,context);require(container['peer'][0]==0 and container['pid_namespace_inode']!=host_ns,'default_container_pid_namespace_sees_host_broker_pid_zero') isolated=verify_reply(proof,pin,phase,'container',container,public,before['observation']['boot_id'],context) require(positive['nonce']!=isolated['nonce'] and positive['verifier_incarnation']!=isolated['verifier_incarnation'],'separate_own_random_challenges') after=proof.fresh();require(before==after and process.verify(module.effective(module.typed_snapshot(proof),True))==start_result['process'] and module.socket_proof(proof,process)==start_result['socket'],'same_runtime_pin_generation_process_listener_after_three_clients') save(pin,phase,'after.json',dict(bind,witness=after,process=process.expected,socket=start_result['socket'])) result=dict(bind,host=positive,root=denied,container=isolated,two_actual_signatures_verified=True,private_signer_read=False,clock_authority=False,mtls_identity_attested=False,sync_ready=False,rmm_jobs_created=False,corehistory_witness='external_root_before_after_receipts_required') save(pin,phase,'result.json',result);print(encoded(result).decode(),end='') except Exception: if phase>=0:save(pin,phase,'failure.json',dict(profile=PROFILE,failed=True,fixed_tag='signature_fixture_failed_original_read_only',no_retry_or_cleanup=True)) raise finally: if process is not None:process.close() if proof is not None:proof.close() if phase>=0:os.close(phase) os.close(case) if __name__=='__main__': try:main() except Exception: print(encoded(dict(profile=PROFILE,failed=True,read_original_phase_only=True)).decode(),end='');raise SystemExit(1)