#!/usr/bin/env python3 """Guarded compatible Linux bootstrap, explicitly coordinated separate phases. No job approval, package operation, reenrollment or private-key transfer. This controller is prepared source; invoking mutations requires Root coordination. """ import argparse import base64 import hashlib import inspect import io import json import os from pathlib import Path import shlex import subprocess import tarfile import uuid import linux_updater_bootstrap as prerequisite import remote_client_bootstrap as transport ROOT=Path(__file__).resolve().parents[1] BASE=ROOT/'devstate/linux-updater-helper-start-build/d674db1c-ebca-48ed-b04c-8f7ec9e45ca1/manifest.json' BASE_SHA='3520d0cfdda856b2c9c075197059047e47a24dab42270f4676416dd1ec5871cf' BOOT='45aba743-be1d-4ae5-ba00-139fb9363bfe' def sha(raw):return hashlib.sha256(raw).hexdigest() def once(path,raw): path.parent.mkdir(mode=0o700,parents=True,exist_ok=True) with path.open('xb') as stream:stream.write(raw);stream.flush();os.fsync(stream.fileno()) path.chmod(0o600) def native_rpc(function,payload,config='linux-vm.conf',timeout=80): # Same strict credential parser and already-confirmed host as existing tooling. cfg=transport.access.load_config(ROOT/'credentials'/config) code='import json,os,subprocess\nfrom pathlib import Path\n'+inspect.getsource(transport.require)+'\n'+inspect.getsource(function)+'\ntry:\n print(json.dumps('+function.__name__+'('+repr(payload)+')))\nexcept Exception as error:\n import traceback\n print(json.dumps({"error_class":type(error).__name__,"frames":[{"function":f.name,"line":f.lineno}for f in traceback.extract_tb(error.__traceback__)]}))\n' ssh=['ssh','-F','/dev/null','-T','-p',cfg.get('port','22'),'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-o','ClearAllForwardings=yes','-o','ConnectTimeout=7','-i',str(Path(cfg['ssh_key_path']).expanduser()),cfg['username']+'@'+cfg['address'],'python3 -I -'] result=subprocess.run(ssh,input=code.encode(),capture_output=True,timeout=timeout) if result.returncode:raise RuntimeError('Bootstrap transport failed; no private diagnostics printed') value=json.loads(result.stdout) if 'error_class'in value:raise RuntimeError('Bootstrap incomplete; retained native intent needs inspection: '+json.dumps(value)) return value def public_inputs(payload): import stat,json,hashlib,os from pathlib import Path require(payload=={'operation':'linux_compatible_public_inputs_v1'}and os.geteuid()==0,'fixed public inputs') result={} for name in ('helper-general.json','general-helper-proof.json','helper-full-maintenance.json','full-maintenance-helper-proof.json','helper-signing-key.json'): path=Path('/etc/rmm-remote')/name;meta=path.lstat();require(stat.S_ISREG(meta.st_mode)and meta.st_uid==0 and meta.st_nlink==1 and not meta.st_mode&0o022 and meta.st_size<=16384,'protected public input') raw=path.read_bytes();require(path.lstat().st_ino==meta.st_ino and path.lstat().st_mtime_ns==meta.st_mtime_ns,'public input changed');result[name]={'bytes':list(raw),'sha256':hashlib.sha256(raw).hexdigest()} general=json.loads(bytes(result['helper-general.json']['bytes']));pin=json.loads(bytes(result['general-helper-proof.json']['bytes'])) require(general['profile']=='general'and general.get('helper_binary_sha256')is None and pin['schema_version']==1 and pin['profile']=='general'and pin.get('helper_binary_sha256')is None,'exact non-binary General identity/policy profile') return result def central_closed(payload): import json,subprocess,datetime,uuid,hashlib from pathlib import Path agent=str(uuid.UUID(payload['agent_id']));tenant=str(uuid.UUID(payload['tenant_id'])) def run(a):return subprocess.check_output(a,text=True,stderr=subprocess.DEVNULL,timeout=15) flags={} for role in ('api','gateway'): container=json.loads(run(['docker','inspect','rust-discovery-server-'+role+'-1']))[0];env=dict(row.split('=',1)for row in container['Config']['Env']);flag=env.get('RMM_DEV_ROOT_ENABLED','false') require(flag in ('true','false'),'known Root gate') expired=False if flag=='true': path=env.get('RMM_DEV_ROOT_POLICY_FILE');require(path=='/root-policy/policy.json','fixed public Root policy') mount=next(m for m in container['Mounts']if m['Destination']=='/root-policy');require(mount['RW']is False,'readonly protected policy') doc=json.loads((Path(mount['Source'])/'policy.json').read_text());expiry=datetime.datetime.fromisoformat(doc['expires_at'].replace('Z','+00:00'));require(expiry.tzinfo is not None,'absolute policy expiry');expired=expiry<=datetime.datetime.now(datetime.timezone.utc) require(flag=='false'or expired,'central Root scope must be closed before compatible bootstrap') require('RMM_AGENT_UPDATE_POLICY_FILE'not in env,'initial updater scope must remain absent') flags[role]={'root_enabled':flag=='true','root_policy_expired':expired,'container_id':container['Id']} query="BEGIN READ ONLY; SELECT count(*) FROM jobs WHERE tenant_id='"+tenant+"' AND agent_id='"+agent+"' AND state NOT IN ('succeeded','failed','cancelled','expired'); COMMIT;" rows=run(['docker','exec','rust-discovery-server-postgres-1','psql','-XqAt','-v','ON_ERROR_STOP=1','-U','postgres','-d','rmm','-c',query]).splitlines();require(rows==['0'],'no open or unknown Linux job') return {'operation':'linux_compatible_closed_scope_v1','tenant_id':tenant,'agent_id':agent,'observed_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'roles':flags,'open_jobs':0,'job_authority':False} def passive_check(payload): import datetime,json,subprocess,uuid tenant=str(uuid.UUID(payload['tenant_id']));agent=str(uuid.UUID(payload['agent_id'])) query="BEGIN READ ONLY; SELECT json_build_object('connection_generation',i.connection_generation,'capabilities',i.capabilities,'last_contact_at',i.last_contact_at,'observed_at',o.observed_at,'received_at',o.received_at,'data',o.data,'payload_sha256',o.payload_sha256) FROM agent_installations i JOIN LATERAL (SELECT * FROM observations WHERE tenant_id=i.tenant_id AND agent_id=i.agent_id AND source_id='agent.update' ORDER BY sequence DESC LIMIT 1)o ON true WHERE i.tenant_id='"+tenant+"' AND i.agent_id='"+agent+"' AND i.revoked_at IS NULL; COMMIT;" output=subprocess.check_output(['docker','exec','rust-discovery-server-postgres-1','psql','-XqAt','-v','ON_ERROR_STOP=1','-U','postgres','-d','rmm','-c',query],stderr=subprocess.DEVNULL,text=True,timeout=15).splitlines();require(len(output)==1,'one actual current installation/passive observation') observed=json.loads(output[0]);sample=observed['data']['agent_update'];now=datetime.datetime.now(datetime.timezone.utc) for text in (observed['last_contact_at'],observed['received_at'],sample['observed_at']): age=(now-datetime.datetime.fromisoformat(text.replace('Z','+00:00'))).total_seconds();require(0<=age<90,'fresh actual persisted passive evidence') require(sample['quality']=='valid'and sample['platform']=='x86_64-unknown-linux-gnu'and sample['activation_floor']==1 and not sample['rolled_back']and sample['helper_observation_sha256']and sample['signed_sync_decision_id'],'actual Full verified passive baseline') require(sample['predecessor']['installed_record_sha256']==payload['record_sha256']and sample['predecessor']['agent_sha256']==payload['agent_sha256']and sample['predecessor']['helper_sha256']==payload['helper_sha256'],'actual current predecessor') require(sample['updater']['binary_sha256']==payload['updater_sha256']and sample['updater']['policy_sha256']==payload['policy_sha256']and sample['updater']['keyring_sha256']==payload['keyring_sha256']and sample['updater']['health_key_pin_sha256']==payload['health_pin_sha256'],'actual protected updater trust bindings') required=['agent.update.apply/1','agent.update.check/1','update_agent','root:update_agent','helper.root.v1','rmm.sync.v1','helper.binary.sha256:'+payload['helper_sha256'],'helper.policy.sha256:'+payload['helper_policy_sha256'],'updater.binary.sha256:'+payload['updater_sha256'],'updater.policy.sha256:'+payload['policy_sha256']] require(all(cap in observed['capabilities']for cap in required),'actual current qualified runtime capabilities, no SQL override') return {'operation':'linux_compatible_passive_qualification_v1','tenant_id':tenant,'agent_id':agent,'sample':sample,'connection_generation':observed['connection_generation'],'capabilities':observed['capabilities'],'observation_payload_sha256':observed['payload_sha256'],'actual_passive_path':True,'database_written':False,'job_authority':False} def stage(payload): import base64,hashlib,json,os,stat,uuid from pathlib import Path require(os.geteuid()==0 and os.uname().machine=='x86_64','root x86 Linux only') ident=str(uuid.UUID(payload['case_id']));base=Path('/var/lib/rmm-updater-bootstrap') if not base.exists():base.mkdir(mode=0o700) meta=base.lstat();require(stat.S_ISDIR(meta.st_mode)and meta.st_uid==0 and stat.S_IMODE(meta.st_mode)==0o700,'protected bootstrap root') folder=base/ident;folder.mkdir(mode=0o700) files=payload['files'];require(set(files)=={'agent.bin','helper.bin','updater.bin','sdk.bin','full-config.json','full-pin.json','updater.service'},'closed bootstrap artifact set') for name,entry in files.items(): raw=base64.b64decode(entry['base64'],validate=True);require(len(raw)==entry['bytes']and hashlib.sha256(raw).hexdigest()==entry['sha256'],'exact public artifact') if name.endswith('.bin'):require(raw[:6]==b'\x7fELF\x02\x01'and raw[18:20]==b'\x3e\x00','Linux x86-64 ELF') fd=os.open(folder/name,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o500 if name.endswith('.bin') else 0o600) with os.fdopen(fd,'wb')as stream:stream.write(raw);stream.flush();os.fsync(stream.fileno()) manifest={k:v for k,v in payload.items()if k!='files'};manifest['files']={n:{k:v for k,v in e.items()if k!='base64'}for n,e in files.items()} with(folder/'manifest.json').open('x')as stream:json.dump(manifest,stream,sort_keys=True);stream.flush();os.fsync(stream.fileno()) return {'case_id':ident,'folder':str(folder),'staged':True,'services_changed':False,'job_authority':False} def pair(payload): import base64,contextlib,fcntl,hashlib,json,os,select,sqlite3,stat,subprocess,time,uuid,datetime from pathlib import Path require(os.geteuid()==0 and os.uname().machine=='x86_64','root x86 Linux only') ident=str(uuid.UUID(payload['case_id']));folder=Path('/var/lib/rmm-updater-bootstrap')/ident;manifest=json.loads((folder/'manifest.json').read_text()) require(Path('/proc/sys/kernel/random/boot_id').read_text().strip()==manifest['boot_id'],'original boot') def sha(raw):return hashlib.sha256(raw).hexdigest() def run(a,timeout=20):return subprocess.check_output(a,text=True,stderr=subprocess.DEVNULL,timeout=timeout).strip() def syncdir(path): fd=os.open(path,os.O_RDONLY|os.O_DIRECTORY) try:os.fsync(fd) finally:os.close(fd) def record(name,value): with(folder/name).open('x')as stream:json.dump(value,stream,sort_keys=True);stream.flush();os.fsync(stream.fileno()) syncdir(folder) def public(path,maximum): path=Path(path);meta=path.lstat();require(stat.S_ISREG(meta.st_mode)and meta.st_uid==0 and meta.st_nlink==1 and not meta.st_mode&0o022 and meta.st_size<=maximum,'protected original public file');return path.read_bytes(),meta def identity(path): m=Path(path).lstat();require(not stat.S_ISLNK(m.st_mode),'no substituted path');return [m.st_dev,m.st_ino,m.st_uid,m.st_gid,m.st_mode,m.st_nlink] def status(unit): fields={k:v for k,v in(line.split('=',1)for line in run(['systemctl','show','--all','--property=Id,ActiveState,SubState,MainPID,ControlPID,InvocationID,Job,ControlGroup,UnitFileState','--',unit]).splitlines())};require(fields['Id']==unit,'exact service');return fields units=['rmm-agent-remote.service','rmm-helper-cloud.service','rmm-full-maintenance-helper.service'] def closed_service(unit,row): empty=row['MainPID']=='0'and row['ControlPID']=='0'and not row['Job']and not row['ControlGroup'] if row['ActiveState']=='inactive':return empty if row['ActiveState']!='failed'or unit!=units[2]or manifest.get('followup_of_case_id')!='ac6cf439-e0a6-4323-82e1-c55df96b2441':return False original=json.loads((Path('/var/lib/rmm-updater-bootstrap/ac6cf439-e0a6-4323-82e1-c55df96b2441')/'pair-started.json').read_text())['status'][unit] failure=dict(line.split('=',1)for line in run(['systemctl','show','--property=Result,ExecMainCode,ExecMainStatus,NRestarts,Restart','--',unit]).splitlines()) return empty and row['InvocationID']==original['InvocationID']and failure=={'Result':'exit-code','ExecMainCode':'1','ExecMainStatus':'1','NRestarts':'0','Restart':'no'} def databases(): result={} for path in ('/var/lib/rmm-agent-remote/journal.sqlite','/var/lib/rmm-agent-remote/consumption.sqlite','/var/lib/rmm-helper/consumption.sqlite'): require(not Path(path+'-wal').exists()and not Path(path+'-shm').exists(),'existing DELETE journals') with contextlib.closing(sqlite3.connect('file:'+path+'?mode=ro',uri=True,timeout=.5))as db: db.execute('PRAGMA query_only=ON');require(db.execute('PRAGMA integrity_check').fetchone()[0]=='ok','original journal integrity') tables={r[0]for r in db.execute("SELECT name FROM sqlite_master WHERE type='table'")};evidence=[] if 'consumed'in tables: require(db.execute('SELECT count(*) FROM consumed WHERE result IS NULL').fetchone()[0]==0,'no unresolved original effect') for row in db.execute('SELECT c.grant_id,c.agent,c.generation,c.job,c.attempt,c.result,e.start,e.outcome FROM consumed c LEFT JOIN execution_evidence e USING(grant_id) ORDER BY c.grant_id'): evidence.append([v if isinstance(v,(str,int))or v is None else sha(v)for v in row]) if 'job_attempts'in tables:require(db.execute("SELECT count(*) FROM job_attempts WHERE state NOT IN ('succeeded','failed','cancelled','expired')").fetchone()[0]==0,'no open original agent job') for name in ('helper_sync_meta','reconcile_meta'): if name in tables:require(db.execute('SELECT count(*) FROM '+name+' WHERE fault IS NOT NULL').fetchone()[0]==0,'no original journal fault') generation=db.execute('SELECT generation FROM reconcile_meta WHERE id=1').fetchone()[0]if 'reconcile_meta'in tables else None result[path]={'file_id':identity(path),'evidence_sha256':sha(json.dumps(evidence,separators=(',',':')).encode()),'consumptions':len(evidence),'generation':generation} return result def retained_metadata(): result={} fixed=['/var/lib/rmm-agent-remote/binding.json','/var/lib/rmm-agent-remote/identity.json','/var/lib/rmm-agent-remote/job-signing-key.json','/var/lib/rmm-agent-remote/device.key','/var/lib/rmm-agent-remote/device.pem','/etc/rmm-remote/agent.env','/etc/rmm-remote/helper-general.json','/etc/rmm-remote/general-helper-proof.json','/etc/rmm-remote/helper-signing-key.json'] cert=Path('/var/lib/rmm-agent-remote/certificates') if cert.exists():fixed.extend(str(p)for p in cert.rglob('*')if p.is_file()) for path in fixed: m=Path(path).lstat();require(stat.S_ISREG(m.st_mode)and m.st_nlink==1,'retained original metadata');result[path]=identity(path)+[m.st_size,m.st_mtime_ns,m.st_ctime_ns] return result for name,entry in manifest['files'].items():require(sha((folder/name).read_bytes())==entry['sha256'],'staged artifact changed') for unit in ('rmm-apt-helper.service','rmm-agent.service','rmm-helper-dev-test.service'): s=status(unit);require(s['ActiveState']=='inactive'and s['MainPID']in('','0')and s['ControlPID']in('','0')and s['Job']==''and s['UnitFileState']in('','disabled'),'APT and legacy remain closed') transitions=[('agent.bin','/usr/local/libexec/rmm-agent-remote',manifest['old_agent_sha256']),('helper.bin','/usr/local/libexec/rmm-privileged-helper',manifest['old_helper_sha256']),('full-config.json','/etc/rmm-remote/helper-full-maintenance.json',manifest['old_config_sha256']),('full-pin.json','/etc/rmm-remote/full-maintenance-helper-proof.json',manifest['old_pin_sha256'])] followup=payload['action']in('install-followup','install-stopped-followup');continuing=payload['action']=='install-stopped-followup' if payload['action']=='validate-staged': result=subprocess.check_output([str(folder/'helper.bin'),'--inspect-full-maintenance-profile'],env={'RMM_HELPER_CONFIG':str(folder/'full-config.json'),'PATH':'/usr/bin:/bin'},stderr=subprocess.DEVNULL,timeout=20);pin=json.loads(result) require(pin==json.loads((folder/'full-pin.json').read_text())and pin['helper_binary_sha256']==manifest['files']['helper.bin']['sha256'],'actual staged helper independently reproduces exact Full pin') record('staged-profile-qualified.json',{'actual_helper_sha256':pin['helper_binary_sha256'],'actual_full_policy_sha256':pin['policy_sha256'],'profile_matches':True,'services_changed':False,'job_authority':False}) return {'case_id':ident,'actual_native_staged_profile_matches':True,'full_policy_sha256':pin['policy_sha256'],'services_changed':False,'job_authority':False} elif payload['action']in('install','install-followup','install-stopped-followup'): if continuing:require(ident=='8fa5c0bd-b0ae-45ec-8cde-3d766d0576d4'and(folder/'pair-install-intent.json').is_file()and not(folder/'pair-followup-continue-intent.json').exists(),'exact known stopped pre-swap followup only') else:require(not(folder/'pair-install-intent.json').exists(),'existing intent means readback, never repeat') fence=payload['central_fence'];require(fence['operation']=='linux_compatible_closed_scope_v1'and fence['open_jobs']==0 and not fence['job_authority']and fence['tenant_id']==manifest['tenant_id']and fence['agent_id']==manifest['agent_id'],'closed central scope') at=datetime.datetime.fromisoformat(fence['observed_at']);require(0<=(datetime.datetime.now(datetime.timezone.utc)-at).total_seconds()<30,'fresh closed-scope readback') before={u:status(u)for u in units};pids=[] if followup: require((folder/'staged-profile-qualified.json').is_file(),'actual native staged Full profile qualification required') require(manifest.get('followup_of_case_id')=='ac6cf439-e0a6-4323-82e1-c55df96b2441'and manifest['files']['agent.bin']['sha256']==manifest['old_agent_sha256']=='7fef8d0f1e2bcf5cd6c373e567a0c17bfb08d8c780cd4d1925b6c1355e572547'and manifest['old_helper_sha256']=='8fdc6ded02278eb18e64003d0bc7bf45d452cd48ded0450e6e900ca66e44d449','exact known failed baseline followup only') failure=dict(line.split('=',1)for line in run(['systemctl','show','--property=Result,ExecMainCode,ExecMainStatus,NRestarts,Restart','--',units[2]]).splitlines());require(failure=={'Result':'exit-code','ExecMainCode':'1','ExecMainStatus':'1','NRestarts':'0','Restart':'no'},'known original failed no-restart Full startup') require(before[units[2]]['ActiveState']=='failed'and before[units[2]]['MainPID']=='0'and before[units[2]]['ControlPID']=='0'and not before[units[2]]['Job'],'closed original failed Full') require(not Path('/etc/rmm-agent-updater/policy.json').exists()and not Path('/var/lib/rmm-agent-updater/installed-record.json').exists()and status('rmm-agent-updater.service')['ActiveState']=='inactive','no trust or update activity before compatible followup') require(sha(Path('/usr/local/libexec/rmm-agent-remote').read_bytes())==manifest['old_agent_sha256'],'unchanged exact V2Agent');transitions=transitions[1:] for u,s in before.items(): if continuing: require(closed_service(u,s),'known fully closed original stop');continue if followup and u==units[2]:continue require(s['ActiveState']=='active'and int(s['MainPID'])>1 and s['ControlPID']=='0'and s['Job']=='','exact active original pair') pid=int(s['MainPID']);fd=os.pidfd_open(pid);pids.append(fd) if continuing: original_intent=json.loads((folder/'pair-install-intent.json').read_text());require(original_intent['files']==manifest['files']and original_intent['known_full_failure']==failure,'exact original admission and known failure') for u,s in before.items(): old=original_intent['before'][u];require(old['InvocationID']==s['InvocationID']and(old['MainPID']=='0'or not Path('/proc/'+old['MainPID']).exists()),'original service invocation retained and original PID exited') original=original_intent['databases'];retained=original_intent['retained'];require(retained_metadata()==retained,'original pre-stop identity PKI General metadata retained') for source,target,oldsha in transitions: path=Path(target);require(not(folder/(source+'-save-intent.json')).exists()and not(folder/(source+'-publish-intent.json')).exists()and not path.with_name(path.name+'.bootstrap-'+ident+'.previous').exists()and not path.with_name(path.name+'.bootstrap-'+ident+'.candidate').exists(),'zero original swap intents or renames, never resume ambiguous effects') else:original=databases();retained=retained_metadata() for source,target,oldsha in transitions: raw,_=public(target,256*1024*1024);require(sha(raw)==oldsha,'original target CAS') if continuing:record('pair-followup-continue-intent.json',{'before':before,'original_stop_sha256':sha((folder/'pair-install-intent.json').read_bytes()),'central_fence':fence,'stop_repeated':False,'job_authority':False}) else: record('pair-install-intent.json',{'before':before,'databases':original,'retained':retained,'central_fence':fence,'files':manifest['files'],'known_full_failure':failure if followup else None}) run(['systemctl','stop','--',units[0],units[2],units[1]],30) for fd in pids: poll=select.poll();poll.register(fd,select.POLLIN);require(poll.poll(1000),'original process not exited');os.close(fd) for u in units: s=status(u);require(closed_service(u,s),'all original processes stopped or exact preserved original Full failure') with contextlib.ExitStack()as held: for path in ('/var/lib/rmm-agent-remote/agent.lock','/var/lib/rmm-helper/executor.lock'): f=held.enter_context(open(path,'rb'));fcntl.flock(f,fcntl.LOCK_EX|fcntl.LOCK_NB) closed=databases() require(all(closed[p]['file_id']==v['file_id']and closed[p]['evidence_sha256']==v['evidence_sha256']for p,v in original.items()),'original effect history changed during stop') for source,target,oldsha in transitions: target=Path(target);old,meta=public(target,256*1024*1024);require(sha(old)==oldsha,'stopped target CAS') previous=target.with_name(target.name+'.bootstrap-'+ident+'.previous');candidate=target.with_name(target.name+'.bootstrap-'+ident+'.candidate');require(not previous.exists()and not candidate.exists(),'create-once bootstrap names') fd=os.open(candidate,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,stat.S_IMODE(meta.st_mode)) with os.fdopen(fd,'wb')as stream:os.fchown(stream.fileno(),meta.st_uid,meta.st_gid);stream.write((folder/source).read_bytes());stream.flush();os.fsync(stream.fileno()) record(source+'-save-intent.json',{'target':str(target),'previous':str(previous),'old_sha256':oldsha});os.rename(target,previous);syncdir(target.parent) record(source+'-publish-intent.json',{'candidate':str(candidate),'target':str(target),'sha256':manifest['files'][source]['sha256']});os.rename(candidate,target);syncdir(target.parent) syncdir(target.parent) require(sha(target.read_bytes())==manifest['files'][source]['sha256']and sha(previous.read_bytes())==oldsha,'exact predecessor and replacement retained') require(retained_metadata()==retained,'original key identity General policy or PKI changed') record('pair-installed.json',{'databases':closed,'retained':retained,'old_generation':original['/var/lib/rmm-agent-remote/journal.sqlite']['generation'],'services_stopped':True,'job_authority':False}) return {'case_id':ident,'compatible_files_installed':True,'services_stopped':True,'next':'separate reviewed unit setup and start phase','job_authority':False} elif payload['action']=='units': installed=json.loads((folder/'pair-installed.json').read_text());require(not(folder/'unit-install-intent.json').exists(),'existing unit intent means readback only') require(retained_metadata()==installed['retained'],'original metadata changed') for u in units: row=status(u);require(row['ActiveState']=='inactive'and row['MainPID']=='0'and row['ControlPID']=='0'and not row['Job'],'pair remains stopped before unit setup') paths={'/usr/local/libexec/rmm-agent-updater':('updater.bin',0o755),'/etc/systemd/system/rmm-agent-updater.service':('updater.service',0o644)} require(all(not Path(path).exists()for path in paths),'stable updater is create-only') require(not Path('/etc/rmm-agent-updater').exists()and not Path('/var/lib/rmm-agent-updater').exists(),'initial trust namespace only') override=Path('/etc/systemd/system/rmm-full-maintenance-helper.service.d/99-rmm-update-closed-start.conf');require(not override.exists(),'create-only closed restart override') record('unit-install-intent.json',{'paths':list(paths),'override':str(override),'restart':'no','services_started':False}) for path,(name,mode)in paths.items(): fd=os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,mode) with os.fdopen(fd,'wb')as stream:stream.write((folder/name).read_bytes());stream.flush();os.fsync(stream.fileno()) if not override.parent.exists():override.parent.mkdir(mode=0o755) require(override.parent.lstat().st_uid==0 and not override.parent.is_symlink()and not override.parent.lstat().st_mode&0o022,'protected Full override parent') with override.open('xb')as stream:stream.write(b'[Service]\nRestart=no\n');stream.flush();os.fsync(stream.fileno()) override.chmod(0o644) for path,mode in [('/etc/rmm-agent-updater',0o755),('/var/lib/rmm-agent-updater',0o700),('/var/lib/rmm-agent-updater/records',0o700),('/var/lib/rmm-agent-updater/handoffs',0o700)]:Path(path).mkdir(mode=mode) binding=json.loads(Path('/var/lib/rmm-agent-remote/binding.json').read_text());key=json.loads(Path('/etc/rmm-remote/helper-signing-key.json').read_text()) require(binding.get('public_key_hex')in('',key['public_key_hex']),'independent effective public key pin');binding['public_key_hex']=key['public_key_hex'] fd=os.open('/etc/rmm-agent-updater/binding.json',os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600) with os.fdopen(fd,'w')as stream:json.dump(binding,stream,separators=(',',':'));stream.flush();os.fsync(stream.fileno()) run(['systemctl','daemon-reload']) require(run(['systemctl','show','--value','--property=Restart','--',units[2]])=='no','actual closed Full restart contract') updater=status('rmm-agent-updater.service');require(updater['ActiveState']=='inactive'and updater['MainPID']=='0'and updater['ControlPID']=='0'and not updater['Job']and updater['UnitFileState']=='disabled','updater remains stopped and disabled') record('units-installed.json',{'updater':updater,'restart_override_sha256':sha(override.read_bytes()),'namespace_provisioned':True,'updater_started':False}) return {'case_id':ident,'updater_unit_installed_not_started':True,'full_restart_no_bound':True,'job_authority':False} elif payload['action']=='adopt-units': require(manifest.get('followup_of_case_id')=='ac6cf439-e0a6-4323-82e1-c55df96b2441'and(folder/'pair-installed.json').is_file(),'exact known baseline followup') require(not(folder/'units-installed.json').exists(),'create-only adopted unit receipt') require(sha(Path('/usr/local/libexec/rmm-agent-updater').read_bytes())==manifest['files']['updater.bin']['sha256']and Path('/etc/systemd/system/rmm-agent-updater.service').read_bytes()==(folder/'updater.service').read_bytes(),'exact previously installed stable updater unit and bytes') require(Path('/etc/systemd/system/rmm-full-maintenance-helper.service.d/99-rmm-update-closed-start.conf').read_bytes()==b'[Service]\nRestart=no\n'and run(['systemctl','show','--value','--property=Restart','--',units[2]])=='no','original closed restart override') for u in units+['rmm-agent-updater.service']: s=status(u);require(closed_service(u,s),'all project roles remain closed before followup start') record('units-installed.json',{'adopted_unchanged_from':manifest['followup_of_case_id'],'updater_started':False,'job_authority':False}) return {'case_id':ident,'existing_units_adopted_unchanged':True,'updater_started':False,'job_authority':False} elif payload['action']=='start': installed=json.loads((folder/'pair-installed.json').read_text());require((folder/'units-installed.json').is_file(),'separate reviewed unit setup required');require(not(folder/'pair-start-intent.json').exists(),'existing start means readback only') require(retained_metadata()==installed['retained'],'original metadata changed') for u in units: s=status(u);require(closed_service(u,s),'pair remains stopped or original known Full failure preserved') record('pair-start-intent.json',{'units':[units[1],units[2],units[0]],'only_once':True}) for u in (units[1],units[2],units[0]): record(u+'-start-intent.json',{'unit':u});run(['systemctl','start','--',u],20);s=status(u);require(s['ActiveState']=='active'and int(s['MainPID'])>1,'single compatible start') if u==units[1]: # A real nonmutating Policy nonce as the provisioned UID proves General # finished initialization before Full is started. No snapshot/apply/job. import socket,struct pin=json.loads(Path('/etc/rmm-remote/general-helper-proof.json').read_text());challenge=str(uuid.uuid4());request={'operation':'general_policy_v1','challenge':challenge,'identity':pin['identity']};wire=json.dumps(request,separators=(',',':')).encode();expected_pid=int(s['MainPID']);ledger_id=identity('/var/lib/rmm-helper/consumption.sqlite');lock_id=identity('/var/lib/rmm-helper/executor.lock') read_fd,write_fd=os.pipe();child=os.fork() if child==0: os.close(read_fd) try: os.setgroups([]);os.setgid(984);os.setuid(993);deadline=time.monotonic()+10;answer=None while time.monotonic()1 and updater['ControlPID']=='0'and not updater['Job'],'actual stable updater started') fd=os.pidfd_open(pid) try: start=Path('/proc/'+str(pid)+'/stat').read_text().rsplit(') ',1)[1].split()[19];image=Path('/proc/'+str(pid)+'/exe').read_bytes();require(sha(image)==manifest['files']['updater.bin']['sha256'],'actual original stable updater image') require(status('rmm-agent-updater.service')==updater,'same updater process held through observation') finally:os.close(fd) record('updater-started.json',{'status':updater,'process_start_ticks':start,'image_sha256':sha(image),'job_authority':False}) return {'case_id':ident,'stable_updater_started_once':True,'pid':pid,'image_sha256':sha(image),'actual_agent_passive_observation_still_required':True,'job_authority':False} elif payload['action']=='readback': names=[p.name for p in folder.glob('*')if p.name.endswith('.json')and p.name!='manifest.json'];public={} for name in ('qualification.json','registry-prepared.json','pair-qualified.json','trust-installed.json','updater-started.json'): path=folder/name if path.exists(): raw=path.read_bytes();require(len(raw)<=192*1024,'bounded public readback');public[name]={'sha256':sha(raw),'base64url':base64.urlsafe_b64encode(raw).rstrip(b'=').decode()} return {'case_id':ident,'records':names,'public_evidence':public,'status':{u:status(u)for u in units+['rmm-agent-updater.service']},'databases':databases(),'job_authority':False} else:raise RuntimeError('unknown fixed pair action') def prepare(sdk_manifest,prior_package=None): require=lambda ok,msg:None if ok else(_ for _ in()).throw(RuntimeError(msg)) require(sha(BASE.read_bytes())==BASE_SHA,'exact capability derivative V2 manifest') build=json.loads(BASE.read_text());sdk=json.loads(sdk_manifest.read_text());require(sdk['profile']=='linux_updater_bootstrap_metadata_sdk_v1'and sdk['release_built']and sdk['clippy_all_targets_passed']and not sdk['target_mutated'],'sealed metadata SDK') inputs=native_rpc(public_inputs,{'operation':'linux_compatible_public_inputs_v1'}) snapshot=transport.rpc('linux-vm.conf',prerequisite.inspect_vm,{'operation':'linux_updater_bootstrap_inspect_v1'}) require(snapshot['boot_id']==BOOT,'original target boot') if prior_package is None:require(not snapshot['updater_provisioned'],'original initial target') else: prior=json.loads(prior_package.read_text());require(prior['case_id']=='ac6cf439-e0a6-4323-82e1-c55df96b2441'and not snapshot['updater_provisioned']and snapshot['binaries']['/usr/local/libexec/rmm-agent-updater']['sha256']==build['stable_updater']['sha256']and snapshot['units']['rmm-agent-updater.service']['status']['ActiveState']=='inactive'and snapshot['units']['rmm-agent-updater.service']['status']['LoadState']=='loaded'and snapshot['units']['rmm-full-maintenance-helper.service']['status']['ActiveState']=='failed','exact previously installed but unprovisioned updater and known original failed Full') full=json.loads(bytes(inputs['helper-full-maintenance.json']['bytes']));key=json.loads(bytes(inputs['helper-signing-key.json']['bytes'])) require(full['signing_key_file']=='/etc/rmm-remote/helper-signing-key.json','independent fixed Full keyfile') binary=Path(sdk['binary']['path']);require(sha(binary.read_bytes())==sdk['binary']['sha256'],'sealed SDK bytes') request={'operation':'render_full','config':inputs['helper-full-maintenance.json']['bytes'],'pin':inputs['full-maintenance-helper-proof.json']['bytes'],'job_public_key_hex':key['public_key_hex'],'new_helper_sha256':build['artifacts']['source0']['helper']['sha256']} command=['docker','run','--rm','-i','--network','none','--read-only','--tmpfs','/tmp:rw,size=64m','-v',str(binary)+':/sdk:ro','--entrypoint','/sdk','sha256:9a76ad3744ebfdddae96ca10001ce8291c1b332fb54c8df5eea0e8e999ac6fc6'] rendered=subprocess.run(command,input=json.dumps(request).encode(),capture_output=True,check=True,timeout=30);transition=json.loads(rendered.stdout) ident=str(uuid.uuid4());folder=ROOT/'devstate/linux-updater-compatible'/ident;folder.mkdir(mode=0o700,parents=True) files={} for name,item in [('agent.bin',build['artifacts']['source0']['agent']),('helper.bin',build['artifacts']['source0']['helper']),('updater.bin',build['stable_updater']),('sdk.bin',sdk['binary'])]: raw=Path(item['path']).read_bytes();require(sha(raw)==item['sha256']and len(raw)==item['bytes'],'sealed exact code artifact');files[name]=raw files['full-config.json']=bytes(transition['config']);files['full-pin.json']=bytes(transition['pin']) unit=ROOT/'devstate/linux-updater-qualification/21d20391-6102-4996-8a7a-efbd3e78bd7d/source0/deploy/linux/rmm-agent-updater.service';files['updater.service']=unit.read_bytes() proof=transition['proof'];require(proof['new_helper_sha256']==build['artifacts']['source0']['helper']['sha256']and proof['old_config_sha256']==inputs['helper-full-maintenance.json']['sha256']and proof['old_pin_sha256']==inputs['full-maintenance-helper-proof.json']['sha256'],'typed exact Full transition') for name,raw in files.items():once(folder/name,raw) binding=full['binding'];payload={'schema_version':1,'profile':'linux_compatible_bootstrap_package_v1','case_id':ident,'boot_id':BOOT,'tenant_id':binding['tenant_id'],'agent_id':binding['agent_id'],'asset_id':binding['asset_id'],'enrollment_generation':binding['enrollment_generation'],'assignment_version':binding['assignment_version'],'build_manifest_sha256':BASE_SHA,'sdk_manifest_sha256':sha(sdk_manifest.read_bytes()),'old_agent_sha256':snapshot['binaries']['/usr/local/libexec/rmm-agent-remote']['sha256'],'old_helper_sha256':snapshot['binaries']['/usr/local/libexec/rmm-privileged-helper']['sha256'],'old_config_sha256':proof['old_config_sha256'],'old_pin_sha256':proof['old_pin_sha256'],'full_transition':proof,'files':{n:{'sha256':sha(raw),'bytes':len(raw),'base64':base64.b64encode(raw).decode()}for n,raw in files.items()},'job_authority':False} if prior_package is not None:payload['followup_of_case_id']=prior['case_id'] once(folder/'package.json',json.dumps(payload,sort_keys=True,separators=(',',':')).encode());once(folder/'readonly-before.json',json.dumps(snapshot,sort_keys=True,indent=2).encode());once(folder/'public-inputs.json',json.dumps(inputs,sort_keys=True,indent=2).encode()) summary={k:v for k,v in payload.items()if k!='files'};summary['files']={n:{k:v for k,v in e.items()if k!='base64'}for n,e in payload['files'].items()};once(folder/'manifest.json',json.dumps(summary,sort_keys=True,indent=2).encode()) print(json.dumps({'package':str(folder/'package.json'),'manifest':str(folder/'manifest.json'),'case_id':ident,'local_only_preparation':True,'target_staged':False,'services_changed':False,'full_policy_sha256':proof['new_policy_sha256']})) def main(): parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('prepare','public-inputs','central-check','stage','validate-staged','install','install-followup','install-stopped-followup','units','adopt-units','start','qualify','registry','trust','updater-start','passive-check','readback'));parser.add_argument('--package',type=Path);parser.add_argument('--sdk-manifest',type=Path);parser.add_argument('--trust-package',type=Path);parser.add_argument('--prior-package',type=Path);args=parser.parse_args() if args.action=='prepare': if args.sdk_manifest is None:parser.error('--sdk-manifest required for preparation') prepare(args.sdk_manifest,args.prior_package);return if args.package is None:parser.error('--package required for fixed native phases') p=json.loads(args.package.read_text());require=lambda ok,msg:None if ok else(_ for _ in()).throw(RuntimeError(msg)) require(p['schema_version']==1 and p['profile']=='linux_compatible_bootstrap_package_v1'and p['boot_id']==BOOT,'reviewed exact package') if args.action=='public-inputs':value=native_rpc(public_inputs,{'operation':'linux_compatible_public_inputs_v1'}) elif args.action=='central-check':value=native_rpc(central_closed,{'agent_id':p['agent_id'],'tenant_id':p['tenant_id']},config='server.conf') elif args.action=='stage':value=native_rpc(stage,p,timeout=120) elif args.action=='passive-check': if args.trust_package is None:parser.error('--trust-package required for exact passive comparison') trust=json.loads(args.trust_package.read_text());files=trust['files'];value=native_rpc(passive_check,{'tenant_id':p['tenant_id'],'agent_id':p['agent_id'],'record_sha256':files['installed-record.json']['sha256'],'policy_sha256':files['policy.json']['sha256'],'keyring_sha256':files['keyring.json']['sha256'],'health_pin_sha256':files['health-key.json']['sha256'],'agent_sha256':p['files']['agent.bin']['sha256'],'helper_sha256':p['files']['helper.bin']['sha256'],'updater_sha256':p['files']['updater.bin']['sha256'],'helper_policy_sha256':p['full_transition']['new_policy_sha256']},config='server.conf') else: payload={'case_id':p['case_id'],'action':args.action} if args.action in('install','install-followup','install-stopped-followup'):payload['central_fence']=native_rpc(central_closed,{'agent_id':p['agent_id'],'tenant_id':p['tenant_id']},config='server.conf') if args.action=='trust': if args.trust_package is None:parser.error('--trust-package required for protected trust installation') payload['trust']=json.loads(args.trust_package.read_text()) value=native_rpc(pair,payload,timeout=120) print(json.dumps(value)) if __name__=='__main__':main()