#!/usr/bin/env python3 """Read-only prerequisite snapshot for preserving Linux updater bootstrap. No apply/start/stop/reenroll/package/policy operation is implemented here. Credentials use the existing strict parser and independently pinned SSH host. Private keys are stat'ed only; no private key or environment bytes are read. """ import argparse import hashlib import json import os from pathlib import Path import uuid import remote_client_bootstrap as transport ROOT=Path(__file__).resolve().parents[1] def inspect_vm(payload): import contextlib import hashlib import json import os from pathlib import Path import sqlite3 import stat import subprocess import time import uuid require(payload=={'operation':'linux_updater_bootstrap_inspect_v1'} and os.geteuid()==0 and os.uname().machine=='x86_64','fixed read-only Linux target') def digest(raw):return hashlib.sha256(raw).hexdigest() def encode(value):return json.dumps(value,separators=(',',':'),ensure_ascii=False).encode() def identity(s):return dict(device=s.st_dev,inode=s.st_ino,uid=s.st_uid,gid=s.st_gid,mode=s.st_mode,links=s.st_nlink) def metadata(path): path=Path(path) try:s=path.lstat() except FileNotFoundError:return None require(not stat.S_ISLNK(s.st_mode),'no metadata symlink') return dict(identity=identity(s),bytes=s.st_size) def public(path,limit=65536): path=Path(path);s=path.lstat() require(stat.S_ISREG(s.st_mode) and s.st_uid==0 and s.st_nlink==1 and not s.st_mode&0o022 and s.st_size<=limit,'bounded protected public input') with path.open('rb') as stream:raw=stream.read(limit+1) after=path.lstat() require(len(raw)==s.st_size and identity(after)==identity(s) and after.st_size==s.st_size and after.st_mtime_ns==s.st_mtime_ns and after.st_ctime_ns==s.st_ctime_ns,'stable public input') return raw def proof(path): raw=public(path,256*1024*1024);s=Path(path).lstat() return dict(identity=identity(s),bytes=len(raw),sha256=digest(raw)) def run(args): result=subprocess.run(args,stdin=subprocess.DEVNULL,stdout=subprocess.PIPE,stderr=subprocess.PIPE, timeout=10,env={'PATH':'/usr/bin:/bin','LC_ALL':'C'}) require(result.returncode in (0,1) and len(result.stdout)<=65536,'bounded read-only systemd response') return result.stdout.decode() services=('rmm-agent-remote.service','rmm-helper-cloud.service','rmm-full-maintenance-helper.service', 'rmm-agent-updater.service','rmm-apt-helper.service','rmm-agent.service','rmm-helper-dev-test.service') names=list(services) for name in services: names.extend((name[:-8]+'.socket',name[:-8]+'.timer')) timers=run(['systemctl','list-units','--all','--no-legend','--plain','--no-pager','rmm-general-startup-rollback-*.timer']) rollback_names=[] for line in timers.splitlines(): name=line.split()[0] require(name.startswith('rmm-general-startup-rollback-') and name.endswith('.timer'),'fixed rollback timer') uuid.UUID(name[len('rmm-general-startup-rollback-'):-len('.timer')]) rollback_names.append(name) names.extend(sorted(rollback_names)) properties=['Id','LoadState','ActiveState','SubState','MainPID','ControlPID','InvocationID','UnitFileState', 'FragmentPath','DropInPaths','Triggers','TriggeredBy','Job','ControlGroup'] units={} for name in names: output=run(['systemctl','show','--all','--property='+','.join(properties),'--',name]) fields={} for line in output.splitlines(): key,value=line.split('=',1);require(key in properties and key not in fields,'exact service properties') fields[key]=value require(fields.get('Id')==name,'exact queried unit') composition=[] if fields.get('LoadState')=='loaded': paths=[fields['FragmentPath']]+fields.get('DropInPaths','').split() for path in paths:composition.append((path,proof(path))) units[name]=dict(status=fields,composition=composition,unit_sha256=digest(encode(composition))) binaries={} for path in ('/usr/local/libexec/rmm-agent-remote','/usr/local/libexec/rmm-privileged-helper','/usr/local/libexec/rmm-agent-updater'): binaries[path]=proof(path) if Path(path).exists() else None configs={} for name in ('helper-general.json','helper-full-maintenance.json'): path=Path('/etc/rmm-remote')/name if not path.exists():configs[name]=None;continue raw=public(path);value=json.loads(raw) configs[name]=dict(sha256=digest(raw),fields={key:value.get(key) for key in ( 'profile','agent_uid','socket_gid','socket','state','signing_key_file','allow_reboot','allow_root_scripts', 'allowed_script_profiles','helper_binary_sha256')},binding={key:value['binding'][key] for key in ( 'tenant_id','asset_id','agent_id','enrollment_generation','assignment_version')}) public_pins={} for name in ('general-helper-proof.json','full-maintenance-helper-proof.json','helper-signing-key.json'): path=Path('/etc/rmm-remote')/name public_pins[name]=proof(path) if path.exists() else None state_paths=[ '/var/lib/rmm-agent-remote','/var/lib/rmm-agent-remote/journal.sqlite', '/var/lib/rmm-agent-remote/consumption.sqlite','/var/lib/rmm-agent-remote/agent.lock', '/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','/var/lib/rmm-agent-remote/certificates', '/var/lib/rmm-helper','/var/lib/rmm-helper/consumption.sqlite','/var/lib/rmm-helper/executor.lock', '/etc/rmm-agent-updater','/var/lib/rmm-agent-updater','/etc/rmm-remote/agent.env'] selector=Path('/var/lib/rmm-agent-remote/certificates/current.json') if selector.exists(): # Public selector only; active private key is metadata-only below. s=selector.lstat();require(stat.S_ISREG(s.st_mode) and s.st_size<=4096,'public TLS selector') current=json.loads(selector.read_bytes());version=str(uuid.UUID(current['version'])) state_paths.extend((str(selector),str(selector.parent/'versions'/version), str(selector.parent/'versions'/version/'device.key'),str(selector.parent/'versions'/version/'device.pem'))) state={path:metadata(path) for path in state_paths} databases={} 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 required') with contextlib.closing(sqlite3.connect('file:'+path+'?mode=ro',uri=True,timeout=2)) as db: db.execute('PRAGMA query_only=ON') require(db.execute('PRAGMA journal_mode').fetchone()[0]=='delete','read-only DELETE journal') tables={row[0] for row in db.execute("SELECT name FROM sqlite_master WHERE type='table'")} counts={name:db.execute('SELECT count(*) FROM '+name).fetchone()[0] for name in ( 'consumed','execution_evidence','helper_sync_decisions','job_attempts','reconcile_decisions') if name in tables} unresolved={} if 'consumed' in tables:unresolved['consumed']=db.execute('SELECT count(*) FROM consumed WHERE result IS NULL').fetchone()[0] if 'job_attempts' in tables:unresolved['job_attempts']=db.execute("SELECT count(*) FROM job_attempts WHERE state NOT IN ('succeeded','failed','cancelled','expired')").fetchone()[0] faults={name:db.execute('SELECT count(*) FROM '+name+' WHERE fault IS NOT NULL').fetchone()[0] for name in ('helper_sync_meta','reconcile_meta') if name in tables} # Hash original evidence bytes inside the target; no stdout/script # body or reconciliation request/signature is exported. evidence=[] if 'execution_evidence' in tables: columns={r[1] for r in db.execute('PRAGMA table_info(execution_evidence)')} for grant,start,outcome in db.execute('SELECT grant_id,start,outcome FROM execution_evidence'): evidence.append(dict(grant_id=grant,start_sha256=digest(start),outcome_sha256=None if outcome is None else digest(outcome))) databases[path]=dict(counts=counts,unresolved=unresolved,faults=faults, evidence_sha256=digest(encode(sorted(evidence,key=lambda r:r['grant_id']))), integrity=db.execute('PRAGMA integrity_check').fetchone()[0]) require(not Path(path+'-wal').exists() and not Path(path+'-shm').exists(),'no SQLite sidecars introduced') host={} for label,path in (('proc','/proc'),('user_namespace','/proc/1/ns/user'),('pid_namespace','/proc/1/ns/pid'),('cgroup_namespace','/proc/1/ns/cgroup')): s=Path(path).stat();host[label+'_device']=s.st_dev;host[label+'_inode']=s.st_ino return dict(schema_version=1,operation=payload['operation'],read_only=True,utc_seconds=int(time.time()), boot_id=Path('/proc/sys/kernel/random/boot_id').read_text().strip(),units=units,binaries=binaries, configs=configs,public_pins=public_pins,state=state,databases=databases,host_context=host, rollback_timers=rollback_names,updater_provisioned=Path('/etc/rmm-agent-updater/policy.json').exists()) def prepare(snapshot_path,agent,helper,updater,qualification): import stat def require(ok,code): if not ok:raise RuntimeError(code) def input_file(path,limit): path=Path(path);meta=path.lstat() require(stat.S_ISREG(meta.st_mode) and not path.is_symlink() and meta.st_nlink==1 and meta.st_uid==os.getuid() and not meta.st_mode&0o022 and 0