Qualify Windows SYSTEM script prerequisites and prepare guarded bootstrap
Rust development slice / linux (push) Failing after 7s
Rust development slice / linux (push) Failing after 7s
This commit is contained in:
@@ -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()
|
||||
Reference in New Issue
Block a user