Files
rust-discovery/deploy/cloud_offline_network_evidence.py
T
2026-11-13 20:24:01 +01:00

82 lines
5.7 KiB
Python

"""One bounded operational transport probe; no RMM job or application data."""
def network_status(payload):
import grp
import stat
account = pwd.getpwnam('rmm-agent')
require(os.geteuid() == 0 and account.pw_uid == 993 and account.pw_gid > 0
and account.pw_gid == grp.getgrnam('rmm-agent').gr_gid, 'named unprivileged Cloud agent')
state = Path('/var/lib/rmm-agent-remote')
require(json.loads((state/'identity.json').read_text())['agent_id'] == payload['agent_id'], 'fixed permanent Cloud identity')
require(hashlib.sha256(Path('/usr/local/libexec/rmm-agent-remote').read_bytes()).hexdigest() == payload['binary_sha256'], 'qualified agent artifact')
identifier = str(uuid.UUID(payload['id']))
phase = payload.get('phase','preflight'); require(phase in ('preflight','window'), 'fixed network phase')
dropin = Path('/etc/systemd/system/rmm-agent-remote.service.d/96-cloud-offline-acceptance.conf')
raw = None
if dropin.exists() and not dropin.is_symlink():
s = dropin.stat()
if stat.S_ISREG(s.st_mode) and s.st_uid == 0 and s.st_size <= 4096: raw = dropin.read_bytes()
own_rule = raw == ('# Cloud MVP offline '+identifier+' '+phase+'\n[Service]\nIPAddressDeny=88.99.80.202/32\n').encode()
properties = ('ActiveState','SubState','MainPID','ControlGroup','IPAddressDeny','IPAddressAllow',
'Result','ExecMainCode','ExecMainStatus','NRestarts')
command = ['systemctl','show','rmm-agent-remote.service']
for name in properties: command.extend(('-p',name))
response = subprocess.run(command,capture_output=True,check=True,timeout=10).stdout.decode()
service = dict(line.split('=',1) for line in response.splitlines())
group = service['ControlGroup']
files = {}
for name in ('journal.sqlite','consumption.sqlite'):
for suffix in ('','-wal','-shm'):
path = state/(name+suffix)
require(not path.is_symlink(), 'fixed SQLite metadata symlink')
if not path.exists(): files[path.name] = dict(exists=False); continue
s = path.stat(); require(stat.S_ISREG(s.st_mode), 'fixed SQLite regular file')
files[path.name] = dict(exists=True,uid=s.st_uid,gid=s.st_gid,mode=oct(stat.S_IMODE(s.st_mode)),
inode=s.st_ino,size=s.st_size)
summary = dict(service=service,dropin_exists=dropin.exists(),own_rule=own_rule,
dropin_sha256=hashlib.sha256(raw).hexdigest() if raw is not None else None,sqlite_files=files,
agent_uid=account.pw_uid,agent_gid=account.pw_gid,probe_cgroup=group,
server_ip='88.99.80.202',port=443,application_data_sent=False,
job_created=False,network_rule_changed=False)
if service['ActiveState'] != 'active' or int(service['MainPID']) <= 1:
return dict(summary,probe=dict(not_run='agent_inactive'))
if not own_rule: return dict(summary,probe=dict(not_run='own_network_rule_absent_or_different'))
require((group == '/system.slice/rmm-agent-remote.service' or group.startswith('/system.slice/rmm-agent-remote.service/'))
and '..' not in group, 'actual fixed agent cgroup')
cgroup = Path('/sys/fs/cgroup'+group)/'cgroup.procs'
require(cgroup.is_file(), 'unified actual cgroup')
# This child moves only itself and sends no application bytes. Numeric TCP
# is a transport probe, never a TLS-verification exception for the agent.
probe = ('import os,socket,json\nfrom pathlib import Path\nstage="cgroup_move"\n'
'try:\n Path('+repr(str(cgroup))+').write_text(str(os.getpid()))\n'
' stage="drop_groups";os.setgroups([])\n'
' stage="drop_gid";os.setgid('+str(account.pw_gid)+')\n'
' stage="drop_uid";os.setuid('+str(account.pw_uid)+')\n'
' stage="connect";s=socket.create_connection(("88.99.80.202",443),2);s.close()\n'
' r={"stage":stage,"connected":True,"timeout":False,"errno":None,"error_class":None}\n'
'except Exception as e:\n'
' name=type(e).__name__;number=getattr(e,"errno",None)\n'
' r={"stage":stage,"connected":False,"timeout":isinstance(e,TimeoutError),'
'"errno":number if type(number) is int else None,'
'"error_class":name if name in ("OSError","PermissionError","ProcessLookupError","FileNotFoundError","TimeoutError","ValueError","RuntimeError") else "OtherError"}\n'
'print(json.dumps(r))\n')
result = dict(stage='probe_process',connected=False,timeout=False,errno=None,error_class='InvalidProbeOutput',exit_code=None)
try:
answer = subprocess.run(['/usr/bin/python3','-I','-c',probe],capture_output=True,check=False,timeout=4)
result['exit_code'] = answer.returncode
if len(answer.stdout) <= 1024:
try: parsed = json.loads(answer.stdout)
except (ValueError,UnicodeError): parsed = None
if (isinstance(parsed,dict) and set(parsed) == {'stage','connected','timeout','errno','error_class'}
and parsed['stage'] in ('cgroup_move','drop_groups','drop_gid','drop_uid','connect')
and type(parsed['connected']) is bool and type(parsed['timeout']) is bool
and (parsed['errno'] is None or type(parsed['errno']) is int)
and parsed['error_class'] in (None,'OSError','PermissionError','ProcessLookupError','FileNotFoundError','TimeoutError','ValueError','RuntimeError','OtherError')):
result.update(parsed)
except subprocess.TimeoutExpired:
result.update(timeout=True,error_class='TimeoutExpired')
except OSError as error:
result.update(errno=error.errno,error_class='OSError')
return dict(summary,probe=result)