Qualify Windows SYSTEM script prerequisites and prepare guarded bootstrap
Rust development slice / linux (push) Failing after 7s

This commit is contained in:
2026-11-16 14:24:44 +01:00
parent c180de6c0c
commit 977f70b268
9 changed files with 1166 additions and 0 deletions
@@ -0,0 +1,80 @@
# Bootstrap only: stages one separate certificate fixture; never executes it.
# Input is one protected stdin JSON line. Never put the enrollment token in arguments.
$ErrorActionPreference = 'Stop'
$p = [Console]::In.ReadLine() | ConvertFrom-Json
if ((($p.PSObject.Properties.Name | Sort-Object) -join ',') -cne 'ca_base64,ca_sha256,case_id,enrollment_token') { throw 'Fixed certificate fixture input' }
if ([string]([guid]$p.case_id) -cne $p.case_id -or [guid]$p.case_id -eq [guid]::Empty -or $p.ca_sha256 -cnotmatch '^[0-9a-f]{64}$' -or $p.enrollment_token -cnotmatch '^[0-9a-f]{64}$') { throw 'Fixture input format' }
$sys = 'S-1-5-18'; $admin = 'S-1-5-32-544'
$actor = (New-Object Security.Principal.NTAccount('NT SERVICE','RmmDiscoveryWindows')).Translate([Security.Principal.SecurityIdentifier]).Value
$sdkHash = 'c6b581b60ce803318ff946cd3cc8306aa8589d6bff6b022c0bf1d48eb8f5a8e1'
$uploaded = 'C:\ProgramData\RustDiscoveryBootstrap\' + $sdkHash + '\WindowsCertificateAcceptanceSDK.exe'
$artifactRoot = 'C:\Program Files\RustDiscoveryCertificateAcceptance'
$version = Join-Path $artifactRoot $sdkHash
$sdk = Join-Path $version 'WindowsCertificateAcceptanceSDK.exe'
$parent = 'C:\ProgramData\RustDiscovery\certificate-acceptance'
$case = Join-Path $parent $p.case_id
function Hash-Bytes([byte[]]$bytes) {
$h = [Security.Cryptography.SHA256]::Create()
try { return ([BitConverter]::ToString($h.ComputeHash($bytes))).Replace('-','').ToLowerInvariant() } finally { $h.Dispose() }
}
function Check-Path([string]$path,[bool]$directory,[bool]$actorWrites) {
$item = Get-Item -LiteralPath $path -Force
if ($item.PSIsContainer -ne $directory -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Protected regular fixture path' }
if (!$directory -and $item.LinkType) { throw 'Fixture hardlink forbidden' }
$acl = Get-Acl -LiteralPath $path
if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -notin @($sys,$admin) -or !$acl.AreAccessRulesProtected) { throw 'Protected fixture owner and DACL' }
$seen = @{}
foreach ($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) {
$sid = $rule.IdentityReference.Value; $rights = [int64]$rule.FileSystemRights
if ($rule.AccessControlType -ne 'Allow' -or $sid -notin @($sys,$admin,$actor)) { throw 'Fixture principal allowlist' }
$expected = 1179817
if ($sid -in @($sys,$admin) -or $actorWrites) { $expected = 2032127 }
if ($rights -ne $expected) { throw 'Exact fixture rights' }
$seen[$sid] = $true
}
foreach ($sid in @($sys,$admin,$actor)) { if (!$seen[$sid]) { throw 'Missing fixture principal' } }
}
function Protect-Path([string]$path,[bool]$directory,[bool]$actorWrites) {
if ($directory) { $acl = New-Object Security.AccessControl.DirectorySecurity } else { $acl = New-Object Security.AccessControl.FileSecurity }
$acl.SetAccessRuleProtection($true,$false)
$acl.SetOwner((New-Object Security.Principal.SecurityIdentifier($admin)))
$inherit = 'None'; if ($directory) { $inherit = 'ContainerInherit,ObjectInherit' }
foreach ($sid in @($sys,$admin,$actor)) {
$rights = 'ReadAndExecute'; if ($sid -in @($sys,$admin) -or $actorWrites) { $rights = 'FullControl' }
$acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),$rights,$inherit,'None','Allow')))
}
Set-Acl -LiteralPath $path -AclObject $acl
Check-Path $path $directory $actorWrites
}
function Ensure-Directory([string]$path,[bool]$actorWrites) {
if (!(Test-Path -LiteralPath $path)) {
New-Item -ItemType Directory -Path $path | Out-Null
Protect-Path $path $true $actorWrites
} else { Check-Path $path $true $actorWrites }
}
function Write-NewPrivate([string]$path,[byte[]]$bytes) {
# Inherited case DACL is checked before any secret byte is written.
$f = [IO.File]::Open($path,'CreateNew','Write','None')
try {
Protect-Path $path $false $true
$f.Write($bytes,0,$bytes.Length); $f.Flush($true)
} finally { $f.Dispose() }
}
$ca = [Convert]::FromBase64String($p.ca_base64)
if ($ca.Length -gt 32768 -or (Hash-Bytes $ca) -cne $p.ca_sha256 -or [Text.Encoding]::ASCII.GetString($ca) -notmatch '^-----BEGIN CERTIFICATE-----') { throw 'Exact public fixture CA' }
if (Test-Path -LiteralPath $case) { throw 'Fixture exists; readback only, never repeat preparation' }
$source = Get-Item -LiteralPath $uploaded -Force
if ($source.PSIsContainer -or ($source.Attributes -band [IO.FileAttributes]::ReparsePoint) -or (Get-FileHash -LiteralPath $uploaded).Hash.ToLowerInvariant() -cne $sdkHash) { throw 'Exact staged SDK required' }
Ensure-Directory $artifactRoot $false
Ensure-Directory $version $false
if (!(Test-Path -LiteralPath $sdk)) {
[IO.File]::Copy($uploaded,$sdk,$false)
Protect-Path $sdk $false $false
} else { Check-Path $sdk $false $false }
if ((Get-FileHash -LiteralPath $sdk).Hash.ToLowerInvariant() -cne $sdkHash) { throw 'Protected SDK hash' }
Ensure-Directory $parent $true
New-Item -ItemType Directory -Path $case | Out-Null
Protect-Path $case $true $true
Write-NewPrivate (Join-Path $case 'ca.pem') $ca
Write-NewPrivate (Join-Path $case 'enrollment-token') ([Text.Encoding]::ASCII.GetBytes($p.enrollment_token))
[pscustomobject]@{schema_version=1;prepared=$true;executed=$false;separate_fixture=$true;case_id=$p.case_id;root=$case;sdk=$sdk;sdk_sha256=$sdkHash;ca_sha256=$p.ca_sha256;service_sid=$actor;permanent_identity_read=$false;services_changed=$false;jobs_created=$false} | ConvertTo-Json -Compress
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""Render one local fixed Windows certificate plan; performs no network or target action.
Actual bootstrap/token staging, MCP submit, UI approval and fixture revocation
are separate coordinated actions. The permanent enrolled device is never revoked.
"""
import argparse
from datetime import timedelta
import hashlib
import json
import os
from pathlib import Path
import uuid
import cloud_mvp_acceptance as cloud
SDK_SHA256 = 'c6b581b60ce803318ff946cd3cc8306aa8589d6bff6b022c0bf1d48eb8f5a8e1'
SDK = 'C:\\Program Files\\RustDiscoveryCertificateAcceptance\\' + SDK_SHA256 + '\\WindowsCertificateAcceptanceSDK.exe'
ROOT = 'C:\\ProgramData\\RustDiscovery\\certificate-acceptance'
def script(case_id, mode):
assert str(uuid.UUID(case_id)) == case_id and mode in ('renew', 'revoked-read')
return ("$ErrorActionPreference = 'Stop'\r\n"
"$exe = '" + SDK + "'\r\n"
"$guard = [IO.File]::Open($exe,'Open','Read','Read')\r\n"
"try {\r\n"
" $sha = [Security.Cryptography.SHA256]::Create()\r\n"
" try { $hash = ([BitConverter]::ToString($sha.ComputeHash($guard))).Replace('-','').ToLowerInvariant() } finally { $sha.Dispose() }\r\n"
" if ($hash -cne '" + SDK_SHA256 + "') { throw 'Certificate SDK hash mismatch' }\r\n"
" $lines = @(& $exe '" + mode + "' '" + case_id + "')\r\n"
" if ($LASTEXITCODE -ne 0) { throw 'Certificate fixture failed; preserve case and do not retry' }\r\n"
" $result = ($lines -join [Environment]::NewLine) | ConvertFrom-Json\r\n"
" if ($result.verified -ne $true -or $result.execution_sid -cne 'S-1-5-19' -or $result.permanent_identity_read -ne $false) { throw 'Exact LocalService fixture proof required' }\r\n"
" Write-Output 'CertificateAcceptance:" + mode + ":verified'\r\n"
"} finally { $guard.Dispose() }\r\n")
def request(case_id, mode):
start = cloud.contract.now()
text = script(case_id, mode)
return dict(tenant_id=cloud.TENANT, action='run_script', targets=dict(asset_ids=[cloud.WINDOWS_ASSET]),
parameters=dict(execution_identity='agent_service', timeout_seconds=120, max_output_bytes=16384,
arguments=[], expected_stdout='CertificateAcceptance:' + mode + ':verified\r\n',
variants=[dict(os_family='windows', interpreter='powershell', encoding='utf-8', script_utf8=text,
windows_execution_profile='powershell_51_remote_signed')]),
schedule=cloud.contract.schedule(start, start + timedelta(minutes=15)),
rollout=dict(max_parallel=1, halt_after_failures=1),
reason='Separate Windows certificate fixture ' + mode + '; permanent identity unchanged; no retry')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--case-id', required=True)
parser.add_argument('--mode', choices=('renew', 'revoked-read'), required=True)
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
if str(uuid.UUID(args.case_id)) != args.case_id or uuid.UUID(args.case_id).int == 0:
parser.error('canonical nonempty fixture UUID required')
os.umask(0o077)
rendered = request(args.case_id, args.mode)
result = dict(schema_version=1, prepared_only=True, executed=False, fixture_provisioned=False,
case_id=args.case_id, mode=args.mode, sdk_sha256=SDK_SHA256,
script_sha256=hashlib.sha256(script(args.case_id,args.mode).encode()).hexdigest(),
public_receipt=ROOT + '\\' + args.case_id + '\\' + ('renewal-result.json' if args.mode == 'renew' else 'revocation-result.json'),
bootstrap_input_keys=['case_id','ca_base64','ca_sha256','enrollment_token'], request=rendered)
with args.output.open('x') as out:
json.dump(result,out,indent=2)
print(args.output)
if __name__ == '__main__':
main()
+355
View File
@@ -0,0 +1,355 @@
#!/usr/bin/env python3
"""Read-only prerequisite capture and preparation for first approved SYSTEM job.
No install/service/policy mutation or RMM job approval is implemented here.
Settings/pin candidates must be rendered by the real typed Rust codec, never
PowerShell ConvertTo-Json. Actual effect acceptance is separate from prerequisite
unit/OS/authenticated-peer qualification.
"""
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import sys
import uuid
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'deploy/windows'))
import client_bootstrap as cb
INSPECT=r'''
$ErrorActionPreference='Stop'
$files=@{}
foreach($path in @('C:\ProgramData\RustDiscoverySystem\helper.json','C:\ProgramData\RustDiscoverySystem\agent-pin.json','C:\ProgramData\RustDiscoverySystem\system-qualification.json','C:\ProgramData\RustDiscoverySystem\system-native-result.json','C:\ProgramData\RustDiscovery\config.json','C:\ProgramData\RustDiscovery\state\helper-probe.json','C:\ProgramData\RustDiscovery\state\job-readiness.json','C:\ProgramData\RustDiscoverySystem\time-attestation.json','C:\Program Files\RustDiscovery\rmm-agent-windows.exe','C:\Program Files\RustDiscovery\rmm-helper-windows.exe')) {
if(!(Test-Path -LiteralPath $path)){$files[$path]=$null;continue}
$item=Get-Item -LiteralPath $path
if($item.PSIsContainer-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)-ne0){throw 'Fixed regular public metadata path'}
$entry=@{sha256=(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant();bytes=$item.Length;sddl=(Get-Acl -LiteralPath $path).Sddl;last_write_utc=$item.LastWriteTimeUtc.ToString('o')}
if($path.EndsWith('.json')){if($item.Length-gt65536){throw 'Public JSON size bound'};$entry.raw_base64=[Convert]::ToBase64String([IO.File]::ReadAllBytes($path))}
$files[$path]=$entry
}
$services=@{}
foreach($name in @('RmmDiscoveryWindows','RmmDiscoverySystemHelper')) {
$service=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'")
if(!$service){throw 'Existing fixed service required'}
$pidValue=[int]$service.ProcessId;$created=$null
if($pidValue-gt0){$process=Get-Process -Id $pidValue;try{$created=$process.StartTime.ToUniversalTime().ToFileTimeUtc().ToString()}finally{$process.Dispose()}}
$services[$name]=@{state=$service.State;start_mode=$service.StartMode;configured_account=$service.StartName;pid=$pidValue;creation_filetime=$created;path=$service.PathName}
}
$policies=@(Get-ExecutionPolicy -List|ForEach-Object{@{scope=[string]$_.Scope;policy=[string]$_.ExecutionPolicy}})
@{schema_version=1;read_only=$true;vm_utc=[DateTime]::UtcNow.ToString('o');services=$services;files=$files;execution_policy=$policies;w32time=[string](Get-Service W32Time).Status;target_effects_executed=$false;rmm_jobs_created=$false;approvals_performed=$false}|ConvertTo-Json -Depth 12 -Compress
'''
def save(path,value):
raw=json.dumps(value,sort_keys=True,indent=2).encode()+b'\n'
fd=os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600)
with os.fdopen(fd,'wb') as stream:stream.write(raw);stream.flush();os.fsync(stream.fileno())
def inspect_guest():
result=cb.powershell(INSPECT,timeout=60)
cb.contract.require(result['schema_version']==1 and result['read_only'] is True
and result['rmm_jobs_created'] is False and result['target_effects_executed'] is False,
'read-only fixed guest metadata')
folder=ROOT/'devstate/windows-system-job-bootstrap'/str(uuid.uuid4());folder.mkdir(mode=0o700,parents=True)
save(folder/'read-only.json',result)
decoded={}
for path,record in result['files'].items():
if record is not None and 'raw_base64' in record:
raw=base64.b64decode(record['raw_base64'],validate=True)
cb.contract.require(hashlib.sha256(raw).hexdigest()==record['sha256'],'original public JSON bytes')
decoded[path]=json.loads(raw)
settings=decoded[r'C:\ProgramData\RustDiscoverySystem\helper.json']
print(json.dumps(dict(report=str(folder/'read-only.json'),read_only=True,
services=result['services'],settings=dict(schema_version=settings['schema_version'],
enable_effects=settings['enable_effects'],allow_reboot=settings['allow_reboot'],
allowed_services=settings['allowed_services'],allowed_script_profiles=settings.get('allowed_script_profiles')))))
def inspect_server(payload):
import json
import subprocess
import hashlib
import os
import stat
from pathlib import Path
require(payload=={'operation':'windows_system_scope_inspect_v1'},'fixed read-only server operation')
root=Path('/opt/rust-discovery')
compose=['docker','compose','--env-file',str(root/'devstate/.env'),'-f',str(root/'deploy/server.compose.yaml')]
def run(args,data=None):
return subprocess.run(args,input=data,stdin=None if data is not None else subprocess.DEVNULL,
capture_output=True,check=True,timeout=20).stdout
names=('RMM_PROFILE','RMM_DEV_AUTH','RMM_SERVER_ROLE','RMM_UI_ORIGIN','RMM_DEV_SYSTEM_ENABLED','RMM_DEV_SYSTEM_POLICY_FILE')
select=' '.join('(eq $key "'+name+'")' for name in names)
template='{{range .Config.Env}}{{$key := index (split . "=") 0}}{{if or '+select+'}}{{println .}}{{end}}{{end}}'
roles={}
for role in ('api','gateway'):
cid=run(compose+['ps','-q',role]).decode().strip()
require(cid and '\n' not in cid,'one actual service container')
environment={}
for line in run(['docker','inspect',cid,'--format',template]).decode().splitlines():
if not line:continue
key,sep,value=line.partition('=');require(sep and key in names and key not in environment,'exact public environment')
environment[key]=value
labels=json.loads(run(['docker','inspect',cid,'--format','{{json .Config.Labels}}']))
compose_files=labels['com.docker.compose.project.config_files'].split(',')
hashes={}
for value in compose_files:
path=Path(value);metadata=path.lstat()
require(path.is_absolute() and path.is_relative_to(root) and stat.S_ISREG(metadata.st_mode)
and metadata.st_uid==0 and not metadata.st_mode&0o022,'protected actual compose closure')
hashes[value]=hashlib.sha256(path.read_bytes()).hexdigest()
roles[role]=dict(container_id=cid,environment=environment,
image=run(['docker','inspect',cid,'--format','{{.Image}}']).decode().strip(),compose_files_sha256=hashes)
tenant='11111111-1111-4111-8111-111111111111';agent='63ea15b2-0643-403d-b5b4-cba1288dbea3'
scope="tenant_id='"+tenant+"' AND agent_id='"+agent+"'"
selected="'automation:"+tenant+"','simulated-testprincipal-a'"
sql=("BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY; SELECT json_build_object("
"'memberships',(SELECT json_agg(q ORDER BY principal) FROM (SELECT tenant_id,principal,kind,permissions,revoked_at FROM memberships WHERE tenant_id='"+tenant+"' AND principal IN ("+selected+")) q),"
"'installation',(SELECT json_build_object('tenant_id',tenant_id,'asset_id',asset_id,'agent_id',agent_id,'enrollment_generation',enrollment_generation,'assignment_version',assignment_version,'capabilities',capabilities,'last_contact_at',last_contact_at,'sync_ready',sync_ready,'helper_ready',helper_sync_ready,'restore_blocked',restore_blocked) FROM agent_installations WHERE "+scope+"),"
"'jobs',(SELECT count(*) FROM jobs WHERE "+scope+"),"
"'system_jobs',(SELECT count(*) FROM jobs WHERE "+scope+" AND convert_from(payload,'UTF8')::jsonb->>'execution_identity'='system'),"
"'unresolved',(SELECT count(*) FROM jobs WHERE "+scope+" AND state NOT IN ('succeeded','failed','cancelled','expired'))); COMMIT;")
database=json.loads(run(compose+['exec','-T','postgres','psql','-X','-qAt','-v','ON_ERROR_STOP=1','-U','postgres','-d','rmm'],sql.encode()).strip())
return dict(schema_version=1,read_only=True,roles=roles,database=database,rmm_jobs_created=False,approvals_performed=False)
def inspect_central():
import remote_client_bootstrap as transport
result=transport.rpc('server.conf',inspect_server,{'operation':'windows_system_scope_inspect_v1'})
folder=ROOT/'devstate/windows-system-job-bootstrap'/str(uuid.uuid4());folder.mkdir(mode=0o700,parents=True)
save(folder/'server-read-only.json',result)
print(json.dumps(dict(report=str(folder/'server-read-only.json'),read_only=True,roles=result['roles'],database=result['database'])))
def prepare_scope(guest_path,server_path,rendered_path):
import datetime as dt
def protected(path):return cb.contract.protected_json(path)
guest=protected(guest_path);central=protected(server_path);rendered=protected(rendered_path)
require=cb.contract.require
require(guest['read_only'] is True and central['read_only'] is True
and rendered['source']=='actual_rust_settings_codec' and rendered['prepared_only'] is True
and rendered['target_mutations'] is False and rendered['target_job_executed'] is False,
'actual independent reads plus typed renderer only')
files={}
for name in ('settings','pin','native_result','qualification'):
raw=bytes(rendered[name+'_bytes']);digest=hashlib.sha256(raw).hexdigest()
require(digest==rendered[name+'_sha256'],'exact typed payload hash')
files[name]=dict(base64=base64.b64encode(raw).decode(),sha256=digest)
settings=json.loads(bytes(rendered['settings_bytes']));qualification=json.loads(bytes(rendered['qualification_bytes']))
require(settings['schema_version']==3 and settings['enable_effects'] is True
and settings['allow_reboot'] is False and settings['allowed_services']==[]
and 'allowed_msi_recipe_sha256' not in settings
and settings['allowed_script_profiles']==['full_maintenance_v1']
and settings['max_runtime_seconds']==30 and qualification['actions']==['run_script']
and qualification['policy_sha256']==rendered['policy_sha256']==rendered['settings_sha256'],
'only typed thirty-second SYSTEM script scope')
target={key:settings['binding'][key] for key in ('tenant_id','asset_id','agent_id','enrollment_generation','assignment_version')}
require(all(central['database']['installation'][key]==value for key,value in target.items())
and central['database']['system_jobs']==0 and central['database']['unresolved']==0,
'actual first SYSTEM job target and closed previous work')
tenant=target['tenant_id'];actors=['automation:'+tenant,'simulated-testprincipal-a']
memberships={row['principal']:row for row in central['database']['memberships']}
require(set(memberships)==set(actors) and all(memberships[name]['revoked_at'] is None
and 'scripts:execute' in memberships[name]['permissions'] for name in actors),
'two existing explicit current actors')
case=str(uuid.uuid4());folder=ROOT/'devstate/windows-system-job-bootstrap'/case;folder.mkdir(mode=0o700,parents=True)
payload=dict(operation='windows_system_script_scope_stopped_v1',phase='apply-stopped',case_id=case,
old_settings_sha256=guest['files'][r'C:\ProgramData\RustDiscoverySystem\helper.json']['sha256'],
old_pin_sha256=guest['files'][r'C:\ProgramData\RustDiscoverySystem\agent-pin.json']['sha256'],
agent_binary_sha256=settings['agent']['binary_sha256'],helper_binary_sha256=settings['helper']['binary_sha256'],
expected_service_processes=[dict(pid=row['pid'],creation_filetime=row['creation_filetime'])
for row in guest['services'].values()],policy_sha256=rendered['policy_sha256'],files=files)
payload['expected_service_definitions']=guest['services']
payload['old_config_sha256']=guest['files'][r'C:\ProgramData\RustDiscovery\config.json']['sha256']
payload['helper_start_transition']=dict(before='Manual',after='Auto')
now=dt.datetime.now(dt.timezone.utc);expiry=now+dt.timedelta(minutes=15)
scope=dict(**target,principals=actors,helper_policy_sha256=rendered['policy_sha256'],
helper_binary_sha256=settings['helper']['binary_sha256'],acceptance_evidence_id=qualification['qualification_reference'],
allowed_services=[],max_runtime_seconds=30,allowed_script_profiles=['full_maintenance_v1'])
policy=dict(schema_version=3,profile='development',expires_at=expiry.isoformat(),scopes=[scope])
permissions=[dict(principal=name,kind=memberships[name]['kind'],
expected_permissions=memberships[name]['permissions'],
add_permissions=[] if 'system:execute' in memberships[name]['permissions'] else ['system:execute']) for name in actors]
overlay={'services':{role:{'environment':{'RMM_DEV_SYSTEM_ENABLED':'true','RMM_DEV_SYSTEM_POLICY_FILE':'/system-policy/policy.json'},
'volumes':['/opt/rust-discovery/devstate/windows-system-policy/'+case+'/mounted:/system-policy:ro']} for role in ('api','gateway')}}
server_intent=dict(operation='windows_system_script_scope_activate_v1',case_id=case,
expected_roles=central['roles'],memberships=[memberships[name] for name in actors],policy=policy)
text=("$ErrorActionPreference = 'Stop'\r\n"
"$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value\r\n"
"if ($sid -cne 'S-1-5-18') { throw 'Expected SYSTEM process' }\r\n"
"Write-Output ('Windows-System-MVP:' + $sid)\r\n")
job_request=dict(tenant_id=tenant,action='run_script',targets=dict(asset_ids=[target['asset_id']]),
parameters=dict(execution_identity='system',privileged_script_profile='full_maintenance_v1',
timeout_seconds=30,max_output_bytes=4096,arguments=[],expected_stdout='Windows-System-MVP:S-1-5-18\r\n',
variants=[dict(os_family='windows',interpreter='powershell',encoding='utf-8',script_utf8=text,
windows_execution_profile='powershell_51_remote_signed')]),
schedule=dict(not_before=now.isoformat(),start_before=(expiry-dt.timedelta(minutes=1)).isoformat(),offline_policy='wait_until_deadline'),
rollout=dict(max_parallel=1,halt_after_failures=1),reason='First separately approved Windows SYSTEM PowerShell script; exact SID and stdout, no retry')
manifest=dict(schema_version=1,prepared_only=True,case_id=case,created_at=now.isoformat(),expires_at=expiry.isoformat(),
scope='first_SYSTEM_run_script_only',source_controller_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
stopped_apply_source_sha256=hashlib.sha256(APPLY_STOPPED.encode()).hexdigest(),
server_activation_source_sha256=hashlib.sha256((ROOT/'deploy/windows_system_scope_server.py').read_bytes()).hexdigest(),
reads={str(path):hashlib.sha256(Path(path).read_bytes()).hexdigest() for path in (guest_path,server_path,rendered_path)},
target_mutations=False,policy_activated=False,actual_SYSTEM_job_completed=False,
permission_changes=permissions,files_owner='same actual UID as mounted RMM_JOB_KEY_FILE; stat metadata only',
files_mode='0600; Root or same owner parent, read-only bind on API and gateway',
root_sequence=['fresh guest/server/source CAS','native quiescent stop and exited PID witnesses',
'hold both original lifetime locks; apply exact settings/pin/qualification while both services stopped',
'change only helper StartType Manual to Automatic with exact SCM-definition CAS',
'independent file/ACL/ledger preservation readback','start helper and agent once',
'fresh role time proofs and ordinary signed sync plus real authenticated helper probe',
'only then provision both actor permissions and both-role bounded policy',
'MCP pending plan, actual simulated WebUI click, exact one SYSTEM script execution',
'independent original consumption/start/outcome/audit readback and policy closure','document and push'])
for name,value in (('manifest.json',manifest),('windows-payload.json',payload),('server-policy.json',policy),
('system-policy.compose.json',overlay),('permission-intent.json',permissions),
('server-activation-intent.json',server_intent),('system-job-request.json',job_request)):
save(folder/name,value)
return folder
def main():
parser=argparse.ArgumentParser(description=__doc__)
commands=parser.add_subparsers(dest='operation',required=True)
commands.add_parser('inspect');commands.add_parser('inspect-server')
prepare=commands.add_parser('prepare')
for name in ('guest-report','server-report','rendered'):prepare.add_argument('--'+name,required=True,type=Path)
args=parser.parse_args()
if args.operation=='inspect':inspect_guest()
elif args.operation=='inspect-server':inspect_central()
else:print(json.dumps(dict(package=str(prepare_scope(args.guest_report,args.server_report,args.rendered)),target_mutations=False)))
# Reviewed source for the coordinating root agent. Deliberately not dispatched
# by this module's CLI. Both existing daemons must already be quiescent/stopped;
# starts and fresh signed-sync/native effect acceptance remain separate steps.
APPLY_STOPPED = r'''
$ErrorActionPreference='Stop'
$p=([Console]::In.ReadLine()|ConvertFrom-Json)
if($p.operation-cne'windows_system_script_scope_stopped_v1'-or$p.phase-cnotin@('apply-stopped','readback')){throw 'Fixed bootstrap operation'}
$caseId=[guid]::ParseExact($p.case_id,'D').ToString('D')
$case=Join-Path 'C:\ProgramData\RustDiscoveryBootstrap' ('system-script-scope-'+$caseId)
$helperRoot='C:\ProgramData\RustDiscoverySystem'
$agentSid='S-1-5-80-2738667961-1084496008-3886777835-2738042298-1934696263'
$helperSid='S-1-5-80-1378800304-2783697212-3564778230-1646893514-1341434273'
$targets=@{settings=(Join-Path $helperRoot 'helper.json');pin=(Join-Path $helperRoot 'agent-pin.json');native_result=(Join-Path $helperRoot 'system-native-result.json');qualification=(Join-Path $helperRoot 'system-qualification.json')}
function HashBytes([byte[]]$bytes){$sha=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($sha.ComputeHash($bytes))).Replace('-','').ToLowerInvariant()}finally{$sha.Dispose()}}
function HashFile([string]$path){return(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}
function CheckPath([string]$path,[bool]$directory){$item=Get-Item -LiteralPath $path;if($item.PSIsContainer-ne$directory-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)-ne0){throw 'Protected regular path'};$acl=Get-Acl -LiteralPath $path;$owner=$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value;if($owner-cnotin@('S-1-5-18','S-1-5-32-544')){throw 'Privileged owner required'};foreach($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){$sid=$rule.IdentityReference.Value;if($rule.AccessControlType-ne[Security.AccessControl.AccessControlType]::Allow){throw 'Unexpected deny ACL'};if($sid-cin@('S-1-5-18','S-1-5-32-544')){continue};if($sid-cnotin@($agentSid,$helperSid)-or([int64]$rule.FileSystemRights-band(-bnot 0x1200a9))-ne0){throw 'Foreign or writable public access'}};return $acl}
function CheckStopped{if($null-eq$p.expected_service_processes-or@($p.expected_service_processes).Count-ne2){throw 'Two actual original process witnesses required'};foreach($old in @($p.expected_service_processes)){if([int]$old.pid-le0-or![string]$old.creation_filetime){throw 'Original kernel creation witness'};$live=Get-Process -Id ([int]$old.pid) -ErrorAction SilentlyContinue;if($null-ne$live){try{if($live.StartTime.ToUniversalTime().ToFileTimeUtc().ToString()-ceq$old.creation_filetime-and!$live.HasExited){throw 'Original service process still live'}}finally{$live.Dispose()}}};foreach($name in @('RmmDiscoveryWindows','RmmDiscoverySystemHelper')){$service=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'");if(!$service-or$service.State-cne'Stopped'-or[int]$service.ProcessId-ne0){throw 'Coordinated quiescent pair stop required'}}}
function PublicAcl{$acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm(('O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;'+$agentSid+')(A;;0x1200a9;;;'+$helperSid+')'));return $acl}
function WritePublicOnce([string]$path,[byte[]]$bytes){
$rights=[Security.AccessControl.FileSystemRights]::ReadWrite
$stream=New-Object IO.FileStream($path,[IO.FileMode]::CreateNew,$rights,[IO.FileShare]::Read,4096,[IO.FileOptions]::WriteThrough,(PublicAcl))
try{$stream.Write($bytes,0,$bytes.Length);$stream.Flush($true)}finally{$stream.Dispose()}
$null=CheckPath $path $false
}
function WritePrivateOnce([string]$path,[byte[]]$bytes){$stream=[IO.File]::Open($path,'CreateNew','Write','Read');try{$stream.Write($bytes,0,$bytes.Length);$stream.Flush($true)}finally{$stream.Dispose()}}
Add-Type -TypeDefinition @'
using System;using System.IO;using System.Runtime.InteropServices;using Microsoft.Win32.SafeHandles;
public sealed class RmmSystemScopeLocks:IDisposable{
[StructLayout(LayoutKind.Sequential)]struct Ov{public UIntPtr I,H;public uint L,U;public IntPtr E;}
[StructLayout(LayoutKind.Sequential)]struct Info{public uint A,CL,CH,AL,AH,WL,WH,V,SH,SL,N,IH,IL;}
[DllImport("kernel32.dll",SetLastError=true)]static extern bool LockFileEx(SafeFileHandle h,uint f,uint z,uint l,uint u,ref Ov o);
[DllImport("kernel32.dll",SetLastError=true)]static extern bool GetFileInformationByHandle(SafeFileHandle h,out Info i);
[DllImport("advapi32.dll",CharSet=CharSet.Unicode,SetLastError=true)]static extern IntPtr OpenSCManager(string a,string b,uint c);
[DllImport("advapi32.dll",CharSet=CharSet.Unicode,SetLastError=true)]static extern IntPtr OpenService(IntPtr m,string n,uint a);
[DllImport("advapi32.dll",EntryPoint="ChangeServiceConfigW",CharSet=CharSet.Unicode,SetLastError=true)]static extern bool ChangeServiceConfig(IntPtr h,uint type,uint start,uint error,string command,string group,IntPtr tag,string deps,string account,string password,string display);
[DllImport("advapi32.dll")]static extern bool CloseServiceHandle(IntPtr h);
readonly FileStream[] files=new FileStream[2];
public RmmSystemScopeLocks(){string[] p={@"C:\ProgramData\RustDiscovery\state\agent.lock",@"C:\ProgramData\RustDiscoverySystem\state\executor.lock"};try{for(int i=0;i<2;i++){files[i]=new FileStream(p[i],FileMode.Open,FileAccess.Read,FileShare.ReadWrite);Ov o=new Ov();if(!LockFileEx(files[i].SafeFileHandle,3,0,uint.MaxValue,uint.MaxValue,ref o))throw new InvalidOperationException("ORIGINAL_LOCK_BUSY");}}catch{Dispose();throw;}}
public string[] LockIds(){string[] r=new string[2];for(int n=0;n<2;n++){Info i;if(!GetFileInformationByHandle(files[n].SafeFileHandle,out i)||i.N!=1||(i.A&0x410)!=0)throw new InvalidOperationException("ORIGINAL_LOCK_ID");r[n]=i.V+":"+i.IH+":"+i.IL;}return r;}
public static string Identity(string path){using(FileStream f=new FileStream(path,FileMode.Open,FileAccess.Read,FileShare.ReadWrite)){Info i;if(!GetFileInformationByHandle(f.SafeFileHandle,out i)||i.N!=1||(i.A&0x410)!=0)throw new InvalidOperationException("PRESERVED_FILE_ID");return i.V+":"+i.IH+":"+i.IL+":"+i.SH+":"+i.SL+":"+i.WH+":"+i.WL;}}
public static void SetHelperAutomatic(){IntPtr m=OpenSCManager(null,null,1);if(m==IntPtr.Zero)throw new InvalidOperationException("SCM_CONNECT");try{IntPtr h=OpenService(m,"RmmDiscoverySystemHelper",2);if(h==IntPtr.Zero)throw new InvalidOperationException("HELPER_CONFIG_OPEN");try{if(!ChangeServiceConfig(h,uint.MaxValue,2,uint.MaxValue,null,null,IntPtr.Zero,null,null,null,null))throw new InvalidOperationException("HELPER_STARTTYPE_CHANGE");}finally{CloseServiceHandle(h);}}finally{CloseServiceHandle(m);}}
public void Dispose(){foreach(FileStream f in files)if(f!=null)f.Dispose();}
}
'@
function ServiceDefinitions {
$rows=[ordered]@{}
foreach($name in @('RmmDiscoveryWindows','RmmDiscoverySystemHelper')){
$s=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'")
if(!$s-or$s.State-cne'Stopped'-or[int]$s.ProcessId-ne0-or$s.ServiceType-cne'Own Process'){throw 'Fixed stopped own-process services'}
$old=$p.expected_service_definitions.$name
if(!$old-or$s.PathName-cne$old.path-or$s.StartName-cne$old.configured_account){throw 'Original SCM command/account CAS'}
$rows[$name]=@{path=$s.PathName;configured_account=$s.StartName;start_mode=$s.StartMode}
}
return $rows
}
function PreservedFiles {
$paths=@('C:\ProgramData\RustDiscovery\state\telemetry.sqlite','C:\ProgramData\RustDiscovery\state\consumption.sqlite','C:\ProgramData\RustDiscoverySystem\state\ledger.sqlite','C:\ProgramData\RustDiscoverySystem\agent-intents\system-intents.sqlite','C:\ProgramData\RustDiscovery\config.json','C:\ProgramData\RustDiscoverySystem\time-attestation.json')
$result=[ordered]@{}
foreach($path in $paths){
if(!(Test-Path -LiteralPath $path)){throw 'Original retained public/control file missing'}
foreach($candidate in @($path,($path+'-wal'),($path+'-shm'))){if(Test-Path -LiteralPath $candidate){$result[$candidate]=@{identity=[RmmSystemScopeLocks]::Identity($candidate);sddl=(Get-Acl -LiteralPath $candidate).Sddl;sha256=(HashFile $candidate)}}}
}
# Private-key bytes are never read. Only existing namespace/security/FileID metadata.
foreach($item in @(Get-ChildItem -LiteralPath 'C:\ProgramData\RustDiscovery\state' -File|Where-Object{$_.Name-like'device*.key'-or$_.Name-like'device*.pem'-or$_.Name-ceq'identity.json'}|Sort-Object FullName)){
if($item.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Preserved identity regular file'}
$result[$item.FullName]=@{identity=[RmmSystemScopeLocks]::Identity($item.FullName);sddl=(Get-Acl -LiteralPath $item.FullName).Sddl}
}
return ($result|ConvertTo-Json -Depth 8 -Compress)
}
$null=CheckPath 'C:\ProgramData\RustDiscoveryBootstrap' $true
$null=CheckPath $helperRoot $true
if($p.phase-ceq'readback'){
$result=@{schema_version=1;read_only=$true;case_present=(Test-Path -LiteralPath $case);files=@{};services=@{}}
foreach($name in $targets.Keys){$path=$targets[$name];$result.files[$name]=if(Test-Path -LiteralPath $path){@{sha256=(HashFile $path);sddl=(Get-Acl -LiteralPath $path).Sddl}}else{$null}}
foreach($name in @('RmmDiscoveryWindows','RmmDiscoverySystemHelper')){$result.services[$name]=[string](Get-Service -Name $name).Status}
$result|ConvertTo-Json -Depth 8 -Compress;exit 0
}
CheckStopped
$definitions=ServiceDefinitions
if($p.helper_start_transition.before-cne'Manual'-or$p.helper_start_transition.after-cne'Auto'-or$definitions.RmmDiscoverySystemHelper.start_mode-cne'Manual'-or$definitions.RmmDiscoveryWindows.start_mode-cne'Auto'){throw 'Exact Manual to Auto helper transition only'}
if((HashFile 'C:\ProgramData\RustDiscovery\config.json')-cne$p.old_config_sha256){throw 'Preserved active configuration CAS'}
$locks=[RmmSystemScopeLocks]::new()
try {
$lockIds=($locks.LockIds()-join',');$preserved=PreservedFiles
$null=CheckPath $targets.settings $false
$null=CheckPath $targets.pin $false
if(Test-Path -LiteralPath $case){throw 'Existing case means readback only'}
foreach($name in @('native_result','qualification')){if(Test-Path -LiteralPath $targets[$name]){throw 'First script scope requires absent prior qualification files'}}
if((HashFile $targets.settings)-cne$p.old_settings_sha256-or(HashFile $targets.pin)-cne$p.old_pin_sha256){throw 'Fresh original public settings and pin CAS'}
if((HashFile 'C:\Program Files\RustDiscovery\rmm-agent-windows.exe')-cne$p.agent_binary_sha256-or(HashFile 'C:\Program Files\RustDiscovery\rmm-helper-windows.exe')-cne$p.helper_binary_sha256){throw 'Actual image pair required'}
$settings=[Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($targets.settings))|ConvertFrom-Json
if($settings.enable_effects-ne$false-or$settings.allow_reboot-ne$false-or@($settings.allowed_services).Count-ne0){throw 'First passive-to-script-only transition'}
$payloads=@{}
foreach($name in @('settings','pin','native_result','qualification')){$item=$p.files.$name;$bytes=[Convert]::FromBase64String($item.base64);if($bytes.Length-lt1-or$bytes.Length-gt65536-or(HashBytes $bytes)-cne$item.sha256){throw 'Exact typed-renderer payload bytes'};$payloads[$name]=$bytes}
$next=[Text.Encoding]::UTF8.GetString($payloads.settings)|ConvertFrom-Json
if($next.schema_version-ne3-or$next.enable_effects-ne$true-or$next.allow_reboot-ne$false-or@($next.allowed_services).Count-ne0-or@($next.allowed_msi_recipe_sha256).Count-ne0-or($next.allowed_script_profiles-join',')-cne'full_maintenance_v1'-or$next.max_runtime_seconds-ne30){throw 'Only explicit schema3 script scope'}
if($next.agent.binary_sha256-cne$p.agent_binary_sha256-or$next.helper.binary_sha256-cne$p.helper_binary_sha256){throw 'Exact target code pins'}
$qualification=[Text.Encoding]::UTF8.GetString($payloads.qualification)|ConvertFrom-Json
$native=[Text.Encoding]::UTF8.GetString($payloads.native_result)|ConvertFrom-Json
if(($qualification.actions-join',')-cne'run_script'-or$qualification.policy_sha256-cne$p.policy_sha256-or$qualification.native_result_sha256-cne$p.files.native_result.sha256-or$native.scope-cne'native_prerequisites_only'-or$native.target_job_executed-ne$false-or$native.status-cne'passed'){throw 'Truthful prerequisite qualification only'}
New-Item -ItemType Directory -Path $case|Out-Null
$private=New-Object Security.AccessControl.DirectorySecurity;$private.SetSecurityDescriptorSddlForm('O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)');Set-Acl -LiteralPath $case -AclObject $private
WritePrivateOnce (Join-Path $case 'intent.json') ([Text.Encoding]::UTF8.GetBytes(($p|ConvertTo-Json -Depth 20 -Compress)))
foreach($name in @('settings','pin','native_result','qualification')){WritePublicOnce (Join-Path $case ($name+'.candidate.json')) $payloads[$name]}
foreach($name in @('settings','pin')){
CheckStopped
$expected=if($name-ceq'settings'){$p.old_settings_sha256}else{$p.old_pin_sha256}
if((HashFile $targets[$name])-cne$expected){throw 'Immediate original file CAS'}
WritePrivateOnce (Join-Path $case ($name+'-replace-intent.json')) ([Text.Encoding]::UTF8.GetBytes('{"create_once":true}'))
$backup=Join-Path $case ($name+'.previous.json')
[IO.File]::Replace((Join-Path $case ($name+'.candidate.json')),$targets[$name],$backup)
if((HashFile $backup)-cne$expected-or(HashFile $targets[$name])-cne$p.files.$name.sha256){throw 'Native replace must retain exact original and candidate'}
$null=CheckPath $targets[$name] $false
}
foreach($name in @('native_result','qualification')){
CheckStopped
if(Test-Path -LiteralPath $targets[$name]){throw 'Public prerequisite target appeared'}
WritePrivateOnce (Join-Path $case ($name+'-publish-intent.json')) ([Text.Encoding]::UTF8.GetBytes('{"create_once":true}'))
[IO.File]::Move((Join-Path $case ($name+'.candidate.json')),$targets[$name])
if((HashFile $targets[$name])-cne$p.files.$name.sha256){throw 'Exact published prerequisite bytes'}
$null=CheckPath $targets[$name] $false
}
CheckStopped
$current=ServiceDefinitions
if(($current|ConvertTo-Json -Depth 6 -Compress)-cne($definitions|ConvertTo-Json -Depth 6 -Compress)){throw 'SCM changed before helper Automatic transition'}
WritePrivateOnce (Join-Path $case 'helper-autostart-intent.json') ([Text.Encoding]::UTF8.GetBytes('{"from":"Manual","to":"Auto","no_start":true}'))
[RmmSystemScopeLocks]::SetHelperAutomatic()
$automatic=ServiceDefinitions
if($automatic.RmmDiscoverySystemHelper.start_mode-cne'Auto'-or$automatic.RmmDiscoveryWindows.start_mode-cne'Auto'){throw 'Actual automatic startup readback'}
if((PreservedFiles)-cne$preserved-or($locks.LockIds()-join',')-cne$lockIds){throw 'Original identities, journals, clock profile and locks must be preserved'}
$result=@{schema_version=1;files_installed=$true;services_started=$false;target_job_executed=$false;approval_performed=$false;state_or_keys_changed=$false;helper_autostart='Auto';services=$automatic;policy_sha256=$p.policy_sha256;next='root must refresh actual SCM/role/time qualification then start pair once and verify fresh signed clock/sync; first actual SYSTEM job requires WebUI approval'}
WritePrivateOnce (Join-Path $case 'completed.json') ([Text.Encoding]::UTF8.GetBytes(($result|ConvertTo-Json -Compress)))
$result|ConvertTo-Json -Compress
} finally {$locks.Dispose()}
'''
if __name__=='__main__':main()
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""Reviewed remote bootstrap source for an explicit 15-minute SYSTEM ceiling.
No CLI dispatch. Root must review the exact public intent and call this through
the existing protected server transport. Never creates/approves jobs. Partial
results are readback-only, never an automatic retry or rollback.
"""
def activate(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_SCOPE_ROOT_BOOTSTRAP')
require(set(payload) == {'operation', 'case_id', 'expected_roles', 'memberships', 'policy'}, 'SYSTEM_SCOPE_INPUT')
require(payload['operation'] == 'windows_system_script_scope_activate_v1', 'SYSTEM_SCOPE_OPERATION')
ident = str(uuid.UUID(payload['case_id']))
require(ident == payload['case_id'], 'SYSTEM_SCOPE_CASE')
tenant = '11111111-1111-4111-8111-111111111111'
agent = '63ea15b2-0643-403d-b5b4-cba1288dbea3'
asset = 'a176520e-8a91-4e93-a78b-8e7620f430e0'
actors = ['automation:' + tenant, 'simulated-testprincipal-a']
root = Path('/opt/rust-discovery')
base = ['docker', 'compose', '--env-file', str(root / 'devstate/.env')]
def run(args, data=None):
return subprocess.run(args, input=data, capture_output=True, check=True, timeout=120).stdout
def enc(value):
return json.dumps(value, sort_keys=True, separators=(',', ':')).encode()
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 out:
os.fchown(out.fileno(), uid, gid)
out.write(data); out.flush(); os.fsync(out.fileno())
roles = payload['expected_roles']
require(set(roles) == {'api', 'gateway'}, 'SYSTEM_SCOPE_BOTH_ROLES')
compose_files = None
config_hashes = None
for role in ('api', 'gateway'):
expected = roles[role]
require(set(expected) == {'container_id', 'image', 'environment', 'compose_files_sha256'}, 'SYSTEM_SCOPE_ROLE_WITNESS')
require(re.fullmatch('[a-f0-9]{64}', expected['container_id']) and re.fullmatch('sha256:[a-f0-9]{64}', expected['image']), 'SYSTEM_SCOPE_CONTAINER_ID')
info = json.loads(run(['docker', 'inspect', expected['container_id']]))[0]
require(info['State']['Running'] and info['Image'] == expected['image'], 'SYSTEM_SCOPE_IMAGE_CAS')
selected = {}
names = {'RMM_PROFILE', 'RMM_DEV_AUTH', 'RMM_SERVER_ROLE', 'RMM_UI_ORIGIN', 'RMM_DEV_SYSTEM_ENABLED', 'RMM_DEV_SYSTEM_POLICY_FILE'}
for entry in info['Config']['Env']:
key, _, value = entry.partition('=')
if key in names:
require(key not in selected, 'SYSTEM_SCOPE_UNIQUE_ENV')
selected[key] = value
require(selected == expected['environment'] and selected == dict(RMM_PROFILE='development', RMM_DEV_AUTH='true', RMM_SERVER_ROLE=role, RMM_UI_ORIGIN='https://localhost:18443'), 'SYSTEM_SCOPE_EXISTING_PRIVATE_DEV_PROFILE')
labels = info['Config']['Labels']
require(labels['com.docker.compose.project'] == 'rust-discovery-server' and labels['com.docker.compose.service'] == role, 'SYSTEM_SCOPE_COMPOSE_ROLE')
files = labels['com.docker.compose.project.config_files'].split(',')
require(files and len(files) <= 12 and all(Path(p).is_absolute() and Path(p).is_relative_to(root) for p in files), 'SYSTEM_SCOPE_COMPOSE_PATHS')
hashes = {}
for value in files:
path = Path(value); m = path.lstat()
require(stat.S_ISREG(m.st_mode) and m.st_uid == 0 and not m.st_mode & 0o022, 'SYSTEM_SCOPE_PROTECTED_COMPOSE')
hashes[value] = hashlib.sha256(path.read_bytes()).hexdigest()
require(hashes == expected['compose_files_sha256'], 'SYSTEM_SCOPE_COMPOSE_CAS')
if compose_files is None:
compose_files = files; config_hashes = hashes
require(files == compose_files and hashes == config_hashes, 'SYSTEM_SCOPE_SAME_COMPOSE_PAIR')
# Bind mounts are deliberately additive; no existing policy/TLS/data
# mount or published port is changed by the generated overlay.
require(not any(m['Destination'] == '/system-policy' for m in info['Mounts']), 'SYSTEM_SCOPE_PREVIOUS_SYSTEM_MOUNT')
compose = base[:]
for path in compose_files:
compose += ['-f', path]
for role in ('api', 'gateway'):
require(run(compose + ['ps', '-q', role]).decode().strip() == roles[role]['container_id'], 'SYSTEM_SCOPE_CURRENT_CONTAINER_CAS')
policy = payload['policy']
require(set(policy) == {'schema_version', 'profile', 'expires_at', 'scopes'} and policy['schema_version'] == 3 and policy['profile'] == 'development' and len(policy['scopes']) == 1, 'SYSTEM_SCOPE_NARROW_POLICY')
now = dt.datetime.now(dt.timezone.utc)
expiry = dt.datetime.fromisoformat(policy['expires_at'].replace('Z', '+00:00'))
require(dt.timedelta(minutes=5) <= expiry - now <= dt.timedelta(minutes=15), 'SYSTEM_SCOPE_FINITE_WINDOW')
scope = policy['scopes'][0]
require(set(scope) == {'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'}, 'SYSTEM_SCOPE_FIELDS')
require(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_SCOPE_ONLY_FULL_SCRIPT')
require(all(re.fullmatch('[a-f0-9]{64}', scope[k]) for k in ('helper_policy_sha256', 'helper_binary_sha256')) and str(uuid.UUID(scope['acceptance_evidence_id'])) == scope['acceptance_evidence_id'], 'SYSTEM_SCOPE_NATIVE_PINS')
memberships = payload['memberships']
require([row['principal'] for row in memberships] == actors, 'SYSTEM_SCOPE_EXISTING_ACTORS')
for n, row in enumerate(memberships):
require(set(row) == {'tenant_id', 'principal', 'kind', 'permissions', 'revoked_at'} and row['tenant_id'] == tenant and row['kind'] == ('automation' if n == 0 else 'test_human') and row['revoked_at'] is None and 'scripts:execute' in row['permissions'] and 'system:execute' not in row['permissions'], 'SYSTEM_SCOPE_MEMBERSHIP_CAS_INPUT')
require(len(set(row['permissions'])) == len(row['permissions']) and all(re.fullmatch('[a-z_:]+', p) for p in row['permissions']), 'SYSTEM_SCOPE_PERMISSION_FORMAT')
sql_read = ("BEGIN READ ONLY; 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,'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; COMMIT;")
observed = json.loads(run(compose + ['exec', '-T', 'postgres', 'psql', '-X', '-qAt', '-v', 'ON_ERROR_STOP=1', '-U', 'postgres', '-d', 'rmm'], sql_read.encode()))
require(observed['ready'] and observed['helper_ready'] and not observed['blocked'] and observed['fresh'] and observed['same_certificate'], 'SYSTEM_SCOPE_CURRENT_AUTHENTICATED_PAIR')
needed = {'windows.base/1', 'rmm.sync.v1', 'helper.system.v1', 'system:run_script', 'script.full_maintenance/1', 'helper.binary.sha256:' + scope['helper_binary_sha256'], 'helper.policy.sha256:' + scope['helper_policy_sha256']}
require(needed <= set(observed['capabilities']) and 'linux.base/1' not in observed['capabilities'], 'SYSTEM_SCOPE_ACTUAL_QUALIFIED_CAPABILITIES')
# Resolve only public image names; never build, pull or alter a deployed image.
configured = json.loads(run(compose + ['config', '--format', 'json']))['services']
for role in ('api', 'gateway'):
actual = run(['docker', 'image', 'inspect', configured[role]['image'], '--format', '{{.Id}}']).decode().strip()
require(actual == roles[role]['image'], 'SYSTEM_SCOPE_NO_IMAGE_CHANGE')
lock = os.open(root / 'devstate/.windows-system-scope.lock', os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600)
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
try:
parent = root / 'devstate/windows-system-policy'
if not parent.exists(): parent.mkdir(mode=0o700)
m = parent.lstat(); require(stat.S_ISDIR(m.st_mode) and m.st_uid == 0 and m.st_mode & 0o777 == 0o700, 'SYSTEM_SCOPE_PRIVATE_PARENT')
case = parent / ident
case.mkdir(mode=0o700) # create-once: lost response means readback only
create(case / 'intent.json', enc(payload))
key = (root / 'devstate/jobs/ed25519.pem').lstat() # metadata only, never read signing key
require(stat.S_ISREG(key.st_mode) and not key.st_mode & 0o077, 'SYSTEM_SCOPE_JOB_KEY_OWNER')
mounted = case / 'mounted'; mounted.mkdir(mode=0o700); os.chown(mounted, key.st_uid, key.st_gid)
raw = enc(policy); require(len(raw) <= 65536, 'SYSTEM_SCOPE_POLICY_LIMIT')
create(mounted / 'policy.json', raw, key.st_uid, key.st_gid)
overlay = {'services': {role: {'environment': {'RMM_DEV_SYSTEM_ENABLED': 'true', 'RMM_DEV_SYSTEM_POLICY_FILE': '/system-policy/policy.json'}, 'volumes': [str(mounted) + ':/system-policy:ro']} for role in ('api', 'gateway')}}
overlay_path = case / 'system-policy.compose.json'; create(overlay_path, enc(overlay))
sql = "BEGIN; LOCK TABLE memberships,jobs,outbox,execution_permits,authorizations IN SHARE ROW EXCLUSIVE MODE; DO $scope$ BEGIN IF EXISTS(SELECT 1 FROM jobs WHERE tenant_id='" + tenant + "' AND state NOT IN ('succeeded','failed','cancelled','expired')) THEN RAISE EXCEPTION 'SYSTEM_SCOPE_INFLIGHT_JOB'; END IF;"
for row in memberships:
permissions = 'ARRAY[' + ','.join("'" + p + "'" for p in row['permissions']) + ']::text[]'
where = "tenant_id='" + tenant + "' AND principal='" + row['principal'] + "' AND kind='" + row['kind'] + "' AND revoked_at IS NULL AND permissions=" + permissions
sql += " IF (SELECT count(*) FROM memberships WHERE " + where + ")<>1 THEN RAISE EXCEPTION 'SYSTEM_SCOPE_MEMBERSHIP_CAS'; END IF; UPDATE memberships SET permissions=permissions||ARRAY['system:execute'] WHERE " + where + ';'
sql += " END $scope$; SELECT json_build_object('memberships_updated',2,'jobs_created',0,'approvals_created',0); COMMIT;"
create(case / 'permissions-entered.json', b'{"retry_allowed":false}')
reply = run(compose + ['exec', '-T', 'postgres', 'psql', '-X', '-qAt', '-v', 'ON_ERROR_STOP=1', '-U', 'postgres', '-d', 'rmm'], sql.encode())
create(case / 'permissions-result.json', reply)
create(case / 'recreate-entered.json', b'{"retry_allowed":false}')
run(compose + ['-f', str(overlay_path), 'up', '-d', '--no-deps', '--no-build', '--pull', 'never', 'api', 'gateway'])
after = {}
for role in ('api', 'gateway'):
cid = run(compose + ['-f', str(overlay_path), 'ps', '-q', role]).decode().strip()
info = json.loads(run(['docker', 'inspect', cid]))[0]
require(info['Image'] == roles[role]['image'] and info['State']['Running'], 'SYSTEM_SCOPE_ROLE_RUNNING')
mount = [m for m in info['Mounts'] if m['Destination'] == '/system-policy']
require(len(mount) == 1 and mount[0]['Type'] == 'bind' and not mount[0]['RW'] and mount[0]['Source'] == str(mounted), 'SYSTEM_SCOPE_READ_ONLY_MOUNT')
after[role] = dict(container_id=cid, image=info['Image'])
result = dict(schema_version=1, activated=True, case_id=ident, expires_at=policy['expires_at'], policy_sha256=hashlib.sha256(raw).hexdigest(), roles=after, jobs_created=False, approvals_created=False, system_target_job_executed=False, automatic_retry=False)
create(case / 'activated.json', enc(result))
return result
finally:
os.close(lock)