#!/usr/bin/env python3 """One native source sample for the fixed proven Chrony generation; no restart/key/clock authority. SharedGenerationProof is read-only. Historical build records and current c9 process identity are checked separately; pin.Original is never instantiated. """ import argparse import hashlib import importlib.util import json import os from pathlib import Path import stat import struct import sys import uuid CASE_ID = 'c9a94f94-eecd-4c66-933d-c45c1a79c7a8' QUALITY_PHASE = 'probe-native-source-v1' BASE = Path('/var/lib/rmm-time-source-bootstrap') / CASE_ID OLD = Path('/var/lib/rmm-time-source-bootstrap/5b358997-3abc-43db-945f-f41855b4e3c0') PROFILE = 'rmm.server-time-source.native-generation-acceptance.v1' UNIT = 'rmm-time-source-probe-native-' + CASE_ID + '.service' PIN_CONTROLLER_SHA = 'fac85dd0399009af36f625232daa5b67ab7fda391dbf95229d4237c307b142ca' PIN_CONTROLLER = Path('/var/lib/rmm-time-source-operators') / PIN_CONTROLLER_SHA / 'pin_bootstrap.py' GENERATION_CONTROLLER_SHA = 'd5d56b38e6e36609b2eca294133758eed83a4e559c1ff05a8a62e085fdf8b9f5' GENERATION_CONTROLLER = Path('/var/lib/rmm-time-source-operators') / GENERATION_CONTROLLER_SHA / 'chrony_generation_bootstrap.py' GENERATION_RESULT_SHA = 'd648daadc43de90cda977ce60615b8e47072b785aa9fbfaea37ef8b58be6c9d4' GENERATION_RECEIPT_SHA = '1173ef78f9ca704afafbf4dbe92e8c654ec47d53f4e9f05fd99be2685991ce59' GENERATION_READ_RECEIPT_SHA = '58970ef8e89af86b68fdbbf2cb5119210bcb37cec603feb23b4f6030b0b36623' PUBLIC_PIN_SHA = '395f170aabf9fd01c24cd7d7939a313befdd147e98343ccd383bca861cbf2c4e' SOURCE_SHA = '0da5ed0d52d3e621ef6a23cbc065f9d7c93e5683547e0a02ae3c8da8a83884a5' MANIFEST_SHA = 'bdf7839f832e2ea0cf230a0bd8a8fbff5d4a72d8fb7ba8208e0d252bad4b56ee' BUILD_RECORDS = {'preflight':'719adce7210742aea8d54b775613fae1eb7665c0b16d57730e1ade4e934348a3', 'stage':'a12a138ea1583eb7d4328049f3d118d82085cd90aa472d02e5beac506b706ed8', 'build':'58eaf0118f8f8573debfa21a295019a224b916cfc5b1a88edda426ec06bed2b5'} ARTIFACT = dict(bytes=848632,sha256='216b4d6a0f29ef47576f5ccc469954623141e55d7b43bd73175c1d956363bbbd',elf_machine=183) BROKER_ARTIFACT = dict(bytes=1067136,sha256='5d8d786925c060eb042f0a592453f11970c32c4287fa4c9464f6f6a6e38cb201',elf_machine=183) IMAGE = OLD / 'build/artifacts/operator_probe' PROBE_RECORDS = ('intent.json','before.json','start-intent.json','execution.json','after.json','result.json','failure.json','probe.log') SAMPLE_KEYS = {'profile','clock_authority','signed_attestation','captured_utc_ns','server_error_ns', 'source_sync_age_ns','server_boot_id','captured_monotonic_ns','sampled_boottime_ns','kernel_state'} GENERATION_RECORDS = {'after-restart.json': {'metadata': {'ctime_ns': 1794739438793733913, 'dev': 2049, 'gid': 0, 'ino': 800469, 'mode': 33152, 'mtime_ns': 1794739438793733913, 'nlink': 1, 'size': 4993, 'uid': 0}, 'sha256': 'effd51775f9de314c8e99fdb785484737f9d315b685bb4b82fb042b11c48020d'}, 'after.json': {'metadata': {'ctime_ns': 1794739446181998648, 'dev': 2049, 'gid': 0, 'ino': 800478, 'mode': 33152, 'mtime_ns': 1794739446181998648, 'nlink': 1, 'size': 9456, 'uid': 0}, 'sha256': '473c3c094a5f2ef950120c33ea4f2785362fa88898e21c8b22c50b456cdd932c'}, 'before.json': {'metadata': {'ctime_ns': 1794739438218723541, 'dev': 2049, 'gid': 0, 'ino': 800464, 'mode': 33152, 'mtime_ns': 1794739438218723541, 'nlink': 1, 'size': 9449, 'uid': 0}, 'sha256': '8a7488dbbef32b12d6c90d82f735308bb5ce88798d875a2ec7ae5ac4abfa623f'}, 'cas-intent.json': {'metadata': {'ctime_ns': 1794739445652017023, 'dev': 2049, 'gid': 0, 'ino': 800476, 'mode': 33152, 'mtime_ns': 1794739445652017023, 'nlink': 1, 'size': 1578, 'uid': 0}, 'sha256': '55e77453996b29e4f9fc5ad9bde90d92302b81315072c98c9dbfb4db83b09630'}, 'intent.json': {'metadata': {'ctime_ns': 1794739438216723505, 'dev': 2049, 'gid': 0, 'ino': 800463, 'mode': 33152, 'mtime_ns': 1794739438216723505, 'nlink': 1, 'size': 1353, 'uid': 0}, 'sha256': '3c83287081e9b5f2c53c8957322ae5304f5ef17c92b2ac03f5394511dce08a59'}, 'new-public-pin.bin': {'metadata': {'ctime_ns': 1794739445916009070, 'dev': 2049, 'gid': 0, 'ino': 800477, 'mode': 33152, 'mtime_ns': 1794739445916009070, 'nlink': 1, 'size': 195, 'uid': 0}, 'sha256': '395f170aabf9fd01c24cd7d7939a313befdd147e98343ccd383bca861cbf2c4e'}, 'old-public-pin.bin': {'metadata': {'ctime_ns': 1794739438220723577, 'dev': 2049, 'gid': 0, 'ino': 800465, 'mode': 33152, 'mtime_ns': 1794739438220723577, 'nlink': 1, 'size': 194, 'uid': 0}, 'sha256': '203f63f150026d345614ca53e641f248397166fbdeb1f28318fc5d7763317e0a'}, 'readiness-01.json': {'metadata': {'ctime_ns': 1794739439400744838, 'dev': 2049, 'gid': 0, 'ino': 800470, 'mode': 33152, 'mtime_ns': 1794739439400744838, 'nlink': 1, 'size': 1772, 'uid': 0}, 'sha256': '9c0680cd15e453d479eaf8badfdc43b04598f7f0edda1221fde8a51168f443c6'}, 'readiness-02.json': {'metadata': {'ctime_ns': 1794739440991773473, 'dev': 2049, 'gid': 0, 'ino': 800471, 'mode': 33152, 'mtime_ns': 1794739440991773473, 'nlink': 1, 'size': 1772, 'uid': 0}, 'sha256': '6b76ba69cd7f8adc8d31fd1283b9a8c0b775a61b861ab6e35df6ac5551a01313'}, 'readiness-03.json': {'metadata': {'ctime_ns': 1794739442592802289, 'dev': 2049, 'gid': 0, 'ino': 800472, 'mode': 33152, 'mtime_ns': 1794739442592802289, 'nlink': 1, 'size': 1771, 'uid': 0}, 'sha256': '730b422dc3b9cbb8992838c2eb5e32a3d5aa9b8e3aa00324b721a614a69168c9'}, 'readiness-04.json': {'metadata': {'ctime_ns': 1794739444128865316, 'dev': 2049, 'gid': 0, 'ino': 800473, 'mode': 33152, 'mtime_ns': 1794739444128865316, 'nlink': 1, 'size': 1771, 'uid': 0}, 'sha256': '038768187254e33b408a50dfb66467d41f0fe5bcaea2fe639d7abbebb7ed583e'}, 'readiness-05.json': {'metadata': {'ctime_ns': 1794739445645016897, 'dev': 2049, 'gid': 0, 'ino': 800474, 'mode': 33152, 'mtime_ns': 1794739445645016897, 'nlink': 1, 'size': 1758, 'uid': 0}, 'sha256': '2440b67a720a6bdf33dde0ffb89f7b0736044126c1f6d7826fc84ba2f3aaff30'}, 'readiness.json': {'metadata': {'ctime_ns': 1794739445648016951, 'dev': 2049, 'gid': 0, 'ino': 800475, 'mode': 33152, 'mtime_ns': 1794739445648016951, 'nlink': 1, 'size': 1721, 'uid': 0}, 'sha256': 'a19ace502cd44835fb941afa011b53f4d0e4bd9b05ecdcd38a2758c5089c1c03'}, 'restart-exit.json': {'metadata': {'ctime_ns': 1794739438591730278, 'dev': 2049, 'gid': 0, 'ino': 800468, 'mode': 33152, 'mtime_ns': 1794739438591730278, 'nlink': 1, 'size': 1254, 'uid': 0}, 'sha256': '6be145a67464f1bea7e8e77aed800118d9d8244bbd7ec0f4d00ed61e3452745f'}, 'restart-intent.json': {'metadata': {'ctime_ns': 1794739438495728549, 'dev': 2049, 'gid': 0, 'ino': 800466, 'mode': 33152, 'mtime_ns': 1794739438495728549, 'nlink': 1, 'size': 1302, 'uid': 0}, 'sha256': 'f993b2617821058736699812e4ac69e73fae92ab3f19e586ba922a63937408b9'}, 'restart.log': {'metadata': {'ctime_ns': 1794739438497728585, 'dev': 2049, 'gid': 0, 'ino': 800467, 'mode': 33152, 'mtime_ns': 1794739438497728585, 'nlink': 1, 'size': 0, 'uid': 0}, 'sha256': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'}, 'result.json': {'metadata': {'ctime_ns': 1794739446183998570, 'dev': 2049, 'gid': 0, 'ino': 800479, 'mode': 33152, 'mtime_ns': 1794739446183998570, 'nlink': 1, 'size': 1972, 'uid': 0}, 'sha256': 'd648daadc43de90cda977ce60615b8e47072b785aa9fbfaea37ef8b58be6c9d4'}} GENERATION_MISSING = ('failure.json', 'readiness-06.json', 'readiness-07.json', 'readiness-08.json', 'readiness-09.json', 'readiness-10.json', 'readiness-11.json', 'readiness-12.json', 'readiness-13.json', 'readiness-14.json', 'readiness-15.json', 'readiness-16.json', 'readiness-17.json', 'readiness-18.json', 'readiness-19.json', 'readiness-20.json', 'readiness-21.json', 'readiness-22.json', 'readiness-23.json', 'readiness-24.json', 'readiness-25.json') class GuardDenied(RuntimeError): pass def require(ok,reason): if not ok: raise GuardDenied(reason) def sha(raw): return hashlib.sha256(raw).hexdigest() def load_pin_controller(): fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) try: for part in PIN_CONTROLLER.parent.parts[1:]: info = os.fstat(fd) require(info.st_uid == 0 and info.st_mode & 0o022 == 0, 'protected_controller_ancestry') next_fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd) os.close(fd) fd = next_fd info = os.fstat(fd) require(info.st_uid == 0 and info.st_mode & 0o022 == 0, 'protected_controller_parent') file_fd = os.open(PIN_CONTROLLER.name, os.O_RDONLY | os.O_NOFOLLOW, dir_fd=fd) with os.fdopen(file_fd, 'rb') as stream: before = os.fstat(stream.fileno()) require(stat.S_ISREG(before.st_mode) and before.st_uid == before.st_gid == 0 and before.st_nlink == 1 and stat.S_IMODE(before.st_mode) == 0o600 and before.st_size <= 128 * 1024, 'reviewed_root_controller_file') raw = stream.read(128 * 1024 + 1) stable = lambda s: tuple(getattr(s, 'st_' + k) for k in ('dev', 'ino', 'uid', 'gid', 'mode', 'nlink', 'size', 'mtime_ns', 'ctime_ns')) require(stable(before) == stable(os.fstat(stream.fileno())) == stable(os.stat(PIN_CONTROLLER.name, dir_fd=fd, follow_symlinks=False)) and len(raw) == before.st_size and sha(raw) == PIN_CONTROLLER_SHA, 'exact_pin_controller_bytes') finally: os.close(fd) pin = importlib.util.module_from_spec(importlib.util.spec_from_loader('rmm_peer_pin_guard', loader=None)) pin.__file__ = str(PIN_CONTROLLER) exec(compile(raw, str(PIN_CONTROLLER), 'exec'), pin.__dict__) held = pin.read_file(PIN_CONTROLLER, 128 * 1024) require(held[0] == raw, 'same_loaded_pin_controller') return pin, lambda: require(pin.read_file(PIN_CONTROLLER, 128 * 1024) == held, 'pin_controller_unchanged') class HeldFile: def __init__(self, pin, path, maximum=65536, mode=0o600, expected=None, metadata=None): self.pin, self.path, self.maximum = pin, path, maximum self.parent = self.fd = -1 try: self.parent = pin.directory(path.parent) self.parent_identity = pin.stable_directory(os.fstat(self.parent)) self.fd = os.open(path.name, os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW, dir_fd=self.parent) self.metadata = pin.identity(os.fstat(self.fd)) require(stat.S_ISREG(self.metadata['mode']) and self.metadata['uid'] == self.metadata['gid'] == 0 and self.metadata['nlink'] == 1 and stat.S_IMODE(self.metadata['mode']) == mode and 0 <= self.metadata['size'] <= maximum, 'protected_bounded_original_held_file') self.raw = os.pread(self.fd, maximum + 1, 0) require(len(self.raw) == self.metadata['size'] and (expected is None or sha(self.raw) == expected) and (metadata is None or self.metadata == metadata), 'exact_frozen_held_file_bytes_and_metadata') self.fresh() except BaseException: self.close() raise def fresh(self): require(self.fd >= 0 and self.pin.identity(os.fstat(self.fd)) == self.metadata and os.pread(self.fd, self.maximum + 1, 0) == self.raw and self.pin.identity(os.stat(self.path.name, dir_fd=self.parent, follow_symlinks=False)) == self.metadata, 'same_held_original_file_and_named_inode') parent = self.pin.directory(self.path.parent) try: require(self.pin.stable_directory(os.fstat(parent)) == self.parent_identity == self.pin.stable_directory(os.fstat(self.parent)), 'same_protected_held_file_parent') finally: os.close(parent) return self.raw, dict(self.metadata) def close(self): for name in ('fd', 'parent'): fd = getattr(self, name) if fd >= 0: os.close(fd) setattr(self, name, -1) class QualifiedBuild: """Historical build/source verification only: never compares an old PID to the host.""" def __init__(self, proof): self.proof, self.source_sha, self.manifest_sha = proof, SOURCE_SHA, MANIFEST_SHA pin, operator = proof.pin, proof.operator records = {name: pin.parsed(proof.hold(OLD / name / 'result.json', expected=digest).raw) for name, digest in BUILD_RECORDS.items()} preflight, stage, build = (records[name] for name in ('preflight', 'stage', 'build')) self.historical_expected = pin.observation_key(preflight) require(build['exit_code'] == 0 and build['runtime_metadata_equal'] is True and build['native_source_quality_tested'] is False and build['artifacts'] == {'examples/operator_probe': ARTIFACT, 'rmm-time-broker-linux': BROKER_ARTIFACT} and pin.observation_key(preflight) == pin.observation_key(build['before']) == pin.observation_key(build['after']), 'successful_frozen_historical_build_not_current_process_authority') proof.hold(OLD / 'source.tar', 2 * 1024 * 1024, expected=SOURCE_SHA) manifest = pin.parsed(proof.hold(OLD / 'workspace/manifest.json', expected=MANIFEST_SHA).raw) require(stage['manifest_sha256'] == build['staged_manifest_sha256'] == MANIFEST_SHA and stage['source_tar_sha256'] == SOURCE_SHA and manifest['operator_sha256'] == pin.OPERATOR_SHA and manifest['package_files'] == stage['package_files'] and manifest['public_commit'] == stage['public_commit'], 'historical_source_manifest_stage_build_binding') pin.source_items(manifest['source_files']) pin.source_items(manifest['package_files']) source = [item for item in manifest['source_files'] if item['path'] == 'crates/time-source-linux/src/native.rs'] require(len(source) == 1 and source[0]['sha256'] == pin.PROVIDER_SHA, 'unchanged_original_named_provider') self.artifacts = {} for name, expected in build['artifacts'].items(): path = OLD / 'build/artifacts' / Path(name).name held = proof.hold(path, 32 * 1024 * 1024, 0o500, expected['sha256']) require(len(held.raw) == expected['bytes'] and held.raw[:6] == b'\x7fELF\x02\x01' and struct.unpack('= 0: os.close(self._case_fd) self._case_fd = -1 def sample_quality(sample, boot): require(type(sample) is dict and set(sample) == SAMPLE_KEYS and sample['profile'] == 'rmm.native-source-quality.once.v1' and sample['clock_authority'] is False and sample['signed_attestation'] is False and sample['server_boot_id'] == boot and str(uuid.UUID(boot)) == boot, 'exact_non_authoritative_native_sample_schema_and_boot') for key, upper in (('captured_utc_ns', 2**63 - 1), ('server_error_ns', 500_000_000), ('source_sync_age_ns', 3_600_000_000_000), ('captured_monotonic_ns', 2**64 - 1), ('sampled_boottime_ns', 2**64 - 1), ('kernel_state', 4)): require(type(sample[key]) is int and 0 <= sample[key] <= upper, 'bounded_numeric_quality_sample') require(sample['captured_utc_ns'] > 0 and sample['captured_monotonic_ns'] > 0 and sample['sampled_boottime_ns'] >= sample['captured_monotonic_ns'], 'positive_native_time_domains') def probe_args(): return ['systemd-run', '--quiet', '--wait', '--pipe', '--collect', '--unit=' + UNIT, '--property=Type=exec', '--property=User=root', '--property=Group=989', '--property=SupplementaryGroups=', '--property=NoNewPrivileges=yes', '--property=CapabilityBoundingSet=CAP_SYS_PTRACE CAP_DAC_OVERRIDE', '--property=AmbientCapabilities=', '--property=ProtectSystem=strict', '--property=ProtectHome=yes', '--property=PrivateTmp=yes', '--property=PrivateDevices=yes', '--property=RestrictAddressFamilies=AF_UNIX', '--property=IPAddressDeny=any', '--property=SystemCallFilter=~@debug ptrace process_vm_readv process_vm_writev', '--property=RuntimeMaxSec=3s', '--property=ReadWritePaths=/run/rmm-time-source/clients', str(IMAGE)] def save(pin, parent, name, value): require(name in PROBE_RECORDS and name.endswith('.json'), 'fixed_probe_record_leaf') raw = pin.encoded(value) require(len(raw) <= 65536, 'bounded_probe_record') fd = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=parent) try: view = memoryview(raw) while view: written = os.write(fd, view) require(written > 0, 'complete_create_once_probe_record') view = view[written:] os.fsync(fd) finally: os.close(fd) os.fsync(parent) def host_read(pin): # No ecb/d5 import, subprocess, NSS, preflight, sample or retry. records = {} for name in PROBE_RECORDS: try: raw, metadata = pin.read_file(BASE / QUALITY_PHASE / name, 65536) records[name] = dict(sha256=sha(raw), metadata=metadata, record=raw.decode('ascii') if name == 'probe.log' else pin.parsed(raw)) except FileNotFoundError: records[name] = None print(pin.encoded(dict(case=CASE_ID, original_case=OLD.name, phase=QUALITY_PHASE, read_only=True, records=records)).decode(), end='') def host_probe(pin): proof = None phase = -1 case = pin.directory(BASE) try: pin.absence(case, QUALITY_PHASE) proof = SharedGenerationProof(pin) binding = proof.binding() require(proof.artifacts['examples/operator_probe'][:2] == (IMAGE, ARTIFACT), 'fixed_original_single_native_probe') def fresh(): value = proof.witness() proof.generation.no_broker(proof.operator) return value before = fresh() os.mkdir(QUALITY_PHASE, 0o700, dir_fd=case) os.fsync(case) phase = os.open(QUALITY_PHASE, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=case) save(pin, phase, 'intent.json', dict(binding, once=True, no_retry=True, sample_limit=1)) save(pin, phase, 'before.json', dict(binding, witness=before)) require(fresh() == before, 'same_proven_generation_before_one_native_sample') save(pin, phase, 'start-intent.json', dict(binding, argv=probe_args(), once=True)) code = proof.operator.long_command(probe_args(), BASE / QUALITY_PHASE / 'probe.log', 10) log, _ = pin.read_file(BASE / QUALITY_PHASE / 'probe.log', 16384) save(pin, phase, 'execution.json', dict(binding, exit_code=code, probe_log_sha256=sha(log))) after = fresh() require(before == after, 'new_generation_runtime_boot_pin_source_preserved') save(pin, phase, 'after.json', dict(binding, witness=after)) sample = pin.parsed(log) if code == 0 else None if code == 0: sample_quality(sample, proof.expected['boot_id']) links = {name + '_witness': dict(filename=name + '.json', sha256=sha(pin.read_file(BASE / QUALITY_PHASE / (name + '.json'), 65536)[0])) for name in ('before','after')} result = dict(binding, **links, exit_code=code, sample=sample, probe_log_sha256=sha(log), source_quality_qualified=code == 0, runtime_boot_pin_source_preserved=True, clock_authority=False, signed_attestation=False, signer_created=False, broker_started=False, http_deployed=False, no_rmm_jobs=True) save(pin, phase, 'result.json', result) if code == 0: proof.quality_proof(sha(pin.read_file(BASE / QUALITY_PHASE / 'result.json', 65536)[0])) print(pin.encoded(result).decode(), end='') except Exception as error: if phase >= 0: tag = str(error) if isinstance(error, GuardDenied) and str(error).isascii() and len(str(error)) <= 128 \ and all(value in 'abcdefghijklmnopqrstuvwxyz0123456789_' for value in str(error)) else 'unexpected_native_probe_exception' save(pin, phase, 'failure.json', dict(profile=PROFILE, case=CASE_ID, phase=QUALITY_PHASE, fixed_tag=tag, failed=True, read_original_phase_only=True)) raise finally: if proof is not None: proof.close() if phase >= 0: os.close(phase) os.close(case) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('command', choices=('host-probe','host-read')) args = parser.parse_args() require(sys.flags.isolated == 1 and os.geteuid() == 0 and os.uname().sysname == 'Linux' and os.uname().machine == 'aarch64', 'isolated_root_server_arm64_only') os.umask(0o077) pin, guard = load_pin_controller() guard() if args.command == 'host-read': host_read(pin) else: host_probe(pin) if __name__ == '__main__': try: main() except Exception: print(json.dumps(dict(profile=PROFILE, case=CASE_ID, phase=QUALITY_PHASE, failed=True, read_original_phase_only=True))) raise SystemExit(1)