197 lines
16 KiB
Python
197 lines
16 KiB
Python
#!/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)<n:
|
|
part=s.recv(n-len(data));assert part;data+=part
|
|
return data
|
|
length=struct.unpack('!I',exact(4))[0];assert 1<=length<=8192
|
|
response=exact(length);assert s.recv(1)==b''
|
|
result={'mode':mode,'peer':peer,'request':raw.decode('utf-8'),'response':response.decode('utf-8')}
|
|
s.close();result.update(uid=os.geteuid(),gid=os.getegid(),pid=os.getpid(),pid_namespace_inode=os.stat('/proc/self/ns/pid').st_ino,elapsed_ns=time.monotonic_ns()-started)
|
|
print(json.dumps(result,separators=(',',':')))
|
|
'''
|
|
|
|
|
|
def require(value,reason):
|
|
if not value:raise RuntimeError(reason)
|
|
|
|
|
|
def encoded(value):
|
|
return (json.dumps(value,sort_keys=True,separators=(',',':'),ensure_ascii=True)+'\n').encode('ascii')
|
|
|
|
|
|
def sha(raw):return hashlib.sha256(raw).hexdigest()
|
|
|
|
|
|
def load_start():
|
|
path=Path('/var/lib/rmm-time-source-operators')/START_SHA/'broker_start_acceptance.py'
|
|
parent=os.open('/',os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW)
|
|
try:
|
|
for name in path.parent.parts[1:]:
|
|
info=os.fstat(parent);require(info.st_uid==0 and info.st_mode&0o022==0,'protected_start_source_ancestry')
|
|
child=os.open(name,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=parent);os.close(parent);parent=child
|
|
directory=os.fstat(parent);require(directory.st_uid==0 and directory.st_mode&0o022==0,'protected_start_source_parent')
|
|
fd=os.open(path.name,os.O_RDONLY|os.O_NOFOLLOW,dir_fd=parent)
|
|
with os.fdopen(fd,'rb') as stream:
|
|
info=os.fstat(stream.fileno());require(stat.S_ISREG(info.st_mode) and info.st_uid==info.st_gid==0 and stat.S_IMODE(info.st_mode)==0o600 and info.st_nlink==1 and info.st_size<=131072,'root_start_source_file')
|
|
raw=stream.read(131073);stamp=lambda x:tuple(getattr(x,'st_'+n) for n in ('dev','ino','uid','gid','mode','nlink','size','mtime_ns','ctime_ns'))
|
|
require(sha(raw)==START_SHA and len(raw)==info.st_size and stamp(info)==stamp(os.fstat(stream.fileno()))==stamp(os.stat(path.name,dir_fd=parent,follow_symlinks=False)),'exact_reviewed_start_source')
|
|
finally:os.close(parent)
|
|
module=importlib.util.module_from_spec(importlib.util.spec_from_loader('rmm_signature_start_proof',loader=None));module.__file__=str(path);exec(compile(raw,str(path),'exec'),module.__dict__)
|
|
bootstrap,pin,guard=module.load_bootstrap();held=pin.read_file(path,131072)
|
|
require(held[0]==raw,'same_held_start_source')
|
|
return module,bootstrap,pin,lambda:(guard(),require(pin.read_file(path,131072)==held,'start_source_unchanged'))
|
|
|
|
|
|
def fixed_inputs():
|
|
require(type(START_RESULT_SHA) is str and re.fullmatch('[0-9a-f]{64}',START_RESULT_SHA),'actual_start_not_bound')
|
|
require(type(CONTAINER_IMAGE) is str and re.fullmatch('sha256:[0-9a-f]{64}',CONTAINER_IMAGE),'actual_cached_python_image_not_bound')
|
|
require(PYTHON_IMAGE_QUALIFIED is True,'cached_arm_python_not_qualified')
|
|
|
|
|
|
def request(raw,expected_context):
|
|
value=json.loads(raw);require(list(value)==['version','endpoint','nonce','context'] and value['version']==1 and value['endpoint']==ENDPOINT and re.fullmatch('[0-9a-f]{64}',value['nonce']),'exact_request_order_nonce_endpoint')
|
|
context=value['context'];require(list(context)==list(CTX_KEYS)+['verifier_incarnation','role','helper_image_sha256','binding_schema'] and all(context[k]==v for k,v in expected_context.items()) and context['role']=='agent' and context['helper_image_sha256'] is None and context['binding_schema']==1 and str(uuid.UUID(context['verifier_incarnation']))==context['verifier_incarnation'] and uuid.UUID(context['verifier_incarnation']).int>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 0<payload['captured_utc_ns']<2**63 and type(payload['server_error_ns']) is int and 0<=payload['server_error_ns']<=500000000 and type(payload['source_sync_age_ns']) is int and 0<=payload['source_sync_age_ns']<=3600000000000,'bound_full_request_server_generation_boot_and_quality')
|
|
save(pin,phase,mode+'.request.json',raw.encode());save(pin,phase,mode+'.response.json',value['response'].encode());save(pin,phase,mode+'.message.bin',DOMAIN+signed['payload'].encode());save(pin,phase,mode+'.signature.bin',bytes.fromhex(signed['signature_hex']))
|
|
result=proof.bootstrap.command(pin,Path('/usr/bin/openssl'),['pkeyutl','-verify','-pubin','-inkey',str(CASE/PHASE/'public.der'),'-keyform','DER','-rawin','-in',str(CASE/PHASE/(mode+'.message.bin')),'-sigfile',str(CASE/PHASE/(mode+'.signature.bin'))])
|
|
require(result.returncode==0,'actual_ed25519_public_signature_verification')
|
|
return dict(request_sha256=payload['request_sha256'],nonce=rq['nonce'],verifier_incarnation=rq['context']['verifier_incarnation'],signature_verified=True,payload=payload,client=value)
|
|
|
|
|
|
def save(pin,parent,name,raw):
|
|
require(name in {'intent.json','before.json','after.json','result.json','failure.json','public.der'} or re.fullmatch('(host|container)\.(request.json|response.json|message.bin|signature.bin)',name),'closed_public_case_filename')
|
|
data=raw if type(raw) is bytes else encoded(raw);require(len(data)<=65536,'bounded_public_evidence')
|
|
fd=os.open(name,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600,dir_fd=parent)
|
|
try:
|
|
view=memoryview(data)
|
|
while view:n=os.write(fd,view);require(n>0,'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)
|