aienos.com
Source of www.aienos.com, served from my own hardware
Brought by drakestapleton
aienos.com / scripts / agora_activation_observers.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Read-only activation observers shared by isolated rehearsal and live gates. |
| 3 | |
| 4 | These host tools are verification oracles, not the Omega registration backend. |
| 5 | No payload capture, response-body logging or implicit mutation retries. |
| 6 | """ |
| 7 | from contextlib import contextmanager |
| 8 | from datetime import datetime, timezone |
| 9 | import json |
| 10 | import hashlib |
| 11 | import os |
| 12 | from pathlib import Path |
| 13 | import re |
| 14 | import select |
| 15 | import subprocess |
| 16 | import stat |
| 17 | import time |
| 18 | |
| 19 | |
| 20 | class Refused(RuntimeError): |
| 21 | pass |
| 22 | |
| 23 | |
| 24 | class Commands: |
| 25 | def __init__(self): |
| 26 | self.records = [] |
| 27 | |
| 28 | def __call__(self, argv, input=None, timeout=30, check=True, private=False, |
| 29 | read_only=False): |
| 30 | attempts = 3 if read_only and argv[0] == 'ssh' else 1 |
| 31 | for attempt in range(1, attempts + 1): |
| 32 | record = {'command': [str(arg) for arg in argv], 'attempt': attempt, |
| 33 | 'utc': datetime.now(timezone.utc).isoformat()} |
| 34 | self.records.append(record) |
| 35 | try: |
| 36 | result = subprocess.run(argv, input=input, capture_output=True, |
| 37 | timeout=timeout) |
| 38 | except subprocess.TimeoutExpired: |
| 39 | record['result'] = 'TIMEOUT' |
| 40 | if attempt == attempts: |
| 41 | raise |
| 42 | continue |
| 43 | record['exit'] = result.returncode |
| 44 | if not private: |
| 45 | record['stdout'] = result.stdout.decode(errors='replace') |
| 46 | record['stderr'] = result.stderr.decode(errors='replace') |
| 47 | else: |
| 48 | record['output'] = 'PRIVATE_NOT_RECORDED' |
| 49 | if check and result.returncode: |
| 50 | if attempt != attempts: |
| 51 | continue |
| 52 | raise Refused('Command failed: ' + str(argv[:3]) + |
| 53 | ' exit=' + str(result.returncode)) |
| 54 | return result |
| 55 | raise Refused('Read-only SSH attempts exhausted') |
| 56 | |
| 57 | |
| 58 | def properties(raw): |
| 59 | result = {} |
| 60 | for line in raw.splitlines(): |
| 61 | if not line: |
| 62 | continue |
| 63 | key, separator, value = line.partition('=') |
| 64 | if not separator or key in result: |
| 65 | raise Refused('Malformed or duplicate property: ' + key) |
| 66 | result[key] = value |
| 67 | return result |
| 68 | |
| 69 | |
| 70 | class Observers: |
| 71 | def __init__(self, run, native, startup, prefix=(), sudo=('sudo', '-n')): |
| 72 | self.run = run |
| 73 | self.native = str(native) |
| 74 | self.startup_native = str(startup) |
| 75 | self.prefix = list(prefix) |
| 76 | self.sudo = list(sudo) |
| 77 | self.observations = [] |
| 78 | |
| 79 | def command(self, argv): |
| 80 | return self.prefix + list(argv) |
| 81 | |
| 82 | def text(self, argv, **kwargs): |
| 83 | return self.run(argv, **kwargs).stdout.decode() |
| 84 | |
| 85 | def show(self, unit, *fields): |
| 86 | argv = ['systemctl', 'show', unit] |
| 87 | for field in fields: |
| 88 | argv += ['-p', field] |
| 89 | return self.text(argv) |
| 90 | |
| 91 | def native_check(self, mode, *args, statuses=(0,)): |
| 92 | result = self.run([self.native, mode, *map(str, args)], check=False) |
| 93 | if result.returncode not in statuses: |
| 94 | raise Refused('Native ' + mode + ' refused: ' + str(result.returncode)) |
| 95 | return result.returncode |
| 96 | |
| 97 | def startup(self, unit, executable, endpoint): |
| 98 | deadline = time.monotonic_ns() + 10000000000 |
| 99 | pid = int(properties(self.show(unit, 'MainPID'))['MainPID']) |
| 100 | if pid <= 0: |
| 101 | raise Refused('No positive initial MainPID') |
| 102 | while time.monotonic_ns() < deadline: |
| 103 | before = properties(self.show(unit, 'MainPID'))['MainPID'] |
| 104 | exe_before = self.text(self.sudo + ['readlink', '-f', f'/proc/{pid}/exe']) |
| 105 | ps_before = self.text(['ps', '-p', str(pid), '-o', 'euid=,egid=']) |
| 106 | ss = self.text(self.command(self.sudo + |
| 107 | ['ss', '-H', '-ltnp', '( sport = :' + endpoint.rsplit(':', 1)[1] + ' )'])) |
| 108 | exe_after = self.text(self.sudo + ['readlink', '-f', f'/proc/{pid}/exe']) |
| 109 | ps_after = self.text(['ps', '-p', str(pid), '-o', 'euid=,egid=']) |
| 110 | after = properties(self.show(unit, 'MainPID'))['MainPID'] |
| 111 | elapsed = 10000000000 - (deadline - time.monotonic_ns()) |
| 112 | row = {'pid': pid, 'before': before, 'exe_before': exe_before, |
| 113 | 'ps_before': ps_before, 'listener': ss, 'exe_after': exe_after, |
| 114 | 'ps_after': ps_after, 'after': after, 'elapsed_ns': elapsed} |
| 115 | self.observations.append(row) |
| 116 | status = self.native_check('snapshot', pid, before, exe_before, |
| 117 | ps_before, ss, exe_after, ps_after, after, |
| 118 | executable, 976, 964, endpoint, elapsed, |
| 119 | 10000000000, statuses=(0, 2)) |
| 120 | if time.monotonic_ns() >= deadline: |
| 121 | raise Refused('Late startup observation') |
| 122 | if status == 0: |
| 123 | result = self.run([self.startup_native, str(deadline), |
| 124 | '1', '976', '964', '1'], check=False) |
| 125 | if result.returncode != 1 or time.monotonic_ns() >= deadline: |
| 126 | raise Refused('Startup policy did not return READY in time') |
| 127 | if int(properties(self.show(unit, 'MainPID'))['MainPID']) != pid: |
| 128 | raise Refused('MainPID changed after readiness') |
| 129 | return pid |
| 130 | time.sleep(0.01) |
| 131 | raise Refused('Startup deadline expired') |
| 132 | |
| 133 | def effective(self, config, pid, allowed_source=None): |
| 134 | proxy = allowed_source or config['allowed_source'] |
| 135 | raw = self.show(config['unit'], 'MainPID', 'User', 'Group', 'FragmentPath', |
| 136 | 'DropInPaths', 'IPAddressAllow', 'IPAddressDeny') |
| 137 | actual = properties(raw) |
| 138 | self.native_check('unit', raw, pid, 'aien-agora', 'aien-agora', |
| 139 | proxy + '/32', '127.0.0.1/32', |
| 140 | config.get('fragment', actual['FragmentPath']), |
| 141 | config.get('dropin', actual['DropInPaths'])) |
| 142 | state = self.show(config['unit'], 'ActiveState', 'SubState', |
| 143 | 'IPAccounting', 'ControlGroup') |
| 144 | group = '/system.slice/' + config['unit'] |
| 145 | self.native_check('state', state, group) |
| 146 | for ancestor in ('-.slice', 'system.slice'): |
| 147 | ancestors = self.text(['systemctl', 'show', '-p', 'IPAddressAllow', |
| 148 | '-p', 'IPAddressDeny', '--', ancestor]) |
| 149 | self.native_check('ancestors', ancestors, 1) |
| 150 | execution = self.show(config['unit'], 'ExecStart') |
| 151 | self.native_check('exec', execution, config['executable'], |
| 152 | config['display_argv'], pid) |
| 153 | actual_group = self.text(self.sudo + ['cat', f'/proc/{pid}/cgroup']) |
| 154 | state_info = Path(config['state']).stat() |
| 155 | if (not stat.S_ISDIR(state_info.st_mode) or state_info.st_uid != 976 |
| 156 | or state_info.st_gid != 964 or stat.S_IMODE(state_info.st_mode) != 0o750): |
| 157 | raise Refused('State directory identity or permissions differ from the approved policy') |
| 158 | activation = properties(self.show(config['unit'], 'TriggeredBy')) |
| 159 | if activation.get('TriggeredBy') != '': |
| 160 | raise Refused('Unexpected socket or other activation trigger') |
| 161 | sockets = self.text(self.command(self.sudo + ['ss', '-H', '-ltnp'])) |
| 162 | owned_rows = [line for line in sockets.splitlines() |
| 163 | if re.search(r'\bpid=' + str(pid) + r',', line)] |
| 164 | expected_endpoint = config['backend_host'] + ':' + str(config['backend_port']) |
| 165 | if len(owned_rows) != 1 or owned_rows[0].split()[3] != expected_endpoint: |
| 166 | raise Refused('Alternate or unexpected backend listener') |
| 167 | self.observations.append({'state_directory_mode': '750', |
| 168 | 'state_uid': state_info.st_uid, |
| 169 | 'state_gid': state_info.st_gid, |
| 170 | 'owned_listener_count': len(owned_rows), |
| 171 | 'activation_triggers': ''}) |
| 172 | if '0::' + group not in actual_group.splitlines(): |
| 173 | raise Refused('Process does not belong to observed cgroup') |
| 174 | if config.get('namespace'): |
| 175 | actual_ns = self.text(self.sudo + ['stat', '-Lc', '%i', |
| 176 | f'/proc/{pid}/ns/net']).strip() |
| 177 | expected_ns = self.text(self.sudo + ['stat', '-Lc', '%i', |
| 178 | '/run/netns/' + config['namespace']]).strip() |
| 179 | if int(actual_ns) != int(expected_ns): |
| 180 | raise Refused('Backend not inside fixture network namespace') |
| 181 | bpf = json.loads(self.text(self.sudo + ['bpftool', '-j', 'cgroup', 'show', |
| 182 | '/sys/fs/cgroup' + group, 'effective'])) |
| 183 | if ({item['attach_type'] for item in bpf} != |
| 184 | {'cgroup_inet_ingress', 'cgroup_inet_egress'} or |
| 185 | any(int(item['id']) <= 0 for item in bpf)): |
| 186 | raise Refused('Effective ingress/egress BPF not proved') |
| 187 | self.observations.append({'gate': 'effective', 'unit': raw, 'state': state, |
| 188 | 'exec': execution, 'bpf': bpf}) |
| 189 | journal = self.text(self.sudo + ['journalctl', '--unit', config['unit'], |
| 190 | '--since', config['journal_since'], '--no-pager', '-o', 'cat'], |
| 191 | private=True) |
| 192 | if re.search(r'(?i)(not supported|unsupported|failed to attach|failed to apply).*(BPF|IP firewall)|' |
| 193 | r'(BPF|IP firewall).*(not supported|unsupported|failed to attach|failed to apply)', journal): |
| 194 | raise Refused('Current invocation reports unsupported or failed IP filtering') |
| 195 | self.observations.append({'current_invocation_filter_warning': 'NONE', |
| 196 | 'since': config['journal_since']}) |
| 197 | return bpf |
| 198 | |
| 199 | def copied_artifacts(self, entries): |
| 200 | observed = [] |
| 201 | for destination, source, mode in entries: |
| 202 | target = Path(destination) |
| 203 | info = target.lstat() |
| 204 | digest = hashlib.sha256(target.read_bytes()).hexdigest() |
| 205 | expected = hashlib.sha256(Path(source).read_bytes()).hexdigest() |
| 206 | if (not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_gid != 0 |
| 207 | or stat.S_IMODE(info.st_mode) != mode or digest != expected): |
| 208 | raise Refused('Copied artifact bytes, identity or mode do not match the approved input') |
| 209 | observed.append({'path': str(target), 'source': str(source), |
| 210 | 'sha256': digest, 'uid': info.st_uid, |
| 211 | 'gid': info.st_gid, 'mode': oct(mode)}) |
| 212 | self.observations.append({'copied_artifacts': observed}) |
| 213 | |
| 214 | @contextmanager |
| 215 | def capture(self, interface, expression): |
| 216 | argv = self.command(self.sudo + ['timeout', '10', 'tcpdump', '-ni', |
| 217 | interface, '-nn', '-tt', '-S', '-l', expression]) |
| 218 | record = {'command': argv, 'kind': 'passive_packet_metadata'} |
| 219 | self.run.records.append(record) |
| 220 | proc = subprocess.Popen(argv, stdout=subprocess.PIPE, |
| 221 | stderr=subprocess.PIPE, bufsize=0) |
| 222 | error = b'' |
| 223 | deadline = time.monotonic_ns() + 10000000000 |
| 224 | try: |
| 225 | while b'listening on ' + interface.encode() not in error: |
| 226 | if proc.poll() is not None or time.monotonic_ns() >= deadline: |
| 227 | raise Refused('Capture not ready') |
| 228 | ready, _, _ = select.select([proc.stderr], [], [], 0.1) |
| 229 | if ready: |
| 230 | error += os.read(proc.stderr.fileno(), 8192) |
| 231 | observation = {} |
| 232 | yield observation |
| 233 | out, rest = proc.communicate(timeout=12) |
| 234 | error += rest |
| 235 | record.update(exit=proc.returncode, stdout=out.decode(), |
| 236 | stderr=error.decode()) |
| 237 | if proc.returncode not in (0, 124): |
| 238 | raise Refused('Passive capture failed') |
| 239 | observation['packets'] = out.decode() |
| 240 | finally: |
| 241 | if proc.poll() is None: |
| 242 | proc.terminate() |
| 243 | out, rest = proc.communicate(timeout=5) |
| 244 | record.update(exit=proc.returncode, stdout=out.decode(), |
| 245 | stderr=(error + rest).decode(), interrupted=True) |
| 246 | |
| 247 | def syn_probe(self, config, source, request, accept): |
| 248 | target, port = config['backend_host'], config['backend_port'] |
| 249 | expression = (f'tcp port {port} and host {source} and ' |
| 250 | '(tcp[tcpflags] & tcp-syn != 0)') |
| 251 | with self.capture(config['interface'], expression) as observation: |
| 252 | response = request() |
| 253 | packets = [] |
| 254 | for match in re.finditer(r'IP (\d+\.\d+\.\d+\.\d+)\.(\d+) > ' |
| 255 | r'(\d+\.\d+\.\d+\.\d+)\.(\d+): ' |
| 256 | r'Flags \[([^\]]+)\]', observation['packets']): |
| 257 | packets.append(match.groups()) |
| 258 | syn = [row for row in packets if row[0] == source and row[2] == target |
| 259 | and int(row[3]) == port and 'S' in row[4] and '.' not in row[4]] |
| 260 | ack = [row for row in packets if row[0] == target and int(row[1]) == port |
| 261 | and row[2] == source and 'S' in row[4] and '.' in row[4]] |
| 262 | if not syn or bool(ack) != accept: |
| 263 | raise Refused('Source SYN/SYNACK proof disagrees with expected policy') |
| 264 | if response.returncode != (0 if accept else 28): |
| 265 | raise Refused('Source HTTP outcome disagrees with expected policy') |
| 266 | if response.stdout.strip() != (b'200' if accept else b'000'): |
| 267 | raise Refused('Unexpected challenge status') |
| 268 | result = {'source': source, 'syn': len(syn), 'synack': len(ack), |
| 269 | 'accept': accept} |
| 270 | self.observations.append(result) |
| 271 | return result |
| 272 | |
| 273 | def counted_get(self, config, request, expected=1): |
| 274 | expression = (f'tcp dst port {config["backend_port"]} and src host ' |
| 275 | f'{config["allowed_source"]} and ' |
| 276 | 'tcp[((tcp[12] & 0xf0)>>2):4] = 0x47455420') |
| 277 | with self.capture(config['interface'], expression) as observation: |
| 278 | result = request() |
| 279 | identities = set() |
| 280 | for match in re.finditer(r'IP (\S+) > (\S+): .*seq (\d+):\d+', |
| 281 | observation['packets']): |
| 282 | identities.add(match.groups()) |
| 283 | if callable(expected): |
| 284 | expected = expected(result) |
| 285 | if len(identities) != expected: |
| 286 | raise Refused('Independent backend GET count: ' + str(len(identities))) |
| 287 | self.observations.append({'backend_gets': len(identities)}) |
| 288 | return result |
| 289 | |
| 290 | def reload(self, config): |
| 291 | args = config['nginx_args'] |
| 292 | self.run(self.command(self.sudo + args + ['-t'])) |
| 293 | master = int(config['nginx_pid']) |
| 294 | def workers(): |
| 295 | rows = self.text(self.sudo + ['ps', '--ppid', str(master), '-o', |
| 296 | 'pid=,args='], check=False) |
| 297 | result = {} |
| 298 | for row in rows.splitlines(): |
| 299 | pid, title = row.strip().split(maxsplit=1) |
| 300 | if 'nginx: worker process' in title: |
| 301 | result[int(pid)] = 'shutting down' in title |
| 302 | return result |
| 303 | def listeners(): |
| 304 | raw = self.text(self.command(self.sudo + ['ss', '-H', '-ltnp'])) |
| 305 | return {int(pid) for pid in re.findall(r'\bpid=(\d+),', raw)} |
| 306 | before = workers() |
| 307 | old_active = {pid for pid, draining in before.items() if not draining} |
| 308 | if not old_active or any(pid in listeners() for pid, draining in |
| 309 | before.items() if draining): |
| 310 | raise Refused('Initial nginx worker/listener state invalid') |
| 311 | self.run(self.command(self.sudo + args + ['-s', 'reload'])) |
| 312 | deadline = time.monotonic_ns() + 30000000000 |
| 313 | while time.monotonic_ns() < deadline: |
| 314 | current = workers() |
| 315 | listening = listeners() |
| 316 | new = {pid for pid, draining in current.items() |
| 317 | if not draining and pid not in before} |
| 318 | ready = new and all(pid not in current or |
| 319 | (current[pid] and pid not in listening) |
| 320 | for pid in old_active) |
| 321 | if ready and time.monotonic_ns() < deadline: |
| 322 | self.observations.append({'reload_before': before, |
| 323 | 'reload_after': current, 'new_active': sorted(new), |
| 324 | 'listening_pids': sorted(listening)}) |
| 325 | return |
| 326 | time.sleep(0.01) |
| 327 | raise Refused('Nginx worker adoption deadline expired') |
| 328 | |
| 329 | def effective_logging(self, config): |
| 330 | raw = self.text(self.command(self.sudo + config['nginx_args'] + ['-T']), |
| 331 | private=True) |
| 332 | sinks = set() |
| 333 | access = set() |
| 334 | temps = set() |
| 335 | for kind, arguments in re.findall( |
| 336 | r'(?m)^\s*(access_log|error_log|[a-z_]+_temp_path)\s+([^;\n]+);', raw): |
| 337 | path = arguments.split()[0] |
| 338 | if kind.endswith('_temp_path'): |
| 339 | temps.add(path) |
| 340 | elif path not in ('off', '/dev/null'): |
| 341 | if not path.startswith('/') or '$' in path: |
| 342 | raise Refused('Effective log sink cannot be directly inspected') |
| 343 | sinks.add(path) |
| 344 | if kind == 'access_log': |
| 345 | access.add(path) |
| 346 | if sinks != set(config['logs']) or temps != set(config['temp_dirs']): |
| 347 | raise Refused('Declared log/temp paths differ from effective nginx configuration') |
| 348 | config['access_logs'] = sorted(access) |
| 349 | self.observations.append({'effective_log_sinks': sorted(sinks), |
| 350 | 'effective_temp_dirs': sorted(temps)}) |
| 351 | |
| 352 | def journal_privacy(self, config, markers): |
| 353 | units = [config['unit'], *config.get('routing_units', [])] |
| 354 | argv = self.sudo + ['journalctl'] |
| 355 | for unit in units: |
| 356 | argv += ['--unit', unit] |
| 357 | result = self.run(argv + ['--since', config['journal_since'], |
| 358 | '--no-pager', '-o', 'cat'], private=True) |
| 359 | if any(marker in result.stdout for marker in markers): |
| 360 | raise Refused('Privacy marker found in fixture service journal') |
| 361 | self.observations.append({'journal_privacy': 'PASS', 'units': units, |
| 362 | 'since': config['journal_since'], |
| 363 | 'markers': len(markers)}) |
| 364 | |
| 365 | def privacy(self, logs, temp_dirs, markers): |
| 366 | paths = list(logs) |
| 367 | for directory in temp_dirs: |
| 368 | result = self.run(self.sudo + ['find', str(directory), '-type', 'f', |
| 369 | '-print0']) |
| 370 | paths += [name.decode() for name in result.stdout.split(b'\0') if name] |
| 371 | if not paths: |
| 372 | raise Refused('No effective log sinks observed') |
| 373 | result = self.run(self.sudo + ['grep', '-F', '-l', '-f', '-', '--', *paths], |
| 374 | input=b'\n'.join(markers) + b'\n', check=False, |
| 375 | private=True) |
| 376 | if result.returncode != 1: |
| 377 | raise Refused('Privacy marker found or effective sink unreadable') |
| 378 | self.observations.append({'privacy': 'PASS', 'log_sinks': list(logs), |
| 379 | 'temp_dirs': list(map(str, temp_dirs)), |
| 380 | 'markers': len(markers)}) |
| 381 | |
| 382 | |
| 383 | def save_private(path, value): |
| 384 | target = Path(path) |
| 385 | descriptor = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) |
| 386 | try: |
| 387 | os.write(descriptor, value.encode()) |
| 388 | os.fsync(descriptor) |
| 389 | finally: |
| 390 | os.close(descriptor) |
| 391 | if target.stat().st_mode & 0o077: |
| 392 | raise Refused('Recovery material permissions not private') |