#!/usr/bin/env python3 """Finite root-only time signer/bootstrap. Never starts/enables a service or signs time. Private seeds are generated only on the target and never returned. Each phase is create-only; failures retain their original partial state for readback. """ import argparse import grp import hashlib import http.client import importlib.util import json import os from pathlib import Path import re import resource import socket import ssl import stat import subprocess import sys import uuid PIN_SHA = 'fac85dd0399009af36f625232daa5b67ab7fda391dbf95229d4237c307b142ca' PIN_CODE = Path('/var/lib/rmm-time-source-operators') / PIN_SHA / 'pin_bootstrap.py' CASE_ID = '5b358997-3abc-43db-945f-f41855b4e3c0' CASE = Path('/var/lib/rmm-time-source-bootstrap') / CASE_ID ETC = Path('/etc/rmm-time-source') SIGNER = ETC / 'signer.json' PUBLIC = ETC / 'time-public-key.json' BINARY = Path('/usr/local/libexec/rmm-time-broker') UNIT = Path('/etc/systemd/system/rmm-time-broker.service') GROUP = 'rmm-time-gateway' BROKER_SHA = '5d8d786925c060eb042f0a592453f11970c32c4287fa4c9464f6f6a6e38cb201' BROKER_BYTES = 1067136 SERVER = Path('/opt/rust-discovery') CERTIFICATES = tuple(SERVER / 'devstate' / kind / leaf for kind in ('pki', 'api-pki') for leaf in ('ca.pem', 'server.pem')) PROFILE = 'rmm.server-time-broker.bootstrap.v1' GENERATION_CASE_ID = 'c9a94f94-eecd-4c66-933d-c45c1a79c7a8' GENERATION_CASE = CASE.parent / GENERATION_CASE_ID QUALITY_PHASE = 'probe-native-source-v1' QUALITY_CONTROLLER_SHA = 'c15f4dad9aeb51270fbee7ba28a545cfe9f6a879d0bc226cf5ddda9036a5a2b6' QUALITY_RESULT_SHA = 'ab8a6511517c6e3c01db2351ccdc5c48c73f34112c9ac863d0ea64de46665933' GROUPADD_SHA = '468289aa24d8e9bacb1f21d315e59dc49febec5f120eb7a01b44fe6e98700ed0' PKCS8 = bytes.fromhex('302e020100300506032b657004220420') SPKI = bytes.fromhex('302a300506032b6570032100') UNIT_RAW = b'''[Unit] Description=RMM local time attestation broker (demand only) ConditionPathExists=/etc/rmm-time-source/signer.json ConditionPathExists=/etc/rmm-time-source/chrony-pin.json [Service] Type=exec User=root Group=_chrony SupplementaryGroups=rmm-time-gateway ExecStart=/usr/local/libexec/rmm-time-broker NoNewPrivileges=yes CapabilityBoundingSet=CAP_SYS_PTRACE CAP_DAC_OVERRIDE AmbientCapabilities= RestrictAddressFamilies=AF_UNIX IPAddressDeny=any ProtectSystem=strict ProtectHome=yes PrivateDevices=yes PrivateTmp=yes SystemCallFilter=~@debug ptrace process_vm_readv process_vm_writev ReadWritePaths=/run/rmm-time-source UMask=0077 LimitCORE=0 Restart=no ''' class Denied(RuntimeError): pass def require(value, reason): if not value: raise Denied(reason) def encoded(value): return (json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True) + '\n').encode('ascii') def sha(raw): return hashlib.sha256(raw).hexdigest() def stamp(info): return tuple(getattr(info, 'st_' + name) for name in ('dev', 'ino', 'uid', 'gid', 'mode', 'nlink', 'size', 'mtime_ns', 'ctime_ns')) def protected_code(): current = Path('/') for part in PIN_CODE.parent.parts[1:]: current /= part info = current.lstat() require(stat.S_ISDIR(info.st_mode) and info.st_uid == 0 and info.st_mode & 0o022 == 0, 'pin_controller_protected_ancestry') fd = os.open(PIN_CODE, os.O_RDONLY | os.O_NOFOLLOW) try: info = os.fstat(fd) require(stat.S_ISREG(info.st_mode) and info.st_uid == info.st_gid == 0 and stat.S_IMODE(info.st_mode) == 0o600 and info.st_nlink == 1 and info.st_size <= 128 * 1024, 'pin_controller_root_file') raw = os.read(fd, 128 * 1024 + 1) require(len(raw) == info.st_size and sha(raw) == PIN_SHA and stamp(os.fstat(fd)) == stamp(info) and stamp(PIN_CODE.lstat()) == stamp(info), 'reviewed_pin_controller_bytes') finally: os.close(fd) module = importlib.util.module_from_spec(importlib.util.spec_from_loader('rmm_reviewed_pin', loader=None)) module.__file__ = str(PIN_CODE) exec(compile(raw, str(PIN_CODE), 'exec'), module.__dict__) return module, lambda: require(module.read_file(PIN_CODE, 128 * 1024) == (raw, module.identity(info)), 'reviewed_pin_controller_unchanged') def protected_generation(pin): require(type(QUALITY_CONTROLLER_SHA) is str and re.fullmatch('[0-9a-f]{64}', QUALITY_CONTROLLER_SHA), 'reviewed_new_generation_controller_not_bound') path = Path('/var/lib/rmm-time-source-operators') / QUALITY_CONTROLLER_SHA / 'new_generation_probe.py' record = pin.read_file(path, 128 * 1024) require(sha(record[0]) == QUALITY_CONTROLLER_SHA, 'exact_reviewed_new_generation_controller') module = importlib.util.module_from_spec(importlib.util.spec_from_loader('rmm_new_generation_guard', loader=None)) module.__file__ = str(path) exec(compile(record[0], str(path), 'exec'), module.__dict__) require(module.CASE_ID == GENERATION_CASE_ID and module.QUALITY_PHASE == QUALITY_PHASE, 'fixed_new_generation_case_and_quality_phase') original = module.SharedGenerationProof(pin) def guard(): require(pin.read_file(path, 128 * 1024) == record, 'reviewed_new_generation_controller_unchanged') return original, guard def command(pin, path, args, data=None): # Fixed public tools only. Private DER is stdin, never argv/environment/file. parent = pin.directory(path.parent) try: info = path.lstat() require(stat.S_ISREG(info.st_mode) and info.st_uid == 0 and info.st_mode & 0o022 == 0, 'protected_fixed_tool') digest = sha(pin.read_file(path, 4 * 1024 * 1024, stat.S_IMODE(info.st_mode))[0]) require(path != Path('/usr/sbin/groupadd') or digest == GROUPADD_SHA, 'actual_reviewed_groupadd_provenance') result = subprocess.run([str(path), *args], input=data, stdin=None if data is not None else subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10, check=False, env={'PATH': '/usr/sbin:/usr/bin:/sbin:/bin', 'LC_ALL': 'C'}) require(len(result.stdout) <= 16384 and len(result.stderr) <= 16384 and stamp(path.lstat()) == stamp(info) and sha(pin.read_file(path, 4 * 1024 * 1024, stat.S_IMODE(info.st_mode))[0]) == digest, 'fixed_tool_identity_output_bound') return result finally: os.close(parent) def derive_public(pin, seed): require(type(seed) is bytes and len(seed) == 32, 'host_seed_length') result = command(pin, Path('/usr/bin/openssl'), ['pkey', '-inform', 'DER', '-pubout', '-outform', 'DER'], PKCS8 + seed) require(result.returncode == 0 and result.stdout.startswith(SPKI) and len(result.stdout) == len(SPKI) + 32, 'ed25519_public_derivation') return result.stdout[len(SPKI):] def certificate_key(pin, raw): result = command(pin, Path('/usr/bin/openssl'), ['x509', '-inform', 'PEM', '-pubkey', '-noout'], raw) require(result.returncode == 0, 'known_public_certificate_parse') result = command(pin, Path('/usr/bin/openssl'), ['pkey', '-pubin', '-outform', 'DER'], result.stdout) require(result.returncode == 0, 'known_public_certificate_spki') return result.stdout[len(SPKI):] if result.stdout.startswith(SPKI) and len(result.stdout) == len(SPKI) + 32 else None def public_material(pin, path, private=False): certificate = path in CERTIFICATES require(certificate != private, 'only_fixed_public_certificates_or_private_reader_token') require(certificate or path == SERVER / 'devstate/operator-a.token', 'fixed_server_material_path') root = pin.directory(SERVER / 'devstate' if certificate else path.parent) parent = -1 try: if certificate: parent = os.open(path.parent.name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=root) directory_proof = os.fstat(parent) require(directory_proof.st_uid == directory_proof.st_gid == 10001 and stat.S_IMODE(directory_proof.st_mode) == 0o700, 'known_server_public_pki_directory') else: parent = os.dup(root) directory_proof = os.fstat(parent) fd = os.open(path.name, os.O_RDONLY | os.O_NOFOLLOW, dir_fd=parent) try: info = os.fstat(fd) owner = 10001 if certificate else 0 require(stat.S_ISREG(info.st_mode) and info.st_uid == info.st_gid == owner and info.st_nlink == 1 and stat.S_IMODE(info.st_mode) == 0o600 and info.st_size <= 16384, 'actual_fixed_server_material_protection') raw = os.read(fd, 16385) require(len(raw) == info.st_size and len(raw) <= 16384 and stamp(os.fstat(fd)) == stamp(info) and stamp(os.stat(path.name, dir_fd=parent, follow_symlinks=False)) == stamp(info) and stamp(os.fstat(parent)) == stamp(directory_proof) and stamp(os.stat(path.parent.name, dir_fd=root, follow_symlinks=False) if certificate else os.fstat(root)) == stamp(directory_proof), 'actual_fixed_server_material_stable') return raw finally: os.close(fd) finally: if parent >= 0: os.close(parent) os.close(root) def forbidden_keys(pin, original): original.fresh() # Independently verifies fixed API/GW image, UID and runtime before the public read. ca = SERVER / 'devstate/pki/ca.pem' ca_raw = public_material(pin, ca) token = public_material(pin, SERVER / 'devstate/operator-a.token', True).decode('ascii').strip() require(re.fullmatch('[A-Za-z0-9._~-]{16,8192}', token), 'private_reader_token_format') context = ssl.create_default_context(cadata=ca_raw.decode('ascii')) class Loopback(http.client.HTTPSConnection): def connect(self): self.sock = self._context.wrap_socket(socket.create_connection(('127.0.0.1', 18443), timeout=10), server_hostname='rmm-dev.internal') client = Loopback('rmm-dev.internal', 18443, timeout=10, context=context) try: client.request('GET', '/api/v1/job-signing-key', headers={'Authorization': 'Bearer ' + token}) response = client.getresponse() require(response.status == 200, 'actual_public_job_key_getter_denied') raw = response.read(4097) require(len(raw) <= 4096, 'public_job_key_response_bound') job = pin.parsed(raw) require(set(job) == {'schema_version', 'algorithm', 'key_id', 'public_key_hex'} and type(job['schema_version']) is int and job['schema_version'] == 1 and job['algorithm'] == 'Ed25519' and type(job['key_id']) is str and re.fullmatch('[A-Za-z0-9_-]{1,128}', job['key_id']) and type(job['public_key_hex']) is str and re.fullmatch('[0-9a-f]{64}', job['public_key_hex']), 'actual_public_job_key_shape') finally: client.close() del token keys = {job['public_key_hex']} certificates = [] for path in CERTIFICATES: raw = public_material(pin, path) public = certificate_key(pin, raw) certificates.append({'path': str(path), 'certificate_sha256': sha(raw), 'ed25519': public is not None}) if public is not None: keys.add(public.hex()) # Root independently observed these exact role roots absent. Do not scan # credentials or private PEMs, or silently ignore newly provisioned roles. for path in (Path('/etc/rmm-agent-updater'), SERVER / 'devstate/agent-updates'): require(not os.path.lexists(path), 'new_update_health_role_context_requires_review') require(1 <= len(keys) <= 32, 'bounded_known_forbidden_roles') original.fresh() return sorted(keys), {'job_public_key_sha256': sha(bytes.fromhex(job['public_key_hex'])), 'certificates': certificates} def quality_proof(pin, original): require(type(QUALITY_RESULT_SHA) is str and re.fullmatch('[0-9a-f]{64}', QUALITY_RESULT_SHA), 'actual_new_generation_quality_pass_not_bound') # The fixed reviewed shared decoder checks the entire new-generation # result/witness/sample contract, not an old successful build or CLI status. records = original.quality_proof(QUALITY_RESULT_SHA) result_path = GENERATION_CASE / QUALITY_PHASE / 'result.json' require(type(records) is dict and result_path in records and sha(records[result_path][0]) == QUALITY_RESULT_SHA, 'actual_new_generation_quality_original_result') for path, record in records.items(): require(pin.read_file(path, 65536) == record, 'actual_new_generation_quality_records_unchanged') return records # Closed system-manager load namespace, including control, attached and # generator precedence. The fixed /lib compatibility alias is verified below. UNIT_ROOTS = tuple(Path(path) for path in ( '/etc/systemd/system.control', '/run/systemd/system.control', '/run/systemd/transient', '/run/systemd/generator.early', '/etc/systemd/system', '/etc/systemd/system.attached', '/run/systemd/system', '/run/systemd/system.attached', '/run/systemd/generator', '/usr/local/lib/systemd/system', '/usr/lib/systemd/system', '/run/systemd/generator.late')) UNIT_LEAVES = (UNIT.name, UNIT.name + '.d', 'rmm-time-.service.d', 'rmm-.service.d', 'service.d', UNIT.name + '.wants', UNIT.name + '.requires', UNIT.name + '.upholds') def manager_unit_paths(context): result = command(context.pin, Path('/usr/bin/systemctl'), ['--system', '--no-ask-password', '--no-pager', 'show', '--property=UnitPath', '--value']) require(result.returncode == 0 and not result.stderr and result.stdout.isascii() and len(result.stdout) <= 4096, 'actual_manager_unit_load_path') paths = tuple(result.stdout.decode('ascii').split()) known = {str(path) for path in UNIT_ROOTS} | {'/lib/systemd/system'} require(paths and len(paths) <= len(known) and len(set(paths)) == len(paths) and set(paths) <= known, 'unknown_manager_unit_load_path') return paths class UnitComposition: """One fixed unit's protected namespace, not a general unit/path resolver.""" def __init__(self, context): self.context = context self.paths = manager_unit_paths(context) self.own = None self.own_identity = None self.verify() def close(self): if self.own is not None: os.close(self.own) self.own = None def created(self, fd): require(self.own is None, 'only_one_owned_broker_unit') self.own = os.dup(fd) proof = self.context.pin.identity(os.fstat(fd)) self.own_identity = {key: proof[key] for key in ('dev', 'ino', 'uid', 'gid', 'nlink')} require(proof['uid'] == proof['gid'] == 0 and proof['nlink'] == 1, 'owned_broker_unit_identity') def verify(self): context = self.context require(manager_unit_paths(context) == self.paths, 'manager_unit_load_path_changed') # Ubuntu's merged-/usr alias is the only permitted symlink ancestry. # All real load roots below are opened independently without symlinks. alias = Path('/lib') alias_before = None merged_alias = False roots = UNIT_ROOTS if os.path.lexists(alias): alias_before = stamp(alias.lstat()) merged_alias = stat.S_ISLNK(alias.lstat().st_mode) if merged_alias: require(alias.lstat().st_uid == 0 and os.readlink(alias) in ('usr/lib', '/usr/lib'), 'fixed_merged_usr_unit_alias') else: fd = context.pin.directory(alias) os.close(fd) roots += (Path('/lib/systemd/system'),) else: require('/lib/systemd/system' not in self.paths, 'missing_actual_legacy_unit_root') for root in roots: try: fd = context.pin.directory(root) except FileNotFoundError: continue try: before = context.pin.stable_directory(os.fstat(fd)) for name in UNIT_LEAVES: try: actual = context.pin.identity(os.stat(name, dir_fd=fd, follow_symlinks=False)) except FileNotFoundError: continue require(root == UNIT.parent and name == UNIT.name and self.own is not None, 'unexpected_existing_broker_unit_composition') held = context.pin.identity(os.fstat(self.own)) require(actual == held and {key: held[key] for key in self.own_identity} == self.own_identity and stat.S_ISREG(held['mode']) and stat.S_IMODE(held['mode']) in (0o600, 0o644), 'owned_broker_unit_named_identity') raw, proof = context.pin.read_file(UNIT, 8192, stat.S_IMODE(held['mode'])) require(raw == UNIT_RAW and proof == context.pin.identity(os.fstat(self.own)), 'owned_broker_unit_immutable_contents') # A pre-existing dangling alias to this name could acquire its # own drop-ins after our file is created. Reject it, never follow. names = os.listdir(fd) require(len(names) <= 8192, 'bounded_systemd_load_directory') for name in names: if stat.S_ISLNK(os.stat(name, dir_fd=fd, follow_symlinks=False).st_mode): require(Path(os.readlink(name, dir_fd=fd)).name != UNIT.name, 'unexpected_broker_unit_alias') require(context.pin.stable_directory(os.fstat(fd)) == before, 'protected_unit_load_directory_changed') finally: os.close(fd) if alias_before is not None: require(stamp(alias.lstat()) == alias_before and (not merged_alias or os.readlink(alias) in ('usr/lib', '/usr/lib')), 'merged_usr_unit_alias_changed') require(manager_unit_paths(context) == self.paths, 'manager_unit_load_path_changed') class Context: def __init__(self, pin, pin_guard): self.pin, self.pin_guard = pin, pin_guard self.retained_records = {} self.composition = None self.original = None # Closed before loading a new source generation, public-role getter, # entropy, phase directory, group or installation effect. require(type(QUALITY_RESULT_SHA) is str and re.fullmatch('[0-9a-f]{64}', QUALITY_RESULT_SHA), 'actual_new_generation_quality_pass_not_bound') try: self.original, self.generation_guard = protected_generation(pin) require(self.original.artifacts['rmm-time-broker-linux'][1] == {'bytes': BROKER_BYTES, 'sha256': BROKER_SHA, 'elf_machine': 183}, 'original_exact_broker_elf') self.quality_records = quality_proof(pin, self.original) self.original.namespace_verify() self.forbidden, self.roles = forbidden_keys(pin, self.original) self.fresh() except BaseException: self.close() raise def close(self): if self.composition is not None: self.composition.close() self.composition = None if self.original is not None: self.original.close() self.original = None def fresh(self): self.pin_guard() self.generation_guard() current = self.original.fresh() self.original.namespace_verify() for path, record in {**self.quality_records, **self.retained_records}.items(): require(self.pin.read_file(path, 65536) == record, 'original_actual_quality_proof_unchanged') raw, proof = self.pin.read_file(ETC / 'chrony-pin.json', 8192) require(raw == self.original.public_pin_raw == encoded(current) and proof == self.original.public_pin_metadata, 'new_generation_chrony_pin_unchanged') for path in (ETC, Path('/run/rmm-time-source'), Path('/run/rmm-time-source/clients')): fd = self.pin.directory(path) try: require(self.pin.stable_directory(os.fstat(fd)) == self.original.target_directories[str(path)], 'original_runtime_directory_identity') finally: os.close(fd) keys, roles = forbidden_keys(self.pin, self.original) require(keys == self.forbidden and roles == self.roles, 'actual_known_public_roles_unchanged') if self.composition is not None: self.composition.verify() def create_file(context, path, raw, mode): context.fresh() parent = context.pin.directory(path.parent) try: context.pin.absence(parent, path.name) fd = os.open(path.name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=parent) try: view = memoryview(raw) while view: n = os.write(fd, view) require(n > 0, 'complete_owned_file_write') view = view[n:] os.fsync(fd) if path == UNIT and context.composition is not None: context.composition.created(fd) context.fresh() os.fchmod(fd, mode) os.fsync(fd) require(context.pin.identity(os.fstat(fd)) == context.pin.identity(os.stat(path.name, dir_fd=parent, follow_symlinks=False)), 'owned_file_named_identity') finally: os.close(fd) os.fsync(parent) actual, proof = context.pin.read_file(path, max(8192, len(raw)), mode) require(actual == raw, 'owned_file_exact_bytes') return proof finally: os.close(parent) def public_fields(configuration, public): return {'schema_version': 1, 'algorithm': 'Ed25519', 'server_instance': configuration['server_instance'], 'key_id': configuration['key_id'], 'key_generation': configuration['key_generation'], 'public_key_hex': public.hex()} def key_phase(context): for path in (SIGNER, PUBLIC): require(not os.path.lexists(path), 'key_target_already_exists') seed = os.getrandom(32) require(len(seed) == 32, 'host_csprng_exact_seed') public = derive_public(context.pin, seed) require(public.hex() not in context.forbidden, 'time_key_role_reuse') configuration = {'schema_version': 1, 'server_instance': str(uuid.uuid4()), 'key_id': 'time-' + uuid.uuid4().hex, 'key_generation': 1, 'signing_key_hex': seed.hex(), 'forbidden_public_keys': context.forbidden, 'expected_server_uid': 10001, 'server_gid': 10001} public_pin = public_fields(configuration, public) require(len(encoded(configuration)) <= 8192, 'bounded_private_signer_configuration') proof = create_file(context, SIGNER, encoded(configuration), 0o600) pubproof = create_file(context, PUBLIC, encoded(public_pin), 0o600) return {'public_pin': public_pin, 'public_pin_sha256': sha(encoded(public_pin)), 'public_pin_metadata': pubproof, 'signer_metadata': proof, 'forbidden_role_evidence': context.roles, 'seed_exported': False, 'broker_started': False, 'time_signed': False} def retained_key(context): record, record_proof = context.pin.read_file(CASE / 'broker-key/result.json', 16384) require(not (CASE / 'broker-key/failure.json').exists(), 'own_key_phase_failed') result = context.pin.parsed(record)['result'] public_raw, proof = context.pin.read_file(PUBLIC, 8192) require(sha(public_raw) == result['public_pin_sha256'] and proof == result['public_pin_metadata'], 'own_public_key_pin_unchanged') public = context.pin.parsed(public_raw) raw, proof = context.pin.read_file(SIGNER, 8192) # Necessary retained-key verification; never return raw or its hash. configuration = context.pin.parsed(raw) require(set(configuration) == {'schema_version', 'server_instance', 'key_id', 'key_generation', 'signing_key_hex', 'forbidden_public_keys', 'expected_server_uid', 'server_gid'} and proof == result['signer_metadata'] and type(configuration['signing_key_hex']) is str and re.fullmatch('[0-9a-f]{64}', configuration['signing_key_hex']) and configuration['forbidden_public_keys'] == context.forbidden and type(configuration['schema_version']) is int and type(configuration['key_generation']) is int and configuration['schema_version'] == configuration['key_generation'] == 1 and configuration['expected_server_uid'] == configuration['server_gid'] == 10001 and str(uuid.UUID(configuration['server_instance'])) == configuration['server_instance'] and uuid.UUID(configuration['server_instance']).int > 0 and type(configuration['key_id']) is str and re.fullmatch('[A-Za-z0-9_-]{1,64}', configuration['key_id']), 'own_retained_signer_configuration') require(public == public_fields(configuration, derive_public(context.pin, bytes.fromhex(configuration['signing_key_hex']))) and public == result['public_pin'] and public['public_key_hex'] not in context.forbidden, 'own_retained_time_key_role') context.retained_records.update({CASE / 'broker-key/result.json': (record, record_proof), PUBLIC: context.pin.read_file(PUBLIC, 8192), SIGNER: (raw, proof)}) return record_proof def group_lookup(name_or_gid): try: value = grp.getgrgid(name_or_gid) if type(name_or_gid) is int else grp.getgrnam(name_or_gid) return {'name': value.gr_name, 'gid': value.gr_gid, 'members': value.gr_mem} except KeyError: return None def group_phase(context): retained_key(context) require(group_lookup(GROUP) is None and group_lookup(10001) is None, 'group_name_or_gid_already_exists') raw, proof = context.pin.read_file(Path('/etc/group'), 1024 * 1024, 0o644) require(raw.endswith(b'\n'), 'canonical_public_group_file') context.fresh() require(group_lookup(GROUP) is None and group_lookup(10001) is None, 'group_name_or_gid_collision_before_create') result = command(context.pin, Path('/usr/sbin/groupadd'), ['--system', '--gid', '10001', GROUP]) require(result.returncode == 0, 'own_groupadd_failed_no_retry') context.fresh() added = {'name': GROUP, 'gid': 10001, 'members': []} require(group_lookup(GROUP) == group_lookup(10001) == added, 'own_group_exact_name_gid_empty_members') after, after_proof = context.pin.read_file(Path('/etc/group'), 1024 * 1024, 0o644) row = (GROUP + ':x:10001:\n').encode() require(after.count(row) == 1 and after.replace(row, b'', 1) == raw, 'only_own_public_group_row_added') return {'group': added, 'public_group_before_sha256': sha(raw), 'public_group_after_sha256': sha(after), 'public_group_before_metadata': proof, 'public_group_after_metadata': after_proof, 'groupadd_sha256': GROUPADD_SHA, 'existing_group_members_unchanged': True, 'service_enabled': False, 'broker_started': False} def install_phase(context): retained_key(context) raw, group_proof = context.pin.read_file(CASE / 'broker-group/result.json', 16384) require(not (CASE / 'broker-group/failure.json').exists(), 'own_group_phase_failed') receipt = context.pin.parsed(raw) require(receipt['profile'] == PROFILE and receipt['case'] == CASE_ID and receipt['phase'] == 'broker-group' and receipt['result']['group'] == {'name': GROUP, 'gid': 10001, 'members': []} and receipt['result']['existing_group_members_unchanged'] is True, 'own_group_creation_provenance') require(group_lookup(GROUP) == group_lookup(10001) == {'name': GROUP, 'gid': 10001, 'members': []} and group_lookup('_chrony')['gid'] == 989 and group_lookup(989)['name'] == '_chrony', 'actual_unit_group_resolution') require(not os.path.lexists(BINARY), 'installation_target_already_exists') context.composition = UnitComposition(context) # Before even a libexec mkdir or binary write. context.retained_records[CASE / 'broker-group/result.json'] = (raw, group_proof) if not os.path.lexists(BINARY.parent): parent = context.pin.directory(BINARY.parent.parent) try: fd = context.pin.new_directory(parent, BINARY.parent.name, 0o755, 0, context) os.close(fd) finally: os.close(parent) else: fd = context.pin.directory(BINARY.parent) os.close(fd) binary, _ = context.pin.read_file(context.original.artifacts['rmm-time-broker-linux'][0], BROKER_BYTES, 0o500) require(len(binary) == BROKER_BYTES and sha(binary) == BROKER_SHA, 'original_broker_copy_bytes') binary_proof = create_file(context, BINARY, binary, 0o500) unit_proof = create_file(context, UNIT, UNIT_RAW, 0o644) return {'binary_sha256': BROKER_SHA, 'binary_bytes': BROKER_BYTES, 'binary_metadata': binary_proof, 'unit_sha256': sha(UNIT_RAW), 'unit_metadata': unit_proof, 'own_group_receipt_sha256': sha(raw), 'manager_unit_load_paths': context.composition.paths, 'daemon_reload': False, 'service_enabled': False, 'broker_started': False, 'time_signed': False} def phase(name, action, pin, pin_guard): case_fd = pin.directory(CASE) phase_fd = -1 context = None try: pin.absence(case_fd, name) # Before a fresh getter, seed or native command. context = Context(pin, pin_guard) context.fresh() os.mkdir(name, 0o700, dir_fd=case_fd) os.fsync(case_fd) phase_fd = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=case_fd) context.fresh() pin.exclusive(phase_fd, 'intent.json', encoded({'profile': PROFILE, 'case': CASE_ID, 'phase': name, 'controller_sha256': sha(Path(__file__).read_bytes()), 'pin_controller_sha256': PIN_SHA, 'source_tar_sha256': context.original.source_sha, 'manifest_sha256': context.original.manifest_sha, 'generation_case': GENERATION_CASE_ID, 'generation_controller_sha256': QUALITY_CONTROLLER_SHA, 'quality_result_sha256': QUALITY_RESULT_SHA, 'chrony_public_pin_sha256': sha(context.original.public_pin_raw)})) result = action(context) context.fresh() receipt = {'profile': PROFILE, 'case': CASE_ID, 'phase': name, 'result': result, 'generation_case': GENERATION_CASE_ID, 'generation_controller_sha256': QUALITY_CONTROLLER_SHA, 'quality_result_sha256': QUALITY_RESULT_SHA, 'chrony_public_pin_sha256': sha(context.original.public_pin_raw)} pin.exclusive(phase_fd, 'result.json', encoded(receipt)) print(encoded(receipt).decode('ascii'), end='') except Exception as error: failure = {'profile': PROFILE, 'case': CASE_ID, 'phase': name, 'failed': True, 'failure_reason': str(error) if isinstance(error, Denied) else 'unexpected_broker_bootstrap_exception', 'read_original_case_only': True, 'no_retry_cleanup_or_adopt': True} if phase_fd >= 0: pin.exclusive(phase_fd, 'failure.json', encoded(failure)) print(encoded(failure).decode('ascii'), end='') raise SystemExit(1) finally: if context is not None: context.close() if phase_fd >= 0: os.close(phase_fd) os.close(case_fd) def read(pin): records = {} for name in ('broker-key', 'broker-group', 'broker-install'): records[name] = {} for leaf in ('intent', 'result', 'failure'): try: raw, proof = pin.read_file(CASE / name / (leaf + '.json'), 16384) records[name][leaf] = {'sha256': sha(raw), 'metadata': proof, 'record': pin.parsed(raw)} except FileNotFoundError: records[name][leaf] = None metadata = {} for path in (SIGNER, PUBLIC, BINARY, UNIT): parent = -1 try: parent = pin.directory(path.parent) metadata[str(path)] = pin.identity(os.stat(path.name, dir_fd=parent, follow_symlinks=False)) except FileNotFoundError: metadata[str(path)] = None except (pin.Denied, NotADirectoryError): metadata[str(path)] = {'inspection_denied': True} finally: if parent >= 0: os.close(parent) print(encoded({'profile': PROFILE, 'case': CASE_ID, 'read_only': True, 'records': records, 'metadata': metadata}).decode('ascii'), end='') def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('command', choices=('host-key', 'host-group', 'host-install', '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_linux_arm64_only') os.umask(0o077) resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) pin, pin_guard = protected_code() pin.case_path(CASE_ID) if args.command == 'host-read': read(pin) else: choices = {'host-key': ('broker-key', key_phase), 'host-group': ('broker-group', group_phase), 'host-install': ('broker-install', install_phase)} phase(*choices[args.command], pin, pin_guard) if __name__ == '__main__': try: main() except Exception: print(encoded({'failed': True, 'failure_reason': 'unexpected_broker_bootstrap_exception', 'read_original_case_only': True}).decode('ascii'), end='') raise SystemExit(1)