Files
rust-discovery/deploy/updater_handoff_linux_acceptance.py
T
kevin_janssen 6d4c75e886
Rust development slice / linux (push) Failing after 7s
Qualify isolated updater handoff contracts on cloud Linux
2026-11-14 19:40:40 +01:00

182 lines
11 KiB
Python

#!/usr/bin/env python3
"""Run only the frozen eight pure handoff contracts on the Cloud Linux VM.
No RMM job, approval, agent/helper operation, release application or updater
installation. Prepare locally; execute one isolated nobody-owned process;
after any lost reply use read only. Original verifier runners remain unchanged.
"""
import argparse
import base64
import hashlib
import inspect
import json
import os
from pathlib import Path
import subprocess
import uuid
import windows_msi_runtime_acceptance as support
ROOT = Path(__file__).resolve().parents[1]
UPDATER = ROOT.parent / 'rust-discovery-agent-updater'
STATE = ROOT / 'devstate/updater-handoff-native'
COMMIT = 'a2efb79'
RECEIPT_SHA = 'e924471166e68629d27d6adae51ebac05a77f04426cdd427e844a9dfb4920f70'
BINARY_SHA = '0c80a2107fff96d9e30aa02b1cb56071a0f7e2be2acb1bec6794324205af9c7a'
TESTS = sorted('''closed_service_sets_reject_omitted_full_and_apt_restart
event_chain_clock_limits_and_canonical_bytes_fail_closed
full_linux_three_service_handoff_replays_exactly_sixteen_events
full_renderer_binds_provisioned_file_key_without_inserting_it_into_raw_config
full_renderer_changes_only_named_hash_spans_preserving_all_other_raw_bytes
full_renderer_rejects_foreign_pins_unknown_duplicate_escaped_and_privilege_changes
health_is_domain_bound_fresh_evidence_and_never_opens_ready
no_ownership_before_stop_no_partial_pair_no_start_before_return'''.splitlines())
def sha(raw):
return hashlib.sha256(raw).hexdigest()
def remote(p):
import base64
import hashlib
import json
import os
from pathlib import Path
import stat
import subprocess
import time
import uuid
def require(ok, message):
if not ok:
raise RuntimeError(message)
def enc(v):
return json.dumps(v, sort_keys=True, separators=(',', ':')).encode()
def create(path, raw, mode=0o600):
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode)
with os.fdopen(fd, 'wb') as f:
f.write(raw); f.flush(); os.fsync(f.fileno())
fd = os.open(path.parent, os.O_DIRECTORY | os.O_RDONLY)
try:
os.fsync(fd)
finally:
os.close(fd)
def run(args, timeout=20):
return subprocess.run(args, capture_output=True, timeout=timeout,
env={'PATH': '/usr/bin:/bin', 'LC_ALL': 'C', 'HOME': '/nonexistent'})
def witness():
out = {'boot_id': Path('/proc/sys/kernel/random/boot_id').read_text().strip(), 'services': {}, 'files': {}}
for name, uid, binary in (
('rmm-agent-remote.service', 993, p['agent_sha256']),
('rmm-helper-cloud.service', 0, p['helper_sha256']),
('rmm-full-maintenance-helper.service', 0, p['helper_sha256'])):
r = run(['systemctl', 'show', name, '-p', 'ActiveState', '-p', 'MainPID', '-p', 'UnitFileState'])
require(r.returncode == 0, 'existing service read')
s = dict(line.split('=', 1) for line in r.stdout.decode().splitlines())
pid = int(s['MainPID']); require(s['ActiveState'] == 'active' and pid > 1, 'three existing services active')
proc = Path('/proc', str(pid)); birth = (proc / 'stat').read_text().rsplit(') ', 1)[1].split()[19]
status = (proc / 'status').read_text().splitlines()
ids = {line.split(':')[0]: line.split()[1:] for line in status if line.startswith(('Uid:', 'Gid:'))}
image = hashlib.sha256((proc / 'exe').read_bytes()).hexdigest()
require(ids['Uid'] == [str(uid)] * 4 and ids['Gid'] == ['984'] * 4 and image == binary
and (proc / 'stat').read_text().rsplit(') ', 1)[1].split()[19] == birth, 'held generation/account/image')
out['services'][name] = dict(s, birth=birth, image=image, ids=ids)
r = run(['systemctl', 'show', 'rmm-apt-helper.service', '-p', 'ActiveState', '-p', 'UnitFileState'])
require(r.returncode == 0, 'APT service read')
apt = dict(line.split('=', 1) for line in r.stdout.decode().splitlines())
require(apt == {'ActiveState': 'inactive', 'UnitFileState': 'disabled'}, 'APT remains closed')
out['apt'] = apt
for name in ('/etc/rmm-remote/helper-general.json', '/etc/rmm-remote/helper-full-maintenance.json',
'/etc/rmm-remote/full-maintenance-helper-proof.json',
'/etc/systemd/system/rmm-full-maintenance-helper.service'):
path = Path(name); m = path.lstat()
require(not path.is_symlink() and stat.S_ISREG(m.st_mode) and m.st_uid == 0 and not m.st_mode & 0o022
and m.st_nlink == 1 and m.st_size < 65536, 'protected known control')
out['files'][name] = [m.st_dev, m.st_ino, m.st_uid, m.st_gid, m.st_mode, m.st_size,
m.st_mtime_ns, m.st_ctime_ns, hashlib.sha256(path.read_bytes()).hexdigest()]
for name in ('/var/lib/rmm-helper/consumption.sqlite', '/var/lib/rmm-helper/executor.lock',
'/var/lib/rmm-agent-remote/journal.sqlite', '/var/lib/rmm-agent-remote/consumption.sqlite'):
path = Path(name); m = path.lstat()
require(not path.is_symlink() and stat.S_ISREG(m.st_mode) and m.st_nlink == 1, 'existing state identity')
out['files'][name] = [m.st_dev, m.st_ino, m.st_uid, m.st_gid, m.st_mode]
return out
require(os.geteuid() == 0 and os.uname().machine == 'x86_64', 'fixed Cloud Linux root bootstrap')
ident = str(uuid.UUID(p['id'])); require(ident == p['id'], 'canonical case')
folder = Path('/var/tmp') / ('rmm-updater-handoff-' + ident)
if p['action'] == 'read':
m = folder.lstat(); require(stat.S_ISDIR(m.st_mode) and not folder.is_symlink() and m.st_uid == 0, 'own original case')
return {'read_only': True, 'id': ident, 'entered': (folder / 'entered.json').exists(),
'result': json.loads((folder / 'result.json').read_bytes()) if (folder / 'result.json').exists() else None,
'current_witness': witness()}
require(p['action'] == 'execute', 'one exact unit action')
os.umask(0o022); folder.mkdir(mode=0o755)
create(folder / 'intent.json', enc({k: v for k, v in p.items() if k != 'binary_b64'}))
raw = base64.b64decode(p['binary_b64'], validate=True)
require(len(raw) == 2261368 and hashlib.sha256(raw).hexdigest() == p['binary_sha256'], 'fixed pure unit bytes')
binary = folder / 'handoff-contract'; create(binary, raw, 0o755)
before = witness(); create(folder / 'before.json', enc(before))
command = ['/usr/bin/setpriv', '--reuid=65534', '--regid=65534', '--clear-groups', '--no-new-privs', str(binary)]
listed = run(command + ['--list', '--format', 'terse'])
create(folder / 'list.stdout', listed.stdout); create(folder / 'list.stderr', listed.stderr)
require(listed.returncode == 0 and listed.stderr == b'', 'native list succeeded')
require(sorted(line[:-6] for line in listed.stdout.decode().splitlines() if line.endswith(': test')) == p['tests']
and len(listed.stdout.decode().splitlines()) == 8, 'exact eight native tests, no filter')
create(folder / 'entered.json', enc({'id': ident, 'run_once': True, 'time_ns': time.time_ns()}))
result = run(command + ['--test-threads=1', '--nocapture'])
create(folder / 'run.stdout', result.stdout); create(folder / 'run.stderr', result.stderr)
after = witness(); create(folder / 'after.json', enc(after))
require(before == after and result.returncode == 0 and result.stderr == b''
and b'8 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out' in result.stdout
and all((b'test ' + name.encode() + b' ... ok') in result.stdout for name in p['tests']), 'native eight and retained services/state')
receipt = dict(id=ident, passed=8, ignored=0, filtered=0, execution_uid=65534, tests=p['tests'],
before=before, after=after, binary_sha256=p['binary_sha256'], source_receipt_sha256=p['receipt_sha256'],
stdout_sha256=hashlib.sha256(result.stdout).hexdigest(), no_rmm_jobs=True, no_apply=True)
create(folder / 'result.json', enc(receipt)); return receipt
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('prepare', 'execute', 'read')); parser.add_argument('--case')
args = parser.parse_args(); os.umask(0o077); STATE.mkdir(mode=0o700, exist_ok=True)
if args.action == 'prepare':
support.require(args.case is None, 'new local case')
receipt = UPDATER / 'devstate/agent-updater-handoff/local-qualification-filekey.json'
support.private(receipt)
raw = receipt.read_bytes(); support.require(sha(raw) == RECEIPT_SHA, 'reviewed local receipt')
local = json.loads(raw)
for item in local['sources']:
blob = subprocess.check_output(['git', '-C', str(UPDATER), 'show', COMMIT + ':' + item['path']])
support.require(len(blob) == item['bytes'] and sha(blob) == item['sha256'], 'exact committed qualified source')
binary = UPDATER / local['binary']['path']; support.require(sha(binary.read_bytes()) == BINARY_SHA, 'qualified binary')
ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700)
support.save(folder / 'intent.json', dict(id=ident, runner_sha256=sha(Path(__file__).read_bytes()),
receipt_sha256=RECEIPT_SHA, binary_sha256=BINARY_SHA, binary_path=str(binary), tests=TESTS,
agent_sha256='0a7ad6eefaefda79ee80b6a41b2df904e9e7f50ae6ebeed01b98c25b6ce5c06f',
helper_sha256='79442727c3ba31cda02a8bc0e67481f14db9f39fc07520a880a90b64f10f1eaf'))
else:
ident = str(uuid.UUID(args.case)); support.require(ident == args.case, 'same original case')
folder = STATE / ident; intent = support.load(folder / 'intent.json')
support.require(intent['runner_sha256'] == sha(Path(__file__).read_bytes()), 'original runner bytes')
if args.action == 'execute':
support.save(folder / 'execute-entered.json', {'once': True, 'no_retry': True})
raw = Path(intent['binary_path']).read_bytes(); support.require(sha(raw) == BINARY_SHA, 'original binary')
intent['binary_b64'] = base64.b64encode(raw).decode()
payload = dict(intent, action=args.action)
code = 'import json\n' + inspect.getsource(remote) + '\nprint(json.dumps(remote(' + repr(payload) + ')))\n'
response = support.transport(support.access_settings(ROOT, 'linux'), 'python3 -', code.encode(), folder)
support.save(folder / (args.action + '-' + str(uuid.uuid4()) + '.json'), response)
if args.action == 'read':
support.require(response['result'] is not None and response['current_witness'] == response['result']['after'], 'readback retained native result')
print(json.dumps({'id': ident, 'action': args.action, 'passed': response.get('passed'), 'read_only': args.action == 'read'})); return
print(json.dumps({'id': ident, 'prepared_locally': True}))
if __name__ == '__main__':
main()