diff --git a/crates/agent-windows/examples/helper_peer_controls.rs b/crates/agent-windows/examples/helper_peer_controls.rs index 3cab823..7e1cf8a 100644 --- a/crates/agent-windows/examples/helper_peer_controls.rs +++ b/crates/agent-windows/examples/helper_peer_controls.rs @@ -1,9 +1,17 @@ //! Negative, read-only raw Probe clients. Never SDK self-refusal as server proof. //! The permanent services, their tokens/configuration and private state stay intact. +// Compile the unchanged production proof in this diagnostic crate. Keeping the +// module public avoids hiding its public transport API behind dead-code lint; +// no new API is exported from the agent library. +#[cfg(all(windows, feature = "system-helper"))] +#[path = "../src/helper_ipc.rs"] +pub mod helper_ipc; +#[cfg(all(windows, feature = "system-helper"))] +pub use rmm_agent_windows::SERVICE_NAME; #[cfg(all(windows, feature = "system-helper"))] mod platform { + use crate::helper_ipc as ipc; use anyhow::{Result, ensure}; - use rmm_agent_windows::helper_ipc as ipc; use serde::Deserialize; use serde_json::json; use std::{ @@ -35,6 +43,7 @@ mod platform { const ROOT: &str = r"C:\ProgramData\RustDiscoveryPeerControls"; static CASE: OnceLock = OnceLock::new(); static IS_PARENT: OnceLock = OnceLock::new(); + static DIRECT_PEER_PROOF: OnceLock = OnceLock::new(); static STATUS: AtomicUsize = AtomicUsize::new(0); fn wide(s: &str) -> Vec { s.encode_utf16().chain(Some(0)).collect() @@ -866,6 +875,33 @@ mod platform { &json!({"schema_version":1,"case_id":case,"source":"own_system_fixed_child_controller","result":result,"no_jobs":true,"read_only":true,"token_exported":false}), ) } + fn direct_peer_proof(case: uuid::Uuid) -> Result<()> { + let identity = token("parent")?; + save(case, "parent-token.json", &identity)?; + let input = read_input(case)?; + let began = Instant::now(); + let proof = (|| -> Result { + let mut peer = ipc::PeerProof::for_service(&input.pin.agent, input.expected_agent_pid)?; + ensure!( + peer.identity().creation_ticks == input.expected_agent_creation, + "CONTROL_ORIGINAL_AGENT_BIRTH" + ); + ensure!(!peer.exited()?, "CONTROL_ORIGINAL_AGENT_EXITED"); + peer.check()?; + Ok(serde_json::to_value(peer.identity())?) + })(); + let result = match proof { + Ok(actual) => json!({"direct_agent_peer_proof":true,"verified":true,"identity":actual}), + Err(error) => { + json!({"direct_agent_peer_proof":true,"verified":false,"error_codes":codes(&error)}) + } + }; + save( + case, + "parent-result.json", + &json!({"schema_version":1,"case_id":case,"source":"own_system_direct_production_agent_peer_proof","result":result,"elapsed_ms":began.elapsed().as_millis(),"expected_agent_pid":input.expected_agent_pid,"expected_agent_creation":input.expected_agent_creation,"no_jobs":true,"read_only":true,"pipe_used":false,"token_duplicated":false,"token_exported":false,"service_or_process_acl_changed":false}), + ) + } fn status(state: u32, error: u32) { let handle = STATUS.load(Ordering::SeqCst) as SERVICE_STATUS_HANDLE; if handle.is_null() { @@ -911,7 +947,11 @@ mod platform { STATUS.store(handle as usize, Ordering::SeqCst); status(SERVICE_RUNNING, 0); let result = if *IS_PARENT.get().unwrap_or(&false) { - parent(*CASE.get().unwrap()) + if *DIRECT_PEER_PROOF.get().unwrap_or(&false) { + direct_peer_proof(*CASE.get().unwrap()) + } else { + parent(*CASE.get().unwrap()) + } } else { run(*CASE.get().unwrap(), "service") }; @@ -924,7 +964,7 @@ mod platform { args.len() == 2 && matches!( args[0].as_str(), - "--admin" | "--service" | "--agent-child" | "--parent" + "--admin" | "--service" | "--agent-child" | "--parent" | "--peer-proof" ), "CONTROL_FIXED_MODE" ); @@ -940,11 +980,14 @@ mod platform { return run(case, "child"); } IS_PARENT - .set(args[0] == "--parent") + .set(matches!(args[0].as_str(), "--parent" | "--peer-proof")) + .map_err(|_| anyhow::anyhow!("CONTROL_MODE_ALREADY_SET"))?; + DIRECT_PEER_PROOF + .set(args[0] == "--peer-proof") .map_err(|_| anyhow::anyhow!("CONTROL_MODE_ALREADY_SET"))?; CASE.set(case) .map_err(|_| anyhow::anyhow!("CONTROL_CASE_ALREADY_SET"))?; - let mut name = wide(if args[0] == "--parent" { + let mut name = wide(if matches!(args[0].as_str(), "--parent" | "--peer-proof") { PARENT_NAME } else { NAME diff --git a/deploy/windows/helper_peer_controls.py b/deploy/windows/helper_peer_controls.py index 75c3d7c..dbee77c 100644 --- a/deploy/windows/helper_peer_controls.py +++ b/deploy/windows/helper_peer_controls.py @@ -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) diff --git a/deploy/windows/test_helper_peer_controls.py b/deploy/windows/test_helper_peer_controls.py index 93fd79a..b60bbd3 100644 --- a/deploy/windows/test_helper_peer_controls.py +++ b/deploy/windows/test_helper_peer_controls.py @@ -34,6 +34,16 @@ class PeerControlGuards(unittest.TestCase): pipe['actual_server_pid']=999 with self.assertRaises(Exception):control.summarize(report,payload,ident) + def test_direct_system_proof_is_not_reported_as_a_pipe_control(self): + report,payload,ident=self.fixture();report['reports'].clear();payload['direct_peer_proof']=True + report['reports']['parent-token']={'user_sid':'S-1-5-18','parent_service_sid_enabled':True} + value={'source':'own_system_direct_production_agent_peer_proof','case_id':ident,'expected_agent_pid':5140,'no_jobs':True,'read_only':True,'pipe_used':False,'token_duplicated':False,'service_or_process_acl_changed':False,'result':{'direct_agent_peer_proof':True,'verified':False,'error_codes':['HELPER_SCM_IMAGE_BINDING']}} + report['reports']['parent-result']=value + result=control.summarize(report,payload,ident) + self.assertFalse(result['direct_agent_peer_proof']['result']['verified']);self.assertEqual(result['controls'],{}) + value['pipe_used']=True + with self.assertRaises(Exception):control.summarize(report,payload,ident) + def test_lost_service_start_reply_cannot_repeat_service_operation(self): with tempfile.TemporaryDirectory() as temporary: state=Path(temporary);ident=str(uuid.uuid4());folder=state/ident;folder.mkdir(mode=0o700) diff --git a/docs/handover.md b/docs/handover.md index ad37d0a..c0776a6 100644 --- a/docs/handover.md +++ b/docs/handover.md @@ -53,6 +53,16 @@ Zugänge und private Rohbelege bleiben gitignoriert. ## Aktuelle Windowsfortsetzung +Direkter produktiver Prozess-Peerproof im neuen Fall `d792c4c6…` bestanden: +eigener SYSTEM-Parent3992 prüfte unverändert Agent5140 mit tatsächlicher +Startzeit `134390970107200328`, SCM-/Token-/Image-/Dateibindung,20ms. Kein +Pipeaufruf, Child, Token-Duplikat oder ACLwechsel. Originale Prozesse, +Metadaten und Zähler erhalten, eigener Dienst entfernt. Ursprünglicher +SSH-Timeout bleibt dokumentiert; vor expliziter Fortsetzung der ersten noch +nicht erreichten Startphase wurden fehlender Startmarker und fehlender eigener +Dienst nur lesend nachgewiesen. Produktive Agentprobe bleibt fehlgeschlagen, +keine positive Pipeabnahme. [Kontrollbericht](windows-helper-peer-controls.md). + Korrigierter Parentdiagnosefall `00703dab…`, Manifest `869a999c…`/EXE `35dea018…`: tatsächlicher SYSTEM-Parent8256, atomar zugeordneter Child7360 mit Agenttoken, Exit0, Originalagent5140 erhalten. Alle fünf Helper-SDK-Vorprüfungen unter SID19/ diff --git a/docs/windows-helper-peer-controls.md b/docs/windows-helper-peer-controls.md index ce4bfdc..db4baa3 100644 --- a/docs/windows-helper-peer-controls.md +++ b/docs/windows-helper-peer-controls.md @@ -65,6 +65,28 @@ ursprüngliche Prozesse/-metadaten, Policies und Windows-/Linuxjobzähler erhalt Der alte Parentfehler bleibt fehlgeschlagen. Die Ursache der tatsächlichen Agentverbindung ist weiter offen. +Der zusätzliche direkte Peerproof-Fall `d792c4c6-1fd6-4a7f-be3f-1c8e515a68e6` +bestand danach mit Manifest `build-f85a85ab…`, EXE `0a7259bf…` und ursprünglichem +Runner `27feeb82…`. Der eigene SYSTEM-Parent3992 führte den unveränderten +produktiven `PeerProof::for_service` gegen Agent5140 aus: tatsächlicher +LocalService-Token mit Agent-Service-SID, Startzeit `134390970107200328`, +Imagehash `2beed7fa…`, SCM- und gehaltene Datei-/Prozessprüfungen bestanden +in20ms. Kein Pipeaufruf, Child, Token-Duplikat oder ACLwechsel. Das ist ein +positiver direkter Prozessbeleg, weiterhin **keine positive Agent-Pipeabnahme**. +Der eigene Parentdienst wurde nach Stopped entfernt; Originalprozesse, +Metadaten, Policies und beide Jobzähler blieben erhalten. + +Der erste SSH-Aufruf dieses Falls verlor nach90s seine Antwort. Readback und +zusätzliche Nur-Lese-Prüfung belegten noch keinen `parent-start-intent.json`, +keinen eigenen Dienst und keine Ergebnisdateien. Erst nach dauerhaftem lokalen +Fortsetzungsintent wurde die noch nicht erreichte erste Startphase im selben +Fall fortgesetzt; ein zusätzlicher entfernter CreateNew-Intent und der bestehende +CreateNew-Startmarker verhindern zwei Starts. Der alte Timeout bleibt erhalten. +Die private Ergänzungsreceipt heißt `first-parent-continuation-result.json`. +Eine frische tatsächliche produktive Agentprobe um05:16UTC blieb zuvor +`HELPER_NOT_AVAILABLE`; weder diese noch der diagnostische Childfehler werden +durch den direkten Peerproof zu Erfolgen umgedeutet. + Der frühere Fall `4a60d264…` bleibt vor jedem Kontrolldienststart fehlgeschlagen. Nach einem verlorenen SSH-Reply bei der Stagingprüfung wurden ausschließlich die bereits übertragenen Hashes und das Fehlen eines entfernten Kontrollfalls