Files
rust-discovery/deploy/script_console_bootstrap.py
2026-11-14 17:42:44 +01:00

246 lines
17 KiB
Python

#!/usr/bin/env python3
"""Prepare the exact preserving bootstrap intent and a READ-ONLY target CAS.
There is deliberately no install/stop/start/policy operation in this preflight.
A runtime index is provenance, never a fresh target observation. Root reviews
this source before invoking snapshot; no client is installed on the notebook.
"""
import argparse
import base64
import hashlib
import inspect
import json
from pathlib import Path
import uuid
ROOT = Path(__file__).resolve().parents[1]
ACCESS_ROOT = Path('/home/kevin/Schreibtisch/Coding/rust-discovery')
SUPPORT = {
'deploy/script_console_acceptance.py': '2b3ba8d548d18627643a9f73c9a4f7bacce4ac2cd5495745c6760d088e078145',
'deploy/windows_msi_runtime_acceptance.py': '833ad8806c90a19342aa6fbc71c33e81975caffb1746550e9b0fbdca7fa0c7ab',
'deploy/vm_access_check.py': '5c8107ea9151a9f498b2530cdc61c1a7a6d745aff853a9b05710f3395838c0dd',
}
for name, digest in SUPPORT.items():
path = ROOT / name
if path.is_symlink() or hashlib.sha256(path.read_bytes()).hexdigest() != digest:
raise RuntimeError('Pinned preflight support source changed')
import script_console_acceptance as native
support = native.support
INDEX = ACCESS_ROOT / 'devstate/cloud-shared-core-current-runtime.json'
INDEX_SHA = 'bf058d30ec7252071acbf39aa09007a083a0d237054a1f0815caf8e8510ce145'
PRIOR = ACCESS_ROOT / 'devstate/shared-core/runtime-upgrade-v2/a2423612-721f-4a6c-a832-b9eef549c41e/intent.json'
PRIOR_SHA = '4a1792151d95b26245464ed9df22a439d0979026c5d88052926b76985495bfc4'
NATIVE = ROOT / 'devstate/script-console-native/7b61ce46-7913-492b-9c6b-414a0c2b6ffc/passed-e214cd9b-21ac-48ce-82dc-d10364329d04.json'
NATIVE_SHA = 'a831a70a3cf76a3e8a9bf5820dcca7100d2ef9860dd9388539fe9c13f949f470'
STATE = ROOT / 'devstate/script-console-bootstrap'
def require(value, code):
if not value:
raise RuntimeError(code)
def snapshot_vm(p):
import base64
import contextlib
import hashlib
import json
import os
from pathlib import Path
import sqlite3
import stat
import subprocess
require(os.geteuid() == 0 and os.uname().machine == 'x86_64'
and p['type'] == 'rmm.script-console.preserving-preflight-v1', 'fixed root preflight')
require(Path('/proc/sys/kernel/random/boot_id').read_text().strip() == p['boot_id'], 'same actual boot')
def sha(data):
return hashlib.sha256(data).hexdigest()
def file(path, owner=0):
path = Path(path); s = path.lstat()
require(not stat.S_ISLNK(s.st_mode) and stat.S_ISREG(s.st_mode)
and s.st_uid == owner and s.st_nlink == 1 and not s.st_mode & 0o022, 'safe fixed file')
return dict(device=s.st_dev, inode=s.st_ino, mode=stat.S_IMODE(s.st_mode), uid=s.st_uid,
gid=s.st_gid, bytes=s.st_size, sha256=sha(path.read_bytes()))
def service(name):
result = subprocess.run(['systemctl', 'show', name, '-p', 'ActiveState', '-p', 'MainPID',
'-p', 'UnitFileState', '-p', 'LoadState'], capture_output=True, check=False, timeout=10)
value=dict(line.split('=',1) for line in result.stdout.decode().splitlines())
if name == 'rmm-full-maintenance-helper.service':
require(result.returncode in (0,1) and value.get('LoadState') == 'not-found'
and value.get('ActiveState') == 'inactive' and value.get('MainPID') == '0',
'only exact new absent unit admits rc0/1')
else:
require(result.returncode == 0, 'known unit query strictly succeeds')
return value
units = {name: service(name) for name in ('rmm-agent-remote.service', 'rmm-helper-cloud.service',
'rmm-apt-helper.service', 'rmm-agent.service', 'rmm-helper-dev-test.service',
'rmm-full-maintenance-helper.service')}
require(all(units[n]['ActiveState'] == 'active' for n in ('rmm-agent-remote.service', 'rmm-helper-cloud.service')),
'known original active pair')
require(all(units[n]['ActiveState'] == 'inactive' and units[n]['UnitFileState'] == 'disabled'
for n in ('rmm-apt-helper.service', 'rmm-agent.service', 'rmm-helper-dev-test.service')),
'APT and legacy daemons remain disabled/inactive')
require(units['rmm-full-maintenance-helper.service']['LoadState'] == 'not-found', 'new Full unit absent')
processes = {}
for name, key, uid in (('rmm-agent-remote.service', 'agent', 993), ('rmm-helper-cloud.service', 'helper', 0)):
pid = int(units[name]['MainPID']); require(pid > 1, 'actual live service PID')
proc=Path('/proc',str(pid))
def start_ticks():
raw=(proc/'stat').read_text(); _,fields=raw.rsplit(') ',1)
return int(fields.split()[19])
before_ticks=start_ticks()
status = (proc/'status').read_text().splitlines()
ids = {line.split(':')[0]: list(map(int, line.split()[1:])) for line in status if line.startswith(('Uid:', 'Gid:'))}
require(ids['Uid'] == [uid] * 4 and ids['Gid'] == [984] * 4, 'actual qualified account identity')
image = Path('/proc', str(pid), 'exe')
image_hash = sha(image.read_bytes())
require(image_hash == p['old_artifacts'][key], 'actual running original code generation')
require(start_ticks() == before_ticks and int(service(name)['MainPID']) == pid,
'same service PID and startticks through code observation')
processes[key] = dict(pid=pid, start_ticks=before_ticks, uids=ids['Uid'], gids=ids['Gid'], sha256=image_hash)
fixed = {
'/usr/local/libexec/rmm-agent-remote': p['old_artifacts']['agent'],
'/usr/local/libexec/rmm-privileged-helper': p['old_artifacts']['helper'],
'/usr/lib/rmm-apt-transaction/apt_transaction.py': p['old_artifacts']['provider'],
'/etc/rmm-remote/helper-general.json': p['general_config_sha256'],
'/etc/rmm-remote/general-helper-proof.json': p['general_pin_sha256'],
'/etc/systemd/system/rmm-agent-remote.service': p['agent_unit_sha256'],
'/etc/systemd/system/rmm-helper-cloud.service': p['general_unit_sha256'],
}
controls = {}
for path, digest in fixed.items():
value = file(path); require(value['sha256'] == digest, 'exact original runtime/control CAS')
controls[path] = value
for path in ('/etc/rmm/apt-helper.json', '/etc/rmm-remote/apt-helper-proof.json',
'/etc/systemd/system/rmm-apt-helper.service', '/usr/lib/rmm-apt-transaction/hook',
'/var/lib/dpkg/status', '/usr/share/rmm-mvp-test/version'):
controls[path] = file(path)
environment = subprocess.run(['systemctl', 'show', 'rmm-agent-remote.service', '-p', 'Environment', '--value'],
capture_output=True, check=True, timeout=10).stdout
require(b'RMM_APT_HELPER_SOCKET=' not in environment and b'RMM_APT_HELPER_PROOF_FILE=' not in environment,
'APT endpoint remains absent')
# Preserve the exact previously proven hardlink exception, never generalize it.
aliases = [Path('/var/lib/rmm-apt-transaction') / name for name in
('acceptance-rmm-apt-fixture-update-1.1.json', 'pending-acceptance-rmm-apt-fixture-update-1.1.json')]
alias_identity = None
for path in aliases:
s = path.lstat()
require(not path.is_symlink() and stat.S_ISREG(s.st_mode) and s.st_nlink == 2
and stat.S_IMODE(s.st_mode) == 0o600 and s.st_uid == 0 and s.st_gid == 984
and sha(path.read_bytes()) == p['apt_alias_sha256'], 'exact known historical APT alias')
identity = (s.st_dev, s.st_ino)
require(identity == (2049,1028362), 'unchanged independently proven APT alias inode')
require(alias_identity is None or identity == alias_identity, 'same original alias inode')
alias_identity = identity
databases = {}
for path, expected in p['database_inodes'].items():
path = Path(path); s = path.lstat(); owner = 0 if path.parent.name == 'rmm-helper' else 993
require(not path.is_symlink() and stat.S_ISREG(s.st_mode) and s.st_nlink == 1 and s.st_uid == owner
and [s.st_dev, s.st_ino] == expected, 'same original database inode/owner')
require(all(not Path(str(path) + suffix).exists() and not Path(str(path) + suffix).is_symlink()
for suffix in ('-wal', '-shm', '-journal')), 'settled DELETE journal required')
with contextlib.closing(sqlite3.connect(path.as_uri() + '?mode=ro', uri=True)) as db:
db.execute('PRAGMA query_only=ON'); db.execute('BEGIN')
require(db.execute('PRAGMA journal_mode').fetchone()[0] == 'delete'
and db.execute('PRAGMA integrity_check').fetchone()[0] == 'ok', 'actual query-only journal integrity')
schemas = dict(db.execute("SELECT name,sql FROM sqlite_master WHERE type='table' ORDER BY name"))
if path.name == 'journal.sqlite':
require(db.execute("SELECT count(*) FROM job_attempts WHERE state NOT IN ('succeeded','failed','cancelled','expired')").fetchone()[0] == 0,
'no unfinished agent attempt')
require(db.execute('SELECT count(*) FROM reconcile_meta WHERE fault IS NOT NULL').fetchone()[0] == 0, 'no agent fault')
if path.parent.name == 'rmm-helper':
rows = db.execute('SELECT c.grant_id,c.agent,c.generation,c.job,c.attempt,c.result,e.start,e.outcome FROM consumed c LEFT JOIN execution_evidence e USING(grant_id) ORDER BY grant_id').fetchall()
row_hashes = {r[0]: sha(json.dumps([dict(sha256=sha(v), size=len(v)) if isinstance(v, bytes) else v for v in r], separators=(',', ':')).encode()) for r in rows}
require(row_hashes == p['root_rows'] and len(rows) == 18 and all(r[5] is not None for r in rows), 'exact original closed Root18')
require(db.execute('SELECT count(*) FROM helper_sync_meta WHERE fault IS NOT NULL').fetchone()[0] == 0, 'no helper fault')
databases[str(path)] = dict(device=s.st_dev, inode=s.st_ino, schema_sha256=sha(json.dumps(schemas, sort_keys=True).encode()), integrity='ok')
require([path.stat().st_dev, path.stat().st_ino] == expected, 'journal was not replaced during read')
binding = json.loads(Path('/var/lib/rmm-agent-remote/binding.json').read_bytes())
require(all(binding[k] == v for k, v in p['target'].items())
and all(binding[k] == p['helper_identity'][k] for k in ('enrollment_generation','assignment_version'))
and sha(bytes.fromhex(binding['public_key_hex'])) == p['helper_identity']['signing_key_id'], 'same enrolled target/generations/public signing identity')
config = json.loads(Path('/etc/rmm-remote/helper-general.json').read_bytes())
require(config['agent_uid'] == 993 and config['socket_gid'] == 984
and config['state'] == '/var/lib/rmm-helper' and config['allow_reboot'] is False, 'unchanged existing helper identity/profile')
for path in ('/etc/rmm-remote/helper-full-maintenance.json','/etc/rmm-remote/full-maintenance-helper-proof.json',
'/etc/systemd/system/rmm-agent-remote.service.d/60-full-maintenance.conf'):
require(not os.path.lexists(path), 'new Full paths absent; do not overwrite partial bootstrap')
full = dict(profile='full_maintenance_v1', binding=config['binding'], agent_uid=993, socket_gid=984,
socket='/run/rmm-helper-maintenance/control.sock', state='/var/lib/rmm-helper',
allowed_services=[], allow_reboot=False, allow_root_scripts=True,
allowed_script_profiles=['full_maintenance_v1'], helper_binary_sha256=p['new_artifacts']['helper'])
if config.get('signing_key_file') is not None:
full['signing_key_file'] = config['signing_key_file']
full_bytes = json.dumps(full, separators=(',', ':')).encode()
return dict(type=p['type'], id=p['id'], boot_id=p['boot_id'], target=p['target'], processes=processes,
controls=controls, databases=databases, root_consumed=18, root_unresolved=0,
apt_endpoint_enabled=False, apt_current_runtime_qualified=False,
full_config_candidate=dict(path='/etc/rmm-remote/helper-full-maintenance.json',
mode=0o600, uid=0, gid=0, bytes_b64=base64.b64encode(full_bytes).decode(), sha256=sha(full_bytes)),
server_gate_verified=False, fresh_target_cas=True, install_authorized=False,
services_changed=False, product_state_writes=False, rmm_jobs=False, grants_created=False,
capabilities_activated=False, approvals=False, reboot_requested=False, package_effects=False)
def local_intent(case_id=None):
import os
os.umask(0o077); STATE.mkdir(mode=0o700, parents=True, exist_ok=True)
support.private(STATE, True)
for path, digest in ((INDEX, INDEX_SHA), (PRIOR, PRIOR_SHA), (NATIVE, NATIVE_SHA)):
require(support.sha(path) == digest, 'exact prior provenance/native proof')
index = support.load(INDEX); old = support.load(PRIOR); proof = support.load(NATIVE)
require(index['verified_passive_runtime_upgrade'] is True and index['apt_endpoint_enabled'] is False
and index['apt_current_runtime_qualified'] is False and index['root_consumed'] == 18
and index['root_unresolved'] == 0 and index['central_counts'] == dict(jobs=30, outbox=30, permits=26, unresolved=0), 'known closed prior index, not a fresh target proof')
require(proof['verified'] is True and proof['manifest_sha256'] == native.MANIFEST_SHA
and proof['native']['passed'] == 84 and proof['native']['ignored_database_cases'] == 5, 'actual Linux-first84 proof')
manifest = support.load(native.PACK / 'manifest.json')
require(support.sha(native.PACK / 'manifest.json') == native.MANIFEST_SHA
and all(support.sha(ROOT / name) == value for name, value in manifest['source_files'].items()), 'frozen158 source qualification')
if case_id is not None:
require(str(uuid.UUID(case_id)) == case_id, 'canonical original local case')
folder = STATE / case_id; intent = support.load(folder / 'intent.json')
require(intent['runner_sha256'] == support.sha(__file__) and intent['support_files'] == SUPPORT
and intent['index_sha256'] == INDEX_SHA and intent['manifest_sha256'] == native.MANIFEST_SHA,
'original immutable preflight intent')
return folder, intent
case_id = str(uuid.uuid4()); folder = STATE / case_id; folder.mkdir(mode=0o700)
intent = dict(type='rmm.script-console.preserving-preflight-v1', id=case_id, runner_sha256=support.sha(__file__),
support_files=SUPPORT, index_sha256=INDEX_SHA, previous_intent_sha256=PRIOR_SHA,
manifest_sha256=native.MANIFEST_SHA, native_proof_sha256=NATIVE_SHA,
boot_id=index['boot_id'], target=index['target'], helper_identity=old['general_pin']['identity'], old_artifacts=index['artifact_sha256'],
new_artifacts={key: manifest['artifacts'][name]['sha256'] for key, name in
(('agent', 'rmm-agent'), ('helper', 'rmm-privileged-helper'))},
root_rows=old['root_rows'], database_inodes=old['database_inodes'], apt_alias_sha256=old['alias_sha256'],
general_config_sha256=old['config_sha256'], general_pin_sha256=old['pin_sha256'],
agent_unit_sha256=old['agent_unit_sha256'], general_unit_sha256=old['general_unit_sha256'],
require_fresh_target_cas=True, require_fresh_server_gate=True, install_authorized=False)
support.save(folder / 'intent.json', intent)
return folder, intent
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('mode', choices=('prepare-local', 'snapshot', 'read-local'))
parser.add_argument('--case')
args = parser.parse_args()
require((args.mode == 'prepare-local') == (args.case is None), 'prepare new local intent; snapshot/read need original case')
folder, intent = local_intent(args.case)
if args.mode == 'snapshot':
for name, digest in SUPPORT.items():
require(support.sha(ROOT / name) == digest, 'support unchanged before target read')
code = inspect.getsource(require) + '\n' + inspect.getsource(snapshot_vm)
code += '\ntry:\n print(__import__("json").dumps(snapshot_vm(' + repr(intent) + ')))\nexcept Exception as e:\n print(__import__("json").dumps(dict(bootstrap_error=True,error_class=type(e).__name__)))\n'
prefix = support.access_settings(ACCESS_ROOT, 'linux')
report = support.transport(prefix, 'python3 -', code.encode(), folder, timeout=60)
support.save(folder / ('snapshot-' + str(uuid.uuid4()) + '.json'), report)
require(report['fresh_target_cas'] is True and report['install_authorized'] is False
and all(report.get(k) is False for k in ('services_changed', 'product_state_writes', 'rmm_jobs',
'grants_created', 'capabilities_activated', 'approvals', 'reboot_requested', 'package_effects')), 'strict read-only preflight scope')
print(json.dumps(dict(case_id=intent['id'], intent=str(folder / 'intent.json'), sha256=support.sha(folder / 'intent.json'),
mode=args.mode, install_authorized=False, target_called=args.mode == 'snapshot')))