Verify Windows ACL regression fix and native denied administrator probe
Rust development slice / linux (push) Failing after 7s
Rust development slice / linux (push) Failing after 7s
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
#requires -Version 5.1
|
||||
<# Standalone diagnostic bootstrap ONLY. Root runs explicitly after qualification.
|
||||
Prepare stages one hash-pinned binary. Start creates one temporary own Manual
|
||||
LocalService service, not an enrolled RMM client/job. Lost replies permit only
|
||||
Readback. Cleanup removes ONLY that exact stopped probe service. No installed
|
||||
product, permanent agent/helper, time service, privilege, boot counter or trust
|
||||
configuration is modified. SCM registration is confined to this temporary probe.
|
||||
Two independent fresh cases can show process independence; matching samples do
|
||||
NOT qualify a reboot/clock-jump invariant or enable a signed-job boot capability.
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param([Parameter(Mandatory=$true)][ValidateSet('Prepare','Start','Readback','Cleanup')][string]$Action,
|
||||
[Parameter(Mandatory=$true)][ValidatePattern('^[a-f0-9]{64}$')][string]$BinarySha256,
|
||||
[Parameter(Mandatory=$true)][ValidatePattern('^[a-f0-9]{64}$')][string]$ExpectedSourceSha256,
|
||||
[Guid]$CaseId=[Guid]::Empty)
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference='Stop'
|
||||
$root='C:\ProgramData\RustDiscoveryBootProbe';$name='RmmWindowsBootIdentityProbe'
|
||||
$binary=Join-Path (Join-Path $root $BinarySha256) 'WindowsBootProbe.exe'
|
||||
$sys='S-1-5-18';$admin='S-1-5-32-544';$local='S-1-5-19'
|
||||
# MS-LSAT service SID is independent of whether this temporary service still
|
||||
# exists. This keeps post-cleanup/lost-reply readback genuinely read-only.
|
||||
$algorithm=[Security.Cryptography.SHA1]::Create()
|
||||
try {$digest=$algorithm.ComputeHash([Text.Encoding]::Unicode.GetBytes($name.ToUpperInvariant()))} finally {$algorithm.Dispose()}
|
||||
$serviceSid='S-1-5-80-'+((0..4|ForEach-Object {[BitConverter]::ToUInt32($digest,$_ * 4)})-join '-')
|
||||
function Require([bool]$v,[string]$code){if(!$v){throw $code}}
|
||||
function Hash([string]$p){return (Get-FileHash -LiteralPath $p -Algorithm SHA256).Hash.ToLowerInvariant()}
|
||||
function No-Reparse([string]$p){$i=Get-Item -LiteralPath $p -Force;while($null -ne $i){Require (($i.Attributes-band[IO.FileAttributes]::ReparsePoint)-eq 0) 'BOOT_PROBE_REPARSE';if($i-is[IO.FileInfo]){$i=$i.Directory}else{$i=$i.Parent}}}
|
||||
function Protect([string]$p,[string]$writer){$a=New-Object Security.AccessControl.DirectorySecurity;$a.SetAccessRuleProtection($true,$false);$a.SetOwner((New-Object Security.Principal.SecurityIdentifier($admin)));foreach($sid in @($sys,$admin,$local,$writer)|Where-Object {$_}|Select-Object -Unique){$rights=if($sid-in@($sys,$admin,$writer)){'FullControl'}else{'ReadAndExecute'};$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),$rights,'ContainerInherit,ObjectInherit','None','Allow')))};Set-Acl -LiteralPath $p -AclObject $a}
|
||||
function Check([string]$p,[string[]]$writers){No-Reparse $p;$a=Get-Acl -LiteralPath $p;Require ($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-in@($sys,$admin)-or(!(Get-Item -LiteralPath $p).PSIsContainer-and$writers.Count-gt 0-and$a.GetOwner([Security.Principal.SecurityIdentifier]).Value-eq$local)) 'BOOT_PROBE_OWNER';$r=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));Require ($r.Count-gt 0) 'BOOT_PROBE_DACL';foreach($ace in $r){$sid=$ace.IdentityReference.Value;Require ($ace.AccessControlType-eq'Allow') 'BOOT_PROBE_ACE';if($sid-notin@($sys,$admin)+$writers){Require ($sid-eq$local-and([long]$ace.FileSystemRights-band 0x500d0156)-eq 0) 'BOOT_PROBE_FOREIGN_WRITE'}}}
|
||||
function Write-New([string]$p,$v){$f=[IO.File]::Open($p,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($v|ConvertTo-Json -Depth 12 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
|
||||
Require ((Hash $PSCommandPath)-ceq$ExpectedSourceSha256) 'BOOT_PROBE_EXACT_SOURCE'
|
||||
if($Action-eq'Prepare'){
|
||||
if(!(Test-Path -LiteralPath $root)){[void](New-Item -ItemType Directory -Path $root);Protect $root ''};Check $root @()
|
||||
$dir=Split-Path $binary -Parent;if(!(Test-Path -LiteralPath $dir)){[void](New-Item -ItemType Directory -Path $dir);Protect $dir ''};Check $dir @()
|
||||
$present=Test-Path -LiteralPath $binary;if($present){Check $binary @();Require ((Hash $binary)-ceq$BinarySha256) 'BOOT_PROBE_STAGED_HASH'}
|
||||
[ordered]@{prepared=$true;binary_present=$present;upload_path=$binary;no_service_change=$true}|ConvertTo-Json -Compress;exit 0
|
||||
}
|
||||
Require ($CaseId-ne[Guid]::Empty) 'BOOT_PROBE_CASE_REQUIRED'
|
||||
Check $root @();Check $binary @();Require ((Hash $binary)-ceq$BinarySha256) 'BOOT_PROBE_BINARY_HASH'
|
||||
$case=Join-Path $root $CaseId.ToString();$command='"'+$binary+'" --service '+$CaseId.ToString()
|
||||
if($Action-eq'Start'){
|
||||
Require (!(Test-Path -LiteralPath $case)-and$null-eq(Get-Service -Name $name -ErrorAction SilentlyContinue)) 'BOOT_PROBE_FRESH_CASE_AND_SERVICE'
|
||||
[void](New-Item -ItemType Directory -Path $case);Protect $case ''
|
||||
Write-New (Join-Path $case 'intent.json') @{case_id=$CaseId.ToString();binary_sha256=$BinarySha256;source_sha256=$ExpectedSourceSha256;command=$command;service=$name;read_only=$true}
|
||||
Write-New (Join-Path $case 'create-attempt.json') @{create_once=$true}
|
||||
New-Service -Name $name -BinaryPathName $command -StartupType Manual -Credential (New-Object Management.Automation.PSCredential('NT AUTHORITY\LocalService',(New-Object Security.SecureString)))|Out-Null
|
||||
$sc=Join-Path ([Environment]::GetFolderPath([Environment+SpecialFolder]::System)) 'sc.exe'
|
||||
& $sc sidtype $name unrestricted|Out-Null;Require ($LASTEXITCODE-eq 0) 'BOOT_PROBE_SERVICE_SID'
|
||||
$sid=(New-Object Security.Principal.NTAccount('NT SERVICE',$name)).Translate([Security.Principal.SecurityIdentifier]).Value
|
||||
Require ($sid-ceq$serviceSid) 'BOOT_PROBE_ACTUAL_SERVICE_SID'
|
||||
Protect $case $sid
|
||||
Write-New (Join-Path $case 'start-attempt.json') @{start_once=$true;no_jobs=$true}
|
||||
Start-Service -Name $name
|
||||
}
|
||||
Check $case @($serviceSid)
|
||||
$intent=Get-Content -LiteralPath (Join-Path $case 'intent.json') -Raw|ConvertFrom-Json
|
||||
Require ($intent.case_id-ceq$CaseId.ToString()-and$intent.binary_sha256-ceq$BinarySha256-and$intent.source_sha256-ceq$ExpectedSourceSha256-and$intent.command-ceq$command-and$intent.service-ceq$name) 'BOOT_PROBE_RETAINED_INTENT'
|
||||
$service=Get-CimInstance Win32_Service -Filter "Name='RmmWindowsBootIdentityProbe'" -OperationTimeoutSec 10
|
||||
if($null-ne$service){Require ($service.PathName-ceq$command-and$service.StartName-in@('NT AUTHORITY\LocalService','NT AUTHORITY\Local Service')-and$service.StartMode-ceq'Manual') 'BOOT_PROBE_SCM_CONFIG'}
|
||||
$limit=[Diagnostics.Stopwatch]::StartNew()
|
||||
while($null-ne$service-and$service.State-ne'Stopped'-and$limit.Elapsed.TotalSeconds-lt 15){Start-Sleep -Milliseconds 250;$service=Get-CimInstance Win32_Service -Filter "Name='RmmWindowsBootIdentityProbe'" -OperationTimeoutSec 10}
|
||||
Require ($null-eq$service-or$service.State-eq'Stopped') 'BOOT_PROBE_RETAIN_ACTIVE_READBACK_ONLY'
|
||||
$result=$null;$path=Join-Path $case 'result.json'
|
||||
if(Test-Path -LiteralPath $path){Check $path @($serviceSid);Require ((Get-Item -LiteralPath $path).Length-le 8192) 'BOOT_PROBE_REPORT_SIZE';$result=Get-Content -LiteralPath $path -Raw|ConvertFrom-Json;Require ($result.case_id-ceq$CaseId.ToString()-and$result.service_name-ceq$name-and$result.user_sid-ceq$local-and$result.administrator_member-eq$false-and$result.scm_callback_entered-eq$true-and$result.read_only-eq$true-and$result.job_binding_qualified-eq$false) 'BOOT_PROBE_ACTUAL_LOCAL_SERVICE'}
|
||||
if($Action-eq'Cleanup'){
|
||||
Require ($null-ne$service-and$service.State-eq'Stopped') 'BOOT_PROBE_ONLY_OWN_STOPPED_SERVICE'
|
||||
Write-New (Join-Path $case 'cleanup-attempt.json') @{service=$name;command=$command;remove_once=$true}
|
||||
$sc=Join-Path ([Environment]::GetFolderPath([Environment+SpecialFolder]::System)) 'sc.exe'; & $sc delete $name|Out-Null;Require ($LASTEXITCODE-eq 0) 'BOOT_PROBE_OWN_CLEANUP'
|
||||
}
|
||||
[ordered]@{case_id=$CaseId.ToString();native_report=$result;service_stopped=($null-eq$service-or$service.State-eq'Stopped');service_exit_code=if($null-ne$service){$service.ExitCode}else{$null};job_binding_qualified=$false;no_jobs=$true;no_clock_change=$true;no_permanent_agent_change=$true}|ConvertTo-Json -Depth 12 -Compress
|
||||
@@ -0,0 +1,195 @@
|
||||
//! Standalone SCM diagnostic. Never enrolls, starts a job or changes the clock.
|
||||
#[path = "../../crates/agent-windows/src/native_boot.rs"]
|
||||
mod native_boot;
|
||||
#[cfg(windows)]
|
||||
mod service {
|
||||
use anyhow::{Result, ensure};
|
||||
use std::{
|
||||
io::Write,
|
||||
mem::size_of,
|
||||
path::PathBuf,
|
||||
ptr,
|
||||
sync::{
|
||||
OnceLock,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::*,
|
||||
Security::*,
|
||||
System::{Services::*, Threading::*},
|
||||
};
|
||||
const NAME: &str = "RmmWindowsBootIdentityProbe";
|
||||
static CASE: OnceLock<uuid::Uuid> = OnceLock::new();
|
||||
static STATUS: AtomicUsize = AtomicUsize::new(0);
|
||||
fn wide(s: &str) -> Vec<u16> {
|
||||
s.encode_utf16().chain(Some(0)).collect()
|
||||
}
|
||||
fn token() -> Result<()> {
|
||||
let mut thread = ptr::null_mut();
|
||||
if unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, 1, &mut thread) } != 0 {
|
||||
unsafe { CloseHandle(thread) };
|
||||
anyhow::bail!("BOOT_PROBE_IMPERSONATION_FORBIDDEN")
|
||||
}
|
||||
ensure!(
|
||||
unsafe { GetLastError() } == ERROR_NO_TOKEN,
|
||||
"BOOT_PROBE_THREAD_TOKEN"
|
||||
);
|
||||
let mut raw = ptr::null_mut();
|
||||
ensure!(
|
||||
unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut raw) } != 0,
|
||||
"BOOT_PROBE_TOKEN"
|
||||
);
|
||||
let result = (|| {
|
||||
let mut needed = 0;
|
||||
unsafe { GetTokenInformation(raw, TokenUser, ptr::null_mut(), 0, &mut needed) };
|
||||
ensure!((1..=4096).contains(&needed), "BOOT_PROBE_TOKEN_SIZE");
|
||||
let mut data = vec![0usize; (needed as usize).div_ceil(size_of::<usize>())];
|
||||
ensure!(
|
||||
unsafe {
|
||||
GetTokenInformation(
|
||||
raw,
|
||||
TokenUser,
|
||||
data.as_mut_ptr().cast(),
|
||||
needed,
|
||||
&mut needed,
|
||||
)
|
||||
} != 0,
|
||||
"BOOT_PROBE_USER"
|
||||
);
|
||||
let user = unsafe { &*data.as_ptr().cast::<TOKEN_USER>() };
|
||||
ensure!(
|
||||
unsafe { IsWellKnownSid(user.User.Sid, WinLocalServiceSid) } != 0,
|
||||
"BOOT_PROBE_LOCAL_SERVICE_REQUIRED"
|
||||
);
|
||||
let mut sid = [0usize; 16];
|
||||
let mut bytes = size_of::<[usize; 16]>() as u32;
|
||||
ensure!(
|
||||
unsafe {
|
||||
CreateWellKnownSid(
|
||||
WinBuiltinAdministratorsSid,
|
||||
ptr::null_mut(),
|
||||
sid.as_mut_ptr().cast(),
|
||||
&mut bytes,
|
||||
)
|
||||
} != 0,
|
||||
"BOOT_PROBE_ADMIN_SID"
|
||||
);
|
||||
let mut admin = 0;
|
||||
ensure!(
|
||||
unsafe {
|
||||
CheckTokenMembership(ptr::null_mut(), sid.as_mut_ptr().cast(), &mut admin)
|
||||
} != 0
|
||||
&& admin == 0,
|
||||
"BOOT_PROBE_ADMIN_FORBIDDEN"
|
||||
);
|
||||
Ok(())
|
||||
})();
|
||||
unsafe { CloseHandle(raw) };
|
||||
result
|
||||
}
|
||||
fn run() -> Result<()> {
|
||||
token()?;
|
||||
let case = CASE.get().unwrap();
|
||||
let path = PathBuf::from(r"C:\ProgramData\RustDiscoveryBootProbe").join(case.to_string());
|
||||
ensure!(
|
||||
std::fs::symlink_metadata(&path)?.is_dir()
|
||||
&& !std::fs::symlink_metadata(&path)?.file_type().is_symlink(),
|
||||
"BOOT_PROBE_CASE_DIRECTORY"
|
||||
);
|
||||
let first = super::native_boot::observe_candidate();
|
||||
std::thread::sleep(Duration::from_millis(750));
|
||||
let second = super::native_boot::observe_candidate();
|
||||
let equal = first.candidate_identifier.is_some()
|
||||
&& first.candidate_identifier == second.candidate_identifier;
|
||||
let report = serde_json::json!({"schema_version":1,"case_id":case,"service_name":NAME,"process_id":std::process::id(),"user_sid":"S-1-5-19","administrator_member":false,"thread_impersonation":false,"scm_callback_entered":true,"read_only":true,"jobs_created":false,"clock_queried":false,"clock_changed":false,"reboot_requested":false,"job_binding_qualified":false,"same_process_samples_equal":equal,"samples":[first,second]});
|
||||
let data = serde_json::to_vec(&report)?;
|
||||
ensure!(data.len() <= 8192, "BOOT_PROBE_REPORT_LIMIT");
|
||||
let mut output = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(path.join("result.json"))?;
|
||||
output.write_all(&data)?;
|
||||
output.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
fn status(state: u32, error: u32) {
|
||||
let handle = STATUS.load(Ordering::SeqCst) as SERVICE_STATUS_HANDLE;
|
||||
if handle.is_null() {
|
||||
return;
|
||||
}
|
||||
let value = SERVICE_STATUS {
|
||||
dwServiceType: SERVICE_WIN32_OWN_PROCESS,
|
||||
dwCurrentState: state,
|
||||
dwControlsAccepted: 0,
|
||||
dwWin32ExitCode: error,
|
||||
dwServiceSpecificExitCode: 0,
|
||||
dwCheckPoint: 0,
|
||||
dwWaitHint: 10000,
|
||||
};
|
||||
unsafe {
|
||||
SetServiceStatus(handle, &value);
|
||||
}
|
||||
}
|
||||
unsafe extern "system" fn control(
|
||||
_: u32,
|
||||
_: u32,
|
||||
_: *mut core::ffi::c_void,
|
||||
_: *mut core::ffi::c_void,
|
||||
) -> u32 {
|
||||
0
|
||||
}
|
||||
unsafe extern "system" fn entry(_: u32, _: *mut *mut u16) {
|
||||
let name = wide(NAME);
|
||||
let handle =
|
||||
unsafe { RegisterServiceCtrlHandlerExW(name.as_ptr(), Some(control), ptr::null_mut()) };
|
||||
if handle.is_null() {
|
||||
return;
|
||||
}
|
||||
STATUS.store(handle as usize, Ordering::SeqCst);
|
||||
status(SERVICE_RUNNING, 0);
|
||||
let result = run();
|
||||
if result.is_ok() {
|
||||
std::thread::sleep(Duration::from_secs(2))
|
||||
};
|
||||
status(SERVICE_STOPPED, if result.is_ok() { 0 } else { 1066 });
|
||||
}
|
||||
pub fn main() -> Result<()> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
ensure!(
|
||||
args.len() == 3 && args[1] == "--service",
|
||||
"BOOT_PROBE_SERVICE_ONLY"
|
||||
);
|
||||
let case = uuid::Uuid::parse_str(&args[2])?;
|
||||
ensure!(!case.is_nil(), "BOOT_PROBE_CASE");
|
||||
CASE.set(case).unwrap();
|
||||
let mut name = wide(NAME);
|
||||
let table = [
|
||||
SERVICE_TABLE_ENTRYW {
|
||||
lpServiceName: name.as_mut_ptr(),
|
||||
lpServiceProc: Some(entry),
|
||||
},
|
||||
SERVICE_TABLE_ENTRYW {
|
||||
lpServiceName: ptr::null_mut(),
|
||||
lpServiceProc: None,
|
||||
},
|
||||
];
|
||||
ensure!(
|
||||
unsafe { StartServiceCtrlDispatcherW(table.as_ptr()) } != 0,
|
||||
"BOOT_PROBE_SCM_REQUIRED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
fn main() -> anyhow::Result<()> {
|
||||
service::main()
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
fn main() {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string(&native_boot::observe_candidate()).unwrap()
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Native negative peer controls and bounded SDK diagnostic, never an RMM job.
|
||||
|
||||
Only Root executes native phases after source review. Failed/ambiguous starts
|
||||
permit readback of the same case only; no token/key/private ledger data export.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
import client_bootstrap as cb
|
||||
import transport_acceptance as base
|
||||
import runtime_feature_upgrade as feature
|
||||
import system_helper_bootstrap as helper
|
||||
import auto_transport_acceptance as auto
|
||||
|
||||
require=cb.contract.require
|
||||
STATE=cb.EVIDENCE/'helper-peer-controls'
|
||||
NAME='RmmDiscoveryPeerControl'
|
||||
PARENT='RmmDiscoveryPeerParent'
|
||||
ROOT=r'C:\ProgramData\RustDiscoveryPeerControls'
|
||||
|
||||
# Shared by real Protect and read-only memory guards. Normalize the collection,
|
||||
# never an invalid individual SID. PS5 if {...} else {@()} assigns $null.
|
||||
ACL_CONSTRUCTORS=r'''function ControlIdentities([string[]]$readers,[string[]]$writers){
|
||||
if($null-eq$readers){$readers=@()};if($null-eq$writers){$writers=@()}
|
||||
$ids=@('S-1-5-18','S-1-5-32-544')+$readers+$writers
|
||||
foreach($id in $ids){if([string]::IsNullOrWhiteSpace($id)){throw 'EMPTY_CONTROL_SID'}}
|
||||
return $ids
|
||||
}
|
||||
function ControlRule([string]$id,[bool]$directory,[bool]$reader,[bool]$writer){
|
||||
[Security.AccessControl.InheritanceFlags]$inheritFlags=[Security.AccessControl.InheritanceFlags]::None
|
||||
if($directory){$inheritFlags=[Security.AccessControl.InheritanceFlags]::ContainerInherit-bor[Security.AccessControl.InheritanceFlags]::ObjectInherit}
|
||||
[Security.AccessControl.FileSystemRights]$rights=[Security.AccessControl.FileSystemRights]::FullControl
|
||||
if($writer){$rights=[Security.AccessControl.FileSystemRights]::Read-bor[Security.AccessControl.FileSystemRights]::Write}
|
||||
elseif($reader){$rights=[Security.AccessControl.FileSystemRights]::ReadAndExecute}
|
||||
$identity=[Security.Principal.SecurityIdentifier]::new($id)
|
||||
return [Security.AccessControl.FileSystemAccessRule]::new($identity,$rights,$inheritFlags,[Security.AccessControl.PropagationFlags]::None,[Security.AccessControl.AccessControlType]::Allow)
|
||||
}
|
||||
'''
|
||||
MEMORY_GUARD=ACL_CONSTRUCTORS+r'''$ErrorActionPreference='Stop'
|
||||
$rows=@()
|
||||
foreach($kind in @('root','controller','admin-leaf','writer-leaf')){
|
||||
$readers=if($kind-ceq'root'){@('S-1-5-80-1','S-1-5-80-2')}else{@()}
|
||||
$writers=if($kind-ceq'writer-leaf'){@('S-1-5-80-3')}else{@()}
|
||||
$ids=@(ControlIdentities $readers $writers);$expected=if($kind-ceq'root'){4}elseif($kind-ceq'writer-leaf'){3}else{2}
|
||||
if($ids.Count-ne$expected-or@($ids|Where-Object{[string]::IsNullOrWhiteSpace($_)}).Count){throw 'NORMALIZED_ROLE_COUNT'}
|
||||
$masks=@();foreach($id in $ids){$r=ControlRule $id ($kind-in@('root','controller')) ($id-in$readers) ($id-in$writers);$masks+=[int64]$r.FileSystemRights}
|
||||
if($masks[0]-ne2032127-or$masks[1]-ne2032127){throw 'EXACT_ADMIN_MASKS'}
|
||||
if($kind-ceq'root'-and($masks[2]-ne1179817-or$masks[3]-ne1179817)){throw 'EXACT_READER_MASKS'}
|
||||
if($kind-ceq'writer-leaf'-and$masks[2]-ne1180063){throw 'EXACT_LEAF_WRITER_MASK'}
|
||||
$rows+=@{case=$kind;constructor_count=$ids.Count;input_readers_null=($null-eq$readers);input_writers_null=($null-eq$writers);masks=$masks}
|
||||
}
|
||||
@{verified=$true;read_only=$true;filesystem_or_acl_mutations=$false;service_changes=$false;cases=$rows}|ConvertTo-Json -Depth 6 -Compress
|
||||
'''
|
||||
|
||||
PREPARE=r'''$ErrorActionPreference='Stop'
|
||||
$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||
if($p.sha -notmatch '^[a-f0-9]{64}$' -or $p.name -notin @('HelperPeerControls.exe','PeerControls.ps1')){throw 'Fixed control artifact'}
|
||||
$root='C:\ProgramData\RustDiscoveryPeerControls'
|
||||
$agent=(New-Object Security.Principal.NTAccount('NT SERVICE','RmmDiscoveryWindows')).Translate([Security.Principal.SecurityIdentifier]).Value
|
||||
$readers=@($agent,$p.control_sid)
|
||||
if($p.control_sid -notmatch '^S-1-5-80-([0-9]+-){4}[0-9]+$'){throw 'Fixed control SID'}
|
||||
function Check($path){$i=Get-Item -LiteralPath $path -Force;if($i.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Control reparse'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Control owner'};foreach($r in $a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($r.AccessControlType-ne'Allow'){throw 'Control deny'};if($r.IdentityReference.Value-in@('S-1-5-18','S-1-5-32-544')){continue};if($r.IdentityReference.Value-notin$readers-or([int64]$r.FileSystemRights-band(-bnot 1179817))){throw 'Control reader'}}}
|
||||
if(!(Test-Path -LiteralPath $root)){
|
||||
New-Item -ItemType Directory -Path $root|Out-Null;$a=New-Object Security.AccessControl.DirectorySecurity;$a.SetAccessRuleProtection($true,$false);$a.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')))
|
||||
foreach($id in @('S-1-5-18','S-1-5-32-544')+$readers){$right=if($id-in$readers){'ReadAndExecute'}else{'FullControl'};$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($id)),$right,'ContainerInherit,ObjectInherit','None','Allow')))};Set-Acl -LiteralPath $root -AclObject $a
|
||||
}
|
||||
Check $root;$version=Join-Path $root $p.sha;if(!(Test-Path -LiteralPath $version)){New-Item -ItemType Directory -Path $version|Out-Null};Check $version
|
||||
$file=Join-Path $version $p.name;$exists=Test-Path -LiteralPath $file;if($exists){Check $file;if((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.sha){throw 'Immutable control artifact'}}
|
||||
@{exists=$exists;sha=$p.sha}|ConvertTo-Json -Compress
|
||||
'''
|
||||
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'}
|
||||
$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
|
||||
$controlSid=$p.control_sid
|
||||
function Hash($path){return (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}
|
||||
function WriteNew($path,$data){$b=[Text.Encoding]::UTF8.GetBytes(($data|ConvertTo-Json -Depth 24 -Compress));$f=[IO.File]::Open($path,'CreateNew','Write','Read');try{$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
|
||||
function Check($path,[bool]$directory,[string[]]$readers,[string[]]$writers){
|
||||
$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$directory-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Fixed regular control path'}
|
||||
$a=Get-Acl -LiteralPath $path;$owner=$a.GetOwner([Security.Principal.SecurityIdentifier]).Value
|
||||
if($owner-notin@('S-1-5-18','S-1-5-32-544')){throw 'SYSTEM/Admin report ownership required'}
|
||||
$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty control DACL'}
|
||||
foreach($r in $rules){
|
||||
$id=$r.IdentityReference.Value;$mask=[int64]$r.FileSystemRights
|
||||
if($r.AccessControlType-ne'Allow'){throw 'Unexpected control ACE'}
|
||||
if($id-in@('S-1-5-18','S-1-5-32-544')){if($mask-ne2032127){throw 'Exact controller administrative rights'}}
|
||||
elseif($id-in$writers){if($mask-ne1180063-or$directory){throw 'Writer only on fixed precreated output leaf'}}
|
||||
elseif($id-in$readers){if($mask-band(-bnot 1179817)){throw 'Reader-only role'}}
|
||||
else{throw 'Foreign control/report principal'}
|
||||
}
|
||||
}
|
||||
function Protect($path,[bool]$directory,[string[]]$readers,[string[]]$writers){
|
||||
$a=if($directory){[Security.AccessControl.DirectorySecurity]::new()}else{[Security.AccessControl.FileSecurity]::new()};$a.SetAccessRuleProtection($true,$false);$a.SetOwner([Security.Principal.SecurityIdentifier]::new('S-1-5-32-544'))
|
||||
foreach($id in (ControlIdentities $readers $writers)){
|
||||
$rule=ControlRule $id $directory ($id-in$readers) ($id-in$writers)
|
||||
$a.AddAccessRule($rule)
|
||||
}
|
||||
Set-Acl -LiteralPath $path -AclObject $a;Check $path $directory $readers $writers
|
||||
}
|
||||
function ReportPath($name){
|
||||
if($name-in@('admin-token','admin-result')){return Join-Path (Join-Path $case 'admin') ($name+'.json')}
|
||||
if($name-in@('service-token','service-result')){return Join-Path (Join-Path $case 'service') ($name+'.json')}
|
||||
if($name-in@('child-token','child-sdk-prechecks','child-result')){return Join-Path (Join-Path $case 'child') ($name+'.json')}
|
||||
return Join-Path $controller ($name+'.json')
|
||||
}
|
||||
function Metadata($path){$i=Get-Item -LiteralPath $path -Force;if($i.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Existing component reparse'};return [ordered]@{name=$i.Name;length=$i.Length;created=$i.CreationTimeUtc.Ticks;written=$i.LastWriteTimeUtc.Ticks;sddl=(Get-Acl -LiteralPath $path).Sddl}}
|
||||
function Baseline {
|
||||
$services=[ordered]@{}
|
||||
foreach($pair in @(@($agentName,$p.agent_pid,'NT AUTHORITY\LocalService',$p.agent_binary,'C:\Program Files\RustDiscovery\rmm-agent-windows.exe'),@($helperName,$p.helper_pid,'LocalSystem',$p.helper_binary,'C:\Program Files\RustDiscovery\rmm-helper-windows.exe'))){
|
||||
$s=Get-CimInstance Win32_Service -Filter ("Name='"+$pair[0]+"'") -OperationTimeoutSec 10
|
||||
if($s.State-cne'Running'-or$s.ProcessId-ne$pair[1]-or$s.StartName-cne$pair[2]-or(Hash $pair[4])-cne$pair[3]){throw 'Original current agent/helper identity'}
|
||||
$process=Get-CimInstance Win32_Process -Filter ('ProcessId='+$s.ProcessId) -OperationTimeoutSec 10
|
||||
$owner=(Invoke-CimMethod -InputObject $process -MethodName GetOwnerSid -OperationTimeoutSec 10).Sid;$expected=if($pair[0]-ceq$agentName){'S-1-5-19'}else{'S-1-5-18'}
|
||||
if($owner-cne$expected-or$process.ExecutablePath-cne$pair[4]){throw 'Original running process identity'}
|
||||
$services[$pair[0]]=[ordered]@{pid=$s.ProcessId;path=$s.PathName;start_mode=$s.StartMode;account=$s.StartName;owner_sid=$owner;creation_filetime=$process.CreationDate.ToUniversalTime().ToFileTimeUtc();binary_sha256=(Hash $pair[4])}
|
||||
}
|
||||
$settings='C:\ProgramData\RustDiscoverySystem\helper.json';$pin='C:\ProgramData\RustDiscoverySystem\agent-pin.json'
|
||||
if((Hash $settings)-cne$p.policy-or(Hash $pin)-cne$p.pin_sha256){throw 'Original passive helper public pin'}
|
||||
$cfg=Get-Content -LiteralPath $settings -Raw|ConvertFrom-Json
|
||||
if($cfg.enable_effects-ne$false-or$cfg.allow_reboot-ne$false-or@($cfg.allowed_services).Count-ne0){throw 'Empty passive policy only'}
|
||||
$files=@(Get-ChildItem -LiteralPath 'C:\ProgramData\RustDiscoverySystem\state' -File -Force|Sort-Object Name|ForEach-Object{Metadata $_.FullName})
|
||||
# Metadata only: never read/hash/copy private ledger or key contents.
|
||||
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}
|
||||
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'}
|
||||
$before=Baseline;New-Item -ItemType Directory -Path $case|Out-Null;Protect $case $true @($agentSid,$controlSid) @()
|
||||
foreach($dir in @('controller','admin','service','child')){
|
||||
$path=Join-Path $case $dir;New-Item -ItemType Directory -Path $path|Out-Null
|
||||
$readers=if($dir-ceq'service'){@($controlSid)}elseif($dir-ceq'child'){@($agentSid)}else{@()}
|
||||
Protect $path $true $readers @()
|
||||
}
|
||||
WriteNew (Join-Path $controller 'intent.json') @{payload=$p;before=$before;no_jobs=$true}
|
||||
# Precreate fixed leaves before ANY actor starts. Their owner stays Admin;
|
||||
# no actor may create files in a report directory or acquire owner WRITE_DAC.
|
||||
foreach($report in @('admin-token','admin-result','service-token','service-result','child-token','child-sdk-prechecks','child-result')){
|
||||
$path=ReportPath $report;$f=[IO.File]::Open($path,'CreateNew','Write','Read');$f.Dispose()
|
||||
$writers=if($report.StartsWith('service-')){@($controlSid)}elseif($report.StartsWith('child-')){@($agentSid)}else{@()}
|
||||
Protect $path $false @() $writers
|
||||
}
|
||||
$pin=Get-Content -LiteralPath 'C:\ProgramData\RustDiscoverySystem\agent-pin.json' -Raw|ConvertFrom-Json
|
||||
WriteNew (Join-Path $case 'input.json') @{schema_version=1;case_id=$p.id;pin=$pin;expected_agent_pid=$p.agent_pid;expected_helper_pid=$p.helper_pid;expected_agent_creation=$before.services.RmmDiscoveryWindows.creation_filetime;control_binary_sha256=$p.binary};Protect (Join-Path $case 'input.json') $false @($agentSid,$controlSid) @()
|
||||
@{prepared=$true;baseline=$before;no_jobs=$true}|ConvertTo-Json -Depth 24 -Compress;exit 0
|
||||
}
|
||||
$intent=ReadIntent;Same $intent.before (Baseline)
|
||||
if($p.action-ceq'admin'){
|
||||
WriteNew (Join-Path $controller 'admin-start-intent.json') @{once=$true;raw_probe_only=$true}
|
||||
$si=New-Object Diagnostics.ProcessStartInfo;$si.FileName=$exe;$si.Arguments='--admin '+$p.id;$si.UseShellExecute=$false;$si.CreateNoWindow=$true;$si.RedirectStandardError=$true;$si.RedirectStandardOutput=$true
|
||||
$proc=New-Object Diagnostics.Process;$proc.StartInfo=$si
|
||||
if(!$proc.Start()){throw 'Own administrator probe start'}
|
||||
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
|
||||
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}
|
||||
else{New-Service -Name $serviceName -BinaryPathName $command -StartupType Manual|Out-Null}
|
||||
& "$env:WINDIR\System32\sc.exe" sidtype $serviceName unrestricted|Out-Null;if($LASTEXITCODE-ne0){throw 'Own control service SID'}
|
||||
Start-Service -Name $serviceName
|
||||
}
|
||||
$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
|
||||
$s=Get-CimInstance Win32_Service -Filter ("Name='"+$serviceName+"'") -OperationTimeoutSec 10
|
||||
if($s){
|
||||
$expected=if($kind-ceq'service'){'NT AUTHORITY\LocalService'}else{'LocalSystem'}
|
||||
if($s.PathName-cne$command-or$s.StartName-cne$expected-or$s.StartMode-cne'Manual'){throw 'Exact own control service only'}
|
||||
while($s.State-cne'Stopped'-and[DateTime]::UtcNow-lt$deadline){Start-Sleep -Milliseconds 100;$s=Get-CimInstance Win32_Service -Filter ("Name='"+$serviceName+"'") -OperationTimeoutSec 10}
|
||||
if($p.action-in@('service','parent','cleanup')){
|
||||
if($s.State-cne'Stopped'){throw 'Own control still active: retain and readback only'}
|
||||
$cleanup=Join-Path $controller ($kind+'-cleanup-intent.json')
|
||||
if(!(Test-Path -LiteralPath $cleanup)){WriteNew $cleanup @{service=$serviceName;command=$command;remove_only_own_stopped_service=$true}}
|
||||
else{Check $cleanup $false @() @();$c=Get-Content -LiteralPath $cleanup -Raw|ConvertFrom-Json;if($c.service-cne$serviceName-or$c.command-cne$command){throw 'Retained cleanup intent'}}
|
||||
& "$env:WINDIR\System32\sc.exe" delete $serviceName|Out-Null;if($LASTEXITCODE-ne0){throw 'Exact stopped own service cleanup'}
|
||||
}
|
||||
}
|
||||
}
|
||||
Same $intent.before (Baseline)
|
||||
$reports=[ordered]@{};$reportTrust=[ordered]@{}
|
||||
foreach($name in @('admin-token','admin-result','service-token','service-result','parent-token','parent-result','child-create-intent','child-started','child-token','child-sdk-prechecks','child-result')){
|
||||
$path=ReportPath $name;$reports[$name]=$null
|
||||
$writers=if($name-in@('service-token','service-result')){@($controlSid)}elseif($name-in@('child-token','child-sdk-prechecks','child-result')){@($agentSid)}else{@()}
|
||||
$readers=if($name-in@('service-token','service-result')){@($controlSid)}elseif($name-in@('child-token','child-sdk-prechecks','child-result')){@($agentSid)}else{@()}
|
||||
Check ([IO.Path]::GetDirectoryName($path)) $true $readers @()
|
||||
if(Test-Path -LiteralPath $path){Check $path $false @() $writers;$i=Get-Item -LiteralPath $path -Force;if($i.Length-gt8192){throw 'Bounded own report'};if($i.Length-gt0){$reports[$name]=Get-Content -LiteralPath $path -Raw|ConvertFrom-Json;$reportTrust[$name]=@{owner_sid=(Get-Acl -LiteralPath $path).GetOwner([Security.Principal.SecurityIdentifier]).Value;allowed_actor_writers=$writers;provenance=$(if($name-in@('child-token','child-sdk-prechecks','child-result')){'agent_token_assertion'}elseif($name-in@('service-token','service-result')){'control_service_assertion'}else{'system_or_bootstrap_administrator'})}}}
|
||||
}
|
||||
@{readback=$true;id=$p.id;reports=$reports;report_trust=$reportTrust;writer_binding_checked=$true;original_preserved=$true;own_services_removed=(!(Get-Service -Name 'RmmDiscoveryPeerControl' -ErrorAction SilentlyContinue)-and!(Get-Service -Name 'RmmDiscoveryPeerParent' -ErrorAction SilentlyContinue));no_jobs=$true;no_private_data_read=$true}|ConvertTo-Json -Depth 24 -Compress
|
||||
'''
|
||||
SCRIPT=ACL_CONSTRUCTORS+SCRIPT
|
||||
LAUNCH=base.LAUNCH_SCRIPT.replace('TransportAcceptance.ps1','PeerControls.ps1').replace('RmmTransportPayload','RmmPeerControlPayload').replace('RustDiscoveryBootstrap','RustDiscoveryPeerControls')
|
||||
|
||||
|
||||
def sources():
|
||||
value=feature.source_files();value['deploy/windows/helper_peer_controls.py']=helper.sha(__file__)
|
||||
return dict(sorted(value.items()))
|
||||
|
||||
|
||||
def build():
|
||||
os.umask(0o077);helper.private_dir(STATE);folder=STATE/('build-'+str(uuid.uuid4()));folder.mkdir(mode=0o700)
|
||||
before=sources();helper.store(folder,'source-before.json',before)
|
||||
target=cb.ROOT/'devstate/windows-peer-controls-target';target.mkdir(mode=0o700,parents=True,exist_ok=True)
|
||||
command='cargo clippy --locked --offline --target '+feature.TARGET+' -p rmm-agent-windows --features system-helper --all-targets -- -D warnings && cargo build --locked --offline --release --target '+feature.TARGET+' -p rmm-agent-windows --features system-helper --example helper_peer_controls'
|
||||
feature.previous.command(['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,size=512m','-v',str(cb.ROOT)+':/src:ro','-v',str(target)+':/target','-e','CARGO_TARGET_DIR=/target','--entrypoint','sh',feature.IMAGE,'-c',command])
|
||||
require(before==sources(),'control source unchanged during build')
|
||||
path=folder/'HelperPeerControls.exe';shutil.copyfile(target/feature.TARGET/'release/examples/helper_peer_controls.exe',path);path.chmod(0o600)
|
||||
manifest=dict(schema_version=1,type='rmm.windows.helper-peer-controls',source_files=before,system_helper_feature=True,artifact=dict(path=str(path.resolve()),sha256=helper.sha(path)),cross_clippy_D_warnings=True,all_targets_checked=True,release_build=True,native_tested=False,no_jobs=True)
|
||||
helper.store(folder,'manifest.json',manifest);print(json.dumps({'manifest':str((folder/'manifest.json').resolve()),'native_tested':False}))
|
||||
|
||||
|
||||
def stage(path,name):
|
||||
digest=helper.sha(path);payload=dict(sha=digest,name=name,control_sid=helper.service_sid(NAME));exists=cb.powershell(PREPARE,payload)
|
||||
if not exists['exists']:
|
||||
access=cb.contract.protected_json(cb.ROOT/'credentials/windows-dev-access.json')['ssh_prefix'];args=['sftp']+[p for p in access[1:-1] if p!='-T']+['-b','-',access[-1]]
|
||||
target='/C:/ProgramData/RustDiscoveryPeerControls/'+digest+'/'+name
|
||||
transferred=subprocess.run(args,input=('put '+json.dumps(str(path.resolve()))+' '+json.dumps(target)+'\n').encode(),capture_output=True,timeout=120)
|
||||
require(transferred.returncode==0 and cb.powershell(PREPARE,payload)['exists'],'exact staged control artifact')
|
||||
return digest
|
||||
|
||||
|
||||
def prepare(manifest_path,helper_case):
|
||||
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()
|
||||
require(str(uuid.UUID(helper_case))==helper_case,'exact existing passive helper case')
|
||||
helper_intent=cb.contract.protected_json(cb.EVIDENCE/'system-helper-bootstrap'/helper_case/'intent.json');profile=helper_intent['payload']
|
||||
require(profile['agent_sha256']==index['binary_sha256'] and profile['helper_sha256']==helper.HELPER_SHA,'exact retained current helper/agent association')
|
||||
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'])
|
||||
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})
|
||||
stage(Path(manifest['artifact']['path']),'HelperPeerControls.exe');stage(source,'PeerControls.ps1')
|
||||
before=dict(counts=auto.scopes(),flags=auto.status());helper.store(folder,'server-before.json',before)
|
||||
report=cb.powershell(LAUNCH,{'sha256':payload['source'],'payload':dict(payload,action='prepare')},timeout=90,remote_signed=True)
|
||||
helper.store(folder,'prepared.json',report);print(json.dumps({'id':ident,'prepared':True,'no_jobs':True}))
|
||||
|
||||
|
||||
def run(ident,action):
|
||||
require(str(uuid.UUID(ident))==ident,'same canonical control case')
|
||||
folder=STATE/ident;intent=cb.contract.protected_json(folder/'intent.json');payload=intent['payload']
|
||||
require(helper.sha(__file__)==intent['source_file_sha256'] and payload['source']==hashlib.sha256(SCRIPT.encode()).hexdigest(),'exact prepared source; no case rebase')
|
||||
require(helper.sha(intent['manifest_path'])==intent['manifest_sha256'] and helper.sha(intent['runtime_index']['path'])==intent['runtime_index']['sha256'],'retained control manifest and current runtime index')
|
||||
cb.contract.protected_json(folder/'prepared.json')
|
||||
if action!='readback':helper.store(folder,action+'-attempt.json',{'once':True,'probe_only':True})
|
||||
report=cb.powershell(LAUNCH,{'sha256':payload['source'],'payload':dict(payload,action=action)},timeout=90,remote_signed=True)
|
||||
helper.store(folder,action+'-readback-'+str(uuid.uuid4())+'.json',report)
|
||||
before=cb.contract.protected_json(folder/'server-before.json');require(auto.scopes()==before['counts'] and auto.status()==before['flags'],'all Windows/Linux job counts and server policy flags unchanged')
|
||||
if action=='readback':
|
||||
print(json.dumps({'id':ident,'read_only':True,'native':report,'no_jobs':True}));return
|
||||
result=summarize(report,payload,ident)
|
||||
helper.store(folder,'result-'+str(uuid.uuid4())+'.json',result);print(json.dumps(result))
|
||||
|
||||
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':{}}
|
||||
for kind in ('admin','service'):
|
||||
value=report['reports'].get(kind+'-result')
|
||||
if value:
|
||||
require(value['pipe']['sdk_self_check_used'] is False,'raw peer test, never SDK self-refusal')
|
||||
require(value.get('case_id')==ident and value.get('mode')==kind and value.get('no_jobs') is True and value.get('read_only') is True,'exact native control receipt')
|
||||
if kind=='admin':require(value['token']['administrator_enabled'] is True and value['token']['user_sid'] not in ('S-1-5-18','S-1-5-19'),'actual bootstrap administrator')
|
||||
if kind=='service':require(value['token']['user_sid']=='S-1-5-19' and value['token']['control_service_sid_enabled'] is True and value['token']['agent_service_sid_enabled'] is False,'actual distinct LocalService service-SID')
|
||||
error=value['pipe'].get('win32_error');opened=value['pipe'].get('opened')
|
||||
require(value['pipe']['rejected'] is True and ((opened is False and error==5) or (opened is True and error in (109,232,233) and value['pipe'].get('actual_server_pid')==payload['helper_pid'])),'BUSY/timeout/response is inconclusive, never claim a denied peer')
|
||||
result['controls'][kind]={'verified_negative':True,'pipe':value['pipe'],'token':value['token']}
|
||||
if report['reports'].get('child-result'):
|
||||
value=report['reports']['child-result'];require(value['token']['user_sid']=='S-1-5-19' and value['token']['agent_service_sid_enabled'] is True and value['token']['actual_process_id']!=payload['agent_pid'],'actual wrong-PID/image child with Agent primary identity')
|
||||
require(value['pipe'].get('received_reply') is False,'impostor unexpectedly received a helper reply')
|
||||
result['controls']['agent_token_child']={'diagnostic_only':True,'report':value,'parent':report['reports'].get('parent-result'),'prechecks':report['reports'].get('child-sdk-prechecks')}
|
||||
return result
|
||||
|
||||
|
||||
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()
|
||||
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)
|
||||
else:require(a.id is not None,'existing explicit control case required');run(a.id,a.action)
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Only local fixtures for peer-control reporting and exactly-once starts."""
|
||||
import copy
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import uuid
|
||||
|
||||
import helper_peer_controls as control
|
||||
|
||||
|
||||
class PeerControlGuards(unittest.TestCase):
|
||||
def fixture(self):
|
||||
ident=str(uuid.uuid4());payload={'helper_pid':6240,'agent_pid':5140}
|
||||
value=dict(schema_version=1,case_id=ident,mode='service',token={'user_sid':'S-1-5-19','control_service_sid_enabled':True,'agent_service_sid_enabled':False},pipe={'sdk_self_check_used':False,'rejected':True,'opened':False,'win32_error':5},no_jobs=True,read_only=True)
|
||||
report={'writer_binding_checked':True,'original_preserved':True,'own_services_removed':True,'reports':{'service-result':value}}
|
||||
return report,payload,ident
|
||||
|
||||
def test_busy_timeout_or_sdk_self_refusal_is_never_server_peer_proof(self):
|
||||
report,payload,ident=self.fixture()
|
||||
self.assertTrue(control.summarize(report,payload,ident)['controls']['service']['verified_negative'])
|
||||
unbound=copy.deepcopy(report);unbound['writer_binding_checked']=False
|
||||
with self.assertRaises(Exception):control.summarize(unbound,payload,ident)
|
||||
for field,value in [('win32_error',231),('win32_error',1460),('sdk_self_check_used',True),('rejected',False)]:
|
||||
bad=copy.deepcopy(report);bad['reports']['service-result']['pipe'][field]=value
|
||||
with self.assertRaises(Exception,msg=field):control.summarize(bad,payload,ident)
|
||||
bad=copy.deepcopy(report);bad['reports']['service-result']['token']['agent_service_sid_enabled']=True
|
||||
with self.assertRaises(Exception):control.summarize(bad,payload,ident)
|
||||
|
||||
def test_raw_closed_pipe_must_name_the_original_helper_process(self):
|
||||
report,payload,ident=self.fixture();pipe=report['reports']['service-result']['pipe'];pipe.update(opened=True,win32_error=109,actual_server_pid=6240)
|
||||
self.assertTrue(control.summarize(report,payload,ident)['controls']['service']['verified_negative'])
|
||||
pipe['actual_server_pid']=999
|
||||
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)
|
||||
manifest=control.helper.store(state,'manifest.json',{'fixture':True});index=control.helper.store(state,'index.json',{'fixture':True})
|
||||
intent={'payload':{'id':ident,'source':hashlib.sha256(control.SCRIPT.encode()).hexdigest()},'source_file_sha256':control.helper.sha(control.__file__),'manifest_path':str(manifest),'manifest_sha256':control.helper.sha(manifest),'runtime_index':{'path':str(index),'sha256':control.helper.sha(index)}}
|
||||
control.helper.store(folder,'intent.json',intent);control.helper.store(folder,'prepared.json',{'prepared':True})
|
||||
with patch.object(control,'STATE',state),patch.object(control.cb,'powershell',side_effect=RuntimeError('lost reply')) as rpc:
|
||||
with self.assertRaisesRegex(RuntimeError,'lost reply'):control.run(ident,'service')
|
||||
with self.assertRaises(FileExistsError):control.run(ident,'service')
|
||||
self.assertEqual(rpc.call_count,1)
|
||||
|
||||
def test_remote_readback_has_no_cleanup_mutation_and_explicit_cleanup_is_separate(self):
|
||||
# The complete remote script is parsed separately. This guard fixes the
|
||||
# security-critical mutation dispatch: readback must not enter cleanup.
|
||||
self.assertIn("if($p.action-in@('service','parent','cleanup')){",control.SCRIPT)
|
||||
self.assertNotIn("if($p.action-in@('service','parent','cleanup','readback'))",control.SCRIPT)
|
||||
self.assertIn("Protect $case $true @($agentSid,$controlSid) @()",control.SCRIPT)
|
||||
self.assertIn("if($mask-ne1180063-or$directory)",control.SCRIPT)
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
Reference in New Issue
Block a user