From b45afe5d90c0a8f490cdc9e6e07c5100bdd77dae Mon Sep 17 00:00:00 2001 From: Kevin Janssen Date: Mon, 16 Nov 2026 23:18:01 +0100 Subject: [PATCH] Canonicalize complete mount comparison and finish only the verified prepared script scope --- deploy/windows_system_scope_renew.py | 80 ++++++++++++++++++- .../windows-system-script-central-scope.json | 21 +++++ docs/windows-system-s0-s2-results.md | 9 +++ 3 files changed, 109 insertions(+), 1 deletion(-) create mode 100644 docs/evidence/windows-system-script-central-scope.json diff --git a/deploy/windows_system_scope_renew.py b/deploy/windows_system_scope_renew.py index 5f5c87e..d161fa7 100644 --- a/deploy/windows_system_scope_renew.py +++ b/deploy/windows_system_scope_renew.py @@ -97,11 +97,12 @@ def renew_existing_expired_policy(payload): 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') + require(len({m['Destination'] for m in c['Mounts']}) == len(c['Mounts']), 'SYSTEM_RENEW_UNIQUE_MOUNT_DESTINATIONS') 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'])} + return {'id': c['Id'], 'image': c['Image'], 'config': conf, 'host': h, 'mounts': sorted(c['Mounts'], key=lambda mount: mount['Destination']), 'networks': sorted(c['NetworkSettings']['Networks'])} before_roles = {role: runtime(role) for role in ('api', 'gateway')} lock_path = root / 'devstate/.windows-system-scope.lock' @@ -220,3 +221,80 @@ def read_existing_policy_renewal(payload): 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} + + +def complete_prepared_policy_renewal(payload): + """Manual single-case completion only; preserve staged bytes and original expiry.""" + import datetime as dt + import fcntl + import hashlib + import json + import os + from pathlib import Path + import stat + import subprocess + def check(value, code): + if not value: raise RuntimeError(code) + def canon(value): return json.dumps(value, sort_keys=True, separators=(',', ':')).encode() + def sha(raw): return hashlib.sha256(raw).hexdigest() + def run(args, raw=None): return subprocess.run(args, input=raw, capture_output=True, check=True, timeout=25).stdout + def sync(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, value): + fd=os.open(path, os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW, 0o600) + with os.fdopen(fd,'wb') as f: os.fchmod(f.fileno(),0o600);f.write(canon(value));f.flush();os.fsync(f.fileno()) + def ident(m): return [m.st_dev,m.st_ino,m.st_uid,m.st_gid,stat.S_IMODE(m.st_mode),m.st_nlink] + def read(path, uid, inode, digest): + fd=os.open(path,os.O_RDONLY|os.O_NOFOLLOW) + with os.fdopen(fd,'rb') as f: + m=os.fstat(f.fileno());check(stat.S_ISREG(m.st_mode) and m.st_uid==m.st_gid==uid and m.st_nlink==1 and stat.S_IMODE(m.st_mode)==0o600 and m.st_ino==inode and m.st_size<=65536,'FINISH_FILE_METADATA') + raw=f.read(65537);check(sha(raw)==digest and ident(path.lstat())==ident(m),'FINISH_EXACT_FILE_CAS');return raw,m + case_id='f4de2612-fca6-4c3b-8fc6-2097bb21b278' + check(os.geteuid()==0 and payload=={'operation':'windows_system_complete_prepared_scope_renew_v1','case_id':case_id},'FINISH_FIXED_ROOT_CASE') + root=Path('/opt/rust-discovery');parent=root/'devstate/windows-system-policy';original=parent/'5fb6d7c9-d2b4-472c-b4fc-2ffea27e3c33';mounted=original/'mounted';case=parent/('renew-'+case_id);active=mounted/'policy.json';stage=mounted/('.renew-'+case_id+'.json') + for path,uid,mode in [(root,0,None),(root/'devstate',0,None),(parent,0,None),(original,0,0o700),(mounted,10001,0o700),(case,0,0o700)]: + m=path.lstat();check(stat.S_ISDIR(m.st_mode) and m.st_uid==m.st_gid==uid and not m.st_mode&0o022 and (mode is None or stat.S_IMODE(m.st_mode)==mode),'FINISH_PROTECTED_DIRECTORY') + old_sha='c4993009e62ef9c384ea11a2f201566c2e657c1ba3b452410bb2a9d4774b0169';new_sha='0730a000d55fc101385705e9531ccb998cc02f3c932109ac6922c193004fcac7' + expected={ + 'api':('d589e4100c3826320958788489908943c6f6e860df275ed2616ba7ea273470fd','f7c4f62069fe54d077478d417a3cca929059b7cf7050038d0988a20a39404759','26068c35192c67595bc1ac4cd2788eb76f087ca5c530351f3e3ffb0442eaff3e','8d38126b1e37e5b4d55083d66e52b3b3455ad2579b9e14e67b3c49a503b8c538'), + 'gateway':('e778410788b2bfe5c004289831798d13780f2435e8511d9430ade549cc26097c','3c2684b4665674437bbff4d2282f80a4b73962af5bc3efd56718d0d96f7ce2fb','567409c041edaf575a540e68c077e280ce9c73fdb0a9feb4d82d904f99dd5047','a74b6ea46a0b05dfddc7870d7e028232acc45b7588c47b59b219948827311a32')} + image='sha256:f0f3b79153e1ecd9f878cd0436a3a48238a8296f71790cf89f20efe1073b8b86' + def runtime(): + result={} + for role,(cid,config_hash,host_hash,mount_hash) in expected.items(): + c=json.loads(run(['docker','inspect',cid]))[0];mounts=c['Mounts'];check(len({m['Destination'] for m in mounts})==len(mounts),'FINISH_UNIQUE_MOUNTS');ordered=sorted(mounts,key=lambda m:m['Destination']) + check(c['Id']==cid and c['Name']=='/rust-discovery-server-'+role+'-1' and c['State']['Running'] and c['Image']==image and sha(canon(c['Config']))==config_hash and sha(canon(c['HostConfig']))==host_hash and sha(canon(ordered))==mount_hash and sorted(c['NetworkSettings']['Networks'])==['rust-discovery-server_backend','rust-discovery-server_ingress'],'FINISH_ACTUAL_RUNTIME_DIGESTS') + result[role]={'container_id':cid,'image':image,'config_sha256':config_hash,'host_sha256':host_hash,'sorted_mounts_sha256':mount_hash} + return result + lock=os.open(root/'devstate/.windows-system-scope.lock',os.O_WRONLY|os.O_NOFOLLOW) + try: + lm=os.fstat(lock);check(stat.S_ISREG(lm.st_mode) and lm.st_uid==lm.st_gid==0 and lm.st_nlink==1 and stat.S_IMODE(lm.st_mode)==0o600,'FINISH_ORIGINAL_LOCK');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) + check(not (case/'finish-intent.json').exists() and not (case/'completed.json').exists(),'FINISH_EXISTING_INTENT_READBACK_ONLY') + epoch_raw,_=read(original/'renew-c4993009-intent.json',0,286476,'cb72566d923722c6e1413fbcd41b96356a628fab637f41794bc1f45ae0814ef5');intent_raw,_=read(case/'intent.json',0,286478,'6afc2629226890f60abc6d353d75a22b24a5a8291799411b1cb76e9027a7bde2') + backup,_=read(case/'original-policy.json',0,286479,old_sha);old_raw,old_meta=read(active,10001,285460,old_sha);raw,stage_meta=read(stage,10001,286480,new_sha) + epoch=json.loads(epoch_raw);intent=json.loads(intent_raw);new=json.loads(raw);request=intent['request'];scope=new['scopes'][0];expiry='2026-11-16T22:23:25.321002+00:00' + tenant='11111111-1111-4111-8111-111111111111';agent='63ea15b2-0643-403d-b5b4-cba1288dbea3';asset='a176520e-8a91-4e93-a78b-8e7620f430e0';actors=['automation:'+tenant,'simulated-testprincipal-a'] + check(epoch['case_id']==case_id and epoch['old_policy_sha256']==intent['old_policy_sha256']==old_sha and epoch['new_policy_sha256']==intent['new_policy_sha256']==new_sha and epoch['new_expires_at']==intent['new_expires_at']==new['expires_at']==expiry and epoch['automatic_retry'] is False and backup==old_raw and ident(old_meta)==intent['old_policy_identity'],'FINISH_ORIGINAL_EPOCH_AND_NAMESPACE') + check(request['case_id']==case_id and request['operation']=='windows_system_existing_expired_script_scope_renew_v1' and request['expected_roles']=={r:{'container_id':v[0],'image':image} for r,v in expected.items()} and request['helper_binary_sha256']=='744dd4e6fd6027cde3f9b7c1f0bbccee9ebbd13a3dd378335e53f1e7af68817e' and request['helper_policy_sha256']=='a65ca9de25d2a3269802a4877874947c76ee8b257adc5ff93a2f545b2797cf3e' and request['acceptance_evidence_id']=='8b70997e-edc5-4438-9870-8a3bb13f8f2b','FINISH_ORIGINAL_REQUEST') + check(new['schema_version']==3 and new['profile']=='development' and len(new['scopes'])==1 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['max_runtime_seconds']==30 and scope['allowed_services']==[] and scope['allowed_script_profiles']==['full_maintenance_v1'],'FINISH_SCRIPT_ONLY_SCOPE') + rebuilt=json.loads(old_raw);rebuilt['expires_at']=expiry;rebuilt['scopes'][0].update({k:request[k] for k in ['helper_binary_sha256','helper_policy_sha256','acceptance_evidence_id']});check(canon(rebuilt)==raw,'FINISH_ONLY_PREPARED_BYTES_NO_NEW_TTL') + check(dt.datetime.now(dt.timezone.utc)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 agent_id='"+agent+"' AND asset_id='"+asset+"' 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'] + check(live and all(live[k] is True for k in ['ready','helper_ready','fresh','same_certificate','auth_fresh']) and live['blocked'] is False and observed['open_jobs']==0 and observed['original221']=='failed','FINISH_FRESH_NORMAL_READY_NO_OPEN_JOBS') + needed={'windows.base/1','rmm.sync.v1','helper.system.v1','system:run_script','script.full_maintenance/1','helper.binary.sha256:'+request['helper_binary_sha256'],'helper.policy.sha256:'+request['helper_policy_sha256']};check(needed<=set(live['capabilities']) and not {'linux.base/1','system:ensure_package','system:set_service_state','system:reboot'}&set(live['capabilities']),'FINISH_ACTUAL_NARROW_CAPS') + members=observed['memberships'];check(members==intent['database_readback']['memberships'] and [m['principal'] for m in members]==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(members)),'FINISH_UNCHANGED_EXISTING_ACTORS') + # Everything above is read-only and may be inspected again before this + # one-shot marker. After it exists, any ambiguity means readback only. + check(runtime()==runtime_before and dt.datetime.now(dt.timezone.utc)