#!/usr/bin/env python3 """Open and revoke a device-bound development window for the built-in Windows Update template.""" import argparse import base64 from datetime import datetime, timedelta, timezone import fcntl import gzip import json import os from pathlib import Path import re import shlex import stat import subprocess import sys import tempfile import time import uuid def require(ok, message): if not ok: raise ValueError(message) def identifier(value): raw = str(value) parsed = uuid.UUID(raw) require(parsed.int and str(parsed) == raw, 'A canonical, nonempty UUID is required') return raw def utc(): return datetime.now(timezone.utc) def stamp(value): result = datetime.fromisoformat(value.replace('Z', '+00:00')) require(result.tzinfo is not None, 'Timestamp lacks timezone') return result def encode(value): return json.dumps(value, separators=(',', ':'), sort_keys=True).encode() def atomic(path, data, owner=None): with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as handle: temp = Path(handle.name) try: if owner is not None: os.fchown(handle.fileno(), *owner) os.fchmod(handle.fileno(), 0o600) handle.write(data) handle.flush() os.fsync(handle.fileno()) os.replace(temp, path) directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY) try: os.fsync(directory) finally: os.close(directory) finally: temp.unlink(missing_ok=True) def read_registry(data): tenant, asset, agent = [identifier(data[k]) for k in ('tenant_id', 'asset_id', 'agent_id')] # Each interpolated value is a canonical UUID; this invocation cannot mutate Postgres. sql = f"""BEGIN READ ONLY; SELECT json_build_object('install',(SELECT json_build_object( 'contact',last_contact_at,'ready',sync_ready AND NOT restore_blocked,'helper_ready',helper_sync_ready, 'fresh',last_authenticated_at > now() - interval '2 minutes' AND certificate_sha256=last_authenticated_certificate_sha256 AND last_contact_at > now() - interval '2 minutes', 'enrollment_generation',enrollment_generation,'assignment_version',assignment_version,'capabilities',capabilities) FROM agent_installations WHERE tenant_id='{tenant}' AND asset_id='{asset}' AND agent_id='{agent}' AND revoked_at IS NULL), 'sync_head',(SELECT json_build_object('journal_id',s.journal_id,'checkpoint',s.checkpoint,'decision_id',s.decision_id, 'helper_id',s.helper_journal_id,'helper_checkpoint',s.helper_checkpoint) FROM agent_sync_state s WHERE tenant_id='{tenant}' AND agent_id='{agent}'), 'open_jobs',(SELECT count(*) FROM jobs WHERE tenant_id='{tenant}' AND agent_id='{agent}' AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown')), 'principal_authorized',EXISTS (SELECT 1 FROM memberships WHERE tenant_id='{tenant}' AND principal='simulated-testprincipal-a' AND revoked_at IS NULL AND kind='test_human' AND 'scripts:execute'=ANY(permissions) AND 'system:execute'=ANY(permissions))); COMMIT;""" raw = subprocess.check_output(['docker', 'exec', '-i', 'rust-discovery-server-postgres-1', 'psql', '-XqAt', '-v', 'ON_ERROR_STOP=1', '-U', 'postgres', '-d', 'rmm'], input=sql.encode()) return json.loads(raw) def policy_location(): base = Path('/opt/rust-discovery/devstate/windows-system-policy') mounts = [] for role in ('api', 'gateway'): container = f'rust-discovery-server-{role}-1' settings = subprocess.check_output(['docker','exec', container, 'printenv','RMM_PROFILE', 'RMM_DEV_SYSTEM_ENABLED','RMM_DEV_SYSTEM_POLICY_FILE'], text=True).splitlines() require(settings == ['development','true','/system-policy/policy.json'], 'Development policy unavailable on '+role) bind = json.loads(subprocess.check_output(['docker','inspect','--format','{{json .Mounts}}', container])) dirs = [Path(m['Source']) for m in bind if m['Destination']=='/system-policy' and m['Type']=='bind' and not m['RW']] require(len(dirs)==1 and dirs[0].parent.parent==base and dirs[0].name=='mounted' and dirs[0].resolve()==dirs[0], 'Unexpected or writable SYSTEM policy mount') mounts.append(dirs[0]) require(mounts[0]==mounts[1], 'API and gateway must use the same directory') return mounts[0]/'policy.json' def usable(observation): install = observation.get('install') or {} return (observation['open_jobs']==0 and observation['principal_authorized'] and install.get('fresh') and install['ready'] and install['enrollment_generation']==install['assignment_version']==1) def scoped(data, observation): if not usable(observation) or not observation['install']['helper_ready']: return False caps=set(observation['install']['capabilities']) needed={'windows.base/1','rmm.sync.v1','helper.system.v1','system:run_script','script.windows_update.long/1', 'helper.policy.sha256:'+data['helper_policy_sha256'], 'helper.binary.sha256:'+data['helper_binary_sha256'], 'run_script','script.powershell/1','script.powershell.process_remote_signed/1'} return needed<=caps and not any(c in caps for c in ('script.full_maintenance/1','system:set_service_state','system:ensure_package','system:reboot','linux.base/1')) def server(action, data): if action=='read': return read_registry(data) case = identifier(data['case_id']) path = policy_location() if action=='preflight': current=json.loads(path.read_bytes()) require(current['profile']=='development' and (stamp(current['expires_at'])<=utc() or not current['scopes']), 'Another live maintenance window is active') return {'dev_scope_available':True} history = path.parent.parent.parent/('update-window-'+case) lockpath = Path('/opt/rust-discovery/devstate/.windows-system-scope.lock') fd = os.open(lockpath, os.O_RDWR|os.O_CREAT|os.O_NOFOLLOW, 0o600) with os.fdopen(fd,'rb') as mutex: fcntl.flock(mutex, fcntl.LOCK_EX) st=path.lstat() require(stat.S_ISREG(st.st_mode) and st.st_uid==st.st_gid==10001 and stat.S_IMODE(st.st_mode)==0o600 and st.st_size<=65536 and st.st_nlink==1, 'Unexpected policy file or ownership') current=path.read_bytes() if action=='revoke': history.mkdir(mode=0o700,exist_ok=True) if history.exists(): original, window=history/'original.json', history/'window.json' # The candidate is recorded durably before replacing the live policy. if not window.exists(): require(not original.exists() or original.read_bytes()==current,'Partial opening has a different live policy') if not (history/'closed').exists(): atomic(history/'closed',b'closed\n') return {'central_scope_closed':True} saved=original.read_bytes() candidate=window.read_bytes() require(current in (candidate,saved), 'Central policy changed since opening. Reconcile before replacing it.') if current!=saved: atomic(path,saved,(st.st_uid,st.st_gid)) if not (history/'closed').exists(): atomic(history/'closed',b'closed\n') return {'central_scope_closed':True} require(action in ('prepare','enable'), 'Unsupported central operation') ids={k:identifier(data[k]) for k in ('case_id','tenant_id','asset_id','agent_id','release_id')} hashes={k:data[k] for k in ('agent_sha256','helper_binary_sha256')} require(all(re.fullmatch('[a-f0-9]{64}',v) for v in hashes.values()), 'Invalid signed image pair') expires=stamp(data['expires_at']) require(utc()=started and not {'helper.system.v1','system:run_script'} & set(row['install']['capabilities']), 180,'Still awaiting a new synchronized non-SYSTEM heartbeat after closing') emit({'closed_case':data['case_id'],'normal_agent_contact':ended['install']['contact']}) if __name__=='__main__': try: if len(sys.argv)==4 and sys.argv[1]=='--on-server': emit(server(sys.argv[2],json.loads(base64.b64decode(sys.argv[3],validate=True)))) else: local() except subprocess.SubprocessError as exc: sys.exit('Remote command failed: '+type(exc).__name__+' (see target diagnostic above)') except (ValueError,OSError,KeyError) as exc: sys.exit(str(exc))