423 lines
26 KiB
Python
423 lines
26 KiB
Python
#!/usr/bin/env python3
|
|
"""Create-only root-helper readiness, never an RMM execution/acceptance grant.
|
|
|
|
Build in a private minimal Docker context, inspect/install with existing strict
|
|
SSH bootstrap. No package/service test, baseline/fixture, reboot, root script,
|
|
agent restart, enrollment, approval API or application database mutation.
|
|
"""
|
|
import argparse
|
|
import base64
|
|
from contextlib import closing
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import shutil
|
|
import sqlite3
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import uuid
|
|
|
|
import vm_job_bootstrap as agent_bootstrap
|
|
from vm_passive_test import execute, remote_python, require
|
|
|
|
ROOT = agent_bootstrap.ROOT
|
|
DIRECTORY = ROOT / 'devstate/vm-root'
|
|
UNIT = 'rmm-helper-dev-test.service'
|
|
|
|
|
|
def sha(data):
|
|
return hashlib.sha256(data).hexdigest()
|
|
|
|
|
|
def helper_config(binding, uid, gid):
|
|
require(uid > 0 and gid > 0, 'non-root agent identity required')
|
|
return dict(binding=dict(binding, public_key_hex=''), signing_key_file='/etc/rmm/helper-signing-key-v1.json',
|
|
agent_uid=uid, socket_gid=gid, socket='/run/rmm-helper/control.sock',
|
|
state='/var/lib/rmm-helper', allowed_services=['rmm-mvp-test.service'],
|
|
allow_reboot=False, allow_root_scripts=False, apt_provider=None)
|
|
|
|
|
|
def helper_can_stop(report):
|
|
return report.get('helper_started') is True and report.get('helper_consumed_count') == 0
|
|
|
|
|
|
def confined_runtime(status, gid):
|
|
mask = sum(1 << number for number in (0, 1, 3, 4, 6, 7, 8, 31))
|
|
return (status['NoNewPrivs'].strip() == '1' and status['Seccomp'].strip() == '2'
|
|
and all(int(value) == 0 for value in status['Uid'].split())
|
|
and all(int(value) == gid for value in status['Gid'].split())
|
|
and int(status['CapEff'].strip(), 16) & ~mask == 0
|
|
and int(status['CapBnd'].strip(), 16) == mask)
|
|
|
|
|
|
def build():
|
|
DIRECTORY.mkdir(mode=0o700, exist_ok=True)
|
|
require(not (DIRECTORY / 'rmm-privileged-helper').exists(), 'build artifact already exists; review version before replacement')
|
|
with tempfile.TemporaryDirectory(prefix='build-', dir=DIRECTORY) as folder:
|
|
folder = Path(folder)
|
|
for name in ('Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml'):
|
|
shutil.copyfile(ROOT / name, folder / name)
|
|
for name in ('crates', 'tools/apt-transaction', 'migrations'):
|
|
shutil.copytree(ROOT / name, folder / name,
|
|
ignore=shutil.ignore_patterns('__pycache__', '*.pyc', 'target', 'node_modules',
|
|
'.git', 'devstate', 'credentials', 'secrets'))
|
|
(folder / 'Dockerfile').write_text('FROM rust:1.99.1-bookworm\nWORKDIR /src\nCOPY . .\nRUN cargo build --locked --release -p rmm-privileged-helper\n')
|
|
pins = {name: sha((folder / 'tools/apt-transaction' / name).read_bytes()) for name in ('apt_transaction.py', 'hook')}
|
|
subprocess.run(['docker', 'build', '-t', 'rmm-root-helper-build:dev', str(folder)], check=True)
|
|
container = execute(['docker', 'create', 'rmm-root-helper-build:dev']).decode().strip()
|
|
try:
|
|
execute(['docker', 'cp', container + ':/src/target/release/rmm-privileged-helper', str(DIRECTORY / 'rmm-privileged-helper')])
|
|
finally:
|
|
execute(['docker', 'rm', container])
|
|
artifact = DIRECTORY / 'rmm-privileged-helper'
|
|
artifact.chmod(0o700)
|
|
(DIRECTORY / 'build.json').write_text(json.dumps(dict(tool_pins=pins, artifact_sha256=sha(artifact.read_bytes())), indent=2))
|
|
print('PASS isolated OpenSSL-3 helper build; no VM changes')
|
|
|
|
|
|
def remote_inspect():
|
|
"""Strictly read-only VM inventory, with only nonsecret readiness facts."""
|
|
import pwd
|
|
account = pwd.getpwnam('rmm-agent')
|
|
paths = {'helper_binary': '/usr/local/libexec/rmm-privileged-helper',
|
|
'helper_state': '/var/lib/rmm-helper', 'helper_runtime': '/run/rmm-helper',
|
|
'helper_config': '/etc/rmm/helper-dev-test-v1.json',
|
|
'helper_key': '/etc/rmm/helper-signing-key-v1.json',
|
|
'helper_unit': '/etc/systemd/system/rmm-helper-dev-test.service',
|
|
'agent_dropin': '/etc/systemd/system/rmm-agent.service.d/10-dev-helper-v1.conf',
|
|
'provider_code': '/usr/lib/rmm-apt-transaction', 'provider_store': '/var/lib/rmm-apt-transaction'}
|
|
result = {'agent_uid': account.pw_uid, 'agent_gid': account.pw_gid, 'paths': {}}
|
|
for name, value in paths.items():
|
|
path = Path(value)
|
|
record = {'exists': path.exists(), 'symlink': path.is_symlink()}
|
|
if path.exists():
|
|
meta = path.lstat()
|
|
record.update(uid=meta.st_uid, gid=meta.st_gid, mode=oct(meta.st_mode & 0o777))
|
|
result['paths'][name] = record
|
|
for name in ('rmm-agent.service', 'rmm-helper-dev-test.service'):
|
|
process = subprocess.run(['systemctl', 'is-active', name], capture_output=True, text=True)
|
|
result[name] = process.stdout.strip() == 'active'
|
|
ports = subprocess.run(['ss', '-H', '-ltn', 'sport = :18443'], capture_output=True, text=True, check=True)
|
|
result['listener_present'] = bool(ports.stdout.strip())
|
|
state = Path('/var/lib/rmm-agent')
|
|
result['agent_state_safe'] = state.is_dir() and state.stat().st_uid == account.pw_uid and state.stat().st_mode & 0o777 == 0o700
|
|
return result
|
|
|
|
|
|
def remote_prepare(payload):
|
|
import pwd
|
|
import socket
|
|
import stat
|
|
os.umask(0o077)
|
|
require(os.geteuid() == 0, 'root bootstrap required')
|
|
facts = remote_inspect()
|
|
require(not facts['rmm-agent.service'] and not facts['rmm-helper-dev-test.service']
|
|
and not facts['listener_present'] and facts['agent_state_safe'], 'existing active lifecycle or unsafe state')
|
|
require(all(not value['exists'] and not value['symlink'] for value in facts['paths'].values()),
|
|
'root installation is create-only; existing resources require explicit review')
|
|
account = pwd.getpwnam('rmm-agent')
|
|
require(account.pw_uid == payload['agent_uid'] and account.pw_gid == payload['agent_gid'] and account.pw_uid > 0,
|
|
'dedicated agent account mismatch')
|
|
# Current operator-authenticated binding must match both preserved enrollment
|
|
# and the already pinned agent authority. No offer/request supplies trust.
|
|
identity = json.loads(Path('/var/lib/rmm-agent/identity.json').read_text())
|
|
binding = json.loads(Path('/etc/rmm/agent-binding.json').read_text())
|
|
require(binding == payload['binding'] and all(identity[name] == binding[name] for name in ('agent_id', 'asset_id')),
|
|
'existing identity/key binding differs; no automatic overwrite')
|
|
snapshot = manifest(Path('/var/lib/rmm-agent'))
|
|
report = {'created': [], 'completed': False, 'helper_started': False,
|
|
'agent_state_before': snapshot, 'no_rmm_jobs_executed': True,
|
|
'apt_execution_enabled': False, 'reboot_enabled': False}
|
|
report_path = Path('/etc/rmm/root-bootstrap-v1-report.json')
|
|
require(not report_path.exists() and not report_path.is_symlink(), 'prior root report requires review')
|
|
binary = Path('/usr/local/libexec/rmm-privileged-helper')
|
|
encoded = base64.b64decode(payload['binary'], validate=True)
|
|
require(sha(encoded) == payload['artifact_sha256'] and encoded[:6] == b'\x7fELF\x02\x01'
|
|
and encoded[18:20] == b'\x3e\x00', 'wrong helper artifact')
|
|
for parent in (binary.parent, Path('/etc/rmm'), Path('/etc/systemd/system'), Path('/var/lib')):
|
|
require(parent.is_dir() and not parent.is_symlink() and parent.stat().st_uid == 0
|
|
and parent.stat().st_mode & 0o022 == 0, 'unsafe root installation parent')
|
|
def create(path, data, mode):
|
|
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, mode)
|
|
with os.fdopen(fd, 'wb') as stream:
|
|
stream.write(data); stream.flush(); os.fsync(stream.fileno()); os.fchmod(stream.fileno(), mode)
|
|
report['created'].append(str(path))
|
|
def save():
|
|
temporary = report_path.with_name('.root-bootstrap-' + uuid.uuid4().hex)
|
|
fd = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
|
|
with os.fdopen(fd, 'w') as stream:
|
|
json.dump(report, stream, indent=2); stream.flush(); os.fsync(stream.fileno())
|
|
os.replace(temporary, report_path)
|
|
try:
|
|
save()
|
|
create(binary, encoded, 0o755)
|
|
subprocess.run(['/lib64/ld-linux-x86-64.so.2', '--list', str(binary)], capture_output=True, check=True)
|
|
# Compiled-in trusted bytes only. No fixtures, baselines, active context,
|
|
# acceptance records, package execution or unsigned grants are produced.
|
|
subprocess.run([str(binary), '--install-apt-provider'], capture_output=True, check=True, umask=0o022)
|
|
report['created'] += ['/usr/lib/rmm-apt-transaction', '/var/lib/rmm-apt-transaction']
|
|
provider = Path('/usr/lib/rmm-apt-transaction')
|
|
require(all(sha((provider / name).read_bytes()) == digest for name, digest in payload['tool_pins'].items()),
|
|
'installed provider does not match reviewed build snapshot')
|
|
store = Path('/var/lib/rmm-apt-transaction')
|
|
metadata_path = store / 'install-metadata.json'
|
|
metadata = json.loads(metadata_path.read_text())
|
|
require(metadata == dict(schema_version=1, provider_sha256=payload['tool_pins']['apt_transaction.py'],
|
|
hook_sha256=payload['tool_pins']['hook']), 'trusted provider metadata mismatch')
|
|
require(metadata_path.stat().st_uid == 0 and metadata_path.stat().st_mode & 0o777 == 0o600
|
|
and {p.name for p in store.iterdir()} == {'archives', 'baselines', 'history', 'install-metadata.json'}
|
|
and all(not any((store / name).iterdir()) for name in ('archives', 'baselines', 'history')),
|
|
'unexpected artifacts, baseline or acceptance evidence')
|
|
report['provider_metadata_verified'] = True
|
|
report['no_fixture_baseline_or_acceptance_created'] = True
|
|
command = ['/usr/bin/python3', '-I', str(provider / 'apt_transaction.py')]
|
|
runtime = subprocess.run(command + ['inspect-runtime'], capture_output=True, check=True).stdout
|
|
runtime_object = json.loads(runtime)
|
|
canonical = json.dumps(runtime_object, sort_keys=True, separators=(',', ':'), ensure_ascii=True).encode()
|
|
config_bytes = subprocess.run(command + ['print-config'], capture_output=True, check=True).stdout
|
|
sandbox = subprocess.run(command + ['inspect-sandbox'], capture_output=True)
|
|
report.update(runtime=runtime_object, runtime_sha256=sha(canonical), apt_config_sha256=sha(config_bytes),
|
|
tool_pins=payload['tool_pins'], inspect_sandbox_exit=sandbox.returncode,
|
|
inspect_sandbox_passed=sandbox.returncode == 0,
|
|
sandbox_note='Direct parent inspection is not the final signed worker sandbox; no fake active context created')
|
|
report['apt_readiness_blockers'] = [
|
|
'apt_provider_is_null_no_package_capability',
|
|
'readiness_unit_denies_mount_and_has_no_CAP_SYS_ADMIN_or_CAP_MKNOD',
|
|
'APT_setup_needs_private_mount_PID_net_namespaces_and_basic_device_nodes',
|
|
'ProtectSystem_strict_does_not_allow_package_database_and_payload_writes',
|
|
'final_child_must_drop_to_exact_eight_capabilities_NNP_seccomp_and_hide_control_sockets',
|
|
'no_signed_active_context_baseline_fixtures_or_native_acceptance_exist']
|
|
require(runtime_object['platform'] == 'ubuntu-24.04-amd64', 'unsupported native platform')
|
|
create(Path('/etc/rmm/helper-signing-key-v1.json'), json.dumps(payload['key']).encode(), 0o600)
|
|
config = helper_config(binding, account.pw_uid, account.pw_gid)
|
|
create(Path('/etc/rmm/helper-dev-test-v1.json'), json.dumps(config).encode(), 0o600)
|
|
state = Path('/var/lib/rmm-helper'); state.mkdir(mode=0o700); report['created'].append(str(state))
|
|
unit = Path('/etc/systemd/system/rmm-helper-dev-test.service')
|
|
create(unit, payload['unit'].encode(), 0o644)
|
|
dropins = Path('/etc/systemd/system/rmm-agent.service.d')
|
|
if not dropins.exists():
|
|
dropins.mkdir(mode=0o755); dropins.chmod(0o755); report['created'].append(str(dropins))
|
|
require(not dropins.is_symlink() and dropins.stat().st_uid == 0 and dropins.stat().st_mode & 0o022 == 0,
|
|
'unsafe agent dropin directory')
|
|
create(dropins / '10-dev-helper-v1.conf', b'[Service]\nEnvironment=RMM_HELPER_SOCKET=/run/rmm-helper/control.sock\n', 0o644)
|
|
subprocess.run(['systemd-analyze', 'verify', str(unit)], capture_output=True, check=True)
|
|
report['unit_verify_passed'] = True
|
|
subprocess.run(['systemctl', 'daemon-reload'], capture_output=True, check=True)
|
|
subprocess.run(['systemctl', 'enable', UNIT], capture_output=True, check=True)
|
|
report['helper_enabled'] = True
|
|
subprocess.run(['systemctl', 'start', UNIT], capture_output=True, check=True)
|
|
report['helper_started'] = True
|
|
path = Path('/run/rmm-helper/control.sock')
|
|
import time
|
|
for _ in range(50):
|
|
if path.exists():
|
|
break
|
|
time.sleep(.1)
|
|
metadata = path.lstat()
|
|
pid = int(subprocess.run(['systemctl', 'show', '--property=MainPID', '--value', UNIT],
|
|
capture_output=True, check=True).stdout)
|
|
require(os.readlink('/proc/' + str(pid) + '/exe') == str(binary), 'helper has not execed reviewed binary')
|
|
status = dict(line.split(':', 1) for line in Path('/proc/' + str(pid) + '/status').read_text().splitlines() if ':' in line)
|
|
require(confined_runtime(status, account.pw_gid), 'helper kernel sandbox not active')
|
|
report['helper_runtime'] = {name: status[name].strip() for name in ('Uid', 'Gid', 'NoNewPrivs', 'Seccomp', 'CapEff', 'CapBnd')}
|
|
report['helper_pid'] = pid
|
|
parent = path.parent.stat()
|
|
require(stat.S_ISSOCK(metadata.st_mode) and metadata.st_uid == 0 and metadata.st_gid == account.pw_gid
|
|
and metadata.st_mode & 0o777 == 0o660 and parent.st_uid == 0 and parent.st_mode & 0o777 == 0o750,
|
|
'helper socket ACL mismatch')
|
|
peer = subprocess.run(['/usr/sbin/runuser', '-u', 'rmm-agent', '--', '/usr/bin/python3', '-I', '-c',
|
|
"import socket;s=socket.socket(socket.AF_UNIX);s.connect('/run/rmm-helper/control.sock');s.close()"],
|
|
capture_output=True, check=True)
|
|
report['socket_acl_verified'] = True
|
|
report['agent_uid_can_connect_without_request'] = peer.returncode == 0
|
|
with closing(sqlite3.connect('/var/lib/rmm-helper/consumption.sqlite')) as db:
|
|
report['helper_consumed_count'] = db.execute('SELECT count(*) FROM consumed').fetchone()[0]
|
|
require(report['helper_consumed_count'] == 0, 'unexpected helper consumption; retain lifecycle')
|
|
report['agent_state_after'] = manifest(Path('/var/lib/rmm-agent'))
|
|
require(snapshot == report['agent_state_after'], 'agent identity/journal changed during root readiness')
|
|
report['agent_state_unchanged'] = True
|
|
report['completed'] = True
|
|
except Exception as error:
|
|
report['error'] = sanitized_error(error)
|
|
raise
|
|
finally:
|
|
if helper_can_stop(report):
|
|
subprocess.run(['systemctl', 'stop', UNIT], capture_output=True, check=True)
|
|
report['helper_stopped'] = True
|
|
save()
|
|
return report
|
|
|
|
|
|
def remote_recheck(expected):
|
|
"""Versioned repair of proven own payload modes plus post-exec readiness."""
|
|
import time
|
|
require(os.geteuid() == 0, 'root required')
|
|
facts = remote_inspect()
|
|
require(not facts['rmm-agent.service'] and not facts['rmm-helper-dev-test.service']
|
|
and not facts['listener_present'], 'unexpected active lifecycle')
|
|
previous = json.loads(Path('/etc/rmm/root-bootstrap-v1-report.json').read_text())
|
|
require(previous['completed'] and previous['helper_consumed_count'] == 0, 'unproven previous bootstrap')
|
|
before = manifest(Path('/var/lib/rmm-agent'))
|
|
require(before == previous['agent_state_after'], 'agent state changed since readiness')
|
|
binary = Path('/usr/local/libexec/rmm-privileged-helper')
|
|
require(sha(binary.read_bytes()) == expected['artifact_sha256'], 'helper artifact changed')
|
|
config = json.loads(Path('/etc/rmm/helper-dev-test-v1.json').read_text())
|
|
require(config['apt_provider'] is None and not config['allow_reboot'] and not config['allow_root_scripts'], 'execution policy unexpectedly enabled')
|
|
report = dict(completed=False, mode_corrections=[], helper_started=False, helper_consumed_count=None)
|
|
report_path = Path('/etc/rmm/root-readiness-v2-report.json')
|
|
require(not report_path.exists() and not report_path.is_symlink(), 'v2 report already exists; no blind recheck')
|
|
code = Path('/usr/lib/rmm-apt-transaction')
|
|
require(not code.is_symlink() and code.stat().st_uid == 0 and code.stat().st_mode & 0o022 == 0, 'unsafe provider directory')
|
|
for name, mode in (('apt_transaction.py', 0o644), ('hook', 0o755)):
|
|
path = code / name
|
|
require(not path.is_symlink() and path.stat().st_uid == 0 and path.stat().st_nlink == 1
|
|
and sha(path.read_bytes()) == expected['tool_pins'][name], 'payload provenance mismatch')
|
|
report['mode_corrections'].append(dict(name=name, old=oct(path.stat().st_mode & 0o777), new=oct(mode)))
|
|
try:
|
|
for correction in report['mode_corrections']:
|
|
(code / correction['name']).chmod(int(correction['new'], 8))
|
|
code.chmod(0o755)
|
|
with closing(sqlite3.connect('/var/lib/rmm-helper/consumption.sqlite')) as db:
|
|
require(db.execute('SELECT count(*) FROM consumed').fetchone()[0] == 0, 'nonempty root ledger')
|
|
subprocess.run(['systemctl', 'start', UNIT], capture_output=True, check=True)
|
|
report['helper_started'] = True
|
|
for _ in range(50):
|
|
if Path('/run/rmm-helper/control.sock').exists():
|
|
break
|
|
time.sleep(.1)
|
|
pid = int(subprocess.run(['systemctl', 'show', '--property=MainPID', '--value', UNIT], capture_output=True, check=True).stdout)
|
|
require(os.readlink('/proc/' + str(pid) + '/exe') == str(binary), 'helper has not execed reviewed artifact')
|
|
status = dict(line.split(':', 1) for line in Path('/proc/' + str(pid) + '/status').read_text().splitlines() if ':' in line)
|
|
require(confined_runtime(status, facts['agent_gid']), 'post-exec kernel sandbox mismatch')
|
|
report.update(helper_pid=pid, kernel_sandbox_verified=True,
|
|
helper_runtime={name: status[name].strip() for name in ('Uid', 'Gid', 'NoNewPrivs', 'Seccomp', 'CapEff', 'CapBnd')})
|
|
with closing(sqlite3.connect('/var/lib/rmm-helper/consumption.sqlite')) as db:
|
|
report['helper_consumed_count'] = db.execute('SELECT count(*) FROM consumed').fetchone()[0]
|
|
require(report['helper_consumed_count'] == 0 and manifest(Path('/var/lib/rmm-agent')) == before,
|
|
'unexpected helper or agent journal change')
|
|
report['agent_state_unchanged'] = True
|
|
report['completed'] = True
|
|
except Exception as error:
|
|
report['error'] = sanitized_error(error)
|
|
raise
|
|
finally:
|
|
if helper_can_stop(report):
|
|
subprocess.run(['systemctl', 'stop', UNIT], capture_output=True, check=True)
|
|
report['helper_stopped'] = True
|
|
fd = os.open(report_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
|
|
with os.fdopen(fd, 'w') as stream:
|
|
json.dump(report, stream, indent=2); stream.flush(); os.fsync(stream.fileno())
|
|
return report
|
|
|
|
|
|
def remote_finish_readiness():
|
|
"""Finish the already-running v2 probe, without restarting or relaxing it."""
|
|
require(os.geteuid() == 0, 'root required')
|
|
previous = json.loads(Path('/etc/rmm/root-readiness-v2-report.json').read_text())
|
|
require(previous['helper_started'] and not previous.get('helper_stopped'), 'no pending owned readiness lifecycle')
|
|
facts = remote_inspect()
|
|
require(not facts['rmm-agent.service'] and not facts['listener_present'], 'unexpected agent or tunnel lifecycle')
|
|
pid = int(subprocess.run(['systemctl', 'show', '--property=MainPID', '--value', UNIT], capture_output=True, check=True).stdout)
|
|
require(pid > 0 and os.readlink('/proc/' + str(pid) + '/exe') == '/usr/local/libexec/rmm-privileged-helper', 'owned helper missing')
|
|
status = dict(line.split(':', 1) for line in Path('/proc/' + str(pid) + '/status').read_text().splitlines() if ':' in line)
|
|
require(confined_runtime(status, facts['agent_gid']), 'observed helper exceeds readiness confinement')
|
|
with closing(sqlite3.connect('file:/var/lib/rmm-helper/consumption.sqlite?mode=ro', uri=True)) as db:
|
|
require(db.execute('SELECT count(*) FROM consumed').fetchone()[0] == 0, 'active root consumption requires reconciliation')
|
|
bootstrap = json.loads(Path('/etc/rmm/root-bootstrap-v1-report.json').read_text())
|
|
require(manifest(Path('/var/lib/rmm-agent')) == bootstrap['agent_state_after'], 'agent state changed')
|
|
report = dict(completed=True, helper_pid=pid, kernel_sandbox_verified=True, helper_consumed_count=0,
|
|
agent_state_unchanged=True, effective_capabilities_subset=True,
|
|
helper_runtime={name: status[name].strip() for name in ('Uid', 'Gid', 'NoNewPrivs', 'Seccomp', 'CapEff', 'CapBnd')},
|
|
supersedes_preexec_v1_and_overstrict_parent_v2_measurements=True)
|
|
path = Path('/etc/rmm/root-readiness-v3-report.json')
|
|
require(not path.exists() and not path.is_symlink(), 'v3 report already exists')
|
|
subprocess.run(['systemctl', 'stop', UNIT], capture_output=True, check=True)
|
|
report['helper_stopped'] = True
|
|
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
|
|
with os.fdopen(fd, 'w') as stream:
|
|
json.dump(report, stream, indent=2); stream.flush(); os.fsync(stream.fileno())
|
|
return report
|
|
|
|
|
|
def program(invocation):
|
|
"""Trusted remote source with one sanitized JSON response, never stderr echo."""
|
|
# Reuse only pure manifest/error functions, not bootstrap transport/config.
|
|
import inspect
|
|
common = '\n\n'.join(inspect.getsource(function) for function in
|
|
(agent_bootstrap.manifest, agent_bootstrap.sanitized_error))
|
|
own = '\n\n'.join(inspect.getsource(function) for function in (sha, helper_config, helper_can_stop, confined_runtime, remote_inspect, remote_prepare, remote_recheck, remote_finish_readiness))
|
|
return ('import base64,hashlib,json,os,subprocess,sqlite3,uuid\nfrom pathlib import Path\nfrom contextlib import closing\n'
|
|
'UNIT="rmm-helper-dev-test.service"\ndef require(value,message):\n if not value: raise RuntimeError(message)\n'
|
|
+ common + '\n' + own + '\ntry:\n print(json.dumps({"result":' + invocation
|
|
+ '}))\nexcept Exception as error:\n print(json.dumps({"error":sanitized_error(error)}))\n')
|
|
|
|
|
|
def remote(code):
|
|
with agent_bootstrap.connection() as (ssh, target, env):
|
|
response = json.loads(remote_python(ssh, target, env, code))
|
|
if 'error' in response:
|
|
print('ROOT_BOOTSTRAP_ERROR=' + json.dumps(response['error']))
|
|
raise RuntimeError('root readiness incomplete; inspect protected remote report before retry')
|
|
return response['result']
|
|
|
|
|
|
def install():
|
|
sys.path.insert(0, str(ROOT / 'tests'))
|
|
from backend_contract import request
|
|
from local_integration import A, STATE, sql
|
|
agent = json.loads((STATE / 'vm-jobs/bootstrap.json').read_text())
|
|
identifier = str(uuid.UUID(agent['agent_id']))
|
|
require(sql(f"SELECT count(*) FROM jobs WHERE agent_id='{identifier}' AND state NOT IN ('succeeded','failed','expired','cancelled');") == '0',
|
|
'unresolved VM job prevents helper bootstrap')
|
|
operator = (STATE / 'operator-a.token').read_text().strip()
|
|
status, _, device = request(f'/api/v1/tenants/{A}/devices/{agent["asset_id"]}', token=operator)
|
|
require(status == 200 and device['agent_id'] == identifier, 'preserved authenticated server binding missing')
|
|
status, _, key = request('/api/v1/job-signing-key', token=operator)
|
|
require(status == 200 and key['algorithm'] == 'Ed25519' and key['schema_version'] == 1
|
|
and len(bytes.fromhex(key['public_key_hex'])) == 32 and sha(bytes.fromhex(key['public_key_hex'])) == key['key_id'],
|
|
'authenticated signing key invalid')
|
|
facts = remote(program('remote_inspect()'))
|
|
print('ROOT_PREFLIGHT=' + json.dumps(facts))
|
|
require(not facts['rmm-agent.service'] and not facts['listener_present'], 'agent or tunnel unexpectedly active')
|
|
data = (DIRECTORY / 'rmm-privileged-helper').read_bytes()
|
|
built = json.loads((DIRECTORY / 'build.json').read_text())
|
|
require(sha(data) == built['artifact_sha256'], 'helper artifact changed after reviewed build')
|
|
versions = execute(['readelf', '--version-info', str(DIRECTORY / 'rmm-privileged-helper')]).decode()
|
|
glibc = max(tuple(map(int, x.split('.'))) for x in re.findall(r'GLIBC_(\d+\.\d+)', versions))
|
|
require(glibc <= (2, 39), 'helper glibc incompatible')
|
|
binding = {name: device[name] for name in ('asset_id', 'agent_id', 'enrollment_generation', 'assignment_version')}
|
|
binding.update(tenant_id=A, public_key_hex=key['public_key_hex'])
|
|
payload = dict(binding=binding, key=key, agent_uid=facts['agent_uid'], agent_gid=facts['agent_gid'],
|
|
binary=base64.b64encode(data).decode(), artifact_sha256=built['artifact_sha256'], tool_pins=built['tool_pins'],
|
|
unit=(ROOT / 'deploy/linux/rmm-helper-dev-test.service').read_text())
|
|
result = remote(program('remote_prepare(' + repr(payload) + ')'))
|
|
result.update(helper_sha256=sha(data), required_glibc='.'.join(map(str, glibc)))
|
|
with (DIRECTORY / 'result.json').open('x') as stream:
|
|
json.dump(result, stream, indent=2)
|
|
print('PASS root-helper install/socket readiness; APT execution/reboot disabled; no RMM job or package mutation')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
os.umask(0o077)
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('mode', choices=('build', 'inspect', 'install', 'verify'))
|
|
args = parser.parse_args()
|
|
try:
|
|
if args.mode == 'build':
|
|
build()
|
|
elif args.mode == 'inspect':
|
|
print(json.dumps(remote(program('remote_inspect()'))))
|
|
elif args.mode == 'install':
|
|
install()
|
|
else:
|
|
result = remote(program('remote_recheck(' + repr(json.loads((DIRECTORY / 'build.json').read_text())) + ')'))
|
|
with (DIRECTORY / 'readiness-v2.json').open('x') as stream:
|
|
json.dump(result, stream, indent=2)
|
|
print('PASS post-exec helper kernel sandbox and provenance-checked payload modes; helper stopped')
|
|
except Exception as error:
|
|
print('ROOT_BOOTSTRAP_INCOMPLETE=' + json.dumps(agent_bootstrap.sanitized_error(error)))
|
|
raise SystemExit(2) from None
|