Record preserved Chrony peer namespace bootstrap on cloud server
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
@@ -0,0 +1,298 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One fixed project-parent ACL and Chrony local peer-socket AppArmor rule.
|
||||
|
||||
No time sample, clock setter, keys, service restart, retry or automatic rollback.
|
||||
The root operator invokes this source independently with python3 -I.
|
||||
"""
|
||||
import argparse
|
||||
import errno
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import struct
|
||||
import sys
|
||||
|
||||
CASE = '5b358997-3abc-43db-945f-f41855b4e3c0'
|
||||
BASE = Path('/var/lib/rmm-time-source-bootstrap') / CASE
|
||||
PHASE = 'peer-namespace-bootstrap-v1'
|
||||
PROFILE = 'rmm.server-time-source.peer-namespace-bootstrap.v1'
|
||||
PIN_CONTROLLER_SHA = 'fac85dd0399009af36f625232daa5b67ab7fda391dbf95229d4237c307b142ca'
|
||||
PIN_CONTROLLER = Path('/var/lib/rmm-time-source-operators') / PIN_CONTROLLER_SHA / 'pin_bootstrap.py'
|
||||
PIN_RESULT_SHA = 'd0a9ac7b46bdf4247c420f01d959c41d6620f7081c40629016d6866828884c4b'
|
||||
PUBLIC_PIN_SHA = '203f63f150026d345614ca53e641f248397166fbdeb1f28318fc5d7763317e0a'
|
||||
PARENT = Path('/run/rmm-time-source')
|
||||
MAIN = Path('/etc/apparmor.d/usr.sbin.chronyd')
|
||||
MAIN_SHA = '214e509af9ab9b713e89b09bf6440c4b4248e97c64d4b0d884d2f869d406e1e2'
|
||||
LOCAL = Path('/etc/apparmor.d/local/usr.sbin.chronyd')
|
||||
TEMP = '.rmm-time-source-peer-' + CASE + '.new'
|
||||
PARSER = '/usr/sbin/apparmor_parser'
|
||||
SETFACL = '/usr/bin/setfacl'
|
||||
PRECONDITION_RECEIPT_SHA = 'd33e5a11cbc5ac779112762c58dc80b43217786f2570deaaf01eefdf730c180e'
|
||||
PARSER_HELP_RECEIPT_SHA = '185c3e51b415b7d4847f0cc4f78034af409fe037d5ba839590a795ea433896e5'
|
||||
LOCAL_BYTES = (b'# Rust Discovery peer namespace; fixed acceptance v1.\n'
|
||||
b'# Original case 5b358997-3abc-43db-945f-f41855b4e3c0.\n'
|
||||
b'@{run}/rmm-time-source/clients/*.sock rw,\n')
|
||||
|
||||
|
||||
def require(ok, reason):
|
||||
if not ok:
|
||||
raise RuntimeError(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')
|
||||
|
||||
|
||||
def acl(fd, name='system.posix_acl_access'):
|
||||
try:
|
||||
value = os.getxattr(fd, name)
|
||||
require(len(value) <= 256, 'bounded_acl_metadata')
|
||||
return value
|
||||
except OSError as error:
|
||||
require(error.errno == errno.ENODATA, 'acl_read_requires_exact_enodata_or_value')
|
||||
return None
|
||||
|
||||
|
||||
def expected_acl():
|
||||
# Linux POSIX ACL v2: owner rwx; original owning group --x; named989 --x;
|
||||
# effective group mask --x; other none. No write/read permission is added.
|
||||
entries = ((1, 7, 0xffffffff), (4, 1, 0xffffffff), (8, 1, 989),
|
||||
(16, 1, 0xffffffff), (32, 0, 0xffffffff))
|
||||
return struct.pack('<I', 2) + b''.join(struct.pack('<HHI', *entry) for entry in entries)
|
||||
|
||||
|
||||
def parser_args(load=False):
|
||||
return [PARSER, '--replace' if load else '--skip-kernel-load', '--skip-cache', str(MAIN)]
|
||||
|
||||
|
||||
def profile_state(pid):
|
||||
# Kernel-managed, fixed proc/sysfs paths; never process arguments/environ.
|
||||
def read(path, limit):
|
||||
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
|
||||
try:
|
||||
value = bytearray()
|
||||
while len(value) <= limit:
|
||||
part = os.read(fd, min(65536, limit + 1 - len(value)))
|
||||
if not part:
|
||||
break
|
||||
value.extend(part)
|
||||
require(len(value) <= limit, 'bounded_kernel_profile_read')
|
||||
return bytes(value)
|
||||
finally:
|
||||
os.close(fd)
|
||||
label = read('/proc/' + str(pid) + '/attr/current', 4096).strip()
|
||||
profiles = read('/sys/kernel/security/apparmor/profiles', 1024 * 1024).splitlines()
|
||||
require(label == b'/usr/sbin/chronyd (enforce)' and label in profiles, 'same_chronyd_profile_enforcing')
|
||||
return dict(chronyd_label=label.decode('ascii'), enforcing=True)
|
||||
|
||||
|
||||
def host_read(pin):
|
||||
records = {}
|
||||
for leaf in ('intent.json', 'before.json', 'local-replace-intent.json', 'local-replaced.json',
|
||||
'offline-intent.json', 'offline-result.json', 'acl-intent.json', 'acl-applied.json',
|
||||
'reload-intent.json', 'reload-result.json', 'after.json', 'result.json', 'failure.json',
|
||||
'offline.log', 'acl.log', 'reload.log'):
|
||||
try:
|
||||
raw, proof = pin.read_file(BASE / PHASE / leaf, 16384)
|
||||
records[leaf] = dict(sha256=sha(raw), metadata=proof,
|
||||
record=raw.decode('ascii') if leaf.endswith('.log') else pin.parsed(raw))
|
||||
except FileNotFoundError:
|
||||
records[leaf] = None
|
||||
except pin.Denied:
|
||||
records[leaf] = dict(inspection_denied=True)
|
||||
print(pin.encoded(dict(original_case=CASE, phase=PHASE, read_only=True, records=records)).decode('ascii'), end='')
|
||||
|
||||
|
||||
def host_apply(pin, pin_guard):
|
||||
case_fd = pin.directory(BASE)
|
||||
phase_fd = parent_fd = local_fd = -1
|
||||
try:
|
||||
pin.absence(case_fd, PHASE)
|
||||
operator, operator_guard = pin.load_operator()
|
||||
original = pin.Original(BASE, operator, operator_guard)
|
||||
pin_raw, pin_proof = pin.read_file(BASE / 'pin/result.json')
|
||||
require(sha(pin_raw) == PIN_RESULT_SHA, 'actual_original_pin_result')
|
||||
pin_result = pin.parsed(pin_raw)
|
||||
main = pin.read_file(MAIN, 65536, 0o644)
|
||||
old_local = pin.read_file(LOCAL, 65536, 0o644)
|
||||
require(sha(main[0]) == MAIN_SHA and
|
||||
b'#include <local/usr.sbin.chronyd>' in [x.strip() for x in main[0].splitlines()] and
|
||||
old_local[0] == b'', 'exact_main_profile_and_empty_local_override')
|
||||
parent_fd = pin.directory(PARENT)
|
||||
parent_identity = pin.stable_directory(os.fstat(parent_fd))
|
||||
recorded = pin_result['targets'][str(PARENT)]
|
||||
require(parent_identity == {k: recorded[k] for k in parent_identity} and
|
||||
os.fstat(parent_fd).st_uid == 0 and os.fstat(parent_fd).st_gid == 10001 and
|
||||
stat.S_IMODE(os.fstat(parent_fd).st_mode) == 0o710 and
|
||||
acl(parent_fd) is None and acl(parent_fd, 'system.posix_acl_default') is None,
|
||||
'original_parent_0710_without_existing_acl')
|
||||
local_fd = pin.directory(LOCAL.parent)
|
||||
local_parent_identity = pin.stable_directory(os.fstat(local_fd))
|
||||
pin.absence(local_fd, TEMP)
|
||||
tools = {path: pin.read_file(Path(path), 16 * 1024 * 1024, 0o755) for path in (PARSER, SETFACL)}
|
||||
|
||||
def fresh(local_expected, acl_expected):
|
||||
pin_guard()
|
||||
actual_pin = original.fresh()
|
||||
require(pin.read_file(BASE / 'pin/result.json') == (pin_raw, pin_proof), 'original_pin_result_unchanged')
|
||||
public_raw, public_proof = pin.read_file(pin.ETC / 'chrony-pin.json', 8192)
|
||||
require(sha(public_raw) == PUBLIC_PIN_SHA == pin_result['public_pin_sha256'] and
|
||||
public_raw == pin.encoded(actual_pin) and public_proof == pin_result['public_pin_metadata'],
|
||||
'original_public_pin_unchanged')
|
||||
require(pin.read_file(MAIN, 65536, 0o644) == main and pin.read_file(LOCAL, 65536, 0o644) == local_expected,
|
||||
'exact_held_main_and_expected_local_profile')
|
||||
current_parent = pin.directory(PARENT)
|
||||
try:
|
||||
require(pin.stable_directory(os.fstat(current_parent)) == parent_identity ==
|
||||
pin.stable_directory(os.fstat(parent_fd)) and acl(current_parent) == acl_expected and
|
||||
acl(current_parent, 'system.posix_acl_default') is None,
|
||||
'same_parent_identity_mode_and_exact_acl')
|
||||
finally:
|
||||
os.close(current_parent)
|
||||
require(pin.stable_directory(os.fstat(local_fd)) == local_parent_identity,
|
||||
'same_protected_local_profile_directory')
|
||||
for path, retained in tools.items():
|
||||
require(pin.read_file(Path(path), 16 * 1024 * 1024, 0o755) == retained, 'same_existing_tool_bytes')
|
||||
return dict(original=original.expected, public_pin_sha256=PUBLIC_PIN_SHA,
|
||||
parent_identity=parent_identity, parent_access_acl_hex=None if acl_expected is None else acl_expected.hex(),
|
||||
main_profile_sha256=MAIN_SHA, local_profile_sha256=sha(local_expected[0]),
|
||||
profile=profile_state(actual_pin['daemon_pid']))
|
||||
|
||||
before = fresh(old_local, None)
|
||||
os.mkdir(PHASE, mode=0o700, dir_fd=case_fd)
|
||||
os.fsync(case_fd)
|
||||
phase_fd = os.open(PHASE, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=case_fd)
|
||||
own_raw, _ = pin.read_file(Path(__file__).absolute(), 128 * 1024)
|
||||
binding = dict(profile=PROFILE, original_case=CASE, phase=PHASE, controller_sha256=sha(own_raw),
|
||||
operator_sha256=pin.OPERATOR_SHA, pin_controller_sha256=PIN_CONTROLLER_SHA,
|
||||
source_tar_sha256=original.source_sha, manifest_sha256=original.manifest_sha,
|
||||
public_pin_sha256=PUBLIC_PIN_SHA, original_main_profile_sha256=MAIN_SHA,
|
||||
old_local_profile_sha256=sha(old_local[0]), new_local_profile_sha256=sha(LOCAL_BYTES),
|
||||
precondition_receipt_sha256=PRECONDITION_RECEIPT_SHA, parser_help_receipt_sha256=PARSER_HELP_RECEIPT_SHA)
|
||||
def save(name, value):
|
||||
pin.exclusive(phase_fd, name, pin.encoded(value))
|
||||
save('intent.json', dict(binding, once=True, no_retry=True, automatic_rollback=False))
|
||||
save('before.json', dict(binding, witness=before, old_local_metadata=old_local[1]))
|
||||
pin.exclusive(phase_fd, 'original-local-profile.bin', old_local[0])
|
||||
save('local-replace-intent.json', dict(binding, exact_empty_original_only=True))
|
||||
fresh(old_local, None)
|
||||
fd = os.open(TEMP, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=local_fd)
|
||||
try:
|
||||
view = memoryview(LOCAL_BYTES)
|
||||
while view:
|
||||
count = os.write(fd, view)
|
||||
require(count > 0, 'complete_new_local_snippet_write')
|
||||
view = view[count:]
|
||||
os.fsync(fd)
|
||||
require(os.fstat(fd).st_uid == os.fstat(fd).st_gid == 0 and os.fstat(fd).st_nlink == 1,
|
||||
'own_single_link_root_snippet')
|
||||
os.fchmod(fd, 0o644) # Only our new file, never an existing daemon directory/socket.
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
os.fsync(local_fd)
|
||||
fresh(old_local, None)
|
||||
require(pin.read_file(LOCAL.parent / TEMP, 16384, 0o644)[0] == LOCAL_BYTES, 'exact_new_snippet_bytes')
|
||||
os.replace(TEMP, LOCAL.name, src_dir_fd=local_fd, dst_dir_fd=local_fd)
|
||||
os.fsync(local_fd)
|
||||
new_local = pin.read_file(LOCAL, 16384, 0o644)
|
||||
require(new_local[0] == LOCAL_BYTES, 'exact_atomic_local_override')
|
||||
save('local-replaced.json', dict(binding, local_metadata=new_local[1]))
|
||||
fresh(new_local, None)
|
||||
save('offline-intent.json', dict(binding, skip_kernel=True, skip_cache=True))
|
||||
code = operator.long_command(parser_args(), BASE / PHASE / 'offline.log', 10)
|
||||
log, _ = pin.read_file(BASE / PHASE / 'offline.log', 16384)
|
||||
save('offline-result.json', dict(binding, exit_code=code, log_sha256=sha(log)))
|
||||
require(code == 0, 'offline_profile_validation_required')
|
||||
fresh(new_local, None)
|
||||
save('acl-intent.json', dict(binding, named_group=989, permissions='--x', mask='--x'))
|
||||
code = operator.long_command([SETFACL, '--no-mask', '--modify=group:989:--x,mask::--x', '--', str(PARENT)],
|
||||
BASE / PHASE / 'acl.log', 10)
|
||||
log, _ = pin.read_file(BASE / PHASE / 'acl.log', 16384)
|
||||
save('acl-applied.json', dict(binding, exit_code=code, log_sha256=sha(log)))
|
||||
require(code == 0, 'named_parent_traverse_acl_required')
|
||||
fresh(new_local, expected_acl())
|
||||
save('reload-intent.json', dict(binding, exact_main_profile_only=True, skip_cache=True))
|
||||
fresh(new_local, expected_acl())
|
||||
code = operator.long_command(parser_args(load=True), BASE / PHASE / 'reload.log', 10)
|
||||
log, _ = pin.read_file(BASE / PHASE / 'reload.log', 16384)
|
||||
save('reload-result.json', dict(binding, exit_code=code, log_sha256=sha(log)))
|
||||
require(code == 0, 'actual_profile_replace_exit_zero_required')
|
||||
after = fresh(new_local, expected_acl())
|
||||
require(before['original'] == after['original'] and before['profile'] == after['profile'],
|
||||
'same_chrony_process_boot_and_runtime_enforcing_profile')
|
||||
save('after.json', dict(binding, witness=after, new_local_metadata=new_local[1]))
|
||||
links = {}
|
||||
for name in ('before', 'after', 'offline-result', 'reload-result', 'acl-applied'):
|
||||
raw, _ = pin.read_file(BASE / PHASE / (name + '.json'), 16384)
|
||||
links[name.replace('-', '_')] = dict(filename=name + '.json', sha256=sha(raw))
|
||||
result = dict(binding, records=links, peer_namespace_configured=True, runtime_boot_chrony_preserved=True,
|
||||
apparmor_enforcing=True, actual_parser_replace_exit_code=0, source_quality_sampled=False,
|
||||
clock_authority=False, signer_created=False, broker_started=False, services_restarted=False)
|
||||
save('result.json', result)
|
||||
print(pin.encoded(result).decode('ascii'), end='')
|
||||
except Exception as error:
|
||||
if phase_fd >= 0:
|
||||
pin.exclusive(phase_fd, 'failure.json', pin.encoded(dict(profile=PROFILE, original_case=CASE,
|
||||
failed=True, exception_type=type(error).__name__, read_original_phase_only=True,
|
||||
automatic_rollback=False)))
|
||||
raise
|
||||
finally:
|
||||
for fd in (local_fd, parent_fd, phase_fd, case_fd):
|
||||
if fd >= 0:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('command', choices=('host-apply', '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_aarch64_only')
|
||||
os.umask(0o077)
|
||||
pin, guard = load_pin_controller()
|
||||
host_read(pin) if args.command == 'host-read' else host_apply(pin, guard)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except Exception:
|
||||
print(json.dumps(dict(failed=True, read_original_phase_only=True, automatic_rollback=False)), flush=True)
|
||||
raise SystemExit(1)
|
||||
Reference in New Issue
Block a user