217 lines
17 KiB
Python
217 lines
17 KiB
Python
#!/usr/bin/env python3
|
|
"""Prepare one original-case-bound SYSTEM creation repair; no transport or execution.
|
|
|
|
Never replay the original setup. The generated controller can create only the
|
|
missing fixed SYSTEM fixture, or read its original repair records. It does not
|
|
finish setup, copy an executable, start/stop a service or remove anything.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import stat
|
|
import uuid
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
CASE = 'efd17b43-7e04-49a7-9bd4-862d13365eec'
|
|
ORIGINAL = ROOT / 'devstate/windows-signed-clock-capture-native' / CASE
|
|
RUNNER_SHA = 'dd6c575a119751429448e40e6f306cf79efa3a86c49bf2cd32a7783937177770'
|
|
MANIFEST_SHA = '806c062bdd458627cf44ff1ef3f27738e1ebf2f407a96f772223efef267db0b1'
|
|
CONTROLLER_SHA = '89c19138e2804f263f1875c7697a7d53f54f40722101677b4d29538c917196f4'
|
|
EXE_SHA = '601c27a43fb67c662f926f9dc289a23a5c31c7e27f62901a77fc9ceaafaea7fb'
|
|
EXE_BYTES = 8566784
|
|
MARKERS_SHA = 'ff8e2eef73139c8350aa0f86c6fed5125fce95f79d535f25224829ce4fa9c565'
|
|
PROFILE = 'rmm.windows.raw-clock.original-system-create-repair.v1'
|
|
|
|
|
|
def require(value, message):
|
|
if not value:
|
|
raise RuntimeError(message)
|
|
|
|
|
|
def sha(raw):
|
|
return hashlib.sha256(raw).hexdigest()
|
|
|
|
|
|
def private_read(path, limit=2 * 1024 * 1024):
|
|
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
|
|
with os.fdopen(fd, 'rb') as stream:
|
|
meta = os.fstat(stream.fileno())
|
|
require(stat.S_ISREG(meta.st_mode) and meta.st_nlink == 1 and meta.st_uid == os.getuid()
|
|
and stat.S_IMODE(meta.st_mode) == 0o600 and meta.st_size <= limit, 'private bounded original evidence')
|
|
raw = stream.read(limit + 1)
|
|
after = os.fstat(stream.fileno())
|
|
require(len(raw) <= limit and (meta.st_ino, meta.st_size, meta.st_mtime_ns, meta.st_ctime_ns)
|
|
== (after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns), 'unchanged original evidence')
|
|
return raw
|
|
|
|
|
|
def write(path, raw):
|
|
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())
|
|
fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
|
try:
|
|
os.fsync(fd)
|
|
finally:
|
|
os.close(fd)
|
|
|
|
|
|
def canonical(value):
|
|
return (json.dumps(value, sort_keys=True, separators=(',', ':')) + '\n').encode()
|
|
|
|
|
|
NATIVE = r'''
|
|
Add-Type -TypeDefinition @'
|
|
using System;
|
|
using System.ComponentModel;
|
|
using System.Runtime.InteropServices;
|
|
using Microsoft.Win32.SafeHandles;
|
|
public static class RmmCaptureSystemRepair {
|
|
const string LocalName="RmmSignedClockCaptureLocalService";
|
|
const string SystemName="RmmSignedClockCaptureSystem";
|
|
const string SystemCommand="\"C:\\ProgramData\\RustDiscoverySignedClockCapture\\efd17b43-7e04-49a7-9bd4-862d13365eec\\SignedClockCapture.exe\" --service efd17b43-7e04-49a7-9bd4-862d13365eec system";
|
|
[DllImport("advapi32.dll",EntryPoint="OpenSCManagerW",ExactSpelling=true,CharSet=CharSet.Unicode,SetLastError=true)] static extern IntPtr OpenManager(string machine,string database,uint access);
|
|
[DllImport("advapi32.dll",EntryPoint="CreateServiceW",ExactSpelling=true,CharSet=CharSet.Unicode,SetLastError=true)] static extern IntPtr CreateService(IntPtr manager,string name,string display,uint access,uint type,uint start,uint error,string command,string group,IntPtr tag,string dependencies,string account,string password);
|
|
[DllImport("advapi32.dll",EntryPoint="OpenServiceW",ExactSpelling=true,CharSet=CharSet.Unicode,SetLastError=true)] static extern IntPtr OpenService(IntPtr manager,string name,uint access);
|
|
[DllImport("advapi32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] static extern bool CloseServiceHandle(IntPtr handle);
|
|
[DllImport("advapi32.dll",EntryPoint="ChangeServiceConfig2W",ExactSpelling=true,SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] static extern bool ChangeServiceConfig2(Service handle,uint level,ref uint value);
|
|
[DllImport("advapi32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] static extern bool QueryServiceStatusEx(Service handle,int level,out Status value,int size,out int needed);
|
|
[DllImport("advapi32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] static extern bool SetServiceObjectSecurity(Service handle,uint info,IntPtr descriptor);
|
|
[DllImport("advapi32.dll",EntryPoint="ConvertStringSecurityDescriptorToSecurityDescriptorW",ExactSpelling=true,CharSet=CharSet.Unicode,SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] static extern bool ConvertSecurity(string text,uint revision,out IntPtr descriptor,out uint size);
|
|
[DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr value);
|
|
[StructLayout(LayoutKind.Sequential)] public struct Status {public uint Type,State,Controls,Win32Exit,SpecificExit,Checkpoint,WaitHint,Pid,Flags;}
|
|
static Exception Failed(string step){int code=Marshal.GetLastWin32Error();return new Win32Exception(code,"CAPTURE_SYSTEM_REPAIR_"+step);}
|
|
public sealed class Service:SafeHandleZeroOrMinusOneIsInvalid {
|
|
internal Service(IntPtr value):base(true){SetHandle(value);}
|
|
protected override bool ReleaseHandle(){return CloseServiceHandle(handle);}
|
|
public Status Read(){Status value;int needed;if(!QueryServiceStatusEx(this,0,out value,Marshal.SizeOf(typeof(Status)),out needed))throw Failed("QueryServiceStatusEx");return value;}
|
|
}
|
|
static IntPtr Manager(uint access){IntPtr value=OpenManager(null,null,access);if(value==IntPtr.Zero)throw Failed("OpenSCManagerW");return value;}
|
|
static Service OpenFixed(string name){IntPtr manager=Manager(1);try{IntPtr value=OpenService(manager,name,4);if(value==IntPtr.Zero)throw Failed("OpenServiceW");return new Service(value);}finally{CloseServiceHandle(manager);}}
|
|
public static Service OpenLocal(){return OpenFixed(LocalName);}
|
|
public static Service OpenSystem(){return OpenFixed(SystemName);}
|
|
public static Service CreateSystemOnce(){
|
|
IntPtr manager=Manager(3);try{
|
|
// Literal managed null is passed to the P/Invoke here. No PowerShell string
|
|
// binding or caller-selected service/account/path reaches CreateServiceW.
|
|
IntPtr value=CreateService(manager,SystemName,SystemName,0xf01ff,16,3,1,SystemCommand,null,IntPtr.Zero,null,null,null);
|
|
if(value==IntPtr.Zero)throw Failed("CreateServiceW");
|
|
Service service=new Service(value);try{
|
|
uint sid=1;if(!ChangeServiceConfig2(service,5,ref sid))throw Failed("ChangeServiceConfig2W");
|
|
IntPtr descriptor;uint bytes;if(!ConvertSecurity("D:P(A;;GA;;;SY)(A;;GA;;;BA)",1,out descriptor,out bytes))throw Failed("ConvertSecurityW");
|
|
try{if(!SetServiceObjectSecurity(service,4,descriptor))throw Failed("SetServiceObjectSecurity");}finally{LocalFree(descriptor);}
|
|
return service;
|
|
}catch{service.Dispose();throw;}
|
|
}finally{CloseServiceHandle(manager);}
|
|
}
|
|
}
|
|
'@
|
|
'''
|
|
|
|
HEADER = r'''
|
|
$ErrorActionPreference='Stop';$request=$global:RmmCaptureSystemRepairPayload
|
|
if(!$request-or(($request.PSObject.Properties.Name|Sort-Object)-join',')-cne'action,id,profile,script_sha256'-or$request.id-cne'efd17b43-7e04-49a7-9bd4-862d13365eec'-or$request.profile-cne'rmm.windows.raw-clock.original-system-create-repair.v1'-or$request.action-notin@('repair','read')-or$request.script_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed original system repair request'}
|
|
$p=@{id='efd17b43-7e04-49a7-9bd4-862d13365eec'};$base='C:\ProgramData\RustDiscoverySignedClockCapture';$case=Join-Path $base $p.id;$control=Join-Path $case 'control';$exe=Join-Path $case 'SignedClockCapture.exe';$boot='C:\ProgramData\RustDiscoveryBootstrap'
|
|
$names=@('RmmSignedClockCaptureLocalService','RmmSignedClockCaptureSystem');$tags=@('local-service','system');$accounts=@('NT AUTHORITY\LocalService','LocalSystem');$sys='S-1-5-18';$admin='S-1-5-32-544'
|
|
'''
|
|
|
|
BODY = r'''
|
|
if($PSCommandPath-cne(Join-Path (Join-Path $boot $request.script_sha256) 'SignedClockCaptureSystemRepair.ps1')-or(HashFile $PSCommandPath)-cne$request.script_sha256){throw 'Actual exact repair controller'}
|
|
Check $PSCommandPath $false;foreach($dir in @($base,$case,$control)){Check $dir $true}
|
|
$oldController=Join-Path (Join-Path $boot '89c19138e2804f263f1875c7697a7d53f54f40722101677b4d29538c917196f4') 'SignedClockCaptureAcceptance.ps1';Check $oldController $false;if((HashFile $oldController)-cne'89c19138e2804f263f1875c7697a7d53f54f40722101677b4d29538c917196f4'){throw 'Original controller hash'}
|
|
$staged=Join-Path (Join-Path $boot '601c27a43fb67c662f926f9dc289a23a5c31c7e27f62901a77fc9ceaafaea7fb') 'SignedClockCapture.exe';Check $staged $false;if((Get-Item -LiteralPath $staged).Length-ne8566784-or(HashFile $staged)-cne'601c27a43fb67c662f926f9dc289a23a5c31c7e27f62901a77fc9ceaafaea7fb'){throw 'Original staged executable'}
|
|
$intent=ReadJson (Join-Path $control 'intent.json');if((($intent.PSObject.Properties.Name|Sort-Object)-join',')-cne'action,exe_bytes,exe_sha256,id,manifest_sha256,profile,script_sha256'-or$intent.action-cne'setup'-or$intent.id-cne$p.id-or$intent.profile-cne'rmm.windows.raw-clock.two-role-bootstrap.v1'-or$intent.exe_bytes-ne8566784-or$intent.exe_sha256-cne'601c27a43fb67c662f926f9dc289a23a5c31c7e27f62901a77fc9ceaafaea7fb'-or$intent.script_sha256-cne'89c19138e2804f263f1875c7697a7d53f54f40722101677b4d29538c917196f4'-or$intent.manifest_sha256-cne'806c062bdd458627cf44ff1ef3f27738e1ebf2f407a96f772223efef267db0b1'){throw 'Exact original setup intent'}
|
|
$active=ReadJson (Join-Path $base 'active.json');if((($active.PSObject.Properties.Name|Sort-Object)-join',')-cne'id,manifest_sha256,no_retry,script_sha256'-or$active.id-cne$p.id-or$active.manifest_sha256-cne$intent.manifest_sha256-or$active.script_sha256-cne$intent.script_sha256-or$active.no_retry-ne$true){throw 'Same original active campaign'}
|
|
$allowed=@('intent.json','local-service-create-attempt.json','local-service-created.json','system-create-attempt.json','system-create-repair-attempt.json','system-create-repair-created.json','system-create-repair-failure.json');foreach($item in @(Get-ChildItem -LiteralPath $control -Force)){if($item.PSIsContainer-or$item.Name-notin$allowed){throw 'Unexpected campaign progress: no repair'}}
|
|
foreach($n in @(0,1)){$attempt=ReadJson (Join-Path $control ($tags[$n]+'-create-attempt.json'));if((($attempt.PSObject.Properties.Name|Sort-Object)-join',')-cne'command,create_once'-or$attempt.create_once-ne$true-or$attempt.command-cne(Command $n)){throw 'Original exact service attempt'}}
|
|
$made=ReadJson (Join-Path $control 'local-service-created.json');$local=Service 0;if((($made.PSObject.Properties.Name|Sort-Object)-join',')-cne'create_once,service'-or$made.create_once-ne$true-or!$local-or!(Equal $local $made.service)){throw 'Same original LocalService definition'}
|
|
$localHandle=[RmmCaptureSystemRepair]::OpenLocal();try{$localStatus=$localHandle.Read();if($localStatus.State-ne1){throw 'Original LocalService must remain stopped'}}finally{$localHandle.Dispose()}
|
|
foreach($path in @($exe,(Join-Path $case 'local-service'),(Join-Path $case 'system'))){if(Test-Path -LiteralPath $path){throw 'Unexpected setup completion or prior role entry'}}
|
|
$repairAttempt=Join-Path $control 'system-create-repair-attempt.json';$repairCreated=Join-Path $control 'system-create-repair-created.json';$repairFailure=Join-Path $control 'system-create-repair-failure.json'
|
|
$system=Get-CimInstance Win32_Service -Filter "Name='RmmSignedClockCaptureSystem'" -OperationTimeoutSec 5
|
|
if($request.action-ceq'read'){
|
|
$records=[ordered]@{};foreach($leaf in @('system-create-repair-attempt.json','system-create-repair-created.json','system-create-repair-failure.json')){$path=Join-Path $control $leaf;$records[$leaf]=$null;if(Test-Path -LiteralPath $path){$records[$leaf]=ReadJson $path}}
|
|
$systemMetadata=$null;if($system){$systemMetadata=@{command=$system.PathName;account=$system.StartName;start=$system.StartMode;type=$system.ServiceType;state=$system.State;definition_unverified=$true}}
|
|
@{id=$p.id;read_only=$true;local_service_verified_stopped=$true;system_present=[bool]$system;system=$systemMetadata;records=$records;setup_completed=$false;service_started=$false;calibrated=$false;clock_authority=$false}|ConvertTo-Json -Depth 24 -Compress;exit 0
|
|
}
|
|
if($system-or(Test-Path -LiteralPath $repairAttempt)-or(Test-Path -LiteralPath $repairCreated)-or(Test-Path -LiteralPath $repairFailure)){throw 'Existing system or repair attempt: original read only'}
|
|
WriteNew $repairAttempt @{id=$p.id;profile=$request.profile;script_sha256=$request.script_sha256;original_manifest_sha256=$intent.manifest_sha256;original_controller_sha256=$intent.script_sha256;create_once=$true;system_account_null_inside_csharp=$true;command=(Command 1);no_retry=$true}
|
|
$handle=$null
|
|
try{
|
|
$handle=[RmmCaptureSystemRepair]::CreateSystemOnce();$status=$handle.Read();if($status.State-ne1){throw 'New SYSTEM fixture must remain stopped'}
|
|
$created=Service 1;if(!$created){throw 'New fixed SYSTEM definition absent'}
|
|
$still=Service 0;if(!(Equal $still $made.service)){throw 'Original LocalService definition changed'}
|
|
WriteNew $repairCreated @{id=$p.id;profile=$request.profile;script_sha256=$request.script_sha256;service=$created;stopped=$true;create_once=$true;setup_completed=$false;service_started=$false;calibrated=$false;clock_authority=$false}
|
|
@{id=$p.id;system_created_stopped=$true;setup_completed=$false;service_started=$false;calibrated=$false;clock_authority=$false}|ConvertTo-Json -Compress
|
|
}catch{
|
|
$inner=$_.Exception;while($null-ne$inner.InnerException){$inner=$inner.InnerException};$native=$null;$step='managed_postcondition';if($inner-is[ComponentModel.Win32Exception]){$native=$inner.NativeErrorCode;if($inner.Message-match'^CAPTURE_SYSTEM_REPAIR_[A-Za-z0-9]+$'){$step=$inner.Message}}
|
|
if(!(Test-Path -LiteralPath $repairFailure)){WriteNew $repairFailure @{id=$p.id;profile=$request.profile;script_sha256=$request.script_sha256;failed=$true;step=$step;native_error_code=$native;read_original_case_only=$true}}
|
|
throw 'SYSTEM repair failed; read the original case only; do not retry'
|
|
}finally{if($null-ne$handle){$handle.Dispose()}}
|
|
'''
|
|
|
|
|
|
def helpers(original):
|
|
# Reuse only the exact original pure ACL/metadata/record helpers. Never
|
|
# import/dot-source/execute the original controller or its setup branch.
|
|
def section(start, end):
|
|
require(original.count(start) == 1 and original.count(end) == 1, 'unique original helper boundaries')
|
|
return original[original.index(start):original.index(end)]
|
|
output = section('function HashBytes', 'function NewDir')
|
|
output += section('function WriteNew', 'function Original')
|
|
require('function NewDir' not in output and 'CreateOnce' not in output and 'function ReadAll' not in output,
|
|
'only bounded original helper subset')
|
|
return output
|
|
|
|
|
|
def prepare():
|
|
require(sha((ROOT / 'deploy/windows/signed_clock_capture_acceptance.py').read_bytes()) == RUNNER_SHA,
|
|
'original runner unchanged')
|
|
original_manifest = private_read(ORIGINAL / 'manifest.json')
|
|
original_script = private_read(ORIGINAL / 'SignedClockCaptureAcceptance.ps1')
|
|
markers = private_read(ORIGINAL / 'marker-query-result-5c07d236-a249-450e-83f8-e5c22c49bae3.json')
|
|
require(sha(original_manifest) == MANIFEST_SHA and sha(original_script) == CONTROLLER_SHA
|
|
and sha(markers) == MARKERS_SHA, 'exact original partial-case provenance')
|
|
marker_value = json.loads(markers)
|
|
require(marker_value == {'names': ['intent.json', 'local-service-create-attempt.json',
|
|
'local-service-created.json', 'system-create-attempt.json'], 'read_only': True},
|
|
'actual original four-marker partial state')
|
|
# Read the already-qualified public executable only; never credentials/pins/keys.
|
|
executable = private_read(ORIGINAL / 'SignedClockCapture.exe', EXE_BYTES)
|
|
require(len(executable) == EXE_BYTES and sha(executable) == EXE_SHA, 'original qualified executable unchanged')
|
|
script = (HEADER + helpers(original_script.decode()) + NATIVE + BODY).encode('ascii')
|
|
require(len(script) <= 32768, 'bounded single-purpose repair controller')
|
|
state = ROOT / 'devstate/windows-signed-clock-capture-system-repair'
|
|
state.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
require(state.stat().st_uid == os.getuid() and stat.S_IMODE(state.stat().st_mode) == 0o700,
|
|
'private local repair artifact root')
|
|
folder = state / str(uuid.uuid4())
|
|
folder.mkdir(mode=0o700)
|
|
write(folder / 'SignedClockCaptureSystemRepair.ps1', script)
|
|
for action in ('repair', 'read'):
|
|
write(folder / ('payload-' + action + '.json'), canonical(dict(id=CASE, profile=PROFILE,
|
|
action=action, script_sha256=sha(script))))
|
|
manifest = {'profile': PROFILE, 'original_case': CASE, 'original_manifest_sha256': MANIFEST_SHA,
|
|
'original_controller_sha256': CONTROLLER_SHA, 'original_runner_sha256': RUNNER_SHA,
|
|
'original_marker_receipt_sha256': MARKERS_SHA, 'exe_sha256': EXE_SHA,
|
|
'repair_script_sha256': sha(script), 'repair_script_bytes': len(script),
|
|
'generator_sha256': sha(Path(__file__).read_bytes()), 'target_executed': False,
|
|
'no_original_controller_replay': True, 'no_start_stop_delete_or_setup_completion': True}
|
|
write(folder / 'manifest.json', canonical(manifest))
|
|
print(json.dumps({'path': str(folder), **manifest}, sort_keys=True))
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('command', choices=['prepare'])
|
|
parser.parse_args()
|
|
prepare()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|