#!/usr/bin/env python3 """Fixed existing expired Windows script ceiling renewal; Root invokes separately. No CLI dispatch, job/approval, container recreation, membership, environment or mount mutation. A committed intent makes this case readback-only, never retry. """ def renew_existing_expired_policy(payload): import datetime as dt import fcntl import hashlib import json import os from pathlib import Path import re import stat import subprocess import uuid def require(value, code): if not value: raise RuntimeError(code) require(os.geteuid() == 0, 'SYSTEM_RENEW_ROOT_BOOTSTRAP') require(set(payload) == {'operation', 'case_id', 'expected_roles', 'helper_binary_sha256', 'helper_policy_sha256', 'acceptance_evidence_id'}, 'SYSTEM_RENEW_FIXED_INPUT') require(payload['operation'] == 'windows_system_existing_expired_script_scope_renew_v1', 'SYSTEM_RENEW_OPERATION') ident = str(uuid.UUID(payload['case_id'])) evidence_id = str(uuid.UUID(payload['acceptance_evidence_id'])) require(ident == payload['case_id'] and evidence_id == payload['acceptance_evidence_id'] and uuid.UUID(ident).int and uuid.UUID(evidence_id).int, 'SYSTEM_RENEW_CANONICAL_IDS') require(all(re.fullmatch('[a-f0-9]{64}', payload[n]) for n in ('helper_binary_sha256', 'helper_policy_sha256')), 'SYSTEM_RENEW_FINAL_PINS') root = Path('/opt/rust-discovery') tenant = '11111111-1111-4111-8111-111111111111' asset = 'a176520e-8a91-4e93-a78b-8e7620f430e0' agent = '63ea15b2-0643-403d-b5b4-cba1288dbea3' actors = ['automation:' + tenant, 'simulated-testprincipal-a'] mounted = root / 'devstate/windows-system-policy/5fb6d7c9-d2b4-472c-b4fc-2ffea27e3c33/mounted' original_sha = 'c4993009e62ef9c384ea11a2f201566c2e657c1ba3b452410bb2a9d4774b0169' case = root / 'devstate/windows-system-policy' / ('renew-' + ident) epoch_intent = mounted.parent / 'renew-c4993009-intent.json' def run(args, data=None): return subprocess.run(args, input=data, capture_output=True, check=True, timeout=25).stdout def encode(value): return json.dumps(value, sort_keys=True, separators=(',', ':')).encode() def digest(data): return hashlib.sha256(data).hexdigest() def sync_directory(path): fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) try: os.fsync(fd) finally: os.close(fd) def create(path, data, uid=0, gid=0): fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) with os.fdopen(fd, 'wb') as stream: os.fchown(stream.fileno(), uid, gid) os.fchmod(stream.fileno(), 0o600) stream.write(data) stream.flush() os.fsync(stream.fileno()) def identity(m): return [m.st_dev, m.st_ino, m.st_uid, m.st_gid, stat.S_IMODE(m.st_mode), m.st_nlink] def directory(path, uid=None): m = path.lstat() require(stat.S_ISDIR(m.st_mode) and not stat.S_ISLNK(m.st_mode) and not m.st_mode & 0o022, 'SYSTEM_RENEW_PROTECTED_DIRECTORY') if uid is not None: require(m.st_uid == uid and m.st_gid == uid and stat.S_IMODE(m.st_mode) == 0o700, 'SYSTEM_RENEW_EXACT_DIRECTORY_OWNER') return identity(m) for parent in [root, root / 'devstate', root / 'devstate/windows-system-policy', mounted.parent, mounted]: directory(parent) directory(mounted.parent, 0) mounted_identity = directory(mounted, 10001) key = (root / 'devstate/jobs/ed25519.pem').lstat() # STAT ONLY, no key content. require(stat.S_ISREG(key.st_mode) and key.st_nlink == 1 and key.st_uid == key.st_gid == 10001 and stat.S_IMODE(key.st_mode) == 0o600, 'SYSTEM_RENEW_JOB_KEY_OWNER_STAT_ONLY') roles = payload['expected_roles'] require(set(roles) == {'api', 'gateway'}, 'SYSTEM_RENEW_BOTH_CURRENT_ROLES') def runtime(role): expected = roles[role] require(set(expected) == {'container_id', 'image'} and re.fullmatch('[a-f0-9]{64}', expected['container_id']) and re.fullmatch('sha256:[a-f0-9]{64}', expected['image']), 'SYSTEM_RENEW_CURRENT_CONTAINER_WITNESS') c = json.loads(run(['docker', 'inspect', expected['container_id']]))[0] h, conf = c['HostConfig'], c['Config'] require(c['Name'] == '/rust-discovery-server-' + role + '-1' and c['State']['Running'] and c['Image'] == expected['image'], 'SYSTEM_RENEW_CONTAINER_CAS') require(conf['User'] == '10001:10001' and h['ReadonlyRootfs'] and h['CapDrop'] == ['ALL'] and not h.get('CapAdd') and h['SecurityOpt'] == ['no-new-privileges:true'] and not h['Privileged'], 'SYSTEM_RENEW_SANDBOX') port = {'api': '18443', 'gateway': '18444'}[role] require(h['PortBindings'] == {'18443/tcp': [{'HostIp': '127.0.0.1', 'HostPort': port}]} and h.get('PidMode', '') == '' and h.get('IpcMode') == 'private' and h.get('UsernsMode', '') == '' and h['NetworkMode'] in c['NetworkSettings']['Networks'] and not h.get('Devices'), 'SYSTEM_RENEW_PRIVATE_NAMESPACES_AND_PORT') env = {} for entry in conf['Env']: name, separator, value = entry.partition('=') require(separator and name not in env, 'SYSTEM_RENEW_ENVIRONMENT') env[name] = value # private RAM only, never output credentials. require(env.get('RMM_PROFILE') == 'development' and env.get('RMM_DEV_SYSTEM_ENABLED') == 'true' and env.get('RMM_DEV_SYSTEM_POLICY_FILE') == '/system-policy/policy.json', 'SYSTEM_RENEW_EXISTING_ENABLED_FILE') mounts = [m for m in c['Mounts'] if m['Destination'] == '/system-policy'] require(len(mounts) == 1 and mounts[0]['Type'] == 'bind' and mounts[0]['Source'] == str(mounted) and mounts[0]['RW'] is False and mounts[0]['Propagation'] == 'rprivate', 'SYSTEM_RENEW_EXISTING_READONLY_DIRECTORY_MOUNT') # Compare the complete actual configuration again after the one file # operation; no env/container/membership delta is permitted. return {'id': c['Id'], 'image': c['Image'], 'config': conf, 'host': h, 'mounts': c['Mounts'], 'networks': sorted(c['NetworkSettings']['Networks'])} before_roles = {role: runtime(role) for role in ('api', 'gateway')} lock_path = root / 'devstate/.windows-system-scope.lock' lock = os.open(lock_path, os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600) try: lm = os.fstat(lock) require(stat.S_ISREG(lm.st_mode) and lm.st_uid == 0 and stat.S_IMODE(lm.st_mode) == 0o600 and lm.st_nlink == 1, 'SYSTEM_RENEW_ORIGINAL_SCOPE_LOCK') fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) require(not case.exists() and not epoch_intent.exists(), 'SYSTEM_RENEW_EXISTING_CASE_OR_EPOCH_READBACK_ONLY') policy_path = mounted / 'policy.json' fd = os.open(policy_path, os.O_RDONLY | os.O_NOFOLLOW) with os.fdopen(fd, 'rb') as original: old_meta = os.fstat(original.fileno()) require(stat.S_ISREG(old_meta.st_mode) and old_meta.st_nlink == 1 and old_meta.st_uid == old_meta.st_gid == 10001 and stat.S_IMODE(old_meta.st_mode) == 0o600 and old_meta.st_size <= 65536, 'SYSTEM_RENEW_EXACT_OLD_POLICY_METADATA') old_raw = original.read(65537) require(len(old_raw) <= 65536 and digest(old_raw) == original_sha, 'SYSTEM_RENEW_OLD_EXPIRED_POLICY_CAS') old = json.loads(old_raw) require(set(old) == {'schema_version', 'profile', 'expires_at', 'scopes'} and old['schema_version'] == 3 and old['profile'] == 'development' and len(old['scopes']) == 1, 'SYSTEM_RENEW_OLD_POLICY_FORM') scope = old['scopes'][0] fields = {'tenant_id', 'asset_id', 'agent_id', 'enrollment_generation', 'assignment_version', 'principals', 'helper_policy_sha256', 'helper_binary_sha256', 'acceptance_evidence_id', 'allowed_services', 'max_runtime_seconds', 'allowed_script_profiles'} require(set(scope) == fields and scope['tenant_id'] == tenant and scope['asset_id'] == asset and scope['agent_id'] == agent and scope['enrollment_generation'] == scope['assignment_version'] == 1 and scope['principals'] == actors and scope['allowed_services'] == [] and scope['max_runtime_seconds'] == 30 and scope['allowed_script_profiles'] == ['full_maintenance_v1'], 'SYSTEM_RENEW_SAME_SCRIPT_ONLY_SCOPE') now = dt.datetime.now(dt.timezone.utc) expiry = dt.datetime.fromisoformat(old['expires_at'].replace('Z', '+00:00')) require(expiry.tzinfo is not None and expiry <= now, 'SYSTEM_RENEW_OLD_WINDOW_MUST_BE_EXPIRED') require(scope['helper_binary_sha256'] != payload['helper_binary_sha256'] and scope['helper_policy_sha256'] != payload['helper_policy_sha256'] and scope['acceptance_evidence_id'] != evidence_id, 'SYSTEM_RENEW_NEW_INDEPENDENT_FINAL_PAIR_PROOF') sql = ("BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY; SELECT json_build_object(" "'installation',(SELECT json_build_object('ready',sync_ready,'helper_ready',helper_sync_ready,'blocked',restore_blocked,'fresh',last_contact_at>clock_timestamp()-interval '45 seconds','same_certificate',certificate_sha256=last_authenticated_certificate_sha256,'auth_fresh',last_authenticated_at>clock_timestamp()-interval '45 seconds','capabilities',capabilities) FROM agent_installations WHERE tenant_id='" + tenant + "' AND asset_id='" + asset + "' AND agent_id='" + agent + "' AND enrollment_generation=1 AND assignment_version=1 AND revoked_at IS NULL)," "'open_jobs',(SELECT count(*) FROM jobs WHERE tenant_id='" + tenant + "' AND agent_id='" + agent + "' AND state NOT IN ('succeeded','failed','cancelled','expired'))," "'original221',(SELECT state FROM jobs WHERE tenant_id='" + tenant + "' AND agent_id='" + agent + "' AND job_id='94047873-5088-433b-bc1b-490d3eafe0da' AND attempt_id='f071e6d6-8635-42f7-92fa-533c681edd8b')," "'memberships',(SELECT json_agg(q ORDER BY principal) FROM (SELECT principal,kind,permissions,revoked_at FROM memberships WHERE tenant_id='" + tenant + "' AND principal IN ('automation:" + tenant + "','simulated-testprincipal-a')) q)); COMMIT;") observed = json.loads(run(['docker', 'exec', '-i', 'rust-discovery-server-postgres-1', 'psql', '-X', '-qAt', '-v', 'ON_ERROR_STOP=1', '-U', 'postgres', '-d', 'rmm'], sql.encode())) live = observed['installation'] require(live and all(live[n] is True for n in ('ready', 'helper_ready', 'fresh', 'same_certificate', 'auth_fresh')) and live['blocked'] is False and observed['open_jobs'] == 0 and observed['original221'] == 'failed', 'SYSTEM_RENEW_ACTUAL_NORMAL_SYNC_AND_TERMINAL221') needed = {'windows.base/1', 'rmm.sync.v1', 'helper.system.v1', 'system:run_script', 'script.full_maintenance/1', 'helper.binary.sha256:' + payload['helper_binary_sha256'], 'helper.policy.sha256:' + payload['helper_policy_sha256']} require(needed <= set(live['capabilities']) and not {'linux.base/1', 'system:ensure_package', 'system:set_service_state', 'system:reboot'} & set(live['capabilities']), 'SYSTEM_RENEW_ACTUAL_NARROW_FINAL_CAPABILITIES') memberships = observed['memberships'] require([m['principal'] for m in memberships] == actors and all(m['revoked_at'] is None and {'scripts:execute', 'system:execute'} <= set(m['permissions']) and m['kind'] == ('automation' if n == 0 else 'test_human') for n, m in enumerate(memberships)), 'SYSTEM_RENEW_SAME_EXISTING_AUTHORIZED_ACTORS') new = json.loads(old_raw) new['expires_at'] = (now + dt.timedelta(minutes=15)).isoformat() new['scopes'][0].update(helper_binary_sha256=payload['helper_binary_sha256'], helper_policy_sha256=payload['helper_policy_sha256'], acceptance_evidence_id=evidence_id) raw = encode(new) create(epoch_intent, encode({'schema_version': 1, 'case_id': ident, 'old_policy_sha256': original_sha, 'new_policy_sha256': digest(raw), 'new_expires_at': new['expires_at'], 'automatic_retry': False})) sync_directory(mounted.parent) case.mkdir(mode=0o700) create(case / 'intent.json', encode({'schema_version': 1, 'request': payload, 'old_policy_sha256': original_sha, 'old_policy_identity': identity(old_meta), 'new_policy_sha256': digest(raw), 'new_expires_at': new['expires_at'], 'database_readback': observed})) create(case / 'original-policy.json', old_raw) sync_directory(case) sync_directory(case.parent) stage_name = '.renew-' + ident + '.json' stage = mounted / stage_name create(stage, raw, 10001, 10001) sync_directory(mounted) require(directory(mounted, 10001) == mounted_identity and identity(policy_path.lstat()) == identity(old_meta) and policy_path.read_bytes() == old_raw and os.fstat(original.fileno()).st_ino == old_meta.st_ino, 'SYSTEM_RENEW_FINAL_NAMESPACE_CAS') require({role: runtime(role) for role in ('api', 'gateway')} == before_roles, 'SYSTEM_RENEW_RUNTIME_CHANGED_BEFORE_SWAP') os.replace(stage, policy_path) sync_directory(mounted) require(policy_path.read_bytes() == raw and policy_path.stat().st_uid == policy_path.stat().st_gid == 10001 and stat.S_IMODE(policy_path.stat().st_mode) == 0o600 and (case / 'original-policy.json').read_bytes() == old_raw, 'SYSTEM_RENEW_EXACT_FILE_READBACK') require({role: runtime(role) for role in ('api', 'gateway')} == before_roles, 'SYSTEM_RENEW_RUNTIME_CHANGED_AFTER_SWAP') result = {'schema_version': 1, 'case_id': ident, 'renewed': True, 'old_policy_sha256': original_sha, 'policy_sha256': digest(raw), 'expires_at': new['expires_at'], 'original_bytes_backup_verified': True, 'containers_unchanged': True, 'environment_unchanged': True, 'mounts_unchanged': True, 'memberships_changed': False, 'jobs_created': False, 'approvals_created': False, 'automatic_retry': False} create(case / 'completed.json', encode(result)) sync_directory(case) return result finally: os.close(lock) def read_existing_policy_renewal(payload): import hashlib import json import os from pathlib import Path import stat import uuid if os.geteuid() != 0 or set(payload) != {'operation', 'case_id'} or payload['operation'] != 'windows_system_existing_script_scope_renew_readback_v1': raise RuntimeError('SYSTEM_RENEW_READBACK_INPUT') ident = str(uuid.UUID(payload['case_id'])) if ident != payload['case_id']: raise RuntimeError('SYSTEM_RENEW_READBACK_CASE') parent = Path('/opt/rust-discovery/devstate/windows-system-policy') case = parent / ('renew-' + ident) active = parent / '5fb6d7c9-d2b4-472c-b4fc-2ffea27e3c33/mounted/policy.json' epoch_path = active.parent.parent / 'renew-c4993009-intent.json' def read(path, owner): m = path.lstat() if not stat.S_ISREG(m.st_mode) or m.st_nlink != 1 or m.st_uid != owner or stat.S_IMODE(m.st_mode) != 0o600 or m.st_size > 65536: raise RuntimeError('SYSTEM_RENEW_READBACK_FILE') raw = path.read_bytes() after = path.lstat() if (m.st_dev, m.st_ino, m.st_mtime_ns, m.st_size) != (after.st_dev, after.st_ino, after.st_mtime_ns, after.st_size): raise RuntimeError('SYSTEM_RENEW_READBACK_CHANGED') return raw raw = read(active, 10001) current_sha = hashlib.sha256(raw).hexdigest() epoch = json.loads(read(epoch_path, 0)) if epoch_path.exists() else None if epoch is not None and epoch['case_id'] != ident: raise RuntimeError('SYSTEM_RENEW_READBACK_EPOCH_BOUND_TO_ANOTHER_CASE') if not case.exists(): return {'read_only': True, 'case_present': False, 'epoch_intent_present': epoch is not None, 'policy_sha256': current_sha, 'retry_authorized': False} m = case.lstat() if not stat.S_ISDIR(m.st_mode) or m.st_uid != 0 or stat.S_IMODE(m.st_mode) != 0o700: raise RuntimeError('SYSTEM_RENEW_READBACK_PRIVATE_CASE') intent = json.loads(read(case / 'intent.json', 0)) backup_ok = False if (case / 'original-policy.json').exists(): backup_ok = hashlib.sha256(read(case / 'original-policy.json', 0)).hexdigest() == intent['old_policy_sha256'] observed = 'unexpected_current_policy' if current_sha == intent['old_policy_sha256']: observed = 'expired_original_observed' elif current_sha == intent['new_policy_sha256']: observed = 'exact_replacement_observed' completed = None if (case / 'completed.json').exists(): completed = json.loads(read(case / 'completed.json', 0)) if completed['case_id'] != ident or completed['policy_sha256'] != intent['new_policy_sha256']: raise RuntimeError('SYSTEM_RENEW_READBACK_COMPLETION_BINDING') return {'schema_version': 1, 'read_only': True, 'case_present': True, 'observed': observed, 'policy_sha256': current_sha, 'original_bytes_backup_verified': backup_ok, 'completed': completed, 'retry_authorized': False, 'jobs_created': False, 'approvals_created': False}