Prove actual Windows agent process identity under SYSTEM diagnostic
Rust development slice / linux (push) Failing after 7s
Rust development slice / linux (push) Failing after 7s
This commit is contained in:
@@ -78,7 +78,8 @@ $file=Join-Path $version $p.name;$exists=Test-Path -LiteralPath $file;if($exists
|
||||
'''
|
||||
SCRIPT=r'''$ErrorActionPreference='Stop'
|
||||
$p=$global:RmmPeerControlPayload
|
||||
if($p.action-notin@('prepare','admin','service','parent','cleanup','readback')-or([guid]::ParseExact($p.id,'D').ToString())-cne$p.id-or$p.binary-notmatch'^[a-f0-9]{64}$'-or$p.source-notmatch'^[a-f0-9]{64}$'){throw 'Fixed control intent'}
|
||||
if($p.action-notin@('prepare','admin','service','parent','cleanup','readback')-or([guid]::ParseExact($p.id,'D').ToString())-cne$p.id-or$p.binary-notmatch'^[a-f0-9]{64}$'-or$p.source-notmatch'^[a-f0-9]{64}$'-or$p.direct_peer_proof-isnot[bool]){throw 'Fixed control intent'}
|
||||
if($p.direct_peer_proof-and$p.action-notin@('prepare','parent','cleanup','readback')){throw 'Direct proof case has no child, administrator or LocalService probe'}
|
||||
$root='C:\ProgramData\RustDiscoveryPeerControls';$case=Join-Path $root $p.id;$controller=Join-Path $case 'controller';$exe=Join-Path (Join-Path $root $p.binary) 'HelperPeerControls.exe'
|
||||
$agentName='RmmDiscoveryWindows';$helperName='RmmDiscoverySystemHelper';$name='RmmDiscoveryPeerControl';$parentName='RmmDiscoveryPeerParent'
|
||||
$agentSid=(New-Object Security.Principal.NTAccount('NT SERVICE',$agentName)).Translate([Security.Principal.SecurityIdentifier]).Value
|
||||
@@ -137,7 +138,7 @@ function Baseline {
|
||||
return [ordered]@{services=$services;private_helper_metadata=$files;agent_config=(Metadata 'C:\ProgramData\RustDiscovery\config.json');agent_config_sha256=(Hash 'C:\ProgramData\RustDiscovery\config.json');device_key_metadata=(Metadata 'C:\ProgramData\RustDiscovery\state\device.key');helper_public_pin_sha256=(Hash $pin);helper_public_settings_sha256=(Hash $settings);helper_private_bytes_read=$false}
|
||||
}
|
||||
function Same($before,$after){if(($before|ConvertTo-Json -Depth 24 -Compress)-cne($after|ConvertTo-Json -Depth 24 -Compress)){throw 'Original agent/helper or private file metadata changed'}}
|
||||
function ReadIntent{Check $case $true @($agentSid,$controlSid) @();Check $controller $true @() @();Check (Join-Path $controller 'intent.json') $false @() @();$i=Get-Content -LiteralPath (Join-Path $controller 'intent.json') -Raw|ConvertFrom-Json;foreach($field in @('id','binary','source','agent_pid','helper_pid','agent_binary','helper_binary','policy','pin_sha256','control_sid')){if($i.payload.$field-cne$p.$field){throw 'Exact retained control intent'}};return $i}
|
||||
function ReadIntent{Check $case $true @($agentSid,$controlSid) @();Check $controller $true @() @();Check (Join-Path $controller 'intent.json') $false @() @();$i=Get-Content -LiteralPath (Join-Path $controller 'intent.json') -Raw|ConvertFrom-Json;foreach($field in @('id','binary','source','agent_pid','helper_pid','agent_binary','helper_binary','policy','pin_sha256','control_sid','direct_peer_proof')){if($i.payload.$field-cne$p.$field){throw 'Exact retained control intent'}};return $i}
|
||||
if((Hash $exe)-cne$p.binary){throw 'Exact control executable'}
|
||||
if($p.action-ceq'prepare'){
|
||||
if((Test-Path -LiteralPath $case)-or(Get-Service -Name $name -ErrorAction SilentlyContinue)-or(Get-Service -Name $parentName -ErrorAction SilentlyContinue)){throw 'No preexisting control case/services'}
|
||||
@@ -168,7 +169,7 @@ if($p.action-ceq'admin'){
|
||||
try{$out=$proc.StandardOutput.ReadToEndAsync();$err=$proc.StandardError.ReadToEndAsync();if(!$proc.WaitForExit(20000)){$proc.Kill();$proc.WaitForExit(5000)|Out-Null;throw 'Own administrator probe timeout'};WriteNew (Join-Path $controller 'admin-exit.json') @{pid=$proc.Id;exit_code=$proc.ExitCode;stdout_bytes=$out.Result.Length;stderr_bytes=$err.Result.Length};if($proc.ExitCode-ne0){throw 'Own administrator probe incomplete'}}finally{$proc.Dispose()}
|
||||
}
|
||||
if($p.action-in@('service','parent')){
|
||||
$kind=$p.action;$serviceName=if($kind-ceq'service'){$name}else{$parentName};$mode=if($kind-ceq'service'){'--service'}else{'--parent'};$command='"'+$exe+'" '+$mode+' '+$p.id
|
||||
$kind=$p.action;$serviceName=if($kind-ceq'service'){$name}else{$parentName};$mode=if($kind-ceq'service'){'--service'}elseif($p.direct_peer_proof){'--peer-proof'}else{'--parent'};$command='"'+$exe+'" '+$mode+' '+$p.id
|
||||
if(Get-Service -Name $serviceName -ErrorAction SilentlyContinue){throw 'Existing control service: readback only'}
|
||||
WriteNew (Join-Path $controller ($kind+'-start-intent.json')) @{once=$true;service=$serviceName;command=$command;probe_only=$true;no_jobs=$true}
|
||||
if($kind-ceq'service'){$credential=New-Object Management.Automation.PSCredential('NT AUTHORITY\LocalService',(New-Object Security.SecureString));New-Service -Name $serviceName -BinaryPathName $command -StartupType Manual -Credential $credential|Out-Null}
|
||||
@@ -178,7 +179,7 @@ if($p.action-in@('service','parent')){
|
||||
}
|
||||
$deadline=[DateTime]::UtcNow.AddSeconds(35)
|
||||
foreach($kind in @('service','parent')){
|
||||
$serviceName=if($kind-ceq'service'){$name}else{$parentName};$mode=if($kind-ceq'service'){'--service'}else{'--parent'};$command='"'+$exe+'" '+$mode+' '+$p.id
|
||||
$serviceName=if($kind-ceq'service'){$name}else{$parentName};$mode=if($kind-ceq'service'){'--service'}elseif($p.direct_peer_proof){'--peer-proof'}else{'--parent'};$command='"'+$exe+'" '+$mode+' '+$p.id
|
||||
$s=Get-CimInstance Win32_Service -Filter ("Name='"+$serviceName+"'") -OperationTimeoutSec 10
|
||||
if($s){
|
||||
$expected=if($kind-ceq'service'){'NT AUTHORITY\LocalService'}else{'LocalSystem'}
|
||||
@@ -235,7 +236,7 @@ def stage(path,name):
|
||||
return digest
|
||||
|
||||
|
||||
def prepare(manifest_path,helper_case):
|
||||
def prepare(manifest_path,helper_case,direct_peer_proof=False):
|
||||
manifest=cb.contract.protected_json(manifest_path)
|
||||
require(manifest['type']=='rmm.windows.helper-peer-controls' and manifest['system_helper_feature'] is True and manifest['source_files']==sources() and helper.sha(manifest['artifact']['path'])==manifest['artifact']['sha256'],'new source-bound control artifact, not old 27-unit proof')
|
||||
index,association,native=helper.current_runtime()
|
||||
@@ -245,7 +246,7 @@ def prepare(manifest_path,helper_case):
|
||||
ident=str(uuid.uuid4());helper.private_dir(STATE);folder=STATE/ident;folder.mkdir(mode=0o700)
|
||||
source=folder/'PeerControls.ps1';fd=os.open(source,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600)
|
||||
with os.fdopen(fd,'wb') as out:out.write(SCRIPT.encode());out.flush();os.fsync(out.fileno())
|
||||
payload=dict(id=ident,binary=manifest['artifact']['sha256'],source=hashlib.sha256(SCRIPT.encode()).hexdigest(),control_sid=helper.service_sid(NAME),agent_pid=native['service']['process_id'],helper_pid=6240,agent_binary=index['binary_sha256'],helper_binary=helper.HELPER_SHA,policy=profile['policy_sha256'],pin_sha256=profile['pin_sha256'])
|
||||
payload=dict(id=ident,binary=manifest['artifact']['sha256'],source=hashlib.sha256(SCRIPT.encode()).hexdigest(),control_sid=helper.service_sid(NAME),agent_pid=native['service']['process_id'],helper_pid=6240,agent_binary=index['binary_sha256'],helper_binary=helper.HELPER_SHA,policy=profile['policy_sha256'],pin_sha256=profile['pin_sha256'],direct_peer_proof=bool(direct_peer_proof))
|
||||
require(payload['agent_pid']==5140,'explicit current accepted agent process; no silent PID adoption')
|
||||
intent=dict(payload=payload,source_file_sha256=helper.sha(__file__),manifest_path=str(manifest_path.resolve()),manifest_sha256=helper.sha(manifest_path),runtime_index=association,helper_case=helper_case,no_jobs=True)
|
||||
helper.store(folder,'intent.json',intent);helper.store(folder,'prepare-attempt.json',{'create_once':True})
|
||||
@@ -274,6 +275,14 @@ def summarize(report,payload,ident):
|
||||
require(report.get('writer_binding_checked') is True,'native owner and exact writer-role checks required')
|
||||
require(report['original_preserved'] is True and report['own_services_removed'] is True,'original services/files preserved and own stopped services removed')
|
||||
result={'id':ident,'original_preserved':True,'own_services_removed':True,'no_jobs':True,'parent_diagnostic':report['reports'].get('parent-result'),'parent_token':report['reports'].get('parent-token'),'report_trust':report.get('report_trust',{}),'controls':{}}
|
||||
if payload.get('direct_peer_proof') and report['reports'].get('parent-result'):
|
||||
value=report['reports']['parent-result'];token=report['reports'].get('parent-token',{})
|
||||
require(token.get('user_sid')=='S-1-5-18' and token.get('parent_service_sid_enabled') is True,'actual own SYSTEM diagnostic parent')
|
||||
require(value.get('source')=='own_system_direct_production_agent_peer_proof' and value.get('case_id')==ident and value.get('expected_agent_pid')==payload['agent_pid'] and value.get('no_jobs') is True and value.get('read_only') is True and value.get('pipe_used') is False and value.get('token_duplicated') is False and value.get('service_or_process_acl_changed') is False,'exact read-only direct proof scope')
|
||||
require(value['result'].get('direct_agent_peer_proof') is True and isinstance(value['result'].get('verified'),bool),'actual direct proof result, never pipe proof')
|
||||
if value['result']['verified']:
|
||||
require(value['result']['identity']['pid']==payload['agent_pid'],'actual original Agent process')
|
||||
result['direct_agent_peer_proof']=value
|
||||
for kind in ('admin','service'):
|
||||
value=report['reports'].get(kind+'-result')
|
||||
if value:
|
||||
@@ -292,11 +301,11 @@ def summarize(report,payload,ident):
|
||||
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser(description=__doc__);p.add_argument('action',choices=['build-local','memory-guard','prepare','admin','service','parent','cleanup','readback']);p.add_argument('--manifest',type=Path);p.add_argument('--helper-case');p.add_argument('--id');a=p.parse_args()
|
||||
p=argparse.ArgumentParser(description=__doc__);p.add_argument('action',choices=['build-local','memory-guard','prepare','admin','service','parent','cleanup','readback']);p.add_argument('--manifest',type=Path);p.add_argument('--helper-case');p.add_argument('--id');p.add_argument('--direct-peer-proof',action='store_true',help='New prepare case: own SYSTEM parent only runs the exact production Agent peer proof, no child or pipe');a=p.parse_args()
|
||||
if a.action=='build-local':build()
|
||||
elif a.action=='memory-guard':
|
||||
value=cb.powershell(MEMORY_GUARD,{},timeout=30);require(value.get('verified') is True and value.get('filesystem_or_acl_mutations') is False,'actual memory-only ACL constructor guard');print(json.dumps(value))
|
||||
elif a.action=='prepare':require(a.manifest is not None and a.helper_case is not None,'new control manifest and explicit existing passive helper case required');prepare(a.manifest,a.helper_case)
|
||||
elif a.action=='prepare':require(a.manifest is not None and a.helper_case is not None,'new control manifest and explicit existing passive helper case required');prepare(a.manifest,a.helper_case,a.direct_peer_proof)
|
||||
else:require(a.id is not None,'existing explicit control case required');run(a.id,a.action)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user