159 lines
8.3 KiB
Python
159 lines
8.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Explicit bootstrap diagnosis in the installed APT unit; never a job/probe.
|
|
|
|
Temporarily replaces only service commands with a read-only controller check.
|
|
All sandbox settings remain in force. No daemon, native probe, package manager,
|
|
grant or approval is invoked. Refuses active services, drop-ins or unresolved
|
|
consumption. Removes only its own exact temporary files and restores the unit.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import inspect
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import uuid
|
|
|
|
import vm_job_bootstrap as bootstrap
|
|
from vm_passive_test import require, remote_python
|
|
|
|
ROOT = bootstrap.ROOT
|
|
# Reviewed pre-fix unit from the preserved 2026-11-12 VM deployment. Accepting
|
|
# this exact version permits diagnosis before the rebuilt helper is deployed.
|
|
PRE_FIX_UNIT_SHA256 = '87c2fa242a604fbb9edb5612dd0ef1e703a362d8b465cb97fb3b7ccb5f781f36'
|
|
|
|
CHECK = '''import json,runpy
|
|
from pathlib import Path
|
|
codes = {
|
|
'ROOT_REQUIRED', 'APT_CONTROLLER_NNP', 'APT_CONTROLLER_OUTER_FILTER',
|
|
'APT_CONTROLLER_CAPABILITIES', 'APT_CONTROLLER_INHERITED_CAPABILITIES',
|
|
'APT_CONTROLLER_UNIT', 'APT_CONTROLLER_READONLY_SYSTEM',
|
|
'APT_CONTROLLER_WRITE_TARGET_REQUIRED', 'APT_CONTROLLER_MOUNTINFO',
|
|
'APT_CONTROLLER_EXTRA_WRITE_MOUNT',
|
|
}
|
|
try:
|
|
module=runpy.run_path('/usr/lib/rmm-apt-transaction/apt_transaction.py',run_name='controller_diagnostic')
|
|
try:
|
|
module['verify_controller_profile']()
|
|
code='passed'
|
|
except module['Veto'] as error:
|
|
code=str(error) if str(error) in codes else 'UNCLASSIFIED_VETO'
|
|
status=dict(line.split(':',1) for line in Path('/proc/self/status').read_text().splitlines() if ':' in line)
|
|
fields={key:status[key].strip() for key in ('NoNewPrivs','Seccomp','CapEff','CapPrm','CapBnd','CapInh','CapAmb')}
|
|
print('RMM_CONTROLLER_DIAGNOSTIC='+json.dumps(dict(code=code,status=fields)),flush=True)
|
|
except Exception:
|
|
print('RMM_CONTROLLER_DIAGNOSTIC='+json.dumps(dict(code='DIAGNOSTIC_FAILED')),flush=True)
|
|
'''
|
|
|
|
|
|
def remote_diagnose(payload):
|
|
import sqlite3
|
|
os.umask(0o077)
|
|
unit = 'rmm-apt-helper.service'
|
|
base = Path('/var/lib/rmm-apt-transaction')
|
|
unit_path = Path('/etc/systemd/system') / unit
|
|
dropdir = Path(str(unit_path) + '.d')
|
|
dropin = dropdir / '90-controller-diagnostic.conf'
|
|
script = base / ('controller-diagnostic-' + payload['id'] + '.py')
|
|
|
|
def run(args):
|
|
return subprocess.run(args, capture_output=True, text=True, timeout=40, check=True).stdout
|
|
|
|
def count():
|
|
with sqlite3.connect('file:/var/lib/rmm-helper/consumption.sqlite?mode=ro', uri=True) as db:
|
|
return db.execute('SELECT count(*) FROM consumed').fetchone()[0]
|
|
|
|
def create(path, content):
|
|
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
|
|
with os.fdopen(fd, 'w') as stream:
|
|
stream.write(content)
|
|
|
|
require(os.geteuid() == 0, 'root bootstrap required')
|
|
require(count() == 0, 'nonempty root ledger; no diagnostic start')
|
|
for name in ('rmm-agent.service', 'rmm-helper-dev-test.service', unit):
|
|
require(run(['systemctl', 'show', name, '-p', 'ActiveState', '--value']).strip() == 'inactive',
|
|
'service is not idle; no stop performed')
|
|
for path, pins in ((unit_path, payload['unit_sha256']),
|
|
(Path('/usr/lib/rmm-apt-transaction/apt_transaction.py'), [payload['provider_sha256']])):
|
|
require(not path.is_symlink() and path.stat().st_uid == 0 and path.stat().st_mode & 0o022 == 0
|
|
and hashlib.sha256(path.read_bytes()).hexdigest() in pins, 'installed source mismatch')
|
|
require(base.is_dir() and not base.is_symlink() and base.stat().st_uid == 0
|
|
and base.stat().st_mode & 0o777 == 0o700, 'unsafe provider store')
|
|
require(not run(['systemctl', 'show', unit, '-p', 'DropInPaths', '--value']).strip(), 'existing unit overrides')
|
|
require(not dropdir.exists(), 'existing drop-in directory; no changes')
|
|
require(not script.exists() and not script.is_symlink(), 'diagnostic script already exists')
|
|
require(not (base / 'native-readiness.json').exists(), 'existing readiness; inspect before diagnosis')
|
|
override = ('[Service]\nType=oneshot\nRestart=no\nExecStartPre=\n'
|
|
'ExecStartPre=/usr/bin/python3 -I ' + str(script) + '\nExecStart=\nExecStart=/usr/bin/true\n')
|
|
if payload['implicit_root']:
|
|
# System services default to root. Clear only the redundant explicit
|
|
# User=root; keep Group, NNP, bounding/ambient sets and all filters.
|
|
override += 'User=\n'
|
|
made_script = made_dir = made_dropin = False
|
|
try:
|
|
create(script, payload['check']); made_script = True
|
|
dropdir.mkdir(mode=0o755); made_dir = True
|
|
create(dropin, override); made_dropin = True
|
|
run(['systemctl', 'daemon-reload'])
|
|
run(['systemctl', 'start', unit])
|
|
# A completed oneshot clears InvocationID. Match our unique marker in
|
|
# the unit journal instead of relying on a live process or stale logs.
|
|
logs = run(['journalctl', '--no-pager', '-u', unit, '-n', '50', '-o', 'cat'])
|
|
prefix = 'RMM_CONTROLLER_DIAGNOSTIC_' + payload['id'] + '='
|
|
records = [json.loads(line.split('=', 1)[1]) for line in logs.splitlines()
|
|
if line.startswith(prefix)]
|
|
require(len(records) == 1, 'missing or ambiguous diagnostic result')
|
|
report = records[0]
|
|
finally:
|
|
# Never stop a daemon: the override runs a finite check and /usr/bin/true.
|
|
require(run(['systemctl', 'show', unit, '-p', 'ActiveState', '--value']).strip()
|
|
in ('inactive', 'failed'), 'unexpected active unit; inspect manually')
|
|
if made_dropin:
|
|
require(dropin.read_text() == override and not dropin.is_symlink(), 'diagnostic override changed')
|
|
dropin.unlink()
|
|
if made_dir:
|
|
dropdir.rmdir()
|
|
if made_script:
|
|
require(script.read_text() == payload['check'] and not script.is_symlink(), 'diagnostic script changed')
|
|
script.unlink()
|
|
run(['systemctl', 'daemon-reload'])
|
|
require(count() == 0 and not (base / 'native-readiness.json').exists(), 'unexpected effect evidence')
|
|
require(not run(['systemctl', 'show', unit, '-p', 'DropInPaths', '--value']).strip(), 'override remains')
|
|
return dict(controller=report, restored=True, root_consumed=0, native_readiness=False,
|
|
package_effects=False, rmm_jobs_executed=False)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--diagnose-installed-profile', action='store_true', required=True)
|
|
parser.add_argument('--implicit-root', action='store_true', help='Test default-root identity with otherwise identical sandbox')
|
|
args = parser.parse_args()
|
|
payload = dict(id=uuid.uuid4().hex, check=CHECK,
|
|
unit_sha256=[PRE_FIX_UNIT_SHA256, hashlib.sha256((ROOT/'deploy/linux/rmm-apt-helper.service').read_bytes()).hexdigest()],
|
|
provider_sha256=hashlib.sha256((ROOT/'tools/apt-transaction/apt_transaction.py').read_bytes()).hexdigest())
|
|
payload['check'] = CHECK.replace('RMM_CONTROLLER_DIAGNOSTIC=',
|
|
'RMM_CONTROLLER_DIAGNOSTIC_' + payload['id'] + '=')
|
|
payload['implicit_root'] = args.implicit_root
|
|
code = ('import os,json,hashlib,subprocess\nfrom pathlib import Path\n'
|
|
'def require(value,message):\n if not value: raise RuntimeError(message)\n' +
|
|
inspect.getsource(remote_diagnose) + '\ntry:\n print(json.dumps(remote_diagnose(' + repr(payload) +
|
|
')))\nexcept Exception:\n print(json.dumps(dict(error="BOOTSTRAP_DIAGNOSTIC_INCOMPLETE")))\n')
|
|
with bootstrap.connection() as (ssh, target, env):
|
|
result = json.loads(remote_python(ssh, target, env, code))
|
|
require('error' not in result, 'bootstrap diagnostic incomplete; inspect unit state before continuing')
|
|
directory = ROOT/'devstate/controller-diagnostic'
|
|
directory.mkdir(mode=0o700, exist_ok=True)
|
|
fd = os.open(directory/(payload['id']+'.json'), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
with os.fdopen(fd, 'w') as stream:
|
|
json.dump(result, stream, indent=2)
|
|
print(json.dumps(result))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
main()
|
|
except Exception:
|
|
print('BOOTSTRAP_DIAGNOSTIC_INCOMPLETE; private details withheld')
|
|
raise SystemExit(2) from None
|