From 79651d3ccc987457df0c1070289e3f599ead90f8 Mon Sep 17 00:00:00 2001 From: Kevin Janssen Date: Sat, 14 Nov 2026 04:54:20 +0100 Subject: [PATCH] Verify Windows ACL regression fix and native denied administrator probe --- .../examples/helper_peer_controls.rs | 976 ++++++++++++++++++ crates/agent-windows/src/native_boot.rs | 170 +++ deploy/windows/BootIdentifierProbe.ps1 | 71 ++ deploy/windows/boot_probe.rs | 195 ++++ deploy/windows/helper_peer_controls.py | 299 ++++++ deploy/windows/test_helper_peer_controls.py | 57 + docs/handover.md | 10 + docs/windows-boot-identity.md | 112 ++ docs/windows-helper-peer-controls.md | 155 +++ 9 files changed, 2045 insertions(+) create mode 100644 crates/agent-windows/examples/helper_peer_controls.rs create mode 100644 crates/agent-windows/src/native_boot.rs create mode 100644 deploy/windows/BootIdentifierProbe.ps1 create mode 100644 deploy/windows/boot_probe.rs create mode 100644 deploy/windows/helper_peer_controls.py create mode 100644 deploy/windows/test_helper_peer_controls.py create mode 100644 docs/windows-boot-identity.md create mode 100644 docs/windows-helper-peer-controls.md diff --git a/crates/agent-windows/examples/helper_peer_controls.rs b/crates/agent-windows/examples/helper_peer_controls.rs new file mode 100644 index 0000000..3cab823 --- /dev/null +++ b/crates/agent-windows/examples/helper_peer_controls.rs @@ -0,0 +1,976 @@ +//! Negative, read-only raw Probe clients. Never SDK self-refusal as server proof. +//! The permanent services, their tokens/configuration and private state stay intact. +#[cfg(all(windows, feature = "system-helper"))] +mod platform { + use anyhow::{Result, ensure}; + use rmm_agent_windows::helper_ipc as ipc; + use serde::Deserialize; + use serde_json::json; + use std::{ + fs::OpenOptions, + io::{Read, Write}, + mem::{size_of, zeroed}, + os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}, + path::PathBuf, + ptr, + sync::{ + OnceLock, + atomic::{AtomicUsize, Ordering}, + }, + time::{Duration, Instant}, + }; + use windows_sys::Win32::{ + Foundation::*, + Security::{Authorization::ConvertSidToStringSidW, *}, + Storage::FileSystem::*, + System::{ + IO::*, JobObjects::*, Pipes::GetNamedPipeServerProcessId, Services::*, Threading::*, + }, + }; + const NAME: &str = "RmmDiscoveryPeerControl"; + // winnt.h TOKEN_GROUPS attributes; avoid adding Cargo feature dependencies. + const SE_GROUP_ENABLED: u32 = 0x4; + const SE_GROUP_USE_FOR_DENY_ONLY: u32 = 0x10; + const PARENT_NAME: &str = "RmmDiscoveryPeerParent"; + const ROOT: &str = r"C:\ProgramData\RustDiscoveryPeerControls"; + static CASE: OnceLock = OnceLock::new(); + static IS_PARENT: OnceLock = OnceLock::new(); + static STATUS: AtomicUsize = AtomicUsize::new(0); + fn wide(s: &str) -> Vec { + s.encode_utf16().chain(Some(0)).collect() + } + fn owned(handle: HANDLE) -> Result { + ensure!( + !handle.is_null() && handle != INVALID_HANDLE_VALUE, + "CONTROL_HANDLE" + ); + Ok(unsafe { OwnedHandle::from_raw_handle(handle) }) + } + fn sid_text(sid: PSID) -> Result { + let mut text = ptr::null_mut(); + ensure!( + unsafe { ConvertSidToStringSidW(sid, &mut text) } != 0, + "CONTROL_SID" + ); + let result = (|| { + let mut n = 0; + while unsafe { *text.add(n) } != 0 { + n += 1; + ensure!(n <= 256, "CONTROL_SID_LIMIT"); + } + Ok(String::from_utf16(unsafe { + std::slice::from_raw_parts(text, n) + })?) + })(); + unsafe { + LocalFree(text.cast()); + } + result + } + fn token_information(token: HANDLE, class: TOKEN_INFORMATION_CLASS) -> Result> { + let mut size = 0; + unsafe { + GetTokenInformation(token, class, ptr::null_mut(), 0, &mut size); + } + ensure!(size > 0 && size <= 65536, "CONTROL_TOKEN_LIMIT"); + let mut bytes = vec![0usize; (size as usize).div_ceil(size_of::())]; + ensure!( + unsafe { + GetTokenInformation(token, class, bytes.as_mut_ptr().cast(), size, &mut size) + } != 0, + "CONTROL_TOKEN_QUERY" + ); + Ok(bytes) + } + fn token(mode: &str) -> Result { + let mut raw = ptr::null_mut(); + ensure!( + unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut raw) } != 0, + "CONTROL_OWN_TOKEN" + ); + let handle = owned(raw)?; + let user = token_information(handle.as_raw_handle(), TokenUser)?; + let user = unsafe { &*user.as_ptr().cast::() }; + let user_sid = sid_text(user.User.Sid)?; + let groups = token_information(handle.as_raw_handle(), TokenGroups)?; + let groups_buffer_bytes = groups.len() * size_of::(); + let groups = unsafe { &*groups.as_ptr().cast::() }; + ensure!( + groups.GroupCount <= 1024 + && std::mem::offset_of!(TOKEN_GROUPS, Groups) + + groups.GroupCount as usize * size_of::() + <= groups_buffer_bytes, + "CONTROL_GROUP_LIMIT" + ); + let values = unsafe { + std::slice::from_raw_parts(groups.Groups.as_ptr(), groups.GroupCount as usize) + }; + let control_sid = if mode == "service" { + ipc::service_sid(NAME)? + } else { + String::new() + }; + let agent_sid = ipc::service_sid(rmm_agent_windows::SERVICE_NAME)?; + let enabled = |sid: &str| -> Result { + for value in values { + if value.Attributes & SE_GROUP_ENABLED != 0 + && value.Attributes & SE_GROUP_USE_FOR_DENY_ONLY == 0 + && sid_text(value.Sid)? == sid + { + return Ok(true); + } + } + Ok(false) + }; + let control = enabled(&control_sid)?; + let agent = enabled(&agent_sid)?; + let admin = enabled("S-1-5-32-544")?; + if mode == "service" { + rmm_agent_windows::native::require_local_service()?; + ensure!( + user_sid == "S-1-5-19" && control && !agent && !admin, + "CONTROL_DISTINCT_LOCAL_SERVICE_SID" + ); + } else if mode == "child" { + rmm_agent_windows::native::require_local_service()?; + ensure!( + user_sid == "S-1-5-19" && agent && !control && !admin, + "CONTROL_DUPLICATED_AGENT_IDENTITY" + ); + } else if mode == "parent" { + ensure!( + user_sid == "S-1-5-18" && enabled(&ipc::service_sid(PARENT_NAME)?)?, + "CONTROL_OWN_SYSTEM_PARENT" + ); + } else { + ensure!( + admin && user_sid != "S-1-5-19" && user_sid != "S-1-5-18" && !agent, + "CONTROL_BOOTSTRAP_ADMIN_ONLY" + ); + } + Ok( + json!({"user_sid":user_sid,"administrator_enabled":admin,"control_service_sid":control_sid,"control_service_sid_enabled":control,"agent_service_sid_enabled":agent,"parent_service_sid":if mode=="parent"{Some(ipc::service_sid(PARENT_NAME)?)}else{None},"parent_service_sid_enabled":mode=="parent","actual_process_id":std::process::id()}), + ) + } + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Input { + schema_version: u32, + case_id: uuid::Uuid, + pin: ipc::Pin, + expected_agent_pid: u32, + expected_helper_pid: u32, + expected_agent_creation: u64, + control_binary_sha256: String, + } + fn read_input(case: uuid::Uuid) -> Result { + let root = PathBuf::from(ROOT).join(case.to_string()); + let path = root.join("input.json"); + for path in [&root, &path] { + let metadata = std::fs::symlink_metadata(path)?; + ensure!(!metadata.is_symlink(), "CONTROL_INPUT_REPARSE"); + } + let mut file = std::fs::File::open(path)?; + ensure!(file.metadata()?.len() <= 32768, "CONTROL_INPUT_SIZE"); + let mut bytes = Vec::new(); + Read::by_ref(&mut file) + .take(32769) + .read_to_end(&mut bytes)?; + ensure!(bytes.len() <= 32768, "CONTROL_INPUT_SIZE"); + let value: Input = serde_json::from_slice(&bytes)?; + value.pin.validate()?; + let current = std::env::current_exe()?; + ensure!( + current + == PathBuf::from(ROOT) + .join(&value.control_binary_sha256) + .join("HelperPeerControls.exe"), + "CONTROL_OWN_FIXED_IMAGE" + ); + let mut image = std::fs::File::open(current)?; + ensure!( + image.metadata()?.len() <= 128 * 1024 * 1024, + "CONTROL_IMAGE_LIMIT" + ); + use sha2::Digest; + let mut hash = sha2::Sha256::new(); + let mut buffer = [0u8; 65536]; + loop { + let count = image.read(&mut buffer)?; + if count == 0 { + break; + } + hash.update(&buffer[..count]); + } + let hash: String = hash.finalize().iter().map(|b| format!("{b:02x}")).collect(); + ensure!(hash == value.control_binary_sha256, "CONTROL_IMAGE_HASH"); + ensure!( + value.schema_version == 1 + && value.case_id == case + && value.expected_agent_pid > 0 + && value.expected_helper_pid > 0, + "CONTROL_INPUT_BINDING" + ); + Ok(value) + } + fn save(case: uuid::Uuid, name: &str, value: &serde_json::Value) -> Result<()> { + let bytes = serde_json::to_vec(value)?; + ensure!(bytes.len() <= 8192, "CONTROL_REPORT_LIMIT"); + let root = PathBuf::from(ROOT).join(case.to_string()); + let (folder, writer) = match name { + "admin-token.json" | "admin-result.json" => ("admin", None), + "service-token.json" | "service-result.json" => { + ("service", Some(ipc::service_sid(NAME)?)) + } + "child-token.json" | "child-sdk-prechecks.json" | "child-result.json" => ( + "child", + Some(ipc::service_sid(rmm_agent_windows::SERVICE_NAME)?), + ), + "parent-token.json" + | "parent-result.json" + | "child-create-intent.json" + | "child-started.json" => ("controller", None), + _ => anyhow::bail!("CONTROL_FIXED_REPORT_NAME"), + }; + let directory = root.join(folder); + let roles: Vec = writer.into_iter().collect(); + // Actor directories are read-only. Bootstrap precreates just the fixed + // writable leaves with SYSTEM/Admin ownership, so SID19 cannot gain + // owner-implied WRITE_DAC or forge a different actor's receipts. + let _parent = ipc::PinnedFile::open(&directory, true, &roles, &[], false)?; + let path = directory.join(name); + if folder != "controller" { + let mut output = ipc::PinnedFile::open(&path, false, &[], &roles, true)?; + ensure!( + output.file.metadata()?.len() == 0, + "CONTROL_REPORT_ALREADY_WRITTEN" + ); + output.file.write_all(&bytes)?; + output.file.sync_all()?; + output.check()?; + } else { + let mut output = OpenOptions::new().create_new(true).write(true).open(path)?; + output.write_all(&bytes)?; + output.sync_all()?; + } + Ok(()) + } + struct Io { + event: OwnedHandle, + overlapped: OVERLAPPED, + } + impl Io { + fn new() -> Result { + let event = owned(unsafe { CreateEventW(ptr::null(), 1, 0, ptr::null()) })?; + let mut overlapped: OVERLAPPED = unsafe { zeroed() }; + overlapped.hEvent = event.as_raw_handle(); + Ok(Self { event, overlapped }) + } + fn wait(&mut self, pipe: HANDLE, deadline: Instant) -> std::result::Result { + let delay = deadline + .saturating_duration_since(Instant::now()) + .as_millis() + .min(5000) as u32; + if unsafe { WaitForSingleObject(self.event.as_raw_handle(), delay) } != WAIT_OBJECT_0 { + unsafe { + CancelIoEx(pipe, &self.overlapped); + } + // Pending kernel IO owns our stack/buffer until cancellation + // completes. Never free it or spawn replacement workers. + if unsafe { WaitForSingleObject(self.event.as_raw_handle(), 1000) } != WAIT_OBJECT_0 + { + std::process::abort(); + } + return Err(ERROR_TIMEOUT); + } + let mut done = 0; + if unsafe { GetOverlappedResult(pipe, &self.overlapped, &mut done, 0) } == 0 { + Err(unsafe { GetLastError() }) + } else { + Ok(done) + } + } + } + fn transfer( + pipe: HANDLE, + bytes: &mut [u8], + write: bool, + deadline: Instant, + ) -> std::result::Result<(), u32> { + let mut offset = 0; + while offset < bytes.len() { + if Instant::now() >= deadline { + return Err(ERROR_TIMEOUT); + } + let mut io = Io::new().map_err(|_| ERROR_INVALID_HANDLE)?; + let mut done = 0; + let part = &mut bytes[offset..]; + let ok = unsafe { + if write { + WriteFile( + pipe, + part.as_ptr(), + part.len() as u32, + &mut done, + &mut io.overlapped, + ) + } else { + ReadFile( + pipe, + part.as_mut_ptr(), + part.len() as u32, + &mut done, + &mut io.overlapped, + ) + } + }; + let count = if ok != 0 { + done + } else { + let error = unsafe { GetLastError() }; + if error != ERROR_IO_PENDING { + return Err(error); + } + io.wait(pipe, deadline)? + }; + if count == 0 { + return Err(ERROR_BROKEN_PIPE); + } + if count as usize > part.len() { + return Err(ERROR_INVALID_DATA); + } + offset += count as usize; + } + Ok(()) + } + fn denied(error: u32) -> bool { + matches!( + error, + ERROR_BROKEN_PIPE | ERROR_NO_DATA | ERROR_PIPE_NOT_CONNECTED + ) + } + fn raw(input: &Input) -> Result { + let call = ipc::Call::new(&input.pin, ipc::Operation::Probe {}); + let mut bytes = serde_json::to_vec(&call)?; + ensure!(bytes.len() <= 32768, "CONTROL_FIXED_PROBE_FRAME"); + let raw = unsafe { + CreateFileW( + wide(ipc::PIPE_NAME).as_ptr(), + ipc::CLIENT_PIPE_RIGHTS, + 0, + ptr::null(), + OPEN_EXISTING, + FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, + ptr::null_mut(), + ) + }; + if raw == INVALID_HANDLE_VALUE { + let error = unsafe { GetLastError() }; + return Ok( + json!({"challenge":call.challenge,"opened":false,"rejected":error==ERROR_ACCESS_DENIED,"stage":"open","win32_error":error,"sdk_self_check_used":false}), + ); + } + let pipe = owned(raw)?; + let mut server_pid = 0; + ensure!( + unsafe { GetNamedPipeServerProcessId(pipe.as_raw_handle(), &mut server_pid) } != 0 + && server_pid == input.expected_helper_pid, + "CONTROL_ACTUAL_HELPER_PID" + ); + let deadline = Instant::now() + Duration::from_secs(5); + let mut header = (bytes.len() as u32).to_be_bytes(); + let result = transfer(pipe.as_raw_handle(), &mut header, true, deadline) + .and_then(|()| transfer(pipe.as_raw_handle(), &mut bytes, true, deadline)) + .and_then(|()| transfer(pipe.as_raw_handle(), &mut [0u8; 4], false, deadline)); + Ok(match result { + Err(error) => { + json!({"challenge":call.challenge,"opened":true,"actual_server_pid":server_pid,"rejected":denied(error),"stage":"framed_probe","win32_error":error,"sdk_self_check_used":false}) + } + Ok(()) => { + json!({"challenge":call.challenge,"opened":true,"actual_server_pid":server_pid,"rejected":false,"stage":"unexpected_response","sdk_self_check_used":false}) + } + }) + } + fn codes(error: &anyhow::Error) -> Vec { + error + .chain() + .filter_map(|cause| { + let text = cause.to_string(); + (text.len() <= 96 + && !text.is_empty() + && text + .bytes() + .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_')) + .then_some(text) + }) + .take(8) + .collect() + } + fn sdk_prechecks(input: &Input) -> Vec { + let mut out = Vec::new(); + let mut check = |stage: &str, run: &mut dyn FnMut() -> Result<()>| match run() { + Ok(()) => out.push(json!({"stage":stage,"ok":true})), + Err(error) => out.push(json!({"stage":stage,"ok":false,"error_codes":codes(&error)})), + }; + check("sdk_self_token", &mut || { + ipc::require_self(&input.pin.agent) + }); + check("public_root_and_pin_acl", &mut || { + let readers = [ + input.pin.agent.service_sid.clone(), + input.pin.helper.service_sid.clone(), + ]; + let _root = ipc::PinnedFile::open( + std::path::Path::new(r"C:\ProgramData\RustDiscoverySystem"), + true, + &readers, + &[], + false, + )?; + let _pin = ipc::PinnedFile::open( + std::path::Path::new(r"C:\ProgramData\RustDiscoverySystem\agent-pin.json"), + false, + &readers, + &[], + false, + )?; + Ok(()) + }); + check("helper_scm_query_config_status", &mut || { + let manager = unsafe { OpenSCManagerW(ptr::null(), ptr::null(), SC_MANAGER_CONNECT) }; + if manager.is_null() { + anyhow::bail!("CONTROL_SCM_MANAGER_WIN32_{}", unsafe { GetLastError() }); + } + let service = unsafe { + OpenServiceW( + manager, + wide(ipc::HELPER_SERVICE).as_ptr(), + SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG, + ) + }; + let error = unsafe { GetLastError() }; + unsafe { + CloseServiceHandle(manager); + } + if service.is_null() { + anyhow::bail!("CONTROL_SCM_HELPER_WIN32_{error}"); + } + let result = (|| { + let mut size = 0; + unsafe { + QueryServiceConfigW(service, ptr::null_mut(), 0, &mut size); + } + ensure!((1..=32768).contains(&size), "CONTROL_HELPER_CONFIG_SIZE"); + let mut data = vec![0usize; (size as usize).div_ceil(size_of::())]; + if unsafe { + QueryServiceConfigW(service, data.as_mut_ptr().cast(), size, &mut size) + } == 0 + { + anyhow::bail!("CONTROL_HELPER_CONFIG_WIN32_{}", unsafe { GetLastError() }); + } + let mut status: SERVICE_STATUS_PROCESS = unsafe { zeroed() }; + if unsafe { + QueryServiceStatusEx( + service, + SC_STATUS_PROCESS_INFO, + (&mut status as *mut SERVICE_STATUS_PROCESS).cast(), + size_of::() as u32, + &mut size, + ) + } == 0 + { + anyhow::bail!("CONTROL_HELPER_STATUS_WIN32_{}", unsafe { GetLastError() }); + } + ensure!( + status.dwCurrentState == SERVICE_RUNNING + && status.dwProcessId == input.expected_helper_pid, + "CONTROL_HELPER_STATUS_PIN" + ); + Ok(()) + })(); + unsafe { + CloseServiceHandle(service); + } + result + }); + check("helper_process_and_token_query", &mut || { + let raw = unsafe { + OpenProcess( + PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, + 0, + input.expected_helper_pid, + ) + }; + if raw.is_null() { + anyhow::bail!("CONTROL_HELPER_PROCESS_WIN32_{}", unsafe { GetLastError() }); + } + let process = owned(raw)?; + let _born = creation(process.as_raw_handle())?; + let mut raw = ptr::null_mut(); + if unsafe { OpenProcessToken(process.as_raw_handle(), TOKEN_QUERY, &mut raw) } == 0 { + anyhow::bail!("CONTROL_HELPER_TOKEN_WIN32_{}", unsafe { GetLastError() }); + } + let token = owned(raw)?; + ipc::verify_token( + token.as_raw_handle(), + "S-1-5-18", + &input.pin.helper.service_sid, + ) + }); + check("helper_image_parent_file_acl_hash", &mut || { + let readers = [ + input.pin.agent.service_sid.clone(), + input.pin.helper.service_sid.clone(), + ]; + let _parent = ipc::PinnedFile::open( + input.pin.helper.binary.parent().unwrap(), + true, + &readers, + &[], + false, + )?; + let mut image = + ipc::PinnedFile::open(&input.pin.helper.binary, false, &readers, &[], false)?; + ensure!( + image.sha256()? == input.pin.helper.binary_sha256, + "CONTROL_HELPER_IMAGE_HASH" + ); + Ok(()) + }); + out + } + fn run(case: uuid::Uuid, mode: &str) -> Result<()> { + let input = read_input(case)?; + let token = token(mode)?; + save(case, &format!("{mode}-token.json"), &token)?; + let report = if mode == "child" { + let call = ipc::Call::new(&input.pin, ipc::Operation::Probe {}); + let prechecks = sdk_prechecks(&input); + save( + case, + "child-sdk-prechecks.json", + &json!({"schema_version":1,"read_only":true,"token_exported":false,"checks":prechecks}), + )?; + let began = Instant::now(); + match ipc::exchange(&input.pin, &call, Duration::from_secs(5)) { + Ok(_) => { + json!({"challenge":call.challenge,"received_reply":true,"rejected":false,"sdk_self_check_used":true,"stage":"unexpected_sdk_reply"}) + } + Err(error) => { + let values = codes(&error); + let elapsed = began.elapsed().as_millis(); + json!({"challenge":call.challenge,"received_reply":false,"error_codes":values,"elapsed_ms":elapsed,"sdk_self_check_used":true,"stage":"sdk_diagnostic","rejected":false,"diagnostic_only":true}) + } + } + } else { + raw(&input)? + }; + save( + case, + &format!("{mode}-result.json"), + &json!({"schema_version":1,"case_id":case,"mode":mode,"token":token,"pipe":report,"source":"native_read_only_peer_control","expected_agent_pid":input.expected_agent_pid,"expected_helper_pid":input.expected_helper_pid,"helper_binary_sha256":input.pin.helper.binary_sha256,"policy_sha256":input.pin.policy_sha256,"own_control_image_sha256":input.control_binary_sha256,"no_jobs":true,"read_only":true,"token_exported":false,"clock_changed":false}), + ) + } + fn creation(process: HANDLE) -> Result { + let (mut c, mut e, mut k, mut u) = unsafe { (zeroed(), zeroed(), zeroed(), zeroed()) }; + ensure!( + unsafe { GetProcessTimes(process, &mut c, &mut e, &mut k, &mut u) } != 0, + "CONTROL_AGENT_CREATION" + ); + Ok((u64::from(c.dwHighDateTime) << 32) | u64::from(c.dwLowDateTime)) + } + fn agent_pid() -> Result { + let manager = unsafe { OpenSCManagerW(ptr::null(), ptr::null(), SC_MANAGER_CONNECT) }; + ensure!(!manager.is_null(), "CONTROL_SCM_MANAGER"); + let service = unsafe { + OpenServiceW( + manager, + wide(rmm_agent_windows::SERVICE_NAME).as_ptr(), + SERVICE_QUERY_STATUS, + ) + }; + unsafe { + CloseServiceHandle(manager); + } + ensure!(!service.is_null(), "CONTROL_SCM_AGENT"); + let mut status: SERVICE_STATUS_PROCESS = unsafe { zeroed() }; + let mut needed = 0; + let ok = unsafe { + QueryServiceStatusEx( + service, + SC_STATUS_PROCESS_INFO, + (&mut status as *mut SERVICE_STATUS_PROCESS).cast(), + size_of::() as u32, + &mut needed, + ) + }; + unsafe { + CloseServiceHandle(service); + } + ensure!( + ok != 0 && status.dwCurrentState == SERVICE_RUNNING, + "CONTROL_AGENT_RUNNING" + ); + Ok(status.dwProcessId) + } + struct Attributes(Vec); + impl Attributes { + fn new() -> Result { + let mut size = 0; + unsafe { + InitializeProcThreadAttributeList(ptr::null_mut(), 1, 0, &mut size); + } + ensure!((1..=65536).contains(&size), "CONTROL_ATTRIBUTE_SIZE"); + let mut data = vec![0usize; size.div_ceil(size_of::())]; + ensure!( + unsafe { + InitializeProcThreadAttributeList(data.as_mut_ptr().cast(), 1, 0, &mut size) + } != 0, + "CONTROL_ATTRIBUTE_INIT" + ); + Ok(Self(data)) + } + fn pointer(&mut self) -> LPPROC_THREAD_ATTRIBUTE_LIST { + self.0.as_mut_ptr().cast() + } + } + impl Drop for Attributes { + fn drop(&mut self) { + unsafe { + DeleteProcThreadAttributeList(self.pointer()); + } + } + } + fn spawn_fixed_child(case: uuid::Uuid, input: &Input) -> Result { + ensure!( + agent_pid()? == input.expected_agent_pid, + "CONTROL_CURRENT_AGENT_PID" + ); + let process = owned(unsafe { + OpenProcess( + PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, + 0, + input.expected_agent_pid, + ) + })?; + ensure!( + creation(process.as_raw_handle())? == input.expected_agent_creation, + "CONTROL_ORIGINAL_AGENT_BIRTH" + ); + let mut image = vec![0u16; 32768]; + let mut length = image.len() as u32; + ensure!( + unsafe { + QueryFullProcessImageNameW( + process.as_raw_handle(), + 0, + image.as_mut_ptr(), + &mut length, + ) + } != 0, + "CONTROL_ORIGINAL_AGENT_IMAGE_QUERY" + ); + let actual_image = String::from_utf16(&image[..length as usize])?; + ensure!( + std::path::Path::new(&actual_image) == input.pin.agent.binary, + "CONTROL_ORIGINAL_AGENT_IMAGE" + ); + let mut actual = ipc::PinnedFile::open( + &input.pin.agent.binary, + false, + &[ + input.pin.agent.service_sid.clone(), + input.pin.helper.service_sid.clone(), + ], + &[], + false, + )?; + ensure!( + actual.sha256()? == input.pin.agent.binary_sha256, + "CONTROL_ORIGINAL_AGENT_HASH" + ); + let mut raw = ptr::null_mut(); + ensure!( + unsafe { + OpenProcessToken( + process.as_raw_handle(), + TOKEN_QUERY | TOKEN_DUPLICATE, + &mut raw, + ) + } != 0, + "CONTROL_AGENT_QUERY_DUPLICATE_ONLY" + ); + let original = owned(raw)?; + ipc::verify_token( + original.as_raw_handle(), + "S-1-5-19", + &input.pin.agent.service_sid, + )?; + let mut raw = ptr::null_mut(); + ensure!( + unsafe { + DuplicateTokenEx( + original.as_raw_handle(), + TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY, + ptr::null(), + SecurityImpersonation, + TokenPrimary, + &mut raw, + ) + } != 0, + "CONTROL_DUPLICATE_PRIMARY" + ); + let duplicate = owned(raw)?; + let job = owned(unsafe { CreateJobObjectW(ptr::null(), ptr::null()) })?; + let mut limits: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { zeroed() }; + limits.BasicLimitInformation.LimitFlags = + JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_ACTIVE_PROCESS; + limits.BasicLimitInformation.ActiveProcessLimit = 1; + ensure!( + unsafe { + SetInformationJobObject( + job.as_raw_handle(), + JobObjectExtendedLimitInformation, + (&limits as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(), + size_of::() as u32, + ) + } != 0, + "CONTROL_CHILD_JOB_LIMIT" + ); + let exe = std::env::current_exe()?; + let mut command = wide(&format!( + "\"{}\" --agent-child {}", + exe.to_string_lossy(), + case + )); + let exe = wide(&exe.to_string_lossy()); + let directory = wide(&PathBuf::from(ROOT).join(case.to_string()).to_string_lossy()); + // The handle array outlives its attribute list. JOB_LIST assigns the + // child atomically, eliminating a suspended unowned-process gap. + // Microsoft UpdateProcThreadAttribute: JOB_LIST (Windows10+). + let jobs = [job.as_raw_handle()]; + let mut attributes = Attributes::new()?; + ensure!( + unsafe { + UpdateProcThreadAttribute( + attributes.pointer(), + 0, + PROC_THREAD_ATTRIBUTE_JOB_LIST as usize, + jobs.as_ptr().cast(), + size_of_val(&jobs), + ptr::null_mut(), + ptr::null(), + ) + } != 0, + "CONTROL_ATOMIC_JOB_ATTRIBUTE" + ); + let mut startup: STARTUPINFOEXW = unsafe { zeroed() }; + startup.StartupInfo.cb = size_of::() as u32; + startup.lpAttributeList = attributes.pointer(); + let mut child: PROCESS_INFORMATION = unsafe { zeroed() }; + // Fixed image/arguments, no inherited handles/shell/profile import. + // CreateProcessAsUser may enable its required privileges only for this + // call on our own SYSTEM token; no explicit adjustment or DACL grant. + save( + case, + "child-create-intent.json", + &json!({"fixed_image_sha256":input.control_binary_sha256,"fixed_argument":"--agent-child","case_id":case,"atomic_job_list":true,"no_jobs":true,"token_exported":false}), + )?; + let ok = unsafe { + CreateProcessAsUserW( + duplicate.as_raw_handle(), + exe.as_ptr(), + command.as_mut_ptr(), + ptr::null(), + ptr::null(), + 0, + CREATE_SUSPENDED | CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT, + ptr::null(), + directory.as_ptr(), + &startup.StartupInfo, + &mut child, + ) + }; + let error = if ok == 0 { + unsafe { GetLastError() } + } else { + 0 + }; + ensure!(ok != 0, "CONTROL_FIXED_CHILD_CREATE_WIN32_{error}"); + let child_process = owned(child.hProcess)?; + let child_thread = owned(child.hThread)?; + let mut assigned = 0; + if unsafe { + IsProcessInJob( + child_process.as_raw_handle(), + job.as_raw_handle(), + &mut assigned, + ) + } == 0 + || assigned == 0 + { + unsafe { + TerminateProcess(child_process.as_raw_handle(), 125); + WaitForSingleObject(child_process.as_raw_handle(), 5000); + } + anyhow::bail!("CONTROL_CHILD_ATOMIC_JOB_NOT_CONFIRMED"); + } + save( + case, + "child-started.json", + &json!({"child_pid":child.dwProcessId,"wrong_agent_pid":child.dwProcessId!=input.expected_agent_pid,"fixed_child_image":true,"agent_primary_token_duplicated":true,"atomic_job_membership_confirmed":true,"token_exported":false}), + )?; + ensure!( + unsafe { ResumeThread(child_thread.as_raw_handle()) } != u32::MAX, + "CONTROL_CHILD_RESUME" + ); + if unsafe { WaitForSingleObject(child_process.as_raw_handle(), 20000) } != WAIT_OBJECT_0 { + unsafe { + TerminateJobObject(job.as_raw_handle(), 125); + } + ensure!( + unsafe { WaitForSingleObject(child_process.as_raw_handle(), 5000) } + == WAIT_OBJECT_0, + "CONTROL_CHILD_CLEANUP" + ); + anyhow::bail!("CONTROL_CHILD_TIMEOUT_NO_RETRY"); + } + let mut exit = 0; + ensure!( + unsafe { GetExitCodeProcess(child_process.as_raw_handle(), &mut exit) } != 0, + "CONTROL_CHILD_EXIT" + ); + ensure!( + agent_pid()? == input.expected_agent_pid + && creation(process.as_raw_handle())? == input.expected_agent_creation + && unsafe { WaitForSingleObject(process.as_raw_handle(), 0) } == WAIT_TIMEOUT, + "CONTROL_AGENT_PRESERVED" + ); + Ok( + json!({"child_pid":child.dwProcessId,"exit_code":exit,"child_exited":true,"agent_preserved":true,"token_exported":false,"existing_process_or_token_acl_changed":false,"diagnostic_only":true}), + ) + } + fn parent(case: uuid::Uuid) -> Result<()> { + let identity = token("parent")?; + save(case, "parent-token.json", &identity)?; + let input = read_input(case)?; + let result = match spawn_fixed_child(case, &input) { + Ok(value) => value, + Err(error) => { + json!({"error_codes":codes(&error),"completed":false,"diagnostic_only":true,"token_exported":false}) + } + }; + save( + case, + "parent-result.json", + &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 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 std::ffi::c_void, + _: *mut std::ffi::c_void, + ) -> u32 { + 0 + } + unsafe extern "system" fn service_main(_: u32, _: *mut *mut u16) { + let handle = unsafe { + RegisterServiceCtrlHandlerExW( + wide(if *IS_PARENT.get().unwrap_or(&false) { + PARENT_NAME + } else { + 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 = if *IS_PARENT.get().unwrap_or(&false) { + parent(*CASE.get().unwrap()) + } else { + run(*CASE.get().unwrap(), "service") + }; + std::thread::sleep(Duration::from_secs(2)); + status(SERVICE_STOPPED, if result.is_ok() { 0 } else { 1066 }); + } + pub fn main() -> Result<()> { + let args: Vec<_> = std::env::args().skip(1).collect(); + ensure!( + args.len() == 2 + && matches!( + args[0].as_str(), + "--admin" | "--service" | "--agent-child" | "--parent" + ), + "CONTROL_FIXED_MODE" + ); + let case = uuid::Uuid::parse_str(&args[1])?; + ensure!( + case.get_version_num() == 4 && case.to_string() == args[1], + "CONTROL_CANONICAL_UUID" + ); + if args[0] == "--admin" { + return run(case, "admin"); + } + if args[0] == "--agent-child" { + return run(case, "child"); + } + IS_PARENT + .set(args[0] == "--parent") + .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" { + PARENT_NAME + } else { + NAME + }); + let table = [ + SERVICE_TABLE_ENTRYW { + lpServiceName: name.as_mut_ptr(), + lpServiceProc: Some(service_main), + }, + SERVICE_TABLE_ENTRYW { + lpServiceName: ptr::null_mut(), + lpServiceProc: None, + }, + ]; + ensure!( + unsafe { StartServiceCtrlDispatcherW(table.as_ptr()) } != 0, + "CONTROL_SERVICE_DISPATCH" + ); + Ok(()) + } +} +#[cfg(all(windows, feature = "system-helper"))] +fn main() -> anyhow::Result<()> { + platform::main() +} +#[cfg(not(all(windows, feature = "system-helper")))] +fn main() -> anyhow::Result<()> { + anyhow::bail!("Windows system-helper build required for native peer controls") +} diff --git a/crates/agent-windows/src/native_boot.rs b/crates/agent-windows/src/native_boot.rs new file mode 100644 index 0000000..7fde1cf --- /dev/null +++ b/crates/agent-windows/src/native_boot.rs @@ -0,0 +1,170 @@ +//! UNWIRED diagnostic candidate, never a job-capable BootSource. +//! +//! Microsoft's public NtQuerySystemInformation contract explicitly permits API +//! changes and recommends dynamic lookup. It does NOT specify class90 or the +//! BootIdentifier layout used below. The fixed32-byte/GUID-prefix hypothesis +//! therefore remains unqualified, even when samples agree on Windows11/26300. +//! No CIM timestamp, wall clock, uptime subtraction or registry counter is used. +//! https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntquerysysteminformation +//! https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtlgetversion +//! https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getfirmwaretype +use serde::Serialize; +use uuid::Uuid; + +pub const CANDIDATE_BUILD: u32 = 26300; +#[derive(Clone, Debug, Serialize)] +pub struct Observation { + pub source: &'static str, + pub quality: &'static str, + pub code: &'static str, + pub windows_build: Option, + pub nt_status: Option, + pub returned_bytes: Option, + pub candidate_identifier: Option, + pub firmware_type: Option, + pub job_binding_qualified: bool, + pub public_class_90_abi_documented: bool, +} +impl Observation { + fn unsupported(code: &'static str) -> Self { + Self { + source: "ntdll/NtQuerySystemInformation/class90/experimental32", + quality: "unsupported", + code, + windows_build: None, + nt_status: None, + returned_bytes: None, + candidate_identifier: None, + firmware_type: None, + job_binding_qualified: false, + public_class_90_abi_documented: false, + } + } +} +#[cfg(any(windows, test))] +fn decode(status: i32, returned: u32, bytes: [u8; 32], firmware: u32) -> Option { + if status != 0 + || returned != 32 + || !matches!(firmware, 1 | 2) + || u32::from_le_bytes(bytes[16..20].try_into().ok()?) != firmware + { + return None; + } + let id = Uuid::from_bytes_le(bytes[..16].try_into().ok()?); + (!id.is_nil()).then_some(id) +} +/// Actual bounded native read, but no qualification/capability follows from it. +pub fn observe_candidate() -> Observation { + #[cfg(windows)] + { + windows::observe() + } + #[cfg(not(windows))] + { + Observation::unsupported("BOOT_CANDIDATE_WINDOWS_ONLY") + } +} +#[cfg(windows)] +mod windows { + use super::*; + use std::mem::{size_of, zeroed}; + use windows_sys::Win32::System::{ + LibraryLoader::{GetModuleHandleW, GetProcAddress}, + SystemInformation::{ + GetFirmwareType, GetNativeSystemInfo, OSVERSIONINFOEXW, PROCESSOR_ARCHITECTURE_AMD64, + SYSTEM_INFO, + }, + }; + type RtlVersion = unsafe extern "system" fn(*mut OSVERSIONINFOEXW) -> i32; + type Query = unsafe extern "system" fn(i32, *mut core::ffi::c_void, u32, *mut u32) -> i32; + pub(super) fn observe() -> Observation { + let mut out = Observation::unsupported("BOOT_CANDIDATE_API_UNAVAILABLE"); + // ntdll is already loaded by the OS. No path/search-based DLL loading. + let name: Vec = "ntdll.dll".encode_utf16().chain(Some(0)).collect(); + let module = unsafe { GetModuleHandleW(name.as_ptr()) }; + if module.is_null() { + return out; + } + let Some(version) = (unsafe { GetProcAddress(module, c"RtlGetVersion".as_ptr().cast()) }) + else { + return out; + }; + let Some(query) = + (unsafe { GetProcAddress(module, c"NtQuerySystemInformation".as_ptr().cast()) }) + else { + return out; + }; + // Public entrypoint calling conventions; class90's returned layout is + // explicitly experimental and checked as bytes, not a dereferenced ABI. + let version: RtlVersion = unsafe { std::mem::transmute(version) }; + let query: Query = unsafe { std::mem::transmute(query) }; + let mut os: OSVERSIONINFOEXW = unsafe { zeroed() }; + os.dwOSVersionInfoSize = size_of::() as u32; + if unsafe { version(&mut os) } != 0 { + return out; + } + out.windows_build = Some(os.dwBuildNumber); + let mut system: SYSTEM_INFO = unsafe { zeroed() }; + unsafe { GetNativeSystemInfo(&mut system) }; + if os.dwMajorVersion != 10 + || os.dwMinorVersion != 0 + || os.dwBuildNumber != CANDIDATE_BUILD + || os.wProductType != 1 + || unsafe { system.Anonymous.Anonymous.wProcessorArchitecture } + != PROCESSOR_ARCHITECTURE_AMD64 + { + out.code = "BOOT_CANDIDATE_BUILD_OR_ARCHITECTURE_UNSUPPORTED"; + return out; + } + let mut firmware = 0; + if unsafe { GetFirmwareType(&mut firmware) } == 0 { + out.code = "BOOT_CANDIDATE_FIRMWARE_CROSSCHECK_UNAVAILABLE"; + return out; + } + // Fixed aligned32-byte capacity; no remote length/allocation or fallback. + let mut data = [0u64; 4]; + let mut returned = 0; + let status = unsafe { query(90, data.as_mut_ptr().cast(), 32, &mut returned) }; + out.nt_status = Some(status); + out.returned_bytes = Some(returned); + out.firmware_type = Some(firmware as u32); + if status == 0xC0000022u32 as i32 { + out.quality = "permission_denied"; + out.code = "BOOT_CANDIDATE_ACCESS_DENIED"; + return out; + } + let mut bytes = [0u8; 32]; + for (i, value) in data.iter().enumerate() { + bytes[i * 8..i * 8 + 8].copy_from_slice(&value.to_ne_bytes()); + } + if let Some(id) = decode(status, returned, bytes, firmware as u32) { + out.candidate_identifier = Some(id); + out.quality = "candidate_unqualified"; + out.code = "BOOT_CANDIDATE_REQUIRES_ABI_AND_NATIVE_LIFECYCLE_QUALIFICATION"; + } else { + out.code = "BOOT_CANDIDATE_STATUS_LENGTH_OR_LAYOUT_UNSUPPORTED"; + } + // Neither raw BootFlags nor unrelated native memory is exposed. + out + } +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn candidate_layout_and_status_never_imply_job_qualification() { + let id = Uuid::parse_str("12345678-9abc-4def-8123-456789abcdef").unwrap(); + let mut bytes = [0u8; 32]; + bytes[..16].copy_from_slice(&id.to_bytes_le()); + bytes[16..20].copy_from_slice(&2u32.to_le_bytes()); + assert_eq!(decode(0, 32, bytes, 2), Some(id)); + assert_eq!(decode(-1, 32, bytes, 2), None); + assert_eq!(decode(0, 31, bytes, 2), None); + assert_eq!(decode(0, 32, bytes, 1), None); + bytes[..16].fill(0); + assert_eq!(decode(0, 32, bytes, 2), None); + let out = Observation::unsupported("TEST"); + assert!(!out.job_binding_qualified); + assert!(!out.public_class_90_abi_documented); + } +} diff --git a/deploy/windows/BootIdentifierProbe.ps1 b/deploy/windows/BootIdentifierProbe.ps1 new file mode 100644 index 0000000..ae9fac0 --- /dev/null +++ b/deploy/windows/BootIdentifierProbe.ps1 @@ -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 diff --git a/deploy/windows/boot_probe.rs b/deploy/windows/boot_probe.rs new file mode 100644 index 0000000..39d9cd9 --- /dev/null +++ b/deploy/windows/boot_probe.rs @@ -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 = OnceLock::new(); + static STATUS: AtomicUsize = AtomicUsize::new(0); + fn wide(s: &str) -> Vec { + 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::())]; + ensure!( + unsafe { + GetTokenInformation( + raw, + TokenUser, + data.as_mut_ptr().cast(), + needed, + &mut needed, + ) + } != 0, + "BOOT_PROBE_USER" + ); + let user = unsafe { &*data.as_ptr().cast::() }; + 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 = 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() + ) +} diff --git a/deploy/windows/helper_peer_controls.py b/deploy/windows/helper_peer_controls.py new file mode 100644 index 0000000..aeeefb8 --- /dev/null +++ b/deploy/windows/helper_peer_controls.py @@ -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() diff --git a/deploy/windows/test_helper_peer_controls.py b/deploy/windows/test_helper_peer_controls.py new file mode 100644 index 0000000..93fd79a --- /dev/null +++ b/deploy/windows/test_helper_peer_controls.py @@ -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() diff --git a/docs/handover.md b/docs/handover.md index 3f216f6..76e9eac 100644 --- a/docs/handover.md +++ b/docs/handover.md @@ -53,6 +53,16 @@ Zugänge und private Rohbelege bleiben gitignoriert. ## Aktuelle Windowsfortsetzung +Helper-Peer-Kontrollfall `603c2f9d…`: native Windows5-Speicherproben der +ACL-Konstruktoren, geschützte Vorbereitung und rohe Administratorkontrolle +bestanden (Pipeöffnen verweigert5, echte Adminidentität, kein SDK-Selbstcheck). +Originale Agent-/Helperprozesse5140/6240 und Windows0/0/0/0/Linux30/30/26/0 +erhalten. LocalService-/Parentphase und positive Agentverbindung noch offen. +Vorheriger Fall `4a60d264…` scheiterte vor Dienststart an einer exakt nativ +reproduzierten Null-Collection aus leerem PowerShell-IF-Zweig; weder +allgemeiner Konstruktorfehler noch nachträglicher Erfolg behauptet. +[Kontrollbericht](windows-helper-peer-controls.md). + Zentrale getrennte SYSTEM-Policy implementiert, lokal und anschließend13 reine Policyguards nativ auf Cloud-Linux bestanden, Fall `13b11ce4…`, Binary `ca1df8b2…`. Rootrecht ist kein SYSTEM-Recht, exakte Geräte-/Helperpins und enge Fixture-SCM- diff --git a/docs/windows-boot-identity.md b/docs/windows-boot-identity.md new file mode 100644 index 0000000..42af47e --- /dev/null +++ b/docs/windows-boot-identity.md @@ -0,0 +1,112 @@ +# Windows-Bootidentität: Bestandsquelle und unqualifizierter Kandidat + +Stand 2026-11-14: Die neue Strecke ist **nur als separate Diagnosequelle +implementiert, lokal geprüft und crossgebaut**. Es wurden **keine nativen +Boot-API-Aufrufe**, keine LocalService-Probe, keine Zeitänderung und kein +OS-Reboot damit ausgeführt. `job_binding_qualified` ist in jedem Ergebnis +`false`. Die produktive Agent-/Helper-Bootquelle wurde nicht geändert; es wird +keine zusätzliche Capability angeboten. + +## Bestehende CIM-Quelle + +Der bestehende Windowscode liest mit einem festen passiven CIM-Aufruf +`Win32_OperatingSystem.LastBootUpTime`, wandelt den Wert in UTC-Ticks um und +bildet daraus einen UUID-förmigen Hash mit dem Namensraum +`rmm.windows.boot.cim.ticks.v1`. Agent und Helper verwenden diese bestehende +Quelle. Die dokumentierte CIM-Eigenschaft bezeichnet den Zeitpunkt des letzten +Betriebssystemstarts; sie ist ein Zeitwert und kein dokumentierter opaker +Boot-Identifier. [Microsoft: Win32_OperatingSystem](https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-operatingsystem). + +Übereinstimmende wiederholte CIM-Abfragen belegen ausschließlich die beobachtete +Übereinstimmung. Sie sind kein Nachweis, dass die Ableitung einen Prozessneustart, +einen Wanduhrsprung, Suspend/Resume, Fast Startup oder einen tatsächlichen +OS-Neustart korrekt voneinander unterscheidet. Hier wurde insbesondere **kein +Fehlerverhalten bei einem Zeitsprung beobachtet oder nachgewiesen**. Aus dem +fehlenden Stabilitätsnachweis folgt weder die Behauptung, CIM ändere sich bei +jedem Zeitsprung, noch eine belastbare Garantie, dass dies niemals geschieht. + +Für gespeichertes passives Inventar bleibt die Herkunft damit nachvollziehbar. +Eine zukünftige Job-/Rebootbindung benötigt einen eigenständig qualifizierten +Vertrag. Ein bloßer Wechsel vom bisherigen Hash zu einer anderen GUID darf nicht +als tatsächlicher Neustart ausgegeben werden; historische Bindungen bleiben +historisch und werden nicht nachträglich umgedeutet. + +## Getrennter nativer Diagnosekandidat + +Der unexportierte [native_boot.rs](../crates/agent-windows/src/native_boot.rs) +fragt ausschließlich einen experimentellen Kandidaten ab. Der Decoder ist auf +**Windows 11, x86-64, Build 26300** beschränkt. Fehlendes API-Symbol, andere Builds, +Architekturen, Rückgabelängen oder ungültige Werte bleiben `unsupported`; +Zugangsverweigerung wird als `permission_denied` ausgewiesen. Es gibt keinen +Fallback auf Wanduhr-/Uptime-Subtraktion oder einen Registry-Bootzähler. + +Die Implementierung löst `NtQuerySystemInformation` und `RtlGetVersion` dynamisch +im bereits geladenen `ntdll.dll` auf. Sie verwendet Klassenwert 90 und einen +festen, ausgerichteten 32-Byte-Puffer. Nur Status 0, exakt 32 zurückgemeldete Bytes, +eine nichtleere GUID aus den ersten 16 Bytes und ein passender Firmwaretyp an +Offset 16 werden als **Kandidatenbeobachtung** akzeptiert. Der Firmwaretyp wird +zusätzlich mit `GetFirmwareType` gelesen. Andere Pufferinhalte werden nicht +exportiert. Der Kandidat wird nicht aus einem Zeitwert berechnet. + +Dabei sind API-Nachweis und Interpretation klar getrennt: + +- Microsoft dokumentiert den allgemeinen dynamisch aufzulösenden + `NtQuerySystemInformation`-Einstieg, warnt aber vor Änderungen interner + Strukturen und nennt **keinen öffentlichen Vertrag für Klasse 90 und deren + BootIdentifier-Layout**. Die hier gewählte Feldinterpretation ist deshalb + ausdrücklich eine zu qualifizierende Hypothese, keine allgemeine Windowszusage. + [Microsoft: NtQuerySystemInformation](https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntquerysysteminformation). +- Die WDK-Dokumentation beschreibt die Versionsstruktur von `RtlGetVersion`; + sie garantiert damit nicht selbst einen unterstützten user-mode Boot-Identifier + aus `ntdll`. Fehlende Exporte werden verweigert. + [Microsoft: RtlGetVersion](https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtlgetversion). +- `GetFirmwareType` ist eine dokumentierte lokale Win32-Abfrage. Ihr Abgleich + prüft die Plausibilität eines Feldes; er beweist weder die GUID-Semantik noch + deren Lebenszyklus. + [Microsoft: GetFirmwareType](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getfirmwaretype). + +Auch zwei gleiche Kandidatenwerte bleiben `candidate_unqualified`. Weder +`job_binding_qualified` noch `public_class_90_abi_documented` werden dadurch wahr. + +## Vorbereitete LocalService-Probe, noch nicht ausgeführt + +[boot_probe.rs](../deploy/windows/boot_probe.rs) ist ein eigenständiges +SCM-Diagnoseprogramm, kein zusätzlicher RMM-Agent. Es akzeptiert ausschließlich +seinen eigenen Serviceaufruf, prüft den tatsächlichen Prozess als LocalService +`S-1-5-19`, verwirft Thread-Impersonation und aktivierte Administratorrolle und +schreibt zwei begrenzte Kandidatenbeobachtungen in einen neuen privaten Fall. +Ein Administrator-Konsolenaufruf ersetzt diesen Nachweis nicht. + +[BootIdentifierProbe.ps1](../deploy/windows/BootIdentifierProbe.ps1) bereitet +gehashte Artefakte vor und kann später ausdrücklich einen eigenen temporären +Manual-/LocalService-Dienst anlegen. Diese SCM-Registrierung ist ausschließlich +Bootstrap für die Probe; es werden keine Registry-Bootzähler, permanenten +Agent-/Helperdienste, Zeiteinstellungen, Privilegien oder Truststores verändert. +Create-only Intents verhindern wiederholtes Starten nach unklarem Reply. +`Readback` liest nur; `Cleanup` entfernt ausschließlich den gebundenen, bereits +beendeten Probedienst. Alte Fälle und Berichte bleiben erhalten. + +Zwei unabhängig gestartete frische Fälle könnten später Prozessunabhängigkeit +beobachtbar machen. Auch das ersetzt weder einen tatsächlichen genehmigten +OS-Reboot noch den noch fehlenden Nachweis der behaupteten Zeitsprungsemantik. +Diese Schritte sind hier **geplant, nicht ausgeführt**. Ein produktiver Wechsel +ist dadurch nicht freigegeben. + +## Tatsächlich ausgeführte Prüfungen und eingefrorene Quellen + +Ein lokaler Decoder-/Fehlerpfadtest bestand ohne Ignorieren: Status, Länge, +Firmware-Abweichung, GUID-Byteordnung und leere GUID führen nicht zu einer +Jobqualifikation. Windows-GNU-Clippy aller Targets mit `-D warnings`, Release-Link +und PowerShell-Parser bestanden. Die resultierende Windows-EXE wurde nicht +nativ ausgeführt. Private Qualifikation: +`devstate/windows-boot-probe/qualification.json`. + +| Quelle | SHA-256 | +| --- | --- | +| `crates/agent-windows/src/native_boot.rs` | `4f4dfcce2ec57b7f901dec878ec19f985f6d86379ec90ef7b582be8218eda18f` | +| `deploy/windows/boot_probe.rs` | `f150fc81b4a5f3d9cfdc5f83ec96209a315bc72d2170d04ec59f899f01c34fe8` | +| `deploy/windows/BootIdentifierProbe.ps1` | `60b6787ab77caebbbea4b39689dd9b80cd618517f9292ec8ca9c1ba8ac3bd539` | + +Der eigenständige Release-Link hat SHA-256 +`7cd57577e8a75b408c9119a6f2f2bf325c0a8978c3f1be1800f254088cfeeb9e`. +Das ist ein Buildnachweis, kein nativer Boot- oder Reboot-Abnahmenachweis. diff --git a/docs/windows-helper-peer-controls.md b/docs/windows-helper-peer-controls.md new file mode 100644 index 0000000..7276929 --- /dev/null +++ b/docs/windows-helper-peer-controls.md @@ -0,0 +1,155 @@ +# Read-only Helper-Peer-Kontrollen und SDK-Diagnose + +Stand 2026-11-14: **Implementiert, lokal gebaut und quellgeprüft; native +Vorbereitung und Administratorkontrolle bestanden.** Die positive Verbindung +des tatsächlichen Agenten ist weiterhin offen: der laufende Agent schrieb nur +`HELPER_NOT_AVAILABLE`. Ein laufender SYSTEM-Helper allein belegt keine +funktionierende gegenseitige Peerprüfung. Der neue Kontrollbuild ersetzt weder +die alte native 21+6-Unitqualifikation noch eine positive Agent-Pipeabnahme. + +Der neue `helper_peer_controls.py` bindet 60 vollständige Build-/Runnerquellen +und erstellt einen eigenen Manifest. Windows-GNU-Alltargets-Clippy mit +`-D warnings`, Release-Link, vier lokale Reporting-/Create-once-Guards und +PowerShell-Parser einschließlich des gemeinsamen speicherinternen Guards +bestanden. Der qualifizierte lokale +Fall ist `build-40f9d096-8532-45a3-b362-62b4983569bc`; sein EXE-SHA256 lautet +`c25243ff6af4d06c578840c929788d74657377a520b856a7fd96791e52bf406e`. +Der native Kontrollfall ist `603c2f9d-a2aa-42cb-b113-ad484cac5b7a`. +Vier tatsächliche Windows-PowerShell5.1-Speicherproben der verwendeten ACL- +Konstruktoren bestanden mit exakten Masken. Die anschließende Vorbereitung +erstellte nur den geschützten eigenen Kontrollfall; keine RMM-Wirkung. +Die Administratorkontrolle (PID9520, echte aktivierte Administratorgruppe, +keine Agent-Service-SID) erhielt beim rohen Pipeöffnen `ACCESS_DENIED`5. +Sie hat keinen SDK-Selbstcheck benutzt. Originale Agent-/Helperprozesse5140/6240, +Konfiguration, Schlüsselmetadaten, private Helperdateimetadaten, Serverflags und +Jobzähler blieben erhalten: Windows0/0/0/0, Linux30/30/26/0. +LocalService- und Parent-/Childdiagnose sind noch nicht ausgeführt. + +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 +gelesen. Erst dann wurde die noch nicht erreichte erste Fallvorbereitung +fortgesetzt. Diese scheiterte beim ACL-Konstruktor: Ein leerer PowerShell- +`if`-Zweig ergab `$null`, Arrayaddition erzeugte einen Null-SID-Eintrag für das +Controllerverzeichnis. Exakte speicherinterne Windows5-Proben reproduzierten +den Fehler; allgemeine/nestende Konstruktoraufrufe ohne diesen Nulleintrag +bestanden. Der Fix normalisiert ausschließlich leere Collections und verweigert +weiterhin ungültige einzelne SIDs. Alter Teilfall und alte Artefakte bleiben +erhalten; der korrigierte Lauf hat einen neuen Manifest und neuen Fall. + +## Ausschließlich feste interne Probeoperation + +`examples/helper_peer_controls.rs` enthält drei getrennte Kontrollarten: + +1. Ein Bootstrap-Administrator sendet einen **rohen**, gültig gerahmten + `Probe {}`-Call. Der SDK-Selbstcheck wird absichtlich nicht benutzt und daher + niemals als serverseitige Ablehnung gewertet. +2. Ein kurzlebiger eigener Dienst `RmmDiscoveryPeerControl` läuft als + LocalService mit seiner eigenen enabled Service-SID. Der tatsächliche Token + muss User-SID19, seine eigene Service-SID und keine Agent-Service-SID enthalten. + Auch dieser Akteur sendet nur den rohen Probe-Frame. Es werden weder Pin noch + bestehende DACLs gelockert, um ihm eine Verbindung zu ermöglichen. +3. Der ausdrücklich erlaubte eigene SYSTEM-Dienst `RmmDiscoveryPeerParent` + bindet den tatsächlichen laufenden Agenten über festen SCM-Namen, PID, + Prozessgeburtszeit, gehaltenes Prozesshandle und Imagepfad/-hash. Er fordert + ausschließlich ProcessQueryLimited/Synchronize und am Originaltoken + Query/Duplicate an. Ein duplizierter PRIMARYtoken startet nur dieselbe feste + Kontroll-EXE mit `--agent-child `, ohne Shell, freie Argumente, + Profilimport, SeDebug oder eigene Privileg-/DACLänderungen. Die Erzeugung mit + `CreateProcessAsUserW` und `STARTUPINFOEX/JOB_LIST` bindet den Child bereits + atomar an den vorher konfigurierten eigenen Kill-on-close-Job mit genau einem + erlaubten Prozess; es gibt keine nachträgliche Zuweisungslücke. Der dauerhafte + Child-Create-Intent steht vor dem API-Aufruf, die tatsächliche Jobmitgliedschaft + wird vor Resume geprüft. Die API kann ihre notwendigen Privilegien ausschließlich + während dieses Aufrufs am eigenen SYSTEM-Token aktivieren. Nach 20 Sekunden beendet der Controller nur + diesen eigenen Job und prüft den unveränderten Originalagenten erneut. + +Der Child zeichnet die tatsächliche SID19-/Agent-Service-SID-Identität auf. Er +prüft ausschließlich seine eigene SDK-Rolle, die öffentliche Root-/Pin-ACL, +Helper-SCM-QueryConfig/QueryStatus, Helperprozess-/TokenQuery sowie öffentliche +Image-/Parent-ACL und Imagehash. Danach ruft er das unveränderte SDK mit einer +Probe auf. Aufgezeichnet werden nur begrenzte statische SDK-Fehlercodes und +unmittelbar bei den separaten WinAPI-Prechecks gewonnene numerische Fehlercodes. +Keine privaten Tokenhandles, Schlüssel, Agentdateien oder privaten Ledgerbytes +werden gelesen, exportiert oder geloggt. Dies ermöglicht die Eingrenzung eines +fehlgeschlagenen Client-Sicherheitschecks ohne Änderung des tatsächlichen Agenten. +Kontrolle3 bleibt **diagnostic_only**: Ein SDK-Fehler wird nicht zu einer +unbeobachteten serverseitigen Fehlerklasse umbenannt. Jede erhaltene Antwort des +Helpers ist für diesen fremden PID-/Image-Child ein Testfehler. + +## Beweis- und Cleanupgrenzen + +Nur `ACCESS_DENIED` beim Öffnen oder eine geschlossene Pipe nach Kontakt mit der +exakten ursprünglichen Helper-PID gelten bei den rohen Kontrollen als negative +Verbindung. BUSY, Timeout, irgendeine Antwort oder SDK-Selbstverweigerung sind +keine positive Negativabnahme. Die eigene Tokenrolle und der konkrete Fall müssen +zum gespeicherten nativen Ergebnis passen. + +Controllerbelege und Intents liegen in einem ausschließlich für SYSTEM und +Administratoren schreibbaren Unterordner. Die übrigen Fallverzeichnisse sind für +Agent-/Control-SID nur lesbar. Bootstrap erstellt vor dem ersten Akteurstart genau +die festen Ausgabe-Leaves mit SYSTEM-/Admin-Owner: Controlausgaben sind ausschließlich +für die eigene Control-SID, Childausgaben ausschließlich für die tatsächliche +Agent-SID schreibbar. Keine dieser Rollen erhält gegenseitige Writerrechte oder +Directory-Create-Rechte; SID19 kann dadurch kein Owner-WRITE_DAC an selbst erzeugten +Reports erlangen. Native Ausgabe öffnet nur den vorerstellten leeren Leaf, validiert +seinen Pin und überschreibt keinen vorhandenen Beleg. Readback prüft Owner und +exakte Writerrolle vor dem JSONlesen und benennt Childausgaben ausdrücklich als +`agent_token_assertion`, niemals als unabhängigen SYSTEM-Beweis. + +Der Runner vergleicht vor und nach jedem Schritt ursprüngliche Agent-/Helper-PID, +Prozessgeburt, Konto, Image, Konfiguration und öffentliche Helperpin-/Policyhashes. +Private Helperdateien und der Geräteschlüssel werden nur anhand ihrer Metadaten +verglichen; es erfolgt keine Zeilenabfrage des privaten Helperledgers. Windows- +und Linux-Jobzähler sowie Serverflags müssen unverändert bleiben. Policyallowlist +bleibt leer, `enable_effects=false`, `allow_reboot=false`, Uhr und Fähigkeiten +bleiben geschlossen. Es gibt keinen Execute-, Snapshot- oder Applyaufruf und +keinen SCM-Fixturejob. + +Vor jeder nativen Phase steht lokal und remote ein create-only Intent. Ein +verlorener SSH-Ausgang erlaubt ausschließlich `readback --id `. +Der Runner wiederholt keinen Dienst-/Childstart. `readback` liest ausschließlich; +es erzeugt remote keine Intents, ACLänderungen oder Dienstlöschungen. Nur als Teil +der Startphase oder durch die gesonderte explizite `cleanup`-Phase löscht der Runner +seine eigenen exakt gebundenen bereits gestoppten Testdienste nach dauerhaftem Cleanupintent; +bestehende Agent-/Helperdienste werden nicht gestoppt, neu gestartet oder verändert. +Aktive Testdienste werden nach dem begrenzten Readbackfenster erhalten und +explizit als unvollständig gemeldet. + +Die fünf Sekunden begrenzen Pipe-Frame-I/O; synchrone SCM-/Datei-/Tokenabfragen +haben dadurch keine harte Gesamtlaufzeitgrenze. Der Child hat den genannten +separaten Prozess-Job; für einen im synchronen Vorlauf hängenden temporären +SYSTEM-Elterndienst ist gegebenenfalls ein eigener, eng geprüfter Cleanupschritt +nötig. Diese Grenze darf nicht als nachgewiesener harter Diensttimeout oder als +vollständig abgeschlossene native Abnahme dargestellt werden. + +Geplant, **nicht ausgeführt**: eigener neuer `prepare --manifest … --helper-case …` +und anschließend die getrennten Phasen `admin`, `service`, `parent` mit derselben +Kontrollfall-ID. Der bestehende tatsächliche Helperfall, aktuelle Runtimeindex +und deren Hashes sind Pflicht; der Runner übernimmt keine fremden PID-/Imagewerte. +Root führt diese Phasen erst nach unabhängigem Review aus. Die +WebUI-Genehmigungsgrenze bleibt für sämtliche tatsächlichen RMM-Jobs unverändert. + +Die atomare Jobliste und ihre Handlelebensdauer folgen +[UpdateProcThreadAttribute](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-updateprocthreadattribute); +Form und Aufrufflag folgen +[STARTUPINFOEXW](https://learn.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-startupinfoexw) +und [CreateProcessAsUserW](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessasuserw). +Die vorherige ungestartete Kontrollversion mit nachträglicher Jobzuweisung bleibt +historisch erhalten und ist für die native Parentphase nicht freigegeben. + +Die erste tatsächliche Prepare-Ausführung des vorherigen Quellstands stoppte im +Fall `4a60d264…` vor jedem SCM-/Kontrollstart. Die unabhängige WindowsPS5- +Speicherprobe reproduzierte den konkreten Fehler: `else {@()}` lieferte bei der +Controller-Verzeichnis-Leserliste `$null`; Array-Plus fügte daraus eine dritte, +ungültige Null-SID nach SYSTEM/Administratoren an. Der allgemeine Fünfargument- +Konstruktor und auch die verschachtelte SID-Konstruktion bestanden separat alle +sechs Rollen-/Inheritancekombinationen und sind keine nachgewiesene Ursache. + +Der neue Quellstand normalisiert nur Null-**Collections** vor der Identitätsliste +zu leeren Arrays; einzelne ungültige SIDwerte werden weiterhin verweigert. +`Protect` und der speicherinterne Guard benutzen dieselben `ControlIdentities`- +und typisierten `ControlRule`-Funktionen. Der echte lokale pwsh7-Test mit leerer +IF-Pipeline bestand; die reine WindowsPS5-Konstruktorphase `memory-guard` ist für +Root vorbereitet, noch kein behauptetes natives Ergebnis. Der alte partielle +Fall bleibt erhalten und wird nicht mit geänderter Quelle erneut vorbereitet.