450 lines
27 KiB
Python
450 lines
27 KiB
Python
#!/usr/bin/env python3
|
|
"""One fixed installed broker reload/start and process/socket observation only.
|
|
|
|
No enable/restart/stop/cleanup, Unix request, time signature or RMM job. Only
|
|
host-read is permitted after uncertain effect; never repeat the start phase.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import importlib.util
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import select
|
|
import stat
|
|
import sys
|
|
import time
|
|
|
|
BOOTSTRAP_SHA = '2fdcbc951fe49f0a606dfd935d2e5b13d8680b7fb8c89209e7efb98b07896ea2'
|
|
BOOTSTRAP = Path('/var/lib/rmm-time-source-operators') / BOOTSTRAP_SHA / 'broker_bootstrap.py'
|
|
CASE_ID = '5b358997-3abc-43db-945f-f41855b4e3c0'
|
|
CASE = Path('/var/lib/rmm-time-source-bootstrap') / CASE_ID
|
|
PHASE = 'broker-start-acceptance-v1'
|
|
PROFILE = 'rmm.server-time-broker.installed-start-acceptance.v1'
|
|
UNIT_NAME = 'rmm-time-broker.service'
|
|
UNIT = Path('/etc/systemd/system') / UNIT_NAME
|
|
BINARY = Path('/usr/local/libexec/rmm-time-broker')
|
|
SOCKET = Path('/run/rmm-time-source/broker.sock')
|
|
UNIT_SHA = '4792bfb65763f5a5146044d2ba152acd0a876b66c29d8cc66c16a5250214af2c'
|
|
BINARY_SHA = '5d8d786925c060eb042f0a592453f11970c32c4287fa4c9464f6f6a6e38cb201'
|
|
RESULTS = {'broker-key':'fa81bde18a68c7c367ae7facf3914711072ba5238f0d10b5eba29c320efa3d75',
|
|
'broker-group':'1f987cbe7e7558ecb1e4dac9542bda69d6f09343a40098c5be4817ac9ebfca45',
|
|
'broker-install':'b52aa57971fcad5a9ff3780765f4712d4029d078aab71f94eaec6d805a642f71'}
|
|
ABI_RECEIPT_SHA = '77c98ef563837e36c487227142258490d57b630b56b2c2f8db6474a51263aa0d'
|
|
BUS_PATH = '/org/freedesktop/systemd1/unit/rmm_2dtime_2dbroker_2eservice'
|
|
SERVICE_IFACE = 'org.freedesktop.systemd1.Service'
|
|
UNIT_IFACE = 'org.freedesktop.systemd1.Unit'
|
|
CAPS = 0x80002
|
|
DEBUG_DENY = ['lookup_dcookie','perf_event_open','pidfd_getfd','process_vm_readv','process_vm_writev',
|
|
'ptrace','rtas','s390_runtime_instr','sys_debug_setcontext']
|
|
OTHER_EXEC = ('ExecCondition','ExecStartPre','ExecStartPost','ExecReload','ExecStop','ExecStopPost')
|
|
RECORDS = ('intent.json','before.json','reload-intent.json','reload-exit.json','effective-before-start.json',
|
|
'start-intent.json','start-exit.json','after.json','result.json','failure.json','reload.log','start.log')
|
|
|
|
|
|
class Denied(RuntimeError):
|
|
pass
|
|
|
|
|
|
def require(value, reason):
|
|
if not value:
|
|
raise Denied(reason)
|
|
|
|
|
|
def sha(raw):
|
|
return hashlib.sha256(raw).hexdigest()
|
|
|
|
|
|
def encoded(value):
|
|
return (json.dumps(value,sort_keys=True,separators=(',',':'),ensure_ascii=True)+'\n').encode('ascii')
|
|
|
|
|
|
def bounded(path,maximum):
|
|
with path.open('rb') as stream:raw = stream.read(maximum+1)
|
|
require(len(raw) <= maximum,'bounded_fixed_kernel_observation')
|
|
return raw
|
|
|
|
|
|
def load_bootstrap():
|
|
current = os.open('/',os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW)
|
|
try:
|
|
for name in BOOTSTRAP.parent.parts[1:]:
|
|
info = os.fstat(current)
|
|
require(info.st_uid == 0 and info.st_mode & 0o022 == 0,'protected_bootstrap_ancestry')
|
|
child = os.open(name,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=current)
|
|
os.close(current); current = child
|
|
info = os.fstat(current)
|
|
require(info.st_uid == 0 and info.st_mode & 0o022 == 0,'protected_bootstrap_parent')
|
|
fd = os.open(BOOTSTRAP.name,os.O_RDONLY|os.O_NOFOLLOW,dir_fd=current)
|
|
with os.fdopen(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
|
|
stat.S_IMODE(before.st_mode) == 0o600 and before.st_nlink == 1 and before.st_size <= 131072,
|
|
'reviewed_root_bootstrap_file')
|
|
raw = stream.read(131073)
|
|
proof = tuple(getattr(before,'st_'+n) for n in ('dev','ino','uid','gid','mode','nlink','size','mtime_ns','ctime_ns'))
|
|
actual = lambda x: tuple(getattr(x,'st_'+n) for n in ('dev','ino','uid','gid','mode','nlink','size','mtime_ns','ctime_ns'))
|
|
require(len(raw) == before.st_size and sha(raw) == BOOTSTRAP_SHA and
|
|
proof == actual(os.fstat(stream.fileno())) == actual(os.stat(BOOTSTRAP.name,dir_fd=current,follow_symlinks=False)),
|
|
'exact_bootstrap_bytes_and_identity')
|
|
finally:
|
|
os.close(current)
|
|
module = importlib.util.module_from_spec(importlib.util.spec_from_loader('rmm_installed_broker_bootstrap',loader=None))
|
|
module.__file__ = str(BOOTSTRAP)
|
|
exec(compile(raw,str(BOOTSTRAP),'exec'),module.__dict__)
|
|
pin,pin_guard = module.protected_code()
|
|
held = pin.read_file(BOOTSTRAP,131072)
|
|
require(held[0] == raw,'same_loaded_bootstrap_bytes')
|
|
def guard():
|
|
pin_guard()
|
|
require(pin.read_file(BOOTSTRAP,131072) == held,'reviewed_bootstrap_unchanged')
|
|
return module,pin,guard
|
|
|
|
|
|
class InstalledProof:
|
|
"""Actual qualified installation, never a bypass/adoption of UnitComposition."""
|
|
def __init__(self,bootstrap,pin,guard):
|
|
self.bootstrap,self.pin,self.guard = bootstrap,pin,guard
|
|
self.load_paths = None
|
|
self.context = None; self.signer_fd = -1; self.signer_parent = -1
|
|
try:
|
|
self.context = bootstrap.Context(pin,guard)
|
|
own = self.context.original.hold(Path(__file__),131072)
|
|
require(own.path.name == 'broker_start_acceptance.py' and own.path.parent.name == sha(own.raw),
|
|
'exact_content_addressed_start_controller')
|
|
self.results = {}
|
|
for phase,digest in RESULTS.items():
|
|
directory = pin.directory(CASE/phase)
|
|
try: pin.absence(directory,'failure.json')
|
|
finally: os.close(directory)
|
|
held = self.context.original.hold(CASE/phase/'result.json',65536,expected=digest)
|
|
value = pin.parsed(held.raw)
|
|
require(value['profile'] == bootstrap.PROFILE and value['case'] == CASE_ID and value['phase'] == phase and
|
|
value['generation_case'] == bootstrap.GENERATION_CASE_ID and
|
|
value['generation_controller_sha256'] == bootstrap.QUALITY_CONTROLLER_SHA and
|
|
value['quality_result_sha256'] == bootstrap.QUALITY_RESULT_SHA,
|
|
'exact_successful_own_installation_origin')
|
|
self.results[phase] = value['result']
|
|
installed = self.results['broker-install']
|
|
require(installed['binary_sha256'] == BINARY_SHA and installed['binary_bytes'] == 1067136 and
|
|
installed['unit_sha256'] == UNIT_SHA and all(installed[k] is False for k in
|
|
('daemon_reload','service_enabled','broker_started','time_signed')),
|
|
'actual_installed_not_started_broker')
|
|
require(sha(bootstrap.UNIT_RAW) == UNIT_SHA and len(bootstrap.UNIT_RAW) == 657,'reviewed_exact_unit_source')
|
|
self.unit = self.context.original.hold(UNIT,8192,0o644,UNIT_SHA,installed['unit_metadata'])
|
|
self.load_paths = tuple(installed['manager_unit_load_paths'])
|
|
self.binary = self.context.original.hold(BINARY,2*1024*1024,0o500,BINARY_SHA,installed['binary_metadata'])
|
|
key = self.results['broker-key']
|
|
self.public = self.context.original.hold(bootstrap.PUBLIC,8192,expected=key['public_pin_sha256'],metadata=key['public_pin_metadata'])
|
|
public = pin.parsed(self.public.raw)
|
|
require(public == key['public_pin'] and public['algorithm'] == 'Ed25519' and
|
|
public['public_key_hex'] not in self.context.forbidden,'retained_separate_public_time_key')
|
|
self.signer_metadata = key['signer_metadata']
|
|
self.signer_parent = pin.directory(bootstrap.SIGNER.parent)
|
|
self.signer_fd = os.open(bootstrap.SIGNER.name,os.O_PATH|os.O_NOFOLLOW,dir_fd=self.signer_parent)
|
|
# Metadata-only O_PATH: this controller never reads signing seeds.
|
|
self.fresh()
|
|
except BaseException:
|
|
self.close(); raise
|
|
|
|
def composition(self):
|
|
# A separate qualified installed proof permits only the original own
|
|
# unit inode. Never instantiate/bypass UnitComposition's absence guard.
|
|
require(self.bootstrap.manager_unit_paths(self.context) == self.load_paths,'same_original_manager_load_paths')
|
|
roots = list(self.bootstrap.UNIT_ROOTS)
|
|
alias = Path('/lib');alias_state = None
|
|
if os.path.lexists(alias):
|
|
alias_state = self.bootstrap.stamp(alias.lstat())
|
|
if alias.is_symlink():
|
|
require(alias.lstat().st_uid == 0 and os.readlink(alias) in ('usr/lib','/usr/lib'),'fixed_merged_usr_alias')
|
|
else:
|
|
extra = self.pin.directory(alias);os.close(extra);roots.append(alias/'systemd/system')
|
|
else:
|
|
require('/lib/systemd/system' not in self.load_paths,'missing_original_legacy_unit_load_root')
|
|
for root in roots:
|
|
try:fd = self.pin.directory(root)
|
|
except FileNotFoundError:continue
|
|
try:
|
|
before = self.pin.stable_directory(os.fstat(fd))
|
|
for leaf in self.bootstrap.UNIT_LEAVES:
|
|
try:meta = self.pin.identity(os.stat(leaf,dir_fd=fd,follow_symlinks=False))
|
|
except FileNotFoundError:continue
|
|
require(root/leaf == UNIT and meta == self.unit.metadata,'unexpected_installed_unit_composition')
|
|
names = os.listdir(fd);require(len(names) <= 8192,'bounded_installed_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_installed_unit_alias')
|
|
require(self.pin.stable_directory(os.fstat(fd)) == before,'same_installed_load_directory')
|
|
finally:os.close(fd)
|
|
if alias_state is not None:
|
|
require(self.bootstrap.stamp(alias.lstat()) == alias_state,'same_merged_usr_alias')
|
|
require(self.bootstrap.manager_unit_paths(self.context) == self.load_paths,'same_original_manager_load_paths')
|
|
|
|
def fresh(self):
|
|
self.guard(); self.context.fresh(); self.composition()
|
|
pin = self.pin
|
|
require(pin.identity(os.fstat(self.signer_fd)) == self.signer_metadata ==
|
|
pin.identity(os.stat(self.bootstrap.SIGNER.name,dir_fd=self.signer_parent,follow_symlinks=False)),
|
|
'same_original_private_signer_metadata_without_read')
|
|
fresh_parent = pin.directory(self.bootstrap.SIGNER.parent)
|
|
try: require(pin.stable_directory(os.fstat(fresh_parent)) == pin.stable_directory(os.fstat(self.signer_parent)),
|
|
'same_private_signer_parent')
|
|
finally: os.close(fresh_parent)
|
|
lookup = self.bootstrap.group_lookup
|
|
require(lookup('rmm-time-gateway') == lookup(10001) == {'name':'rmm-time-gateway','gid':10001,'members':[]} and
|
|
lookup('_chrony')['gid'] == 989 and lookup(989)['name'] == '_chrony','exact_existing_installed_groups')
|
|
return self.context.original.witness()
|
|
|
|
def close(self):
|
|
for name in ('signer_fd','signer_parent'):
|
|
value = getattr(self,name)
|
|
if value >= 0: os.close(value); setattr(self,name,-1)
|
|
if self.context is not None: self.context.close(); self.context = None
|
|
|
|
|
|
def typed(proof,interface,name,signature):
|
|
raw = proof.context.original.operator.run(['/usr/bin/busctl','--system','--json=short','get-property',
|
|
'org.freedesktop.systemd1',BUS_PATH,interface,name],timeout=3,limit=32768)
|
|
value = proof.pin.parsed(raw)
|
|
require(type(value) is dict and set(value) == {'type','data'} and value['type'] == signature,
|
|
'exact_typed_loaded_property')
|
|
return value['data']
|
|
|
|
|
|
def typed_snapshot(proof):
|
|
# Actual Root-read ABI: systemd259.5 Ubuntu, receipt77c98e. No invented zeros.
|
|
specs = {'User':'s','Group':'s','SupplementaryGroups':'as','Type':'s','Restart':'s','NRestarts':'u',
|
|
'CapabilityBoundingSet':'t','AmbientCapabilities':'t','NoNewPrivileges':'b','ProtectSystem':'s','ProtectHome':'s',
|
|
'PrivateTmp':'b','PrivateDevices':'b','RestrictAddressFamilies':'(bas)','IPAddressDeny':'a(iayu)',
|
|
'IPAddressAllow':'a(iayu)','SystemCallFilter':'(bas)','ReadWritePaths':'as','UMask':'u','LimitCORE':'t',
|
|
'MainPID':'u','ControlPID':'u','ControlGroup':'s','ExecStartEx':'a(sasasttttuii)'}
|
|
value = {name:typed(proof,SERVICE_IFACE,name,signature) for name,signature in specs.items()}
|
|
for name in OTHER_EXEC:
|
|
value[name] = typed(proof,SERVICE_IFACE,name,'a(sasbttttuii)')
|
|
value[name+'Ex'] = typed(proof,SERVICE_IFACE,name+'Ex','a(sasasttttuii)')
|
|
for name,signature in {'Id':'s','LoadState':'s','ActiveState':'s','SubState':'s','FragmentPath':'s',
|
|
'DropInPaths':'as','UnitFileState':'s','NeedDaemonReload':'b','Job':'(uo)','InvocationID':'ay'}.items():
|
|
value[name] = typed(proof,UNIT_IFACE,name,signature)
|
|
return value
|
|
|
|
|
|
def effective(value,running=False):
|
|
require(value['Id'] == UNIT_NAME and value['LoadState'] == 'loaded' and value['FragmentPath'] == str(UNIT) and
|
|
value['DropInPaths'] == [] and value['UnitFileState'] == 'static' and value['NeedDaemonReload'] is False and
|
|
value['Job'] == [0,'/'],'exact_loaded_fragment_no_dropins_enable_or_pending_job')
|
|
require(value['Type'] == 'exec' and value['Restart'] == 'no' and type(value['NRestarts']) is int and value['NRestarts'] == 0 and
|
|
value['User'] == 'root' and value['Group'] == '_chrony' and value['SupplementaryGroups'] == ['rmm-time-gateway'],
|
|
'exact_effective_identity_type_and_no_restart')
|
|
require(type(value['CapabilityBoundingSet']) is int and value['CapabilityBoundingSet'] == CAPS and
|
|
type(value['AmbientCapabilities']) is int and value['AmbientCapabilities'] == 0 and
|
|
all(value[k] is True for k in ('NoNewPrivileges','PrivateTmp','PrivateDevices')) and
|
|
value['ProtectHome'] == 'yes' and value['ProtectSystem'] == 'strict' and
|
|
value['RestrictAddressFamilies'] == [True,['AF_UNIX']] and value['IPAddressAllow'] == [] and
|
|
value['IPAddressDeny'] == [[2,[0]*4,0],[10,[0]*16,0]] and value['SystemCallFilter'] == [False,DEBUG_DENY] and
|
|
value['ReadWritePaths'] == ['/run/rmm-time-source'] and value['UMask'] == 0o77 and value['LimitCORE'] == 0,
|
|
'exact_effective_caps_network_filesystem_and_syscall_limits')
|
|
rows = value['ExecStartEx']
|
|
require(type(rows) is list and len(rows) == 1 and type(rows[0]) is list and len(rows[0]) == 10 and
|
|
rows[0][:3] == [str(BINARY),[str(BINARY)],[]] and
|
|
all(type(v) is int and 0 <= v < 2**64 for v in rows[0][3:7]) and
|
|
type(rows[0][7]) is int and 0 <= rows[0][7] < 2**32 and
|
|
all(type(v) is int and -(2**31) <= v < 2**31 for v in rows[0][8:]) and
|
|
all(value[name] == value[name+'Ex'] == [] for name in OTHER_EXEC),
|
|
'single_exact_argv_without_flags_or_other_exec_commands')
|
|
require(type(value['MainPID']) is int and type(value['ControlPID']) is int and value['ControlPID'] == 0,
|
|
'actual_service_process_properties')
|
|
require(type(value['InvocationID']) is list and
|
|
all(type(x) is int and 0 <= x <= 255 for x in value['InvocationID']),'typed_actual_invocation_id')
|
|
if running:
|
|
require(value['ActiveState'] == 'active' and value['SubState'] == 'running' and value['MainPID'] > 1 and
|
|
value['ControlGroup'] == '/system.slice/'+UNIT_NAME and
|
|
len(value['InvocationID']) == 16 and any(value['InvocationID']),
|
|
'one_running_broker_generation')
|
|
else:
|
|
require(value['ActiveState'] == 'inactive' and value['SubState'] == 'dead' and value['MainPID'] == 0 and
|
|
value['InvocationID'] == [],
|
|
'installed_broker_initially_inactive')
|
|
return value
|
|
|
|
|
|
class ProcessProof:
|
|
def __init__(self,proof,state):
|
|
self.proof,self.pid = proof,state['MainPID']; self.pidfd = -1; self.image_fd = -1
|
|
try:
|
|
self.pidfd = os.pidfd_open(self.pid)
|
|
self.image_fd = os.open('/proc/'+str(self.pid)+'/exe',os.O_RDONLY|os.O_CLOEXEC)
|
|
self.expected = None
|
|
self.verify(state)
|
|
except BaseException:
|
|
self.close(); raise
|
|
|
|
def verify(self,state):
|
|
effective(state,True); require(state['MainPID'] == self.pid,'same_started_broker_pid')
|
|
poll = select.poll();poll.register(self.pidfd,select.POLLIN)
|
|
require(not poll.poll(0),'held_started_broker_alive')
|
|
proc = Path('/proc')/str(self.pid)
|
|
before = (proc/'stat').read_text().rsplit(') ',1)[1].split(); birth = int(before[19])
|
|
fields = {}
|
|
for line in (proc/'status').read_text().splitlines():
|
|
key,sep,data = line.partition(':')
|
|
if key in ('Uid','Gid','Groups','CapEff','CapBnd','CapPrm','CapAmb','NoNewPrivs','Seccomp'):
|
|
require(sep and key not in fields,'unique_native_process_status');fields[key] = data.split()
|
|
require(set(fields) == {'Uid','Gid','Groups','CapEff','CapBnd','CapPrm','CapAmb','NoNewPrivs','Seccomp'} and
|
|
fields['Uid'] == ['0']*4 and fields['Gid'] == ['989']*4 and
|
|
set(map(int,fields['Groups'])) <= {0,989,10001} and 10001 in set(map(int,fields['Groups'])) and
|
|
all(len(fields[k]) == 1 and int(fields[k][0],16) == CAPS for k in ('CapEff','CapBnd','CapPrm')) and
|
|
fields['CapAmb'] == ['0000000000000000'] and fields['NoNewPrivs'] == ['1'] and fields['Seccomp'] == ['2'],
|
|
'actual_broker_credentials_capabilities_nnp_seccomp')
|
|
meta = self.proof.pin.identity(os.fstat(self.image_fd))
|
|
require(meta == self.proof.binary.metadata == self.proof.pin.identity((proc/'exe').stat()),
|
|
'held_actual_broker_image_is_exact_installed_inode')
|
|
for name in ('user','pid','cgroup'):
|
|
a,b = (proc/'ns'/name).stat(),(Path('/proc/1/ns')/name).stat()
|
|
require((a.st_dev,a.st_ino) == (b.st_dev,b.st_ino),'broker_actual_host_namespaces')
|
|
mounts = bounded(proc/'mountinfo',1024*1024)
|
|
roots = [line.split() for line in mounts.decode('ascii').splitlines() if len(line.split()) >= 7 and line.split()[4] == '/']
|
|
require(len(roots) == 1 and 'ro' in roots[0][5].split(','),'actual_protected_system_root_readonly')
|
|
cgroup = (proc/'cgroup').read_text().splitlines()
|
|
require(cgroup == ['0::/system.slice/'+UNIT_NAME],'broker_single_expected_cgroup')
|
|
members = (Path('/sys/fs/cgroup/system.slice')/UNIT_NAME/'cgroup.procs').read_text().split()
|
|
require(members == [str(self.pid)],'only_original_broker_cgroup_process')
|
|
require(int((proc/'stat').read_text().rsplit(') ',1)[1].split()[19]) == birth and not poll.poll(0),
|
|
'same_alive_broker_birth_after_observation')
|
|
result = dict(pid=self.pid,birth_ticks=birth,image_sha256=BINARY_SHA,image_metadata=meta,
|
|
invocation_id=state['InvocationID'],uid=0,gid=989,groups=sorted(map(int,fields['Groups'])),
|
|
cap_effective=CAPS,cap_bounding=CAPS,no_new_privileges=True,seccomp_mode=2,
|
|
host_namespaces=True,root_readonly=True,cgroup=state['ControlGroup'])
|
|
require(self.expected is None or self.expected == result,'same_original_started_broker_generation')
|
|
self.expected = result
|
|
return result
|
|
|
|
def close(self):
|
|
for name in ('image_fd','pidfd'):
|
|
value = getattr(self,name)
|
|
if value >= 0:os.close(value);setattr(self,name,-1)
|
|
|
|
|
|
def socket_proof(proof,process):
|
|
parent = proof.pin.directory(SOCKET.parent)
|
|
try:
|
|
before = proof.pin.stable_directory(os.fstat(parent))
|
|
meta = proof.pin.identity(os.stat(SOCKET.name,dir_fd=parent,follow_symlinks=False))
|
|
require(stat.S_ISSOCK(meta['mode']) and stat.S_IMODE(meta['mode']) == 0o660 and
|
|
meta['uid'] == 0 and meta['gid'] == 10001 and meta['nlink'] == 1,'exact_new_broker_socket_inode')
|
|
raw = bounded(Path('/proc/net/unix'),2*1024*1024)
|
|
lines = [line.split() for line in raw.decode('ascii').splitlines()[1:] if len(line.split()) == 8 and line.split()[7] == str(SOCKET)]
|
|
require(len(lines) == 1 and lines[0][3:6] == ['00010000','0001','01'] and re.fullmatch('[1-9][0-9]*',lines[0][6]),
|
|
'one_actual_listening_unix_stream_socket')
|
|
kernel_inode = int(lines[0][6]);fds = Path('/proc')/str(process.pid)/'fd';names = list(fds.iterdir())
|
|
require(len(names) <= 256,'bounded_owned_broker_descriptors')
|
|
holders = [int(path.name) for path in names if os.readlink(path) == 'socket:['+str(kernel_inode)+']']
|
|
require(len(holders) == 1,'actual_original_broker_holds_listener')
|
|
require(proof.pin.identity(os.stat(SOCKET.name,dir_fd=parent,follow_symlinks=False)) == meta and
|
|
proof.pin.stable_directory(os.fstat(parent)) == before,'same_broker_socket_and_parent_after_observation')
|
|
return dict(metadata=meta,kernel_inode=kernel_inode,broker_fd=holders[0])
|
|
finally:
|
|
os.close(parent)
|
|
|
|
|
|
def save(pin,fd,name,value):
|
|
require(name in RECORDS and name.endswith('.json'),'fixed_own_phase_record')
|
|
raw = encoded(value);require(len(raw) <= 65536,'bounded_own_phase_record')
|
|
file = os.open(name,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600,dir_fd=fd)
|
|
try:
|
|
view = memoryview(raw)
|
|
while view:
|
|
count = os.write(file,view);require(count > 0,'complete_create_only_record_write');view = view[count:]
|
|
os.fsync(file)
|
|
finally:os.close(file)
|
|
os.fsync(fd)
|
|
|
|
|
|
def binding():
|
|
return dict(profile=PROFILE,original_case=CASE_ID,phase=PHASE,controller_sha256=sha(Path(__file__).read_bytes()),
|
|
bootstrap_controller_sha256=BOOTSTRAP_SHA,installation_result_sha256=RESULTS['broker-install'],
|
|
typed_abi_receipt_sha256=ABI_RECEIPT_SHA,unit_sha256=UNIT_SHA,binary_sha256=BINARY_SHA)
|
|
|
|
|
|
def host_start(bootstrap,pin,guard,preflight=False):
|
|
case = pin.directory(CASE);phase = -1;proof = process = None
|
|
try:
|
|
pin.absence(case,PHASE)
|
|
proof = InstalledProof(bootstrap,pin,guard)
|
|
require(not os.path.lexists(SOCKET),'broker_socket_initially_absent_no_adopt')
|
|
before = proof.fresh()
|
|
# Read-only property observation may load the installed unit; no reload/start.
|
|
state = typed_snapshot(proof)
|
|
effective(state,False)
|
|
if preflight:
|
|
print(encoded(dict(binding(),read_only=True,before=before,effective_unit=state,broker_started=False)).decode(),end='');return
|
|
os.mkdir(PHASE,0o700,dir_fd=case);os.fsync(case)
|
|
phase = os.open(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,daemon_reload_once=True,start_once=True))
|
|
save(pin,phase,'before.json',dict(binding(),witness=before,effective_unit=state))
|
|
proof.fresh()
|
|
save(pin,phase,'reload-intent.json',dict(binding(),argv=['/usr/bin/systemctl','daemon-reload'],once=True))
|
|
code = proof.context.original.operator.long_command(['/usr/bin/systemctl','daemon-reload'],CASE/PHASE/'reload.log',10)
|
|
save(pin,phase,'reload-exit.json',dict(binding(),exit_code=code));require(code == 0,'one_reload_failed_read_original_only')
|
|
proof.fresh();state = effective(typed_snapshot(proof),False)
|
|
require(not os.path.lexists(SOCKET),'no_socket_before_single_start')
|
|
save(pin,phase,'effective-before-start.json',dict(binding(),effective_unit=state))
|
|
save(pin,phase,'start-intent.json',dict(binding(),argv=['/usr/bin/systemctl','start','--',UNIT_NAME],once=True))
|
|
code = proof.context.original.operator.long_command(['/usr/bin/systemctl','start','--',UNIT_NAME],CASE/PHASE/'start.log',15)
|
|
save(pin,phase,'start-exit.json',dict(binding(),exit_code=code));require(code == 0,'one_start_failed_no_retry_or_cleanup')
|
|
state = effective(typed_snapshot(proof),True);process = ProcessProof(proof,state)
|
|
deadline = time.monotonic()+5
|
|
while not os.path.lexists(SOCKET):
|
|
require(time.monotonic() < deadline,'broker_socket_not_ready_read_original_only')
|
|
process.verify(effective(typed_snapshot(proof),True));time.sleep(0.05)
|
|
socket = socket_proof(proof,process)
|
|
after = proof.fresh();final_state = effective(typed_snapshot(proof),True);actual_process = process.verify(final_state)
|
|
require(before == after and socket_proof(proof,process) == socket,'runtime_generation_pin_configuration_socket_preserved')
|
|
save(pin,phase,'after.json',dict(binding(),witness=after,effective_unit=final_state,process=actual_process,socket=socket))
|
|
result = dict(binding(),daemon_reload_executed=True,start_executed_once=True,effective_unit_qualified=True,
|
|
process=actual_process,socket=socket,source_runtime_generation_pin_preserved=True,
|
|
signer_seed_read_by_controller=False,service_enabled=False,restart_executed=False,
|
|
unix_request_sent=False,signed_attestation=False,http_deployed=False,rmm_jobs_created=False,
|
|
corehistory_witness='external_root_before_after_receipts_required')
|
|
save(pin,phase,'result.json',result);print(encoded(result).decode(),end='')
|
|
except Exception as error:
|
|
if phase >= 0:
|
|
tag = str(error) if isinstance(error,Denied) and re.fullmatch('[a-z0-9_]{1,128}',str(error)) else 'unexpected_broker_start_exception'
|
|
save(pin,phase,'failure.json',dict(binding(),fixed_tag=tag,failed=True,read_original_phase_only=True,
|
|
no_retry_restart_stop_cleanup_or_adopt=True))
|
|
raise
|
|
finally:
|
|
if process is not None:process.close()
|
|
if proof is not None:proof.close()
|
|
if phase >= 0:os.close(phase)
|
|
os.close(case)
|
|
|
|
|
|
def host_read(pin):
|
|
records = {}
|
|
for name in RECORDS:
|
|
try:
|
|
raw,metadata = pin.read_file(CASE/PHASE/name,65536)
|
|
records[name] = dict(sha256=sha(raw),metadata=metadata,
|
|
record=raw.decode('ascii') if name.endswith('.log') else pin.parsed(raw))
|
|
except FileNotFoundError:records[name] = None
|
|
print(encoded(dict(binding(),read_only=True,records=records,no_service_control=True)).decode(),end='')
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__);parser.add_argument('command',choices=('host-preflight','host-start','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)
|
|
bootstrap,pin,guard = load_bootstrap()
|
|
if args.command == 'host-read':host_read(pin)
|
|
else:host_start(bootstrap,pin,guard,args.command == 'host-preflight')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:main()
|
|
except Exception:
|
|
print(encoded(dict(profile=PROFILE,phase=PHASE,failed=True,read_original_phase_only=True)).decode(),end='')
|
|
raise SystemExit(1)
|