#!/usr/bin/python3 """Root-helper-only, fail-closed local-archive APT transaction provider. No network API, resolver approval, grant verifier, or automatic retry lives here. See README.md before integrating. Python 3.9+, Linux amd64 only. """ import ctypes import errno import fcntl import hashlib import io import json import os from pathlib import Path import re import selectors import socket import stat import subprocess import sys import tarfile import time import uuid from dataclasses import dataclass from typing import Optional, Tuple from urllib.parse import unquote_to_bytes BASE = Path('/var/lib/rmm-apt-transaction') ACTIVE = BASE / 'active' CODE = Path('/usr/lib/rmm-apt-transaction/apt_transaction.py') HOOK = '/usr/lib/rmm-apt-transaction/hook' APT_UNIT = Path('/etc/systemd/system/rmm-apt-helper.service') PRIVATE_CONTROL_DIRECTORIES = ('/etc/rmm', '/etc/rmm-remote', '/var/lib/rmm-helper', '/var/lib/rmm-agent', '/var/lib/rmm-agent-remote') MAX_INPUT = 1024 * 1024 MAX_PACKAGES = 128 RESOLVER = 'rmm-apt-local-v1' FIXTURE_RECIPES = {'rmm-apt-fixture-install-1.0': (None, '1.0'), 'rmm-apt-fixture-update-1.1': ('1.0', '1.1')} # Generated deterministic USTAR/ar bytes below; pinned after independent local # dpkg-deb control/payload inspection. No runtime-supplied fixture hash is trusted. FIXTURE_SHA256 = {'1.0': '74036ae81223deab3aae994fd2a2a695af408741777e1ce17dcb4e32f1235867', '1.1': 'ef67c9fe0ba1443fcfe465768e1204763063c369a2a1da04af6027d8a9c00491'} HISTORICAL_CONFIGURED_RECOVERY = { 'grant_id': '33775478-15b0-46ec-b059-44f500dbb0b6', 'previous_grant_id': '31ef5e5e-5dbd-4428-a9a1-cbd15de2f5a0', 'partial_proof_sha256': 'dc3bf3870ea77c12f9291bac712c53ae72194eaec980a8646155a7fb5c0dbe21', 'provider_sha256': '5ff260f75cb2959678f6be729d3a806a4ea29febd5ae4003317fed41afc25327', } ENV = {'PATH': '/usr/sbin:/usr/bin:/sbin:/bin', 'LC_ALL': 'C', 'DEBIAN_FRONTEND': 'noninteractive', 'HOME': '/root'} NAME = re.compile(r'[a-z0-9][a-z0-9+.-]{1,127}\Z') VERSION = re.compile(r'[0-9][A-Za-z0-9.+:~\-]{0,255}\Z') HASH = re.compile(r'[0-9a-f]{64}\Z') IDENT = re.compile(r'[A-Za-z0-9_.-]{1,128}\Z') FORBIDDEN = re.compile(r'^(linux-|kernel|grub|shim|systemd|initramfs|dracut|' r'uboot|u-boot|firmware|base-files|ubuntu-release-upgrader|' r'dpkg$|apt$|libapt|libc6$|libseccomp|python3|util-linux)') class Veto(Exception): """A stable, non-secret error code, not raw child output.""" def require(condition, code): if not condition: raise Veto(code) def exact(obj, keys): require(type(obj) is dict and set(obj) == set(keys.split()), 'SCHEMA_FIELDS') def digest(data): return hashlib.sha256(data).hexdigest() def canonical(obj): return json.dumps(obj, sort_keys=True, separators=(',', ':'), ensure_ascii=True).encode('ascii') def json_bytes(data): require(len(data) <= MAX_INPUT, 'INPUT_LIMIT') def pairs(items): result = {} for key, value in items: require(key not in result, 'DUPLICATE_JSON_KEY') result[key] = value return result try: return json.loads(data, object_pairs_hook=pairs, parse_constant=lambda _: (_ for _ in ()).throw(Veto('JSON_NUMBER'))) except (ValueError, UnicodeError, RecursionError): raise Veto('MALFORMED_JSON') from None def token(value, pattern, code): require(type(value) is str and pattern.fullmatch(value) is not None, code) return value def secure_path(path, directory=False, private=False): """All components must be real root-owned, non-writable-by-others paths. Root administrators remain trusted. No testing UID override in production. """ path = Path(path) require(path.is_absolute() and str(path) == os.path.normpath(str(path)), 'PATH') for component in [*reversed(path.parents), path]: st = component.lstat() require(st.st_uid == 0 and not st.st_mode & 0o022 and not stat.S_ISLNK(st.st_mode), 'PATH_OWNERSHIP_MODE') st = path.lstat() require(stat.S_ISDIR(st.st_mode) if directory else stat.S_ISREG(st.st_mode), 'PATH_TYPE') if private: require(not st.st_mode & 0o077, 'PATH_NOT_PRIVATE') return path def archive_metadata(st, expected_size): require(st.st_uid == 0 and not st.st_mode & 0o022 and stat.S_ISREG(st.st_mode), 'ARCHIVE_OWNERSHIP_MODE') require(st.st_size == expected_size and st.st_nlink == 1, 'ARCHIVE_SIZE_LINKS') def sealed_read(path, limit=MAX_INPUT): secure_path(path) fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC) with os.fdopen(fd, 'rb') as stream: require(os.fstat(stream.fileno()).st_size <= limit, 'FILE_LIMIT') data = stream.read(limit + 1) require(len(data) <= limit, 'FILE_LIMIT') return data def durable_once(path, obj): """O_EXCL is the exactly-one handoff; partial/old files veto, never reset.""" secure_path(path.parent, directory=True, private=True) try: fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) except FileExistsError: raise Veto('ALREADY_HANDED_OFF') from None with os.fdopen(fd, 'wb') as stream: stream.write(canonical(obj)) stream.flush() os.fsync(stream.fileno()) fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY) try: os.fsync(fd) finally: os.close(fd) def run_read(argv, limit=MAX_INPUT, timeout=30, pass_fds=(), env=None, expected_returncode=0, merge_stderr=False): """Bound stdout/stderr while reading, not only after communicate().""" proc = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=ENV if env is None else env, pass_fds=pass_fds) output = bytearray() total = 0 deadline = time.monotonic() + timeout with selectors.DefaultSelector() as selector: selector.register(proc.stdout, selectors.EVENT_READ, True) selector.register(proc.stderr, selectors.EVENT_READ, False) try: while selector.get_map(): require(time.monotonic() < deadline, 'READ_TIMEOUT') for key, _ in selector.select(min(0.2, max(0, deadline - time.monotonic()))): chunk = os.read(key.fileobj.fileno(), 65536) if not chunk: selector.unregister(key.fileobj) total += len(chunk) require(total <= limit, 'CHILD_OUTPUT_LIMIT') if key.data or merge_stderr: output.extend(chunk) require(proc.wait(timeout=max(0.01, deadline - time.monotonic())) == expected_returncode, 'READ_COMMAND_FAILED') except BaseException: # Only harmless read commands use this routine. NEVER kill apt/dpkg. proc.kill() proc.wait() raise finally: proc.stdout.close() proc.stderr.close() return bytes(output) @dataclass(frozen=True) class PackageArchive: name: str architecture: str old_version: Optional[str] new_version: str origin: str sha256: str size: int archive_path: str @classmethod def parse(cls, obj, configure_only=False): exact(obj, 'name architecture old_version new_version origin sha256 size archive_path') token(obj['name'], NAME, 'PACKAGE_NAME') require(not FORBIDDEN.match(obj['name']), 'PROTECTED_PACKAGE') require(obj['architecture'] in ('amd64', 'all'), 'ARCHITECTURE') token(obj['new_version'], VERSION, 'VERSION') if configure_only: require(obj['old_version'] == obj['new_version'] == '1.0', 'RECOVERY_VERSION') if obj['old_version'] is not None: token(obj['old_version'], VERSION, 'VERSION') # Debian ordering, not lexical/semver ordering. Read-only argv. require((obj['old_version'] == obj['new_version'] == '1.0') if configure_only else subprocess.run(['/usr/bin/dpkg', '--compare-versions', obj['old_version'], 'lt', obj['new_version']], env=ENV, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0, 'DOWNGRADE_OR_REINSTALL') token(obj['origin'], re.compile(r'(rmm-test|catalog:[A-Za-z0-9_.-]{1,128})\Z'), 'ORIGIN') token(obj['sha256'], HASH, 'SHA256') require(type(obj['size']) is int and 0 < obj['size'] <= 256 * 1024 * 1024, 'SIZE') expected = str(BASE / 'archives' / (obj['sha256'] + '.deb')) require(obj['archive_path'] == expected, 'UNSEALED_ARCHIVE_PATH') return cls(**obj) @dataclass(frozen=True) class ResolvedAptTransaction: schema_version: int recipe_id: str recipe_version: str platform: str resolver_config_version: str no_reboot: bool status_fingerprint: str baseline_sha256: str packages: Tuple[PackageArchive, ...] operation: Optional[str] = None @classmethod def parse(cls, obj): version = obj.get('schema_version') if type(obj) is dict else None exact(obj, 'schema_version recipe_id recipe_version platform resolver_config_version ' 'no_reboot status_fingerprint baseline_sha256 packages' + (' operation' if version == 2 else '')) require(type(version) is int and version in (1, 2), 'SCHEMA_VERSION') configure_only = version == 2 require(not configure_only or obj['operation'] == 'configure_only', 'TRANSACTION_OPERATION') token(obj['recipe_id'], IDENT, 'RECIPE_ID') token(obj['recipe_version'], IDENT, 'RECIPE_VERSION') require(obj['platform'] == 'ubuntu-24.04-amd64', 'UNSUPPORTED_PLATFORM') require(obj['resolver_config_version'] == RESOLVER, 'RESOLVER_VERSION') require(obj['no_reboot'] is True, 'REBOOT_FORBIDDEN') token(obj['status_fingerprint'], HASH, 'FINGERPRINT') token(obj['baseline_sha256'], HASH, 'FINGERPRINT') require(type(obj['packages']) is list and 0 < len(obj['packages']) <= MAX_PACKAGES, 'PACKAGE_COUNT') packages = tuple(PackageArchive.parse(p, configure_only=configure_only) for p in obj['packages']) require(len({(p.name, p.architecture) for p in packages}) == len(packages), 'DUPLICATE_PACKAGE') transaction = cls(**{**obj, 'packages': packages}) if configure_only: fixture_scope(transaction) return transaction @dataclass(frozen=True) class VerifiedHelperContext: transaction_sha256: str effect_armed_ledger_id: str grant_id: str not_before_ms: int start_before_ms: int boot_id: str monotonic_start_before_ns: int schema_version: int job_payload_sha256: str action: str execution_profile: str job_id: str attempt_id: str authorization_id: str plan_sha256: str @classmethod def parse(cls, obj): exact(obj, 'transaction_sha256 effect_armed_ledger_id grant_id not_before_ms ' 'start_before_ms boot_id monotonic_start_before_ns schema_version ' 'job_payload_sha256 action execution_profile job_id attempt_id authorization_id plan_sha256') require(type(obj['schema_version']) is int and obj['schema_version'] == 2, 'CONTEXT_SCHEMA') require(obj['action'] in ('apt-execute', 'apt-native-acceptance'), 'CONTEXT_ACTION') require(obj['execution_profile'] in ('dev-test', 'production'), 'CONTEXT_PROFILE') token(obj['transaction_sha256'], HASH, 'TRANSACTION_HASH') for key in ('job_payload_sha256', 'plan_sha256'): token(obj[key], HASH, 'CONTEXT_HASH') for key in ('effect_armed_ledger_id', 'grant_id', 'boot_id', 'job_id', 'attempt_id', 'authorization_id'): token(obj[key], IDENT, 'CONTEXT_ID') for key in ('not_before_ms', 'start_before_ms', 'monotonic_start_before_ns'): require(type(obj[key]) is int and obj[key] > 0, 'CONTEXT_TIME') require(0 < obj['start_before_ms'] - obj['not_before_ms'] <= 60000, 'GRANT_WINDOW') return cls(**obj) def check_deadline(self, now_ms=None, monotonic_ns=None, boot_id=None): now_ms = time.time_ns() // 1000000 if now_ms is None else now_ms monotonic_ns = time.monotonic_ns() if monotonic_ns is None else monotonic_ns if boot_id is None: boot_id = Path('/proc/sys/kernel/random/boot_id').read_text().strip() require(boot_id == self.boot_id, 'BOOT_CHANGED') require(self.not_before_ms <= now_ms < self.start_before_ms and monotonic_ns < self.monotonic_start_before_ns, 'START_DEADLINE') def fixture_archive(version): """Deterministic, script/trigger/dependency-free Debian ar archive.""" require(version in ('1.0', '1.1'), 'FIXTURE_VERSION') def tar(entries): output = io.BytesIO() with tarfile.open(fileobj=output, mode='w', format=tarfile.USTAR_FORMAT) as archive: for name, data in entries: entry = tarfile.TarInfo(name) entry.uid = entry.gid = 0 entry.uname = entry.gname = 'root' entry.mtime = 1794441600 entry.mode = 0o755 if data is None else 0o644 entry.type = tarfile.DIRTYPE if data is None else tarfile.REGTYPE entry.size = 0 if data is None else len(data) archive.addfile(entry, None if data is None else io.BytesIO(data)) return output.getvalue() control = ('Package: rmm-mvp-test\nVersion: ' + version + '\nArchitecture: all\n' 'Maintainer: RMM development fixture \n' 'Section: misc\nPriority: optional\n' 'Description: Harmless manually imported RMM acceptance fixture\n').encode('ascii') members = [('debian-binary', b'2.0\n'), ('control.tar', tar([('./control', control)])), ('data.tar', tar([('./usr', None), ('./usr/share', None), ('./usr/share/rmm-mvp-test', None), ('./usr/share/rmm-mvp-test/version', (version + '\n').encode('ascii'))]))] result = bytearray(b'!\n') for name, data in members: header = '{:<16}{:<12}{:<6}{:<6}{:<8}{:<10}`\n'.format( name + '/', 1794441600, 0, 0, '100644', len(data)).encode('ascii') require(len(header) == 60, 'FIXTURE_AR_HEADER') result.extend(header + data + (b'\n' if len(data) % 2 else b'')) return bytes(result) def fixture_scope(transaction): require(transaction.recipe_id in FIXTURE_RECIPES and transaction.recipe_version == '1', 'FIXTURE_RECIPE') require(len(transaction.packages) == 1, 'FIXTURE_CLOSURE') old, new = FIXTURE_RECIPES[transaction.recipe_id] if transaction.operation == 'configure_only': require(transaction.schema_version == 2 and transaction.recipe_id == 'rmm-apt-fixture-install-1.0', 'RECOVERY_FIXED_RECIPE') old = new = '1.0' package = transaction.packages[0] require(package.name == 'rmm-mvp-test' and package.architecture == 'all' and package.origin == 'rmm-test' and package.old_version == old and package.new_version == new, 'FIXTURE_PACKAGE') require(package.sha256 == FIXTURE_SHA256[new] == digest(fixture_archive(new)) and package.size == len(fixture_archive(new)), 'FIXTURE_PINNED_BYTES') return {'recipe_id': transaction.recipe_id, 'recipe_version': '1', 'packages': [package.__dict__]} def load_signed_action(transaction, context): """Helper verified this exact payload hash against the signed grant first. This is NOT a second root-unsigned manifest that can replace the signed action: the nested resolved transaction is required in the signed bytes. """ raw = sealed_read(ACTIVE / 'signed-action.json') require(digest(raw) == context.job_payload_sha256, 'SIGNED_ACTION_HASH') job = json_bytes(raw) exact(job, 'schema_version tenant_id asset_id agent_id enrollment_generation assignment_version ' 'job_id attempt_id action execution_identity not_before start_before max_runtime_seconds max_output_bytes') require(type(job['schema_version']) is int and job['schema_version'] == 1 and job['execution_identity'] == 'root' and job['job_id'] == context.job_id and job['attempt_id'] == context.attempt_id, 'SIGNED_JOB_BINDING') require(type(job['action']) is dict, 'SIGNED_JOB_ACTION') outer_action = job['action'].get('action') require(outer_action in ('ensure_package', 'apply_updates', 'apt_native_acceptance') and context.action == ('apt-native-acceptance' if outer_action == 'apt_native_acceptance' else 'apt-execute'), 'DEDICATED_HELPER_ACTION_REQUIRED') action = job['action'].get('apt_manifest') manifest_keys = 'type schema_version action execution_profile transaction_sha256 ' manifest_keys += ('resolved_apt_transaction provider_sha256 hook_sha256 apt_config_sha256 ' 'runtime_sha256 test_result_id transaction_bytes') version = action.get('schema_version') if type(action) is dict else None exact(action, manifest_keys + (' native_retry' if version == 3 else ' native_recovery' if version == 4 else '')) require(action['type'] == 'rmm.apt.helper-action' and type(version) is int and version in (2, 3, 4), 'SIGNED_ACTION_SCHEMA') if version == 3: validate_retry_reference(action['native_retry']) require(context.action == 'apt-native-acceptance' and context.execution_profile == 'dev-test', 'RETRY_NATIVE_TEST_ONLY') if version == 4: validate_recovery_reference(action['native_recovery']) require(context.action == 'apt-native-acceptance' and context.execution_profile == 'dev-test' and transaction.operation == 'configure_only', 'RECOVERY_NATIVE_CONFIGURE_ONLY') else: require(transaction.operation is None, 'RECOVERY_MANIFEST_REQUIRED') expected_bytes = sealed_read(ACTIVE / 'expectation.json') require(type(action['transaction_bytes']) is list and len(action['transaction_bytes']) <= 65536 and all(type(value) is int and 0 <= value <= 255 for value in action['transaction_bytes']) and bytes(action['transaction_bytes']) == expected_bytes and digest(expected_bytes) == context.transaction_sha256, 'SIGNED_TRANSACTION_EXACT_BYTES') require(action['action'] == context.action and action['execution_profile'] == context.execution_profile and action['transaction_sha256'] == context.transaction_sha256 and canonical(action['resolved_apt_transaction']) == canonical(json_bytes(expected_bytes)), 'SIGNED_ACTION_BINDING') if outer_action == 'apply_updates': require(job['action'].get('provider') == 'apt' and job['action'].get('packages') == ['rmm-mvp-test'] and job['action'].get('reboot_policy') == 'never' and transaction.recipe_id == 'rmm-apt-fixture-update-1.1', 'SIGNED_UPDATE_SELECTION') else: require(job['action'].get('recipe_id') == transaction.recipe_id and job['action'].get('recipe_version') == transaction.recipe_version, 'SIGNED_RECIPE_PARAMETERS') token(action['test_result_id'], IDENT, 'TEST_RESULT_ID') for field in ('provider_sha256', 'hook_sha256', 'apt_config_sha256', 'runtime_sha256'): token(action[field], HASH, 'SIGNED_ACTION_HASH') require(action['provider_sha256'] == digest(sealed_read(CODE)) and action['hook_sha256'] == digest(sealed_read(Path(HOOK))) and action['apt_config_sha256'] == digest(apt_config()), 'SIGNED_CODE_RECIPE') return action def record_path(transaction): # Fixed allowlist before deriving filenames; no arbitrary recipe/path input. fixture_scope(transaction) return BASE / ('acceptance-' + transaction.recipe_id + '.json') def check_native_gate(transaction, context, action, runtime, native_acceptance): scope = fixture_scope(transaction) require(action['runtime_sha256'] == digest(canonical(runtime)), 'SIGNED_RUNTIME_BINDING') require(context.execution_profile == 'dev-test', 'PRODUCTION_ACCEPTANCE_REQUIRED') require(context.action == ('apt-native-acceptance' if native_acceptance else 'apt-execute'), 'DEDICATED_HELPER_ACTION_REQUIRED') path = record_path(transaction) if native_acceptance: if action.get('native_recovery') is not None: verify_recovery_reference(transaction, context, action) require(not os.path.lexists(BASE / ('recovery-' + action['native_recovery']['previous_grant_id'] + '.json')), 'RECOVERY_ALREADY_RECORDED') return require(not path.exists(), 'ACCEPTANCE_ALREADY_RECORDED') return proof = json_bytes(sealed_read(path)) validate_acceptance_record(proof, scope, runtime) def validate_acceptance_record(proof, scope, runtime): exact(proof, 'schema_version scope runtime test_acceptance noProductionEvidence ' 'test_result_id transaction_sha256 job_payload_sha256 grant_id job_id attempt_id ' 'authorization_id plan_sha256 native_prechecks_sha256 hook_marker_sha256 ' 'postconditions_sha256 completed_at_ms native_prechecks_schema_version host_reboot_before_sha256 ' 'host_reboot_required_before host_reboot_required_after reboot_required_introduced') require(type(proof['schema_version']) is int and proof['schema_version'] == 3 and proof['scope'] == scope and proof['runtime'] == runtime and proof['test_acceptance'] is True and proof['noProductionEvidence'] is True, 'NATIVE_PROOF_SCOPE_OR_RUNTIME') for key in ('transaction_sha256', 'job_payload_sha256', 'plan_sha256', 'native_prechecks_sha256', 'hook_marker_sha256', 'postconditions_sha256', 'host_reboot_before_sha256'): token(proof[key], HASH, 'NATIVE_PROOF_HASH') for key in ('test_result_id', 'grant_id', 'job_id', 'attempt_id', 'authorization_id'): token(proof[key], IDENT, 'NATIVE_PROOF_ID') require(type(proof['completed_at_ms']) is int and proof['completed_at_ms'] > 0, 'NATIVE_PROOF_TIME') require(type(proof['native_prechecks_schema_version']) is int and proof['native_prechecks_schema_version'] == 2 and type(proof['host_reboot_required_before']) is bool and type(proof['host_reboot_required_after']) is bool and proof['host_reboot_required_before'] == proof['host_reboot_required_after'] and proof['reboot_required_introduced'] is False, 'NATIVE_PROOF_BOUND_HOST_REBOOT') def runtime_identity(): """Versioned actual code/config/binary/OS identity, also signed in the job.""" require(os.uname().machine == 'x86_64', 'UNSUPPORTED_PLATFORM') os_release = sealed_read(Path('/etc/os-release').resolve(strict=True)) require(b'\nID=ubuntu\n' in b'\n' + os_release and b'\nVERSION_ID="24.04"\n' in b'\n' + os_release, 'UNSUPPORTED_PLATFORM') paths = [str(CODE), HOOK, '/usr/local/libexec/rmm-privileged-helper', '/usr/bin/apt-get', '/usr/bin/dpkg', '/usr/bin/dpkg-deb', '/usr/bin/dpkg-query', '/usr/bin/python3', '/usr/bin/unshare', '/usr/bin/mount', '/bin/sh'] # Identify the actually loaded shared library, not a guessed soname path. lib = ctypes.CDLL('libseccomp.so.2') require(bool(lib), 'SECCOMP_LIBRARY') libraries = {line.split()[-1] for line in Path('/proc/self/maps').read_text().splitlines() if '/libseccomp.so.' in line and line.split()[-1].startswith('/')} require(len(libraries) == 1, 'SECCOMP_LIBRARY_IDENTITY') paths.extend(sorted(libraries)) binaries = {} for path in paths: resolved = Path(path).resolve(strict=True) binaries[path] = {'resolved_path': str(resolved), 'sha256': digest(sealed_read(resolved, 64 * MAX_INPUT))} versions = {} for program in ('apt-get', 'dpkg', 'dpkg-deb', 'dpkg-query', 'python3', 'unshare', 'mount'): versions[program] = run_read(['/usr/bin/' + program, '--version']).decode('utf-8').splitlines()[0] return {'schema_version': 1, 'platform': 'ubuntu-24.04-amd64', 'os_release_sha256': digest(os_release), 'kernel_release': os.uname().release, 'binaries': binaries, 'versions': versions, 'apt_config_sha256': digest(apt_config()), 'dpkg_config_sha256': dpkg_config_fingerprint(), 'unit_profile_sha256': digest(sealed_read(APT_UNIT))} def attempt_binding(context): return {'transaction_sha256': context.transaction_sha256, 'job_payload_sha256': context.job_payload_sha256, 'grant_id': context.grant_id, 'attempt_id': context.attempt_id} def validate_retry_reference(ref): exact(ref, 'schema_version previous_grant_id previous_attempt_id bootstrap_marker_sha256') require(type(ref['schema_version']) is int and ref['schema_version'] == 1, 'RETRY_SCHEMA') for key in ('previous_grant_id', 'previous_attempt_id'): value = ref[key] require(type(value) is str and str(uuid.UUID(value)) == value, 'RETRY_ID') token(ref['bootstrap_marker_sha256'], HASH, 'RETRY_MARKER_HASH') def validate_recovery_reference(ref): exact(ref, 'schema_version previous_grant_id previous_attempt_id partial_proof_sha256') require(type(ref['schema_version']) is int and ref['schema_version'] == 1, 'RECOVERY_SCHEMA') for key in ('previous_grant_id', 'previous_attempt_id'): value = ref[key] require(type(value) is str and str(uuid.UUID(value)) == value and uuid.UUID(value).int != 0, 'RECOVERY_ID') token(ref['partial_proof_sha256'], HASH, 'RECOVERY_PROOF_HASH') def validate_partial_proof(proof): exact(proof, 'schema_version type transaction_sha256 job_payload_sha256 effect_armed_ledger_id ' 'grant_id job_id attempt_id authorization_id plan_sha256 original_evidence_sha256 ' 'original_baseline_sha256 observed_snapshot_sha256 status_fingerprint fixture_payload_sha256 ' 'snapshot checked_at_ms partial_effect postconditions_passed reboot_required') require(type(proof['schema_version']) is int and proof['schema_version'] == 1 and proof['type'] == 'rmm.apt.partial-reconciliation' and proof['partial_effect'] is True and proof['postconditions_passed'] is False and proof['reboot_required'] is False and type(proof['checked_at_ms']) is int and proof['checked_at_ms'] > 0, 'RECOVERY_PROOF_TYPE') for key in ('transaction_sha256', 'job_payload_sha256', 'plan_sha256', 'original_evidence_sha256', 'original_baseline_sha256', 'observed_snapshot_sha256', 'status_fingerprint', 'fixture_payload_sha256'): token(proof[key], HASH, 'RECOVERY_PROOF_HASH') for key in ('grant_id','job_id','attempt_id','authorization_id'): value = proof[key] require(type(value) is str and str(uuid.UUID(value)) == value and uuid.UUID(value).int != 0, 'RECOVERY_PROOF_ID') token(proof['effect_armed_ledger_id'], IDENT, 'RECOVERY_PROOF_LEDGER') require(type(proof['snapshot']) is dict and digest(canonical(proof['snapshot'])) == proof['observed_snapshot_sha256'] and proof['snapshot'].get('rmm-mvp-test:all') == {'version':'1.0','status':'install ok unpacked'} and proof['fixture_payload_sha256'] == digest(b'1.0\n'), 'RECOVERY_PROOF_SNAPSHOT') def verify_recovery_reference(transaction, context, action): """Only immutable linkage here; current state is checked before the hook. RootHelper additionally requires this proof in its original shared SQLite ledger with terminal classified failure and the original verified Request. Caller-provided JSON or a root-owned file alone never grants authority. """ ref = action['native_recovery']; validate_recovery_reference(ref) require(context.action == 'apt-native-acceptance' and context.execution_profile == 'dev-test' and action['schema_version'] == 4 and transaction.schema_version == 2 and transaction.operation == 'configure_only', 'RECOVERY_DEDICATED_ACTION') fixture_scope(transaction) raw_proof = sealed_read(ACTIVE / 'partial-proof.json') proof = json_bytes(raw_proof); validate_partial_proof(proof) require(raw_proof == canonical(proof) and digest(raw_proof) == ref['partial_proof_sha256'] and proof['grant_id'] == ref['previous_grant_id'] and proof['attempt_id'] == ref['previous_attempt_id'], 'RECOVERY_IMMUTABLE_PROOF_BINDING') require(context.grant_id != proof['grant_id'] and context.attempt_id != proof['attempt_id'] and context.job_id != proof['job_id'] and context.authorization_id != proof['authorization_id'] and context.plan_sha256 != proof['plan_sha256'], 'RECOVERY_NEW_APPROVAL_REQUIRED') require(transaction.baseline_sha256 == proof['observed_snapshot_sha256'] and transaction.status_fingerprint == proof['status_fingerprint'] and sealed_read(ACTIVE / 'baseline.json') == canonical(proof['snapshot']), 'RECOVERY_BASELINE_BINDING') previous = BASE / 'history' / ref['previous_grant_id'] secure_path(previous, directory=True, private=True) names = ('context.json','signed-action.json','expectation.json','baseline.json','launch.json', 'native-prechecks.json','sandbox-ready.json','sandbox-result.json','hook-armed.json') historical = {name: sealed_read(previous / name) for name in names} for prefix in ('bootstrap-attempt-', 'bootstrap-retry-'): name = prefix + 'rmm-apt-fixture-install-1.0.json' historical[name] = sealed_read(BASE / name) require(digest(canonical({name:digest(raw) for name,raw in historical.items()})) == proof['original_evidence_sha256'], 'RECOVERY_HISTORY_CHANGED') old = VerifiedHelperContext.parse(json_bytes(historical['context.json'])) require(all(getattr(old, key) == proof[key] for key in ('transaction_sha256','job_payload_sha256','effect_armed_ledger_id','grant_id', 'job_id','attempt_id','authorization_id','plan_sha256')) and digest(historical['signed-action.json']) == proof['job_payload_sha256'] and digest(historical['expectation.json']) == proof['transaction_sha256'] and digest(historical['baseline.json']) == proof['original_baseline_sha256'], 'RECOVERY_ORIGINAL_CONTEXT_BINDING') old_job = json_bytes(historical['signed-action.json']) new_job = json_bytes(sealed_read(ACTIVE / 'signed-action.json')) require(all(old_job[key] == new_job[key] for key in ('tenant_id','asset_id','agent_id','enrollment_generation','assignment_version')) and digest(sealed_read(previous / 'apt.conf')) == old_job['action']['apt_manifest']['apt_config_sha256'], 'RECOVERY_ORIGINAL_TARGET_OR_CONFIG') require(not os.path.lexists(BASE / 'acceptance-rmm-apt-fixture-install-1.0.json') and not os.path.lexists(BASE / 'pending-acceptance-rmm-apt-fixture-install-1.0.json'), 'RECOVERY_NOT_INSTALL_ACCEPTANCE') return proof def historical_retry_evidence(transaction, context, action): """Recheck immutable no-handoff evidence, never turn unknown into failed. The parent separately verifies its signed saved request and definitive HOOK_NOT_HANDED_OFF result in the SAME consumed ledger before this call. This evidence check cannot itself authorize a retry: the reference must be inside the NEW exact signed/UI-approved job payload and consumed attempt. """ ref = action['native_retry'] validate_retry_reference(ref) require(context.action == 'apt-native-acceptance' and context.execution_profile == 'dev-test' and context.grant_id != ref['previous_grant_id'] and context.attempt_id != ref['previous_attempt_id'], 'RETRY_NEW_APPROVED_ATTEMPT_REQUIRED') original_path = BASE / ('bootstrap-attempt-' + transaction.recipe_id + '.json') original_bytes = sealed_read(original_path) require(digest(original_bytes) == ref['bootstrap_marker_sha256'], 'RETRY_ORIGINAL_MARKER_HASH') previous = BASE / 'history' / ref['previous_grant_id'] secure_path(previous, directory=True, private=True) require(not os.path.lexists(previous / 'hook-armed.json') and not os.path.lexists(record_path(transaction)) and not os.path.lexists(BASE / ('pending-acceptance-' + transaction.recipe_id + '.json')), 'RETRY_PRIOR_EFFECT_OR_ACCEPTANCE') names = ('context.json', 'signed-action.json', 'expectation.json', 'baseline.json', 'launch.json', 'sandbox-result.json') raw = {name: sealed_read(previous / name) for name in names} old = VerifiedHelperContext.parse(json_bytes(raw['context.json'])) require(old.action == 'apt-native-acceptance' and old.execution_profile == 'dev-test' and old.grant_id == ref['previous_grant_id'] and old.attempt_id == ref['previous_attempt_id'] and json_bytes(original_bytes) == attempt_binding(old), 'RETRY_ORIGINAL_ATTEMPT_BINDING') require(digest(raw['signed-action.json']) == old.job_payload_sha256 and digest(raw['expectation.json']) == old.transaction_sha256, 'RETRY_PRIOR_PAYLOAD_HASH') old_tx = ResolvedAptTransaction.parse(json_bytes(raw['expectation.json'])) require(fixture_scope(old_tx) == fixture_scope(transaction) and old_tx.status_fingerprint == transaction.status_fingerprint and old_tx.baseline_sha256 == transaction.baseline_sha256, 'RETRY_BASELINE_OR_RECIPE_CHANGED') require(digest(canonical(json_bytes(raw['baseline.json']))) == old_tx.baseline_sha256 and raw['baseline.json'] == sealed_read(ACTIVE / 'baseline.json'), 'RETRY_COMPLETE_BASELINE') previous_job = json_bytes(raw['signed-action.json']) current_job = json_bytes(sealed_read(ACTIVE / 'signed-action.json')) require(all(previous_job[key] == current_job[key] for key in ('tenant_id', 'asset_id', 'agent_id', 'enrollment_generation', 'assignment_version')) and previous_job['job_id'] == old.job_id and previous_job['attempt_id'] == old.attempt_id and previous_job['execution_identity'] == 'root' and previous_job['action']['action'] == 'apt_native_acceptance', 'RETRY_DEVICE_OR_JOB_BINDING') old_manifest = previous_job['action']['apt_manifest'] require(old_manifest['schema_version'] == 2 and 'native_retry' not in old_manifest and old_manifest['transaction_sha256'] == old.transaction_sha256 and bytes(old_manifest['transaction_bytes']) == raw['expectation.json'] and old_manifest['resolved_apt_transaction'] == json_bytes(raw['expectation.json']), 'RETRY_ORIGINAL_SIGNED_TRANSACTION') require(json_bytes(raw['launch.json']) == { 'transaction_sha256': old.transaction_sha256, 'effect_armed_ledger_id': old.effect_armed_ledger_id} and json_bytes(raw['sandbox-result.json']) == { 'transaction_sha256': old.transaction_sha256, 'apt_exit_code': 100, 'reboot_required': False}, 'RETRY_KNOWN_PRE_HOOK_FAILURE_REQUIRED') require(context.job_id != old.job_id and context.authorization_id != old.authorization_id and context.plan_sha256 != old.plan_sha256, 'RETRY_NEW_APPROVAL_REQUIRED') return digest(canonical({name: digest(data) for name, data in raw.items()})) def bootstrap_binding(transaction, context, action): binding = attempt_binding(context) if action.get('native_recovery') is not None: verify_recovery_reference(transaction, context, action) binding.update(native_recovery=action['native_recovery']) return BASE / ('recovery-attempt-' + action['native_recovery']['previous_grant_id'] + '.json'), binding if action.get('native_retry') is not None: binding.update(native_retry=action['native_retry'], previous_evidence_sha256= historical_retry_evidence(transaction, context, action)) return BASE / ('bootstrap-retry-' + transaction.recipe_id + '.json'), binding return BASE / ('bootstrap-attempt-' + transaction.recipe_id + '.json'), binding def check_bootstrap_attempt(transaction, context, action=None): action = load_signed_action(transaction, context) if action is None else action path, binding = bootstrap_binding(transaction, context, action) require(json_bytes(sealed_read(path)) == binding, 'BOOTSTRAP_ATTEMPT_BINDING') def invalid_control_syscall_probes(): """Never pass valid reboot magic, valid kexec flags or valid kexec fds.""" seccomp = ctypes.CDLL('libseccomp.so.2') seccomp.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] seccomp.seccomp_syscall_resolve_name.restype = ctypes.c_int libc = ctypes.CDLL(None, use_errno=True) libc.syscall.restype = ctypes.c_long probes = [('reboot', (0, 0, 0, 0)), ('kexec_load', (0, 0, 0, ctypes.c_ulong(0xffffffffffffffff))), ('kexec_file_load', (-1, -1, 0, 0, ctypes.c_ulong(0xffffffffffffffff)))] for name, args in probes: number = seccomp.seccomp_syscall_resolve_name(name.encode('ascii')) require(number >= 0, 'PROBE_SYSCALL') ctypes.set_errno(0) result = libc.syscall(ctypes.c_long(number), *args) require(result == -1 and ctypes.get_errno() == errno.EPERM, 'SECCOMP_CONTROL_PROBE') return {'invalid_reboot_magic': 'EPERM', 'invalid_kexec_load_flags': 'EPERM', 'invalid_kexec_file_fds_flags': 'EPERM'} def frontend_lock_probe(config_path=None): """Real APT check (read-only), while this process holds the actual lock. Upstream apt-get.cc DoCheck only Cache.Open()/CheckDeps(), no dpkg/install. Never unlink a native lock, kill an owner, or use a simulated APT lock. """ path = secure_path(Path('/var/lib/dpkg/lock-frontend')) fd = os.open(path, os.O_RDWR | os.O_NOFOLLOW | os.O_CLOEXEC) try: try: fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: raise Veto('FRONTEND_LOCK_BUSY') from None data = run_read(['/usr/bin/apt-get', '-o', 'DPkg::Lock::Timeout=0', 'check'], env={**ENV, 'APT_CONFIG': str(config_path or ACTIVE / 'apt.conf')}, expected_returncode=100, merge_stderr=True, timeout=15) require(b'/var/lib/dpkg/lock-frontend' in data and (b'Could not get lock' in data or b'Unable to acquire' in data), 'NATIVE_APT_LOCK_CONFLICT_NOT_PROVEN') finally: os.close(fd) return 'native-apt-check-conflict' def sandbox_checks(workspace=None): workspace = ACTIVE if workspace is None else workspace inspect_sandbox(workspace) # Inspect mount flags, not a claim that setup commands probably worked. mounts = {} for line in Path('/proc/self/mountinfo').read_text().splitlines(): fields = line.split() separator = fields.index('-') mounts[fields[4]] = (set(fields[5].split(',')), fields[separator + 1]) for path in ('/sys', '/proc/sys', '/usr/lib/rmm-apt-transaction', str(BASE / 'archives')): require(path in mounts and 'ro' in mounts[path][0], 'NATIVE_READONLY_MOUNT') for path in ('/run', '/tmp', '/var/tmp', '/dev'): require(path in mounts and mounts[path][1] == 'tmpfs', 'NATIVE_PRIVATE_TMPFS') require(stat.S_ISCHR(Path('/proc/sysrq-trigger').stat().st_mode), 'NATIVE_SYSRQ_MASK') probes = invalid_control_syscall_probes() conflict = frontend_lock_probe() if workspace == ACTIVE else frontend_lock_probe(workspace / 'apt.conf') return {'namespaces_caps_nnp_seccomp': True, 'readonly_controlpaths': True, 'private_tmpfs_sockets': True, 'control_syscalls': probes, 'frontend_lock': conflict} def native_prechecks(context): checks = sandbox_checks() context.check_deadline() before, before_sha = load_host_reboot_before(context) return {'schema_version': 2, 'transaction_sha256': context.transaction_sha256, 'job_payload_sha256': context.job_payload_sha256, 'boot_id': context.boot_id, 'host_reboot_before_sha256': before_sha, 'host_reboot_required_before': before['host_reboot_required'], 'checks': checks} def capture_host_reboot_before(context): """Parent namespace only, BEFORE unshare replaces /run with private tmpfs.""" context.check_deadline() record = {'schema_version': 1, 'transaction_sha256': context.transaction_sha256, 'job_payload_sha256': context.job_payload_sha256, 'effect_armed_ledger_id': context.effect_armed_ledger_id, 'grant_id': context.grant_id, 'boot_id': context.boot_id, 'host_reboot_required': Path('/run/reboot-required').exists(), 'observed_at_ms': time.time_ns() // 1000000} durable_once(ACTIVE / 'host-reboot-before.json', record) context.check_deadline() def load_host_reboot_before(context): raw = sealed_read(ACTIVE / 'host-reboot-before.json') record = json_bytes(raw) exact(record, 'schema_version transaction_sha256 job_payload_sha256 effect_armed_ledger_id ' 'grant_id boot_id host_reboot_required observed_at_ms') require(raw == canonical(record) and type(record['schema_version']) is int and record['schema_version'] == 1 and all(record[key] == getattr(context, key) for key in ('transaction_sha256', 'job_payload_sha256', 'effect_armed_ledger_id', 'grant_id', 'boot_id')) and type(record['host_reboot_required']) is bool and type(record['observed_at_ms']) is int and context.not_before_ms <= record['observed_at_ms'] < context.start_before_ms and record['observed_at_ms'] <= time.time_ns() // 1000000, 'HOST_REBOOT_BEFORE_BINDING') return record, digest(raw) def verify_host_reboot_after(context, evidence): """Parent namespace observation; ambient true is honest pending evidence. The private worker must never introduce a reboot request. Equal HOST flags (including true/true) do not imply that a reboot was requested or performed. """ before, before_sha = load_host_reboot_before(context) after = Path('/run/reboot-required').exists() require(Path('/proc/sys/kernel/random/boot_id').read_text().strip() == context.boot_id, 'BOOT_CHANGED_DURING_TRANSACTION') child = json_bytes(sealed_read(ACTIVE / 'sandbox-result.json')) exact(child, 'transaction_sha256 apt_exit_code reboot_required') require(child['transaction_sha256'] == context.transaction_sha256 and type(child['apt_exit_code']) is int and child['apt_exit_code'] == 0 and child['reboot_required'] is False, 'FIXTURE_PRIVATE_REBOOT_FLAG_INTRODUCED') require(after == before['host_reboot_required'] and evidence['reboot_required'] is after, 'HOST_REBOOT_STATE_CHANGED_DURING_TRANSACTION') return {'host_reboot_required_before': before['host_reboot_required'], 'host_reboot_required_after': after, 'host_reboot_before_sha256': before_sha, 'reboot_required_introduced': False} def complete_acceptance(transaction, context, action, runtime, evidence): """Called only after real child success, armed hook AND independent verify.""" require(context.action == 'apt-native-acceptance' and context.execution_profile == 'dev-test', 'DEDICATED_HELPER_ACTION_REQUIRED') check_bootstrap_attempt(transaction, context, action) prechecks = json_bytes(sealed_read(ACTIVE / 'native-prechecks.json')) expected_checks = {'namespaces_caps_nnp_seccomp': True, 'readonly_controlpaths': True, 'private_tmpfs_sockets': True, 'control_syscalls': {'invalid_reboot_magic': 'EPERM', 'invalid_kexec_load_flags': 'EPERM', 'invalid_kexec_file_fds_flags': 'EPERM'}, 'frontend_lock': 'native-apt-check-conflict'} before, before_sha = load_host_reboot_before(context) require(prechecks == {'schema_version': 2, 'transaction_sha256': context.transaction_sha256, 'job_payload_sha256': context.job_payload_sha256, 'boot_id': context.boot_id, 'host_reboot_before_sha256': before_sha, 'host_reboot_required_before': before['host_reboot_required'], 'checks': expected_checks}, 'NATIVE_PRECHECKS_REQUIRED') evidence.update(verify_host_reboot_after(context, evidence)) require(runtime_identity() == runtime, 'RUNTIME_CHANGED_DURING_ACCEPTANCE') proof = {'schema_version': 3, 'scope': fixture_scope(transaction), 'runtime': runtime, 'test_acceptance': True, 'noProductionEvidence': True, 'test_result_id': action['test_result_id'], 'transaction_sha256': context.transaction_sha256, 'job_payload_sha256': context.job_payload_sha256, 'grant_id': context.grant_id, 'job_id': context.job_id, 'attempt_id': context.attempt_id, 'authorization_id': context.authorization_id, 'plan_sha256': context.plan_sha256, 'native_prechecks_sha256': digest(canonical(prechecks)), 'native_prechecks_schema_version': 2, 'host_reboot_before_sha256': before_sha, 'host_reboot_required_before': evidence['host_reboot_required_before'], 'host_reboot_required_after': evidence['host_reboot_required_after'], 'reboot_required_introduced': False, 'hook_marker_sha256': digest(sealed_read(ACTIVE / 'hook-armed.json')), 'postconditions_sha256': digest(canonical(evidence)), 'completed_at_ms': time.time_ns() // 1000000} # Stage+fsync complete bytes before publishing. Failed writes never leave a # parseable final partial record. An existing final record is never replaced. recovery = action.get('native_recovery') if recovery is not None: verify_recovery_reference(transaction, context, action) proof.update(schema_version=2, type='rmm.apt.native-recovery', operation='configure_only', native_recovery=recovery) path = BASE / ('recovery-' + recovery['previous_grant_id'] + '.json') staged = BASE / ('pending-recovery-' + recovery['previous_grant_id'] + '.json') else: path = record_path(transaction) staged = BASE / ('pending-acceptance-' + transaction.recipe_id + '.json') durable_once(staged, proof) linked = False try: os.link(staged, path, follow_symlinks=False) linked = True directory_fd = os.open(BASE, os.O_RDONLY | os.O_DIRECTORY) try: os.fsync(directory_fd) finally: os.close(directory_fd) except BaseException: if linked: path.unlink() raise # Retain staged bytes as an immutable record witness; never reset attempts. if recovery is not None: return {'test_acceptance': True, 'noProductionEvidence': True, 'native_recovery': True, 'recovery_record_sha256': digest(canonical(proof)), 'partial_proof_sha256': recovery['partial_proof_sha256'], 'test_result_id': action['test_result_id']} return {'test_acceptance': True, 'noProductionEvidence': True, 'native_record_sha256': digest(canonical(proof)), 'test_result_id': action['test_result_id']} @dataclass(frozen=True) class Action: name: str old_version: str old_arch: str old_multiarch: str direction: str new_version: str new_arch: str new_multiarch: str action: str def decode_config(value): require(not re.search(r'%(?![0-9A-Fa-f]{2})', value), 'CONFIG_ESCAPE') try: return unquote_to_bytes(value).decode('utf-8', 'strict') except UnicodeError: raise Veto('CONFIG_ENCODING') from None def parse_protocol3(data): """Real nine-field APT v3; config supports repeated unnamed list keys.""" require(type(data) is bytes and 0 < len(data) <= MAX_INPUT, 'INPUT_LIMIT') try: text = data.decode('ascii') except UnicodeError: raise Veto('PROTOCOL_ENCODING') from None require(text.endswith('\n') and not re.search(r'[\x00-\x09\x0b-\x1f\x7f]', text), 'PROTOCOL_CONTROL') lines = text.split('\n') require(lines.pop(0) == 'VERSION 3', 'PROTOCOL_VERSION') require('' in lines, 'CONFIG_TERMINATOR') config = [] while lines and lines[0] != '': line = lines.pop(0) require(len(line) <= 16384 and '=' in line, 'CONFIG_LINE') key, value = line.split('=', 1) require(key != '', 'CONFIG_KEY') config.append((decode_config(key), decode_config(value))) lines.pop(0) require(lines.pop() == '' and 0 < len(lines) <= MAX_PACKAGES * 2, 'ACTION_COUNT') actions = [] for line in lines: fields = line.split(' ') require(len(fields) == 9 and all(fields), 'ACTION_FIELDS') action = Action(*fields) token(action.name, NAME, 'PACKAGE_NAME') for version in (action.old_version, action.new_version): require(version == '-' or VERSION.fullmatch(version), 'VERSION') require(action.direction in ('<', '>', '='), 'DIRECTION') for arch in (action.old_arch, action.new_arch): require(arch in ('-', 'amd64', 'all'), 'ARCHITECTURE') for multiarch in (action.old_multiarch, action.new_multiarch): require(multiarch in ('none', 'no', 'same', 'foreign', 'allowed'), 'MULTIARCH') require((action.old_version == '-') == (action.old_arch == '-'), 'OLD_ARCH') require((action.new_version == '-') == (action.new_arch == '-'), 'NEW_ARCH') actions.append(action) return tuple(config), tuple(actions) def validate_actions(transaction, actions): if transaction.operation == 'configure_only': fixture_scope(transaction) require(len(actions) == 1 and actions[0] == Action( 'rmm-mvp-test', '1.0', 'all', 'none', '=', '1.0', 'all', 'none', '**CONFIGURE**'), 'RECOVERY_CONFIGURE_ACTION_ONLY') return expected = {(p.name, p.architecture): p for p in transaction.packages} seen = set() for action in actions: key = (action.name, action.new_arch) require(key in expected, 'EXTRA_ACTION') package = expected[key] require(action.old_version == (package.old_version or '-') and action.new_version == package.new_version and action.direction == '<' and action.old_arch == (package.architecture if package.old_version else '-'), 'ACTION_VERSION_ARCH') # APT expands one CONFIGURE for every install before sending the hook. kind = 'configure' if action.action == '**CONFIGURE**' else 'install' require(action.action == '**CONFIGURE**' or action.action == package.archive_path, 'ACTION_PATH_OR_REMOVAL') require((key, kind) not in seen, 'DUPLICATE_ACTION') seen.add((key, kind)) require(seen == {(key, kind) for key in expected for kind in ('install', 'configure')}, 'INCOMPLETE_TRANSACTION') def verify_archive(package): path = secure_path(package.archive_path) fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC) try: st = os.fstat(fd) archive_metadata(st, package.size) sha = hashlib.sha256() while True: chunk = os.read(fd, 65536) if not chunk: break sha.update(chunk) require(sha.hexdigest() == package.sha256, 'ARCHIVE_HASH') # Refer to our already opened inode, not a second path traversal. fields = run_read(['/usr/bin/dpkg-deb', '--show', '--showformat=${Package}\n${Version}\n${Architecture}\n' '${Essential}\n${Protected}\n${Conflicts}\n${Breaks}\n${Replaces}\n', '/proc/self/fd/' + str(fd)], limit=16384, pass_fds=(fd,)) values = fields.decode('utf-8', 'strict').splitlines() require(len(values) == 8 and values[:3] == [package.name, package.new_version, package.architecture] and values[3] in ('', 'no') and values[4] in ('', 'no') and values[5:] == ['', '', ''], 'DEB_CONTROL_OR_CONFLICT') payload = run_read(['/usr/bin/dpkg-deb', '--fsys-tarfile', '/proc/self/fd/' + str(fd)], limit=64 * MAX_INPUT, pass_fds=(fd,)) validate_payload(payload) finally: os.close(fd) def validate_payload(payload): """Reject boot/control-plane payloads even if the package has an innocent name.""" forbidden = ('boot', 'lib/modules', 'usr/lib/modules', 'etc/kernel', 'etc/apt', 'etc/systemd', 'usr/lib/systemd', 'lib/systemd', 'etc/init', 'etc/cron', 'var/spool/cron', 'usr/lib/rmm-apt-transaction', 'var/lib/rmm-apt-transaction', 'proc', 'sys', 'dev', 'run') try: with tarfile.open(fileobj=io.BytesIO(payload), mode='r:') as archive: count = 0 for entry in archive: count += 1 require(count <= 10000, 'DEB_PAYLOAD_LIMIT') name = entry.name if name.startswith('./'): name = name[2:] name = name.rstrip('/') require(not name.startswith('/') and '..' not in name.split('/'), 'DEB_PAYLOAD_PATH') require(not any(name == prefix or name.startswith(prefix + '/') or (prefix == 'etc/cron' and name.startswith(prefix)) for prefix in forbidden), 'DEB_PROTECTED_PATH') require(entry.isfile() or entry.isdir() or entry.issym(), 'DEB_PAYLOAD_TYPE') if entry.issym(): # Restrictive v1: no absolute or escaping package symlinks. require(not entry.linkname.startswith('/') and '..' not in entry.linkname.split('/'), 'DEB_SYMLINK_TARGET') except tarfile.TarError: raise Veto('DEB_PAYLOAD_FORMAT') from None def status_fingerprint(): """Resolver-relevant state, under native APT lock at hook time.""" updates = Path('/var/lib/dpkg/updates') require(not list(updates.iterdir()), 'DPKG_DIRTY_UPDATES') records = {} for path in (Path('/var/lib/dpkg/status'), Path('/var/lib/dpkg/arch'), Path('/var/lib/apt/extended_states')): records[str(path)] = digest(sealed_read(path, 64 * MAX_INPUT)) if path.exists() else None triggers = Path('/var/lib/dpkg/triggers') for path in sorted(triggers.iterdir()): if path.name != 'Lock': records[str(path)] = digest(sealed_read(path, 16 * MAX_INPUT)) require(not (triggers / 'Unincorp').read_bytes(), 'DPKG_PENDING_TRIGGERS') return digest(canonical(records)) def dpkg_config_fingerprint(): # dpkg has its own global configuration, independent of APT_CONFIG. Its # exact contents require administrator review in the native acceptance. records = {} paths = [Path('/etc/dpkg/dpkg.cfg')] directory = Path('/etc/dpkg/dpkg.cfg.d') if directory.exists(): secure_path(directory, directory=True) paths.extend(sorted(directory.iterdir())) for path in paths: records[str(path)] = digest(sealed_read(path)) if path.exists() else None return digest(canonical(records)) def installed_snapshot(): data = run_read(['/usr/bin/dpkg-query', '--show', '--showformat=${Package}\t${Architecture}\t${Version}\t${Status}\n'], limit=32 * MAX_INPUT) snapshot = {} for line in data.decode('utf-8', 'strict').splitlines(): fields = line.split('\t') require(len(fields) == 4, 'DPKG_QUERY_FORMAT') name, arch, version, status = fields key = name + ':' + arch require(key not in snapshot, 'DPKG_QUERY_DUPLICATE') require(status in ('install ok installed', 'deinstall ok config-files', 'purge ok not-installed', 'unknown ok not-installed'), 'DPKG_INCONSISTENT') snapshot[key] = {'version': version, 'status': status} return snapshot def check_current_baseline(transaction, baseline): require(digest(canonical(baseline)) == transaction.baseline_sha256, 'BASELINE_HASH') require(status_fingerprint() == transaction.status_fingerprint, 'STATUS_FINGERPRINT') snapshot = partial_installed_snapshot() if transaction.operation == 'configure_only' else installed_snapshot() require(snapshot == baseline, 'STATUS_BASELINE_CHANGED') if transaction.operation == 'configure_only': fixture_scope(transaction) require(baseline.get('rmm-mvp-test:all') == {'version': '1.0', 'status': 'install ok unpacked'} and sealed_read(Path('/usr/share/rmm-mvp-test/version'), limit=32) == b'1.0\n', 'RECOVERY_PARTIAL_PRECONDITION') def check_preconditions(transaction, baseline): check_current_baseline(transaction, baseline) for p in transaction.packages: current = baseline.get(p.name + ':' + p.architecture) require((current is None if p.old_version is None else current == {'version': p.old_version, 'status': 'install ok unpacked' if transaction.operation == 'configure_only' else 'install ok installed'}), 'PACKAGE_PRECONDITION') def apt_config(): """Constant bytes: no job string, URL, shell interpolation, global hooks.""" # APT's default selection rewrite erases explicit Configure operations and # substitutes --configure --pending. Keep the exact target Configure instead # while both pending modes remain disabled (upstream dpkgpm.cc, APT 2.7.14). return ('''Dir::Etc::parts "/var/lib/rmm-apt-transaction/active/empty"; Dir::Etc::main "/dev/null"; Dir::Etc::sourcelist "/dev/null"; Dir::Etc::sourceparts "/var/lib/rmm-apt-transaction/active/empty"; Dir::Etc::preferences "/dev/null"; Dir::Etc::preferencesparts "/var/lib/rmm-apt-transaction/active/empty"; Dir::State::status "/var/lib/dpkg/status"; Dir::State::lists "/var/lib/rmm-apt-transaction/active/lists"; Dir::Cache::archives "/var/lib/rmm-apt-transaction/active/cache"; Dir::Cache::pkgcache ""; Dir::Cache::srcpkgcache ""; Dir::Bin::dpkg "/usr/bin/dpkg"; Dir::Log "/var/lib/rmm-apt-transaction/log"; Dir::Log::Terminal "term.log"; Dir::Log::History "history.log"; Dir::State::extended_states "/var/lib/rmm-apt-transaction/state/extended_states"; DPkg::Options { "--log=/var/lib/rmm-apt-transaction/log/dpkg.log"; }; APT::Architecture "amd64"; APT::Architectures { "amd64"; }; APT::Install-Recommends "false"; APT::Install-Suggests "false"; APT::Get::AutomaticRemove "false"; APT::Get::Fix-Broken "false"; APT::Get::Fix-Missing "false"; APT::Get::Download "true"; APT::Get::allow-Downgrades "false"; APT::Get::allow-Remove-Essential "false"; DPkg::Lock::Timeout "10"; DPkg::ConfigurePending "false"; DPkg::TriggersPending "false"; dpkg::selection::remove::approved "false"; DPkg::Inhibit-Shutdown "false"; DPkg::Use-Pty "false"; DPkg::Pre-Install-Pkgs { "/usr/lib/rmm-apt-transaction/hook"; }; DPkg::Tools::Options::/usr/lib/rmm-apt-transaction/hook::Version "3"; DPkg::Tools::Options::/usr/lib/rmm-apt-transaction/hook::InfoFD "0"; ''').encode('ascii') def apt_argv(transaction): if transaction.operation == 'configure_only': fixture_scope(transaction) return ['/usr/bin/apt-get', '--yes', '--no-remove', '--no-install-recommends', 'install', '--', 'rmm-mvp-test=1.0'] # APT's --no-download also prevents the local file method from resolving # its Install filename (v3 emits **ERROR**). Permit local acquisition of # the already sealed/hash-checked archive. Empty sources, fixed paths and # the verified AF_UNIX-only private worker still forbid network retrieval. return ['/usr/bin/apt-get', '--yes', '--no-remove', '--no-install-recommends', 'install', '--'] + [p.archive_path for p in transaction.packages] def check_hook_config(config): hooks = [(key.lower(), value) for key, value in config if key.lower().startswith(('dpkg::pre-', 'dpkg::post-')) and value] require(hooks == [('dpkg::pre-install-pkgs::', HOOK)], 'HOOK_CONFIG') for key, expected in ( ('dpkg::tools::options::' + HOOK + '::version', '3'), ('dpkg::tools::options::' + HOOK + '::infofd', '0'), ('dir::bin::dpkg', '/usr/bin/dpkg'), ('dir::state::status', '/var/lib/dpkg/status'), ('dpkg::configurepending', 'false'), ('dpkg::triggerspending', 'false'), ('dpkg::selection::remove::approved', 'false')): require([value for name, value in config if name.lower() == key] == [expected], 'APT_CONFIG_BINDING') def load_active(): secure_path(ACTIVE, directory=True, private=True) raw = sealed_read(ACTIVE / 'expectation.json') transaction = ResolvedAptTransaction.parse(json_bytes(raw)) context = VerifiedHelperContext.parse(json_bytes(sealed_read(ACTIVE / 'context.json'))) require(digest(raw) == context.transaction_sha256, 'TRANSACTION_BINDING') baseline = json_bytes(sealed_read(ACTIVE / 'baseline.json')) return transaction, context, baseline def hook(): require(os.geteuid() == 0, 'ROOT_REQUIRED') require(os.environ.get('APT_HOOK_INFO_FD') == '0' and os.environ.get('DPKG_FRONTEND_LOCKED') == 'true', 'NATIVE_APT_HOOK_REQUIRED') transaction, context, baseline = load_active() action = load_signed_action(transaction, context) native_acceptance = context.action == 'apt-native-acceptance' check_native_gate(transaction, context, action, runtime_identity(), native_acceptance) if native_acceptance: check_bootstrap_attempt(transaction, context, action) ready = json_bytes(sealed_read(ACTIVE / 'sandbox-ready.json')) require(ready == {'transaction_sha256': context.transaction_sha256, 'sandbox_version': 1}, 'SANDBOX_HANDSHAKE') inspect_sandbox() config, actions = parse_protocol3(sys.stdin.buffer.read(MAX_INPUT + 1)) check_hook_config(config) validate_actions(transaction, actions) check_preconditions(transaction, baseline) for package in transaction.packages: verify_archive(package) # Last gate AFTER hashing/read checks. Deadline applies before first dpkg. context.check_deadline() durable_once(ACTIVE / 'hook-armed.json', { 'effect_armed_ledger_id': context.effect_armed_ledger_id, 'grant_id': context.grant_id, 'transaction_sha256': context.transaction_sha256, 'protocol_sha256': digest(canonical([a.__dict__ for a in actions])), 'armed_at_ms': time.time_ns() // 1000000}) # File/directory fsync can outlive the startgrant. Veto before returning # success to APT; retain the armed marker for conservative reconciliation, # never reset it or permit another handoff after this uncertain boundary. context.check_deadline() def seccomp_filter(): # libseccomp resolves native syscall numbers; no hardcoded x86 syscall IDs. lib = ctypes.CDLL('libseccomp.so.2', use_errno=True) lib.seccomp_init.argtypes = [ctypes.c_uint32] lib.seccomp_init.restype = ctypes.c_void_p lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] lib.seccomp_syscall_resolve_name.restype = ctypes.c_int lib.seccomp_rule_add.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.c_int, ctypes.c_uint] lib.seccomp_load.argtypes = [ctypes.c_void_p] lib.seccomp_release.argtypes = [ctypes.c_void_p] class ArgCompare(ctypes.Structure): _fields_ = [('arg', ctypes.c_uint), ('op', ctypes.c_uint), ('datum_a', ctypes.c_uint64), ('datum_b', ctypes.c_uint64)] lib.seccomp_rule_add_array.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.c_int, ctypes.c_uint, ctypes.POINTER(ArgCompare)] ctx = lib.seccomp_init(0x7fff0000) # SCMP_ACT_ALLOW require(bool(ctx), 'SECCOMP_INIT') try: for name in ('reboot', 'kexec_load', 'kexec_file_load', 'mount', 'umount2', 'pivot_root', 'chroot', 'unshare', 'setns', 'fsopen', 'fsconfig', 'fsmount', 'move_mount', 'open_tree', 'mount_setattr', 'ptrace', 'process_vm_writev', 'bpf', 'init_module', 'finit_module', 'delete_module', 'swapon', 'swapoff', 'iopl', 'ioperm'): number = lib.seccomp_syscall_resolve_name(name.encode('ascii')) require(number >= 0, 'SECCOMP_SYSCALL_UNAVAILABLE') require(lib.seccomp_rule_add(ctx, 0x50000 | errno.EPERM, number, 0) == 0, 'SECCOMP_RULE') # clone3 has pointer-based flags: deny with ENOSYS so libc can fall back # to ordinary clone/fork. clone's namespace flags are explicitly denied, # including NEWUSER/NEWTIME, not just flags requiring CAP_SYS_ADMIN. clone3 = lib.seccomp_syscall_resolve_name(b'clone3') clone = lib.seccomp_syscall_resolve_name(b'clone') require(clone3 >= 0 and clone >= 0, 'SECCOMP_CLONE_ABI') require(lib.seccomp_rule_add(ctx, 0x50000 | errno.ENOSYS, clone3, 0) == 0, 'SECCOMP_CLONE3') for flag in (0x80, 0x20000, 0x2000000, 0x4000000, 0x8000000, 0x10000000, 0x20000000, 0x40000000): compare = ArgCompare(0, 7, flag, flag) # SCMP_CMP_MASKED_EQ require(lib.seccomp_rule_add_array(ctx, 0x50000 | errno.EPERM, clone, 1, ctypes.byref(compare)) == 0, 'SECCOMP_CLONE_FLAGS') require(lib.seccomp_load(ctx) == 0, 'SECCOMP_LOAD') finally: lib.seccomp_release(ctx) def drop_capabilities(): libc = ctypes.CDLL(None, use_errno=True) # Keep only filesystem ownership/access and uid/gid capabilities needed by # dpkg. No KILL, SYS_ADMIN, SYS_BOOT, SYS_PTRACE, SYS_RAWIO, NET_ADMIN, MKNOD. allowed = {0, 1, 3, 4, 6, 7, 8, 31} # CHOWN,DAC_OVERRIDE,FOWNER,FSETID,SETGID,SETUID,SETPCAP,SETFCAP last = int(Path('/proc/sys/kernel/cap_last_cap').read_text()) require(last < 64, 'CAPABILITY_ABI') for number in range(last + 1): if number not in allowed: require(libc.prctl(24, number, 0, 0, 0) == 0, 'CAP_BOUNDING_DROP') class Header(ctypes.Structure): _fields_ = [('version', ctypes.c_uint32), ('pid', ctypes.c_int)] class Data(ctypes.Structure): _fields_ = [('effective', ctypes.c_uint32), ('permitted', ctypes.c_uint32), ('inheritable', ctypes.c_uint32)] mask = sum(1 << cap for cap in allowed) header = Header(0x20080522, 0) values = (Data * 2)(Data(mask & 0xffffffff, mask & 0xffffffff, 0), Data(0, 0, 0)) require(libc.capset(ctypes.byref(header), values) == 0, 'CAPSET') require(libc.prctl(38, 1, 0, 0, 0) == 0, 'NO_NEW_PRIVILEGES') def mount(argv): require(subprocess.run(['/usr/bin/mount'] + argv, env=ENV, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0, 'SANDBOX_MOUNT') def inspect_sandbox(workspace=None): """Check inherited kernel enforcement inside worker AND hook.""" status = dict(line.split(':', 1) for line in Path('/proc/self/status').read_text().splitlines() if ':' in line) require(status['NoNewPrivs'].strip() == '1' and status['Seccomp'].strip() == '2', 'SANDBOX_SECCOMP') for key in ('CapEff', 'CapPrm', 'CapBnd'): caps = int(status[key].strip(), 16) require(caps == sum(1 << n for n in (0, 1, 3, 4, 6, 7, 8, 31)), 'SANDBOX_CAPS') require(int(status['CapInh'].strip(), 16) == 0 and int(status['CapAmb'].strip(), 16) == 0, 'SANDBOX_INHERITED_CAPS') verify_no_ip_sockets() # Host PID1 must not be visible. Namespace PID1 is this trusted Python worker. require(Path('/proc/1/cmdline').read_bytes().startswith(b'/usr/bin/python3\x00-I\x00'), 'SANDBOX_PID1') require(not any(Path(path).exists() for path in ( '/run/systemd/private', '/run/dbus/system_bus_socket', '/run/rmm/privileged-helper.sock', '/var/run/dbus/system_bus_socket')), 'SANDBOX_HOST_SOCKETS') require(not Path('/var/lib/rmm-helper/consumption.sqlite').exists() and not Path('/etc/rmm/helper.json').exists() and not Path('/etc/rmm/apt-helper.json').exists(), 'SANDBOX_LEDGER_OR_KEYS_VISIBLE') inspect_private_control_paths() # Parent gives us the original namespace identities; cannot accept flags alone. workspace = ACTIVE if workspace is None else workspace ids = json_bytes(sealed_read(workspace / 'host-namespaces.json')) for name in ('pid', 'mnt', 'net'): require(os.readlink('/proc/self/ns/' + name) != ids[name], 'SANDBOX_NAMESPACE') def verify_no_ip_sockets(): """Kernel enforcement, not a no-download flag or a network configuration claim.""" for family in (socket.AF_INET, socket.AF_INET6): try: candidate = socket.socket(family, socket.SOCK_STREAM) except OSError as error: require(error.errno in (errno.EAFNOSUPPORT, errno.EPERM, errno.EACCES), 'SANDBOX_IP_SOCKET_CHECK') else: candidate.close() raise Veto('SANDBOX_IP_SOCKET_ALLOWED') def inspect_private_control_paths(): # Validate directory contents rather than guessing future key filenames. # Both historical and current cloud identity/config layouts must be hidden. for name in PRIVATE_CONTROL_DIRECTORIES: path = Path(name) require(not path.is_symlink() and (not path.exists() or (path.is_dir() and next(path.iterdir(), None) is None)), 'SANDBOX_LEDGER_OR_KEYS_VISIBLE') def setup_sandbox(workspace=None, probe_db=None): """One trusted setup implementation for real jobs AND read-only probes.""" workspace = ACTIVE if workspace is None else workspace require(os.geteuid() == 0 and os.getpid() == 1, 'SANDBOX_NAMESPACE') for fd in os.listdir('/proc/self/fd'): if int(fd) > 2: try: os.close(int(fd)) except OSError as error: require(error.errno == errno.EBADF, 'SANDBOX_INHERITED_FD') # unshare makes a private mount namespace; never propagate these mounts. mount(['--make-rprivate', '/']) if probe_db is not None: mount(['--bind', str(probe_db), '/var/lib/dpkg']) # Neither the signed-key/config files nor shared SQLite/flock inodes are # available to the package child. Only the outside root controller sees them. for hidden in ('/etc/rmm', '/var/lib/rmm-helper'): require(Path(hidden).is_dir(), 'SANDBOX_PRIVATE_CONTROL_PATH_REQUIRED') for hidden in (*PRIVATE_CONTROL_DIRECTORIES, '/home', '/root'): if Path(hidden).is_dir(): require(not Path(hidden).is_symlink(), 'SANDBOX_PRIVATE_CONTROL_PATH_REQUIRED') mount(['-t', 'tmpfs', '-o', 'mode=0700,nosuid,nodev,noexec', 'tmpfs', hidden]) # Hide ALL conventional host control sockets, not merely systemctl binaries. mount(['-t', 'tmpfs', '-o', 'mode=0755,nosuid,nodev,noexec', 'tmpfs', '/run']) mount(['-t', 'tmpfs', '-o', 'mode=1777,nosuid,nodev', 'tmpfs', '/tmp']) mount(['-t', 'tmpfs', '-o', 'mode=1777,nosuid,nodev', 'tmpfs', '/var/tmp']) mount(['-t', 'tmpfs', '-o', 'mode=0755,nosuid,noexec', 'tmpfs', '/dev']) # Bind only basic devices from proc fd? /dev was hidden, so use mknod while # CAP_MKNOD is still held; no block devices or consoles are exposed. for name, mode, major, minor in (('null', 0o666, 1, 3), ('zero', 0o666, 1, 5), ('random', 0o666, 1, 8), ('urandom', 0o666, 1, 9)): os.mknod('/dev/' + name, stat.S_IFCHR | mode, os.makedev(major, minor)) os.symlink('/proc/self/fd', '/dev/fd') for path in ('/sys', '/proc/sys', '/proc/irq', '/proc/bus', '/boot', '/usr/lib/rmm-apt-transaction', str(BASE / 'archives'), '/etc/systemd', '/usr/lib/systemd', '/etc/cron.d', '/etc/crontab', '/etc/cron.daily', '/etc/cron.hourly', '/etc/cron.weekly', '/etc/cron.monthly', '/var/spool/cron'): if Path(path).exists(): mount(['--bind', path, path]) mount(['-o', 'remount,bind,ro,nosuid,nodev', path]) for path in ('/proc/sysrq-trigger', '/proc/kcore', '/proc/keys', '/proc/timer_list'): if Path(path).exists(): mount(['--bind', '/dev/null', path]) drop_capabilities() seccomp_filter() inspect_sandbox(workspace) def sandbox_worker(): transaction, context, _ = load_active() action = load_signed_action(transaction, context) check_native_gate(transaction, context, action, runtime_identity(), context.action == 'apt-native-acceptance') if context.action == 'apt-native-acceptance': check_bootstrap_attempt(transaction, context, action) setup_sandbox() # Executed natively in the actual mutation sandbox, never synthesized by # the parent or by a bootstrap flag. Also required for record-backed runs. durable_once(ACTIVE / 'native-prechecks.json', native_prechecks(context)) durable_once(ACTIVE / 'sandbox-ready.json', { 'transaction_sha256': context.transaction_sha256, 'sandbox_version': 1}) context.check_deadline() # Never timeout/kill an active package manager. Parent journals unknown on # transport/process loss; it must not retry. Native lock wait itself is 10s. proc = subprocess.Popen(apt_argv(transaction), env={**ENV, 'APT_CONFIG': str(ACTIVE / 'apt.conf')}, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) code = proc.wait() # As namespace PID1, do not exit and implicitly SIGKILL any orphaned dpkg # child if APT itself died. Reap/wait for all adopted descendants first. while True: try: os.waitpid(-1, 0) except ChildProcessError: break # /run is private: export this observation before the namespace disappears. # Parent also checks the host flag; neither observation initiates a reboot. durable_once(ACTIVE / 'sandbox-result.json', { 'transaction_sha256': context.transaction_sha256, 'apt_exit_code': code, 'reboot_required': Path('/run/reboot-required').exists()}) os._exit(0 if code == 0 else 100) def verify_after(transaction, baseline): observed = installed_snapshot() expected = dict(baseline) for package in transaction.packages: expected[package.name + ':' + package.architecture] = { 'version': package.new_version, 'status': 'install ok installed'} require(observed == expected, 'POSTCONDITION_OR_UNEXPECTED_CHANGE') require(run_read(['/usr/bin/dpkg', '--audit'], limit=MAX_INPUT) == b'', 'DPKG_AUDIT') evidence = {'snapshot_sha256': digest(canonical(observed)), 'reboot_required': Path('/run/reboot-required').exists(), 'packages': [{'name': p.name, 'architecture': p.architecture, 'version': p.new_version} for p in transaction.packages]} if transaction.recipe_id in FIXTURE_RECIPES: fixture_scope(transaction) data = sealed_read(Path('/usr/share/rmm-mvp-test/version'), limit=32) require(data == (transaction.packages[0].new_version + '\n').encode('ascii'), 'FIXTURE_PAYLOAD_POSTCONDITION') evidence['fixture_payload_sha256'] = digest(data) return evidence def partial_installed_snapshot(): """Readonly original-job verification, never a general planning baseline. Only this exact script/trigger/dependency-free fixture may be unpacked. Normal inventory/planning/execution keep rejecting inconsistent dpkg state. """ data = run_read(['/usr/bin/dpkg-query', '--show', '--showformat=${Package}\t${Architecture}\t${Version}\t${Status}\n'], limit=32 * MAX_INPUT) snapshot = {} for line in data.decode('utf-8', 'strict').splitlines(): fields = line.split('\t') require(len(fields) == 4, 'DPKG_QUERY_FORMAT') name, arch, version, status = fields key = name + ':' + arch require(key not in snapshot, 'DPKG_QUERY_DUPLICATE') ordinary = status in ('install ok installed', 'deinstall ok config-files', 'purge ok not-installed', 'unknown ok not-installed') partial = key == 'rmm-mvp-test:all' and version == '1.0' and status == 'install ok unpacked' require(ordinary or partial, 'PARTIAL_OTHER_INCONSISTENT_PACKAGE') snapshot[key] = {'version': version, 'status': status} return snapshot def verify_partial(request): """Recheck ONLY the fixed original job's postcondition, with no mutation. RootHelper independently verifies its historical signed Request and the unresolved consumed row first. These caller bindings are not authority to execute: this mode has no APT/dpkg effect call or writable metadata path. Current code/config/runtime need not equal the historical execution runtime; original signed bytes and original apt.conf remain immutable evidence. """ require(os.geteuid() == 0, 'ROOT_REQUIRED') fields = ('transaction_sha256 job_payload_sha256 effect_armed_ledger_id grant_id ' 'job_id attempt_id authorization_id plan_sha256') exact(request, fields) for key in ('transaction_sha256', 'job_payload_sha256', 'plan_sha256'): token(request[key], HASH, 'PARTIAL_REQUEST_HASH') token(request['effect_armed_ledger_id'], IDENT, 'PARTIAL_REQUEST_LEDGER') for key in ('grant_id', 'job_id', 'attempt_id', 'authorization_id'): value = request[key] require(type(value) is str and str(uuid.UUID(value)) == value and uuid.UUID(value).int != 0, 'PARTIAL_REQUEST_ID') secure_path(BASE, directory=True, private=True) secure_path(ACTIVE, directory=True, private=True) names = ('context.json', 'signed-action.json', 'expectation.json', 'baseline.json', 'launch.json', 'native-prechecks.json', 'sandbox-ready.json', 'sandbox-result.json', 'hook-armed.json') raw = {name: sealed_read(ACTIVE / name) for name in names} ctx = VerifiedHelperContext.parse(json_bytes(raw['context.json'])) require(ctx.action == 'apt-native-acceptance' and ctx.execution_profile == 'dev-test' and all(getattr(ctx, key) == request[key] for key in fields.split()), 'PARTIAL_CONTEXT_BINDING') require(Path('/proc/sys/kernel/random/boot_id').read_text().strip() == ctx.boot_id, 'PARTIAL_BOOT_CHANGED') require(digest(raw['signed-action.json']) == ctx.job_payload_sha256 and digest(raw['expectation.json']) == ctx.transaction_sha256, 'PARTIAL_SIGNED_BYTES') tx = ResolvedAptTransaction.parse(json_bytes(raw['expectation.json'])) fixture_scope(tx) require(tx.recipe_id == 'rmm-apt-fixture-install-1.0', 'PARTIAL_FIXED_INSTALL_ONLY') baseline = json_bytes(raw['baseline.json']) require(type(baseline) is dict and raw['baseline.json'] == canonical(baseline) and digest(raw['baseline.json']) == tx.baseline_sha256 and 'rmm-mvp-test:all' not in baseline, 'PARTIAL_ORIGINAL_BASELINE') job = json_bytes(raw['signed-action.json']) exact(job, 'schema_version tenant_id asset_id agent_id enrollment_generation assignment_version ' 'job_id attempt_id action execution_identity not_before start_before max_runtime_seconds max_output_bytes') require(type(job['schema_version']) is int and job['schema_version'] == 1 and job['job_id'] == ctx.job_id and job['attempt_id'] == ctx.attempt_id and job['execution_identity'] == 'root', 'PARTIAL_ORIGINAL_JOB') outer = job['action'] exact(outer, 'action recipe_id recipe_version apt_manifest') require(outer['action'] == 'apt_native_acceptance' and outer['recipe_id'] == tx.recipe_id and outer['recipe_version'] == tx.recipe_version, 'PARTIAL_ORIGINAL_ACTION') action = outer['apt_manifest'] exact(action, 'type schema_version action execution_profile transaction_sha256 ' 'resolved_apt_transaction provider_sha256 hook_sha256 apt_config_sha256 ' 'runtime_sha256 test_result_id transaction_bytes native_retry') require(action['type'] == 'rmm.apt.helper-action' and type(action['schema_version']) is int and action['schema_version'] == 3 and action['action'] == ctx.action and action['execution_profile'] == ctx.execution_profile and action['transaction_sha256'] == ctx.transaction_sha256 and canonical(action['resolved_apt_transaction']) == canonical(json_bytes(raw['expectation.json'])) and type(action['transaction_bytes']) is list and all(type(n) is int and 0 <= n <= 255 for n in action['transaction_bytes']) and bytes(action['transaction_bytes']) == raw['expectation.json'], 'PARTIAL_ORIGINAL_MANIFEST') for key in ('provider_sha256', 'hook_sha256', 'apt_config_sha256', 'runtime_sha256'): token(action[key], HASH, 'PARTIAL_ORIGINAL_RUNTIME_HASH') token(action['test_result_id'], IDENT, 'PARTIAL_ORIGINAL_TEST_ID') require(digest(sealed_read(ACTIVE / 'apt.conf')) == action['apt_config_sha256'], 'PARTIAL_ORIGINAL_CONFIG') # This reuses only immutable historical binding checks, never the current # executable gate or an acceptance publication. It also verifies both once # markers and the original failed no-handoff history referenced by retry. check_bootstrap_attempt(tx, ctx, action) for prefix in ('bootstrap-attempt-', 'bootstrap-retry-'): name = prefix + tx.recipe_id + '.json' raw[name] = sealed_read(BASE / name) for prefix in ('acceptance-', 'pending-acceptance-'): require(not os.path.lexists(BASE / (prefix + tx.recipe_id + '.json')), 'PARTIAL_ACCEPTANCE_ALREADY_EXISTS') require(canonical(json_bytes(raw['launch.json'])) == canonical({ 'transaction_sha256': ctx.transaction_sha256, 'effect_armed_ledger_id': ctx.effect_armed_ledger_id}), 'PARTIAL_LAUNCH_BINDING') prechecks = {'schema_version': 1, 'transaction_sha256': ctx.transaction_sha256, 'job_payload_sha256': ctx.job_payload_sha256, 'boot_id': ctx.boot_id, 'checks': {'namespaces_caps_nnp_seccomp': True, 'readonly_controlpaths': True, 'private_tmpfs_sockets': True, 'control_syscalls': {'invalid_reboot_magic': 'EPERM', 'invalid_kexec_load_flags': 'EPERM', 'invalid_kexec_file_fds_flags': 'EPERM'}, 'frontend_lock': 'native-apt-check-conflict'}} require(canonical(json_bytes(raw['native-prechecks.json'])) == canonical(prechecks) and canonical(json_bytes(raw['sandbox-ready.json'])) == canonical({ 'sandbox_version': 1, 'transaction_sha256': ctx.transaction_sha256}) and canonical(json_bytes(raw['sandbox-result.json'])) == canonical({ 'transaction_sha256': ctx.transaction_sha256, 'apt_exit_code': 0, 'reboot_required': False}), 'PARTIAL_NATIVE_COMPLETION_REQUIRED') marker = json_bytes(raw['hook-armed.json']) exact(marker, 'armed_at_ms effect_armed_ledger_id grant_id protocol_sha256 transaction_sha256') require(marker['effect_armed_ledger_id'] == ctx.effect_armed_ledger_id and marker['grant_id'] == ctx.grant_id and marker['transaction_sha256'] == ctx.transaction_sha256 and type(marker['armed_at_ms']) is int and ctx.not_before_ms <= marker['armed_at_ms'] < ctx.start_before_ms, 'PARTIAL_HOOK_BINDING') token(marker['protocol_sha256'], HASH, 'PARTIAL_HOOK_PROTOCOL_HASH') require(not observe_host_frontend_lock() and not observe_host_frontend_lock(Path('/var/lib/dpkg/lock')), 'FOREIGN_PACKAGE_LOCK') fingerprint = status_fingerprint() observed = partial_installed_snapshot() expected = dict(baseline) expected['rmm-mvp-test:all'] = {'version': '1.0', 'status': 'install ok unpacked'} require(observed == expected, 'PARTIAL_UNEXPECTED_PACKAGE_CHANGE') verify_archive(tx.packages[0]) payload = sealed_read(Path('/usr/share/rmm-mvp-test/version'), limit=32) require(payload == b'1.0\n', 'PARTIAL_FIXTURE_PAYLOAD') require(status_fingerprint() == fingerprint and partial_installed_snapshot() == observed and not observe_host_frontend_lock() and not observe_host_frontend_lock(Path('/var/lib/dpkg/lock')), 'PARTIAL_STATE_CHANGED') # Re-read the historical witnesses too: a stable live package projection # cannot compensate for changed/tampered original evidence. for name, data in raw.items(): path = ACTIVE / name if name in names else BASE / name require(sealed_read(path) == data, 'PARTIAL_HISTORICAL_EVIDENCE_CHANGED') proof = dict(schema_version=1, type='rmm.apt.partial-reconciliation', **request, original_evidence_sha256=digest(canonical({name: digest(data) for name, data in raw.items()})), original_baseline_sha256=tx.baseline_sha256, observed_snapshot_sha256=digest(canonical(observed)), status_fingerprint=fingerprint, fixture_payload_sha256=digest(payload), snapshot=observed, checked_at_ms=time.time_ns() // 1000000, partial_effect=True, postconditions_passed=False, reboot_required=False) result = dict(effect_state='known_failed', code='APT_PARTIAL_UNCONFIGURED_VERIFIED', proof=proof) require(len(canonical(result)) <= MAX_INPUT, 'PARTIAL_PROOF_LIMIT') return result def verify_configured_recovery(request): """Readonly classification of the ONE historical schema-4 attempt. Rust independently checks the original signed Request, immutable ledger unknown code and the closed original partial proof. No host-before sample exists for this old runtime: even complete package effects NEVER become a retroactive acceptance or success. No package mutation or metadata write. """ require(os.geteuid() == 0, 'ROOT_REQUIRED') fields = ('transaction_sha256 job_payload_sha256 effect_armed_ledger_id grant_id ' 'job_id attempt_id authorization_id plan_sha256') exact(request, fields) for key in ('transaction_sha256', 'job_payload_sha256', 'plan_sha256'): token(request[key], HASH, 'CONFIGURED_REQUEST_HASH') token(request['effect_armed_ledger_id'], IDENT, 'CONFIGURED_REQUEST_LEDGER') for key in ('grant_id', 'job_id', 'attempt_id', 'authorization_id'): value = request[key] require(type(value) is str and str(uuid.UUID(value)) == value and uuid.UUID(value).int != 0, 'CONFIGURED_REQUEST_ID') pin = HISTORICAL_CONFIGURED_RECOVERY require(request['grant_id'] == pin['grant_id'], 'CONFIGURED_HISTORICAL_GRANT_ONLY') secure_path(BASE, directory=True, private=True) secure_path(ACTIVE, directory=True, private=True) names = ('context.json', 'signed-action.json', 'expectation.json', 'baseline.json', 'launch.json', 'native-prechecks.json', 'sandbox-ready.json', 'sandbox-result.json', 'hook-armed.json', 'partial-proof.json') raw = {name: sealed_read(ACTIVE / name) for name in names} for name in ('bootstrap-attempt-rmm-apt-fixture-install-1.0.json', 'bootstrap-retry-rmm-apt-fixture-install-1.0.json', 'recovery-attempt-' + pin['previous_grant_id'] + '.json'): raw[name] = sealed_read(BASE / name) require(not os.path.lexists(ACTIVE / 'host-reboot-before.json'), 'CONFIGURED_HISTORICAL_BEFORE_SAMPLE_ABSENT') context = VerifiedHelperContext.parse(json_bytes(raw['context.json'])) require(context.action == 'apt-native-acceptance' and context.execution_profile == 'dev-test' and all(getattr(context, key) == request[key] for key in fields.split()), 'CONFIGURED_CONTEXT_BINDING') require(Path('/proc/sys/kernel/random/boot_id').read_text().strip() == context.boot_id, 'CONFIGURED_BOOT_CHANGED') require(digest(raw['signed-action.json']) == context.job_payload_sha256 and digest(raw['expectation.json']) == context.transaction_sha256, 'CONFIGURED_SIGNED_BYTES') transaction = ResolvedAptTransaction.parse(json_bytes(raw['expectation.json'])) fixture_scope(transaction) require(transaction.schema_version == 2 and transaction.operation == 'configure_only', 'CONFIGURED_FIXED_OPERATION') baseline = json_bytes(raw['baseline.json']) require(type(baseline) is dict and raw['baseline.json'] == canonical(baseline) and digest(raw['baseline.json']) == transaction.baseline_sha256 and baseline.get('rmm-mvp-test:all') == {'version': '1.0', 'status': 'install ok unpacked'}, 'CONFIGURED_ORIGINAL_PARTIAL_BASELINE') job = json_bytes(raw['signed-action.json']) exact(job, 'schema_version tenant_id asset_id agent_id enrollment_generation assignment_version ' 'job_id attempt_id action execution_identity not_before start_before max_runtime_seconds max_output_bytes') require(type(job['schema_version']) is int and job['schema_version'] == 1 and job['execution_identity'] == 'root' and job['job_id'] == context.job_id and job['attempt_id'] == context.attempt_id, 'CONFIGURED_ORIGINAL_JOB') outer = job['action']; exact(outer, 'action recipe_id recipe_version apt_manifest') require(outer['action'] == 'apt_native_acceptance' and outer['recipe_id'] == transaction.recipe_id and outer['recipe_version'] == transaction.recipe_version, 'CONFIGURED_ORIGINAL_ACTION') action = outer['apt_manifest'] exact(action, 'type schema_version action execution_profile transaction_sha256 ' 'resolved_apt_transaction provider_sha256 hook_sha256 apt_config_sha256 runtime_sha256 ' 'test_result_id transaction_bytes native_recovery') require(action['type'] == 'rmm.apt.helper-action' and type(action['schema_version']) is int and action['schema_version'] == 4 and action['action'] == context.action and action['execution_profile'] == context.execution_profile and action['provider_sha256'] == pin['provider_sha256'] and action['transaction_sha256'] == context.transaction_sha256 and canonical(action['resolved_apt_transaction']) == canonical(json_bytes(raw['expectation.json'])) and type(action['transaction_bytes']) is list and all(type(value) is int and 0 <= value <= 255 for value in action['transaction_bytes']) and bytes(action['transaction_bytes']) == raw['expectation.json'], 'CONFIGURED_ORIGINAL_MANIFEST') for key in ('provider_sha256', 'hook_sha256', 'apt_config_sha256', 'runtime_sha256'): token(action[key], HASH, 'CONFIGURED_ORIGINAL_RUNTIME_HASH') token(action['test_result_id'], IDENT, 'CONFIGURED_ORIGINAL_TEST_ID') require(digest(sealed_read(ACTIVE / 'apt.conf')) == action['apt_config_sha256'], 'CONFIGURED_ORIGINAL_APT_CONFIG') reference = action['native_recovery']; validate_recovery_reference(reference) require(reference['previous_grant_id'] == pin['previous_grant_id'] and reference['partial_proof_sha256'] == pin['partial_proof_sha256'], 'CONFIGURED_ORIGINAL_PARTIAL_REFERENCE') verify_recovery_reference(transaction, context, action) check_bootstrap_attempt(transaction, context, action) require(canonical(json_bytes(raw['launch.json'])) == canonical({ 'transaction_sha256': context.transaction_sha256, 'effect_armed_ledger_id': context.effect_armed_ledger_id}) and canonical(json_bytes(raw['sandbox-ready.json'])) == canonical({ 'transaction_sha256': context.transaction_sha256, 'sandbox_version': 1}) and canonical(json_bytes(raw['sandbox-result.json'])) == canonical({ 'transaction_sha256': context.transaction_sha256, 'apt_exit_code': 0, 'reboot_required': False}), 'CONFIGURED_NATIVE_COMPLETION') checks = {'schema_version': 1, 'transaction_sha256': context.transaction_sha256, 'job_payload_sha256': context.job_payload_sha256, 'boot_id': context.boot_id, 'checks': {'namespaces_caps_nnp_seccomp': True, 'readonly_controlpaths': True, 'private_tmpfs_sockets': True, 'control_syscalls': {'invalid_reboot_magic': 'EPERM', 'invalid_kexec_load_flags': 'EPERM', 'invalid_kexec_file_fds_flags': 'EPERM'}, 'frontend_lock': 'native-apt-check-conflict'}} require(canonical(json_bytes(raw['native-prechecks.json'])) == canonical(checks), 'CONFIGURED_HISTORICAL_PRECHECKS') marker = json_bytes(raw['hook-armed.json']) exact(marker, 'armed_at_ms effect_armed_ledger_id grant_id protocol_sha256 transaction_sha256') require(marker['effect_armed_ledger_id'] == context.effect_armed_ledger_id and marker['grant_id'] == context.grant_id and marker['transaction_sha256'] == context.transaction_sha256 and type(marker['armed_at_ms']) is int and context.not_before_ms <= marker['armed_at_ms'] < context.start_before_ms, 'CONFIGURED_HOOK_BINDING') token(marker['protocol_sha256'], HASH, 'CONFIGURED_HOOK_PROTOCOL_HASH') require(marker['protocol_sha256'] == digest(canonical([ Action('rmm-mvp-test', '1.0', 'all', 'none', '=', '1.0', 'all', 'none', '**CONFIGURE**').__dict__])), 'CONFIGURED_EXACT_CONFIGURE_PROTOCOL') for name in ('acceptance-rmm-apt-fixture-install-1.0.json', 'pending-acceptance-rmm-apt-fixture-install-1.0.json', 'recovery-' + pin['previous_grant_id'] + '.json', 'pending-recovery-' + pin['previous_grant_id'] + '.json'): require(not os.path.lexists(BASE / name), 'CONFIGURED_NO_RETROACTIVE_ACCEPTANCE') require(not observe_host_frontend_lock() and not observe_host_frontend_lock(Path('/var/lib/dpkg/lock')), 'FOREIGN_PACKAGE_LOCK') fingerprint = status_fingerprint(); observed = installed_snapshot() expected = dict(baseline); expected['rmm-mvp-test:all'] = {'version': '1.0', 'status': 'install ok installed'} require(observed == expected, 'CONFIGURED_UNEXPECTED_PACKAGE_CHANGE') verify_archive(transaction.packages[0]) require(run_read(['/usr/bin/dpkg', '--audit']) == b'', 'CONFIGURED_DPKG_AUDIT') payload = sealed_read(Path('/usr/share/rmm-mvp-test/version'), limit=32) require(payload == b'1.0\n', 'CONFIGURED_FIXTURE_PAYLOAD') host_marker = sealed_read(Path('/run/reboot-required'), limit=4096) require(Path('/run/reboot-required').exists(), 'CONFIGURED_ACTUAL_HOST_REBOOT_FLAG') require(status_fingerprint() == fingerprint and installed_snapshot() == observed and run_read(['/usr/bin/dpkg', '--audit']) == b'' and sealed_read(Path('/usr/share/rmm-mvp-test/version'), limit=32) == payload and sealed_read(Path('/run/reboot-required'), limit=4096) == host_marker and Path('/run/reboot-required').exists() and Path('/proc/sys/kernel/random/boot_id').read_text().strip() == context.boot_id and not observe_host_frontend_lock() and not observe_host_frontend_lock(Path('/var/lib/dpkg/lock')), 'CONFIGURED_CURRENT_STATE_CHANGED') verify_recovery_reference(transaction, context, action) for name, data in raw.items(): require(sealed_read(ACTIVE / name if name in names else BASE / name) == data, 'CONFIGURED_HISTORICAL_EVIDENCE_CHANGED') require(not os.path.lexists(ACTIVE / 'host-reboot-before.json'), 'CONFIGURED_HISTORICAL_BEFORE_SAMPLE_ABSENT') proof = dict(schema_version=1, type='rmm.apt.configured-recovery-reconciliation', **request, original_evidence_sha256=digest(canonical({name: digest(data) for name, data in raw.items()})), partial_proof_sha256=reference['partial_proof_sha256'], original_baseline_sha256=transaction.baseline_sha256, observed_snapshot_sha256=digest(canonical(observed)), status_fingerprint=fingerprint, fixture_payload_sha256=digest(payload), snapshot=observed, checked_at_ms=time.time_ns() // 1000000, effect_complete=True, partial_effect=False, postconditions_passed=False, reboot_required=True, host_reboot_required=True, host_reboot_marker_sha256=digest(host_marker)) result = dict(effect_state='known_failed', code='APT_RECOVERY_CONFIGURED_ACCEPTANCE_REBOOT_FLAG_VERIFIED', proof=proof) require(len(canonical(result)) <= MAX_INPUT, 'CONFIGURED_PROOF_LIMIT') return result def verified_no_change(transaction, baseline, context): """Independently verify the full selected postcondition, never run APT.""" fixture_scope(transaction) # Cannot promote unknown catalog recipes. if not all(baseline.get(p.name + ':' + p.architecture) == {'version': p.new_version, 'status': 'install ok installed'} for p in transaction.packages): return None require(not observe_host_frontend_lock() and not observe_host_frontend_lock(Path('/var/lib/dpkg/lock')), 'FOREIGN_PACKAGE_LOCK') check_current_baseline(transaction, baseline) evidence = verify_after(transaction, baseline) # Repeat after the independent query/audit/payload check. Dirty/changed or # unknown state is never a successful declarative observation. check_current_baseline(transaction, baseline) require(not observe_host_frontend_lock() and not observe_host_frontend_lock(Path('/var/lib/dpkg/lock')), 'FOREIGN_PACKAGE_LOCK') context.check_deadline() evidence.update(changed=False, already_desired=True, postcondition_already_met=True, transaction_executed=False, effect_armed_ledger_id=context.effect_armed_ledger_id) return evidence def execute(request, native_acceptance=False): """Only called by the privileged helper AFTER its own durable grant consume.""" armed = False launched = False try: require(os.geteuid() == 0, 'ROOT_REQUIRED') exact(request, 'transaction_sha256 effect_armed_ledger_id') secure_path(BASE, directory=True, private=True) lockfd = os.open(BASE / 'provider.lock', os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) try: fcntl.flock(lockfd, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: os.close(lockfd) raise Veto('PROVIDER_BUSY') from None try: transaction, context, baseline = load_active() armed = (ACTIVE / 'hook-armed.json').exists() launched = (ACTIVE / 'launch.json').exists() require(not armed and not launched, 'PRIOR_ATTEMPT_UNKNOWN') require(request == {'transaction_sha256': context.transaction_sha256, 'effect_armed_ledger_id': context.effect_armed_ledger_id}, 'HELPER_BINDING') action = load_signed_action(transaction, context) runtime = runtime_identity() check_native_gate(transaction, context, action, runtime, native_acceptance) secure_path(CODE) require(sealed_read(Path(HOOK)) == hook_script(), 'HOOK_CODE_BINDING') require(sealed_read(ACTIVE / 'apt.conf') == apt_config(), 'UNTRUSTED_APT_CONFIG') require(not list(secure_path(ACTIVE / 'empty', directory=True).iterdir()) and not list(secure_path(ACTIVE / 'lists', directory=True).iterdir()), 'ISOLATED_APT_DIRS') secure_path(ACTIVE / 'cache', directory=True, private=True) for path in ('hook-armed.json', 'sandbox-ready.json', 'sandbox-result.json', 'native-prechecks.json', 'host-namespaces.json', 'host-reboot-before.json', 'launch.json'): require(not (ACTIVE / path).exists(), 'PRIOR_ATTEMPT_UNKNOWN') check_current_baseline(transaction, baseline) for package in transaction.packages: verify_archive(package) # The exact bound unpacked fixture is the declared recovery input; # ordinary jobs continue to require a clean audit before mutation. if transaction.operation != 'configure_only': require(run_read(['/usr/bin/dpkg', '--audit']) == b'', 'DPKG_AUDIT') context.check_deadline() if not native_acceptance: evidence = verified_no_change(transaction, baseline, context) if evidence is not None: return {'effect_state': 'verified_no_change', 'code': 'POSTCONDITION_ALREADY_MET', 'evidence': evidence} # Only the mutating path requires the recipe's historical version. # No reinstall/downgrade/remove is introduced by the no-change path. check_preconditions(transaction, baseline) if native_acceptance: # Original marker never changes. One separately signed retry # may reference proven no-handoff history; it has its OWN # create-once tombstone, never a reset of the original attempt. path, binding = bootstrap_binding(transaction, context, action) durable_once(path, binding) capture_host_reboot_before(context) durable_once(ACTIVE / 'host-namespaces.json', { name: os.readlink('/proc/self/ns/' + name) for name in ('pid', 'mnt', 'net')}) durable_once(ACTIVE / 'launch.json', {'transaction_sha256': context.transaction_sha256, 'effect_armed_ledger_id': context.effect_armed_ledger_id}) launched = True proc = subprocess.Popen(['/usr/bin/unshare', '--mount', '--pid', '--fork', '--mount-proc', '--net', '/usr/bin/python3', '-I', str(CODE), 'sandbox-worker'], env=ENV, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) code = proc.wait() armed = (ACTIVE / 'hook-armed.json').exists() if not armed: # Trusted fixed config makes a missing hook a veto, not an # after-the-fact substitute for pre-dpkg validation. current = partial_installed_snapshot() if transaction.operation == 'configure_only' else installed_snapshot() require(current == baseline, 'MISSING_HOOK_WITH_CHANGE') return {'effect_state': 'known_failed', 'code': 'HOOK_NOT_HANDED_OFF', 'evidence': {'test_acceptance': True, 'noProductionEvidence': True} if native_acceptance else {}} marker = json_bytes(sealed_read(ACTIVE / 'hook-armed.json')) require(marker.get('transaction_sha256') == context.transaction_sha256 and marker.get('effect_armed_ledger_id') == context.effect_armed_ledger_id and marker.get('grant_id') == context.grant_id, 'HOOK_MARKER_BINDING') evidence = verify_after(transaction, baseline) require(code == 0, 'APT_EXIT_AFTER_POSSIBLE_EFFECT') child_result = json_bytes(sealed_read(ACTIVE / 'sandbox-result.json')) exact(child_result, 'transaction_sha256 apt_exit_code reboot_required') require(child_result['transaction_sha256'] == context.transaction_sha256 and type(child_result['apt_exit_code']) is int and child_result['apt_exit_code'] == 0 and type(child_result['reboot_required']) is bool, 'SANDBOX_RESULT_BINDING') evidence['reboot_required'] |= child_result['reboot_required'] evidence['effect_armed_ledger_id'] = context.effect_armed_ledger_id evidence.update(verify_host_reboot_after(context, evidence)) if native_acceptance: evidence.update(complete_acceptance(transaction, context, action, runtime, evidence)) # This recipe has version/consistency postconditions, not post-boot # conditions. Reboot-needed is evidence; never invoke a reboot. return {'effect_state': 'verified', 'code': 'POSTCONDITIONS_VERIFIED', 'evidence': evidence} finally: os.close(lockfd) except (Veto, OSError, ValueError, UnicodeError, subprocess.SubprocessError) as error: return {'effect_state': 'unknown' if armed or launched else 'known_failed', 'code': str(error) if isinstance(error, Veto) else 'PROVIDER_IO_FAILURE', 'evidence': {'test_acceptance': True, 'noProductionEvidence': True} if native_acceptance else {}} def hook_script(): return b'#!/bin/sh\nexec /usr/bin/python3 -I /usr/lib/rmm-apt-transaction/apt_transaction.py hook\n' def provision_fixture_store(): """Explicit administrator artifact preparation, never package installation. Run before planning/final grants. Only code-pinned bytes can be imported; this creates neither authorization nor native-acceptance evidence. """ require(os.geteuid() == 0, 'ROOT_REQUIRED') secure_path(BASE, directory=True, private=True) secure_path(BASE / 'archives', directory=True, private=True) secure_path(BASE / 'baselines', directory=True, private=True) records = [] for version in ('1.0', '1.1'): data = fixture_archive(version) sha = FIXTURE_SHA256[version] require(digest(data) == sha, 'FIXTURE_PINNED_BYTES') path = BASE / 'archives' / (sha + '.deb') fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) with os.fdopen(fd, 'wb') as stream: stream.write(data) stream.flush() os.fsync(stream.fileno()) directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY) try: os.fsync(directory) finally: os.close(directory) durable_once(BASE / ('prefetch-' + sha + '.json'), { 'schema_version': 1, 'sha256': sha, 'size': len(data), 'sealed_at_ms': time.time_ns() // 1000000}) records.append({'version': version, 'sha256': sha, 'size': len(data)}) return {'fixtures': records, **prepare_baseline_store()} def prepare_baseline_store(): """Pre-grant planning snapshot; no artifact overwrite or job authority.""" require(os.geteuid() == 0, 'ROOT_REQUIRED') secure_path(BASE, directory=True, private=True) secure_path(BASE / 'baselines', directory=True, private=True) baseline = canonical(installed_snapshot()) baseline_sha = digest(baseline) path = BASE / 'baselines' / (baseline_sha + '.json') if path.exists(): require(sealed_read(path) == baseline, 'SEALED_BASELINE_MISMATCH') else: # durable_once uses the same canonical codec as this computed hash. durable_once(path, json_bytes(baseline)) return {'baseline_sha256': baseline_sha, 'status_fingerprint': status_fingerprint(), 'authorization_created': False, 'native_acceptance_created': False} def recovery_planning(request): """Fresh passive projection of one ledger-verified, closed partial failure. Rust verifies the signed original request, terminal failure and immutable SQLite proof before invoking this fixed mode. No job or execution is made. """ exact(request, 'native_recovery proof') ref, proof = request['native_recovery'], request['proof'] validate_recovery_reference(ref) validate_partial_proof(proof) require(digest(canonical(proof)) == ref['partial_proof_sha256'] and proof['grant_id'] == ref['previous_grant_id'] and proof['attempt_id'] == ref['previous_attempt_id'], 'RECOVERY_PLANNING_PROOF_BINDING') fields = ('transaction_sha256 job_payload_sha256 effect_armed_ledger_id grant_id ' 'job_id attempt_id authorization_id plan_sha256') current = verify_partial({key: proof[key] for key in fields.split()})['proof'] require({key: value for key, value in current.items() if key != 'checked_at_ms'} == {key: value for key, value in proof.items() if key != 'checked_at_ms'}, 'RECOVERY_PLANNING_STATE_CHANGED') require(not os.path.lexists(BASE / ('recovery-attempt-' + ref['previous_grant_id'] + '.json')) and not os.path.lexists(BASE / ('recovery-' + ref['previous_grant_id'] + '.json')), 'RECOVERY_ALREADY_ATTEMPTED') result = _planning_status(proof) result['native_recovery'] = ref return result def planning_status(): return _planning_status() def _planning_status(recovery_proof=None): """Fixed passive fixture projection; complete dpkg state remains root-private. Only content-addressed, fsynced helper metadata may be created here. No artifact download, acceptance, package manager write, grant or job exists. The caller bounds this entire metadata subprocess, including runtime reads. """ require(os.geteuid() == 0, 'ROOT_REQUIRED') secure_path(BASE, directory=True, private=True) secure_path(BASE / 'baselines', directory=True, private=True) require(not observe_host_frontend_lock() and not observe_host_frontend_lock(Path('/var/lib/dpkg/lock')), 'FOREIGN_PACKAGE_LOCK') fingerprint = status_fingerprint() # Vetoes dirty updates/pending triggers. snapshot_reader = partial_installed_snapshot if recovery_proof is not None else installed_snapshot snapshot = snapshot_reader() host_reboot_required = Path('/run/reboot-required').exists() if recovery_proof is not None: require(snapshot == recovery_proof['snapshot'] and fingerprint == recovery_proof['status_fingerprint'], 'RECOVERY_PLANNING_STATE_CHANGED') runtime = runtime_identity() prefetch = {} for version in ('1.0', '1.1'): sha = FIXTURE_SHA256[version] path = BASE / 'archives' / (sha + '.deb') data = sealed_read(path, 20672) archive_metadata(path.lstat(), 20672) require(len(data) == 20672 and digest(data) == sha, 'PREFETCH_ARCHIVE_HASH') receipt = json_bytes(sealed_read(BASE / ('prefetch-' + sha + '.json'))) exact(receipt, 'schema_version sha256 size sealed_at_ms') require(type(receipt['schema_version']) is int and receipt['schema_version'] == 1 and receipt['sha256'] == sha and type(receipt['size']) is int and receipt['size'] == len(data) and type(receipt['sealed_at_ms']) is int and 0 < receipt['sealed_at_ms'] <= time.time_ns() // 1000000, 'PREFETCH_RECEIPT') prefetch[sha] = receipt require(status_fingerprint() == fingerprint and snapshot_reader() == snapshot and Path('/run/reboot-required').exists() == host_reboot_required, 'PLANNING_STATE_CHANGED') require(not observe_host_frontend_lock() and not observe_host_frontend_lock(Path('/var/lib/dpkg/lock')), 'FOREIGN_PACKAGE_LOCK') baseline = canonical(snapshot) baseline_sha = digest(baseline) path = BASE / 'baselines' / (baseline_sha + '.json') if path.exists(): require(sealed_read(path, 32 * MAX_INPUT) == baseline, 'SEALED_BASELINE_MISMATCH') # A previous bounded metadata process may have died after writing its # full bytes but before fsync. Re-establish durability before calling an # existing content-addressed file a seal; never rewrite/repair its data. fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC) try: os.fsync(fd) finally: os.close(fd) fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC) try: os.fsync(fd) finally: os.close(fd) else: durable_once(path, snapshot) # Do not publish a stale baseline if state changed during fsync. require(status_fingerprint() == fingerprint and snapshot_reader() == snapshot and Path('/run/reboot-required').exists() == host_reboot_required, 'PLANNING_STATE_CHANGED') return {'observed_at': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()), 'host_reboot_required': host_reboot_required, 'fixture_package': snapshot.get('rmm-mvp-test:all'), 'baseline_sha256': baseline_sha, 'sealed_baseline_sha256': baseline_sha, 'status_fingerprint': fingerprint, 'dpkg_updates_empty': True, 'pending_triggers_empty': True, 'runtime': runtime, 'runtime_sha256': digest(canonical(runtime)), 'provider_sha256': digest(sealed_read(CODE)), 'hook_sha256': digest(sealed_read(Path(HOOK))), 'apt_config_sha256': digest(apt_config()), 'prefetch': prefetch} def observe_host_frontend_lock(path=Path('/var/lib/dpkg/lock-frontend')): """F_GETLK on O_RDONLY only. Never F_SETLK/flock/lockf a host probe fd.""" path = secure_path(path) class Lock(ctypes.Structure): _fields_ = [('kind', ctypes.c_short), ('whence', ctypes.c_short), ('start', ctypes.c_long), ('length', ctypes.c_long), ('pid', ctypes.c_int)] lock = Lock(fcntl.F_WRLCK, os.SEEK_SET, 0, 0, 0) fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC) try: answer = fcntl.fcntl(fd, fcntl.F_GETLK, bytes(lock)) finally: os.close(fd) return Lock.from_buffer_copy(answer).kind != fcntl.F_UNLCK def probe_config(workspace): # All substitutions are fixed/generated root-private workspace paths, not # caller arguments. No sources, hooks or installer command is used here. text = apt_config().decode('ascii').replace(str(ACTIVE), str(workspace)) text = text.replace(str(BASE / 'log'), str(workspace / 'log')) text = text.replace(str(BASE / 'state'), str(workspace / 'state')) return ('\n'.join(line for line in text.splitlines() if not line.startswith(('DPkg::Pre-Install-Pkgs', 'DPkg::Tools::Options'))) + '\n').encode('ascii') def probe_worker(): request = json_bytes(sys.stdin.buffer.read(MAX_INPUT + 1)) exact(request, 'probe_id') probe_id = str(uuid.UUID(request['probe_id'])) require(probe_id == request['probe_id'], 'PROBE_ID') workspace = BASE / 'probes' / probe_id secure_path(workspace, directory=True, private=True) require(sealed_read(workspace / 'apt.conf') == probe_config(workspace), 'PROBE_CONFIG') setup_sandbox(workspace, workspace / 'dpkg') checks = sandbox_checks(workspace) # The negative lock test above and this positive check see ONLY copied dpkg # state, bound over /var/lib/dpkg in the new mount namespace. run_read(['/usr/bin/apt-get', '-o', 'DPkg::Lock::Timeout=0', 'check'], env={**ENV, 'APT_CONFIG': str(workspace / 'apt.conf')}) durable_once(workspace / 'probe-result.json', { 'probe_id': probe_id, 'checks': checks, 'isolated_dpkg_check': True, 'namespaces': {name: os.readlink('/proc/self/ns/' + name) for name in ('pid', 'mnt', 'net')}}) def validate_probe_result(result, probe_id, parents): exact(result, 'probe_id checks isolated_dpkg_check namespaces') expected = {'namespaces_caps_nnp_seccomp': True, 'readonly_controlpaths': True, 'private_tmpfs_sockets': True, 'control_syscalls': {'invalid_reboot_magic': 'EPERM', 'invalid_kexec_load_flags': 'EPERM', 'invalid_kexec_file_fds_flags': 'EPERM'}, 'frontend_lock': 'native-apt-check-conflict'} require(result['probe_id'] == probe_id and result['isolated_dpkg_check'] is True and result['checks'] == expected, 'NATIVE_PROBE_RESULT') for key in ('namespaces_caps_nnp_seccomp', 'readonly_controlpaths', 'private_tmpfs_sockets'): require(result['checks'][key] is True, 'NATIVE_PROBE_BOOLEAN') exact(result['namespaces'], 'pid mnt net') exact(parents, 'pid mnt net') for name in ('pid', 'mnt', 'net'): token(result['namespaces'][name], re.compile(name + r':\[[0-9]+\]\Z'), 'PROBE_NAMESPACE_ID') token(parents[name], re.compile(name + r':\[[0-9]+\]\Z'), 'PROBE_PARENT_NAMESPACE_ID') require(result['namespaces'][name] != parents[name], 'PROBE_NAMESPACE_NOT_PRIVATE') def probe_native(): """Root ADMIN readiness only: no grant, packages, receipt or effect marker.""" require(os.geteuid() == 0, 'ROOT_REQUIRED') verify_controller_profile() secure_path(BASE, directory=True, private=True) runtime = runtime_identity() probes = BASE / 'probes' secure_path(probes, directory=True, private=True) probe_id = str(uuid.uuid4()) workspace = probes / probe_id workspace.mkdir(mode=0o700) for name in ('dpkg', 'empty', 'lists', 'cache', 'log', 'state'): (workspace / name).mkdir(mode=0o700) for name in ('updates', 'triggers'): (workspace / 'dpkg' / name).mkdir(mode=0o700) status = sealed_read(Path('/var/lib/dpkg/status'), 64 * MAX_INPUT) # Exclusive writes into a generated directory. Never open host status or # lock for writing, never invoke an install command for a readiness probe. for name, data in [('status', status), ('lock', b''), ('lock-frontend', b'')]: path = workspace / 'dpkg' / name fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) with os.fdopen(fd, 'wb') as stream: stream.write(data) stream.flush() os.fsync(stream.fileno()) (workspace / 'dpkg' / 'triggers' / 'Unincorp').touch(mode=0o600, exist_ok=False) (workspace / 'state' / 'extended_states').touch(mode=0o600, exist_ok=False) (workspace / 'apt.conf').write_bytes(probe_config(workspace)) (workspace / 'apt.conf').chmod(0o600) durable_once(workspace / 'host-namespaces.json', { name: os.readlink('/proc/self/ns/' + name) for name in ('pid', 'mnt', 'net')}) foreign_lock = observe_host_frontend_lock() # Only the read-only, copied-database probe can be timeout-aborted. The # mutation driver's no-kill semantics remain unchanged. completed = subprocess.run(['/usr/bin/unshare', '--mount', '--pid', '--fork', '--mount-proc', '--net', '/usr/bin/python3', '-I', str(CODE), 'probe-worker'], input=canonical({'probe_id': probe_id}), env=ENV, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=90) require(completed.returncode == 0, 'NATIVE_PROBE_FAILED') result = json_bytes(sealed_read(workspace / 'probe-result.json')) parents = json_bytes(sealed_read(workspace / 'host-namespaces.json')) validate_probe_result(result, probe_id, parents) require(sealed_read(Path('/var/lib/dpkg/status'), 64 * MAX_INPUT) == status, 'HOST_STATUS_CHANGED_DURING_PROBE') require(runtime_identity() == runtime, 'PROBE_RUNTIME_CHANGED') report = {'schema_version': 1, 'profile': 'apt_only', 'probe_id': probe_id, 'runtime': runtime, 'boot_id': Path('/proc/sys/kernel/random/boot_id').read_text().strip(), 'host_status_sha256': digest(status), 'foreign_frontend_lock': foreign_lock, 'result': result, 'parent_namespaces': parents, 'readiness_only': True, 'native_acceptance': False} durable_once(workspace / 'readiness-report.json', report) target = BASE / 'native-readiness.json' if target.exists(): secure_path(target, private=True) os.replace(workspace / 'readiness-report.json', target) fd = os.open(BASE, os.O_RDONLY | os.O_DIRECTORY) try: os.fsync(fd) finally: os.close(fd) return {'readiness_report_sha256': digest(canonical(report)), 'readiness_only': True, 'native_acceptance': False, 'probe_id': probe_id} def verify_controller_profile(): """The real service profile, not a root shell/JSON assertion, is required.""" require(os.geteuid() == 0, 'ROOT_REQUIRED') status = dict(line.split(':', 1) for line in Path('/proc/self/status').read_text().splitlines() if ':' in line) mask = sum(1 << bit for bit in (0, 1, 3, 4, 6, 7, 8, 31, 21, 27)) require(status.get('NoNewPrivs', '').strip() == '1', 'APT_CONTROLLER_NNP') require(status.get('Seccomp', '').strip() == '2', 'APT_CONTROLLER_OUTER_FILTER') for key in ('CapEff', 'CapPrm', 'CapBnd'): require(int(status[key].strip(), 16) == mask, 'APT_CONTROLLER_CAPABILITIES') require(int(status['CapInh'].strip(), 16) == 0 and int(status['CapAmb'].strip(), 16) == 0, 'APT_CONTROLLER_INHERITED_CAPABILITIES') require(any(line.rsplit(':', 1)[-1].rstrip('/').endswith('/rmm-apt-helper.service') for line in Path('/proc/self/cgroup').read_text().splitlines()), 'APT_CONTROLLER_UNIT') for path in ('/usr', '/etc', '/var'): require(bool(os.statvfs(path).f_flag & os.ST_RDONLY), 'APT_CONTROLLER_READONLY_SYSTEM') writable = ('/var/lib/dpkg', '/var/lib/rmm-helper', str(BASE), '/usr/share/rmm-mvp-test') for path in writable: require(not os.statvfs(path).f_flag & os.ST_RDONLY, 'APT_CONTROLLER_WRITE_TARGET_REQUIRED') # Reject broad or unexpected writable submounts even when parent /usr/etc/ # var remains readonly (e.g. an unreviewed systemd drop-in adding /usr/share). for line in Path('/proc/self/mountinfo').read_text().splitlines(): fields = line.split() require(len(fields) >= 7, 'APT_CONTROLLER_MOUNTINFO') target = fields[4] if 'rw' in fields[5].split(',') and target.startswith(('/usr/', '/etc/', '/var/')): require(any(target == path or target.startswith(path + '/') for path in (*writable, '/var/tmp')), 'APT_CONTROLLER_EXTRA_WRITE_MOUNT') def readiness_status(): require(os.geteuid() == 0, 'ROOT_REQUIRED') runtime = runtime_identity() report = json_bytes(sealed_read(BASE / 'native-readiness.json')) exact(report, 'schema_version profile probe_id runtime boot_id host_status_sha256 ' 'foreign_frontend_lock result parent_namespaces readiness_only native_acceptance') require(type(report['schema_version']) is int and str(uuid.UUID(report['probe_id'])) == report['probe_id'], 'READINESS_SCHEMA_OR_ID') require(report.get('schema_version') == 1 and report.get('profile') == 'apt_only' and report.get('readiness_only') is True and report.get('native_acceptance') is False and report.get('runtime') == runtime and report.get('boot_id') == Path('/proc/sys/kernel/random/boot_id').read_text().strip(), 'READINESS_STALE_OR_UNVERIFIED') validate_probe_result(report['result'], report['probe_id'], report['parent_namespaces']) accepted = [] for recipe, (old, version) in FIXTURE_RECIPES.items(): path = BASE / ('acceptance-' + recipe + '.json') if not path.exists(): continue proof = json_bytes(sealed_read(path)) expected_package = {'name': 'rmm-mvp-test', 'architecture': 'all', 'old_version': old, 'new_version': version, 'origin': 'rmm-test', 'sha256': FIXTURE_SHA256[version], 'size': len(fixture_archive(version)), 'archive_path': str(BASE / 'archives' / (FIXTURE_SHA256[version] + '.deb'))} validate_acceptance_record(proof, {'recipe_id': recipe, 'recipe_version': '1', 'packages': [expected_package]}, runtime) accepted.append(recipe) return {'schema_version': 1, 'fixture_acceptance_ready': True, 'accepted_recipes': accepted, 'runtime_sha256': digest(canonical(runtime)), 'readiness_report_sha256': digest(canonical(report))} def main(): require(len(sys.argv) == 2, 'CLI_MODE') mode = sys.argv[1] if mode in ('execute', 'native-acceptance'): result = execute(json_bytes(sys.stdin.buffer.read(MAX_INPUT + 1)), native_acceptance=mode == 'native-acceptance') print(canonical(result).decode('ascii')) return 0 if mode == 'hook': hook() elif mode == 'sandbox-worker': sandbox_worker() elif mode == 'print-config': sys.stdout.buffer.write(apt_config()) elif mode == 'inspect-runtime': require(os.geteuid() == 0, 'ROOT_REQUIRED') sys.stdout.buffer.write(canonical(runtime_identity()) + b'\n') elif mode == 'provision-fixture-store': sys.stdout.buffer.write(canonical(provision_fixture_store()) + b'\n') elif mode == 'prepare-baseline': sys.stdout.buffer.write(canonical(prepare_baseline_store()) + b'\n') elif mode == 'planning-status': sys.stdout.buffer.write(canonical(planning_status()) + b'\n') elif mode == 'recovery-planning': sys.stdout.buffer.write(canonical(recovery_planning(json_bytes(sys.stdin.buffer.read(MAX_INPUT + 1)))) + b'\n') elif mode == 'probe-native': sys.stdout.buffer.write(canonical(probe_native()) + b'\n') elif mode == 'probe-worker': probe_worker() elif mode == 'readiness-status': sys.stdout.buffer.write(canonical(readiness_status()) + b'\n') elif mode == 'verify-partial': sys.stdout.buffer.write(canonical(verify_partial(json_bytes(sys.stdin.buffer.read(MAX_INPUT + 1)))) + b'\n') elif mode == 'verify-configured-recovery': sys.stdout.buffer.write(canonical(verify_configured_recovery(json_bytes(sys.stdin.buffer.read(MAX_INPUT + 1)))) + b'\n') elif mode == 'verify-controller': verify_controller_profile() elif mode == 'inspect-sandbox': inspect_sandbox() else: raise Veto('CLI_MODE') return 0 if __name__ == '__main__': try: sys.exit(main()) except (Veto, OSError, ValueError, UnicodeError, subprocess.SubprocessError): # Hook exits nonzero; no secret/raw protocol/child diagnostics escape. print('APT_TRANSACTION_VETO', file=sys.stderr) sys.exit(100)