//! Local, mutually pinned SYSTEM-helper pipe. This transport never approves jobs. //! No generic write rights on the pipe: FILE_APPEND_DATA also creates instances. use anyhow::{Context, Result, ensure}; use rmm_agent_core::{ auth::{Binding, Outcome, Request}, helper_reconcile::{NoStartAnchor, SignedResponse, Snapshot}, }; use rmm_domain::jobs::hash; use serde::{Deserialize, Serialize, de::DeserializeOwned}; use sha2::{Digest, Sha256}; use std::{ ffi::c_void, fs::File, io::{Read, Write}, mem::{size_of, zeroed}, os::windows::{ ffi::OsStrExt, io::{AsRawHandle, FromRawHandle, OwnedHandle}, }, path::{Path, PathBuf}, ptr, time::{Duration, Instant}, }; use uuid::Uuid; use windows_sys::Win32::{ Foundation::*, Security::{Authorization::*, *}, Storage::FileSystem::*, System::{IO::*, Pipes::*, Services::*, Threading::*}, }; pub const HELPER_SERVICE: &str = "RmmDiscoverySystemHelper"; // Framing v2 is deliberately a separate endpoint. Old peers cannot send a // v1 call to this server or interpret the drain receipt as another reply. pub const PIPE_NAME: &str = r"\\.\pipe\RustDiscovery-System-v2"; pub const TIME_PIPE_NAME: &str = r"\\.\pipe\RustDiscovery-System-Time-v1"; const FRAME_TAG: [u8; 8] = *b"RDPIPC02"; const DRAIN_TAG: [u8; 8] = *b"RDPACK02"; const FRAME_HEADER_LEN: usize = 12; const DRAIN_RECEIPT_LEN: usize = 56; pub const FRAME_LIMIT: usize = 1024 * 1024; pub const CLIENT_PIPE_RIGHTS: u32 = 0x0012_0083; // data R/W, attributes R, RC, synchronize; no bit4 const READ_MASK: u32 = 0x0012_00a9; /// Static diagnostic contexts only; no caller input or error text is serialized. #[derive(Clone, Copy, Debug)] pub enum Stage { DiscoverPin, ClientSelfRole, ClientOpenPipe, ClientHelperPeer, ClientSendFrame, ClientReadReply, ClientReplyBinding, ClientDrainReceipt, ClientReport, ServerConnect, ServerReadHeader, ServerClientPeer, ServerImpersonate, ServerVerifyToken, ServerReadBody, ServerCallBinding, ServerRecheckPeer, ServerReply, ServerDrainReceipt, Unclassified, } impl Stage { fn name(self) -> &'static str { match self { Self::DiscoverPin => "discover_pin", Self::ClientSelfRole => "client_self_role", Self::ClientOpenPipe => "client_open_pipe", Self::ClientHelperPeer => "client_helper_peer", Self::ClientSendFrame => "client_send_frame", Self::ClientReadReply => "client_read_reply", Self::ClientReplyBinding => "client_reply_binding", Self::ClientDrainReceipt => "client_drain_receipt", Self::ClientReport => "client_report", Self::ServerConnect => "server_connect", Self::ServerReadHeader => "server_read_header", Self::ServerClientPeer => "server_client_peer", Self::ServerImpersonate => "server_impersonate", Self::ServerVerifyToken => "server_verify_client_token", Self::ServerReadBody => "server_read_body", Self::ServerCallBinding => "server_call_binding", Self::ServerRecheckPeer => "server_recheck_peer", Self::ServerReply => "server_reply", Self::ServerDrainReceipt => "server_drain_receipt", Self::Unclassified => "unclassified", } } } impl std::fmt::Display for Stage { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.name()) } } #[derive(Clone, Copy, Debug, Serialize)] pub struct Diagnostic { pub stage: &'static str, pub code: &'static str, #[serde(skip_serializing_if = "Option::is_none")] pub win32: Option, } impl std::fmt::Display for Diagnostic { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.code) } } impl std::error::Error for Diagnostic {} #[derive(Debug)] struct CapturedWin32(u32); impl std::fmt::Display for CapturedWin32 { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("WIN32_CAPTURED") } } impl std::error::Error for CapturedWin32 {} fn api_failure(code: &'static str) -> anyhow::Error { let captured = unsafe { GetLastError() }; anyhow::anyhow!(code).context(CapturedWin32(captured)) } fn known_code(text: &str) -> Option<&'static str> { const CODES: &[&str] = &[ "HELPER_BINARY_HASH", "HELPER_CALL_BINDING", "HELPER_EMPTY_DACL", "HELPER_EXCESSIVE_WRITER_RIGHTS", "HELPER_FILE_ID", "HELPER_FILE_ID_CHANGED", "HELPER_FILE_INFORMATION", "HELPER_FILE_TYPE", "HELPER_FRAME_CAPACITY", "HELPER_FRAME_EMPTY", "HELPER_FRAME_LENGTH", "HELPER_FRAME_VERSION", "HELPER_DRAIN_RECEIPT", "HELPER_HANDLE", "HELPER_IMAGE_PARENT", "HELPER_IMAGE_SIZE", "HELPER_IMPERSONATED_SELF", "HELPER_LOCAL_ABSOLUTE_PATH", "HELPER_NETWORK_AGENT_ADMIN_FORBIDDEN", "HELPER_NULL_DACL", "HELPER_PATH_ACE", "HELPER_PATH_ACE_TYPE", "HELPER_PATH_OWNER", "HELPER_PATH_REPLACED", "HELPER_PATH_SECURITY", "HELPER_PATH_WRITABLE_OR_FOREIGN", "HELPER_PEER_RESTARTED", "HELPER_PEER_TOKEN_QUERY", "HELPER_PEER_TOKEN_RECHECK", "HELPER_PIN_PROFILE", "HELPER_PIPE_CONNECT", "HELPER_PIPE_EOF", "HELPER_PIPE_IMPERSONATED_TOKEN", "HELPER_PIPE_IMPERSONATION", "HELPER_PIPE_IO", "HELPER_PIPE_SCM_PID", "HELPER_PIPE_TIMEOUT", "HELPER_PIPE_UNAVAILABLE_OR_BUSY", "HELPER_PROCESS_IDENTITY", "HELPER_PROCESS_IMAGE", "HELPER_PROCESS_IMAGE_BINDING", "HELPER_PROCESS_IMAGE_IDENTITY", "HELPER_PROCESS_TIME", "HELPER_PROCESS_TOKEN_IDENTITY", "HELPER_REPARSE_ANCESTOR", "HELPER_REPLY_BINDING", "HELPER_REPLY_OPERATION", "HELPER_SCM_CONFIG", "HELPER_SCM_CONFIG_SIZE", "HELPER_SCM_IMAGE_BINDING", "HELPER_SCM_MANAGER", "HELPER_SCM_NOT_RUNNING", "HELPER_SCM_SERVICE", "HELPER_SELF_TOKEN", "HELPER_SERVICE_SID_NOT_ENABLED", "HELPER_THREAD_TOKEN_UNVERIFIED", "HELPER_TOKEN_GROUPS_SIZE", "HELPER_TOKEN_INFORMATION", "HELPER_TOKEN_SIZE", "HELPER_TOKEN_USER", "SYSTEM_LEDGER_OR_LOCK_REPLACED", "SYSTEM_HELD_FILE_CHANGED", "SYSTEM_DB_FILE_ID", "SYSTEM_CALL_BINDING", ]; CODES.iter().copied().find(|code| *code == text) } pub fn diagnostic(error: &anyhow::Error) -> Diagnostic { if let Some(value) = error.downcast_ref::() { return *value; } let code = error .chain() .find_map(|cause| known_code(&cause.to_string())) .unwrap_or("UNCLASSIFIED_IO_OR_CODEC"); Diagnostic { stage: error .downcast_ref::() .copied() .unwrap_or(Stage::Unclassified) .name(), code, win32: error.downcast_ref::().map(|v| v.0), } } pub fn remote_denial(stage: Stage, code: &str) -> anyhow::Error { Diagnostic { stage: stage.name(), code: known_code(code).unwrap_or("UNCLASSIFIED_REMOTE_DENIAL"), win32: None, } .into() } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct PeerPin { pub service_name: String, pub service_sid: String, pub user_sid: String, pub binary: PathBuf, pub binary_sha256: String, } impl PeerPin { pub fn validate(&self, helper: bool) -> Result<()> { let name = if helper { HELPER_SERVICE } else { crate::SERVICE_NAME }; ensure!( self.service_name == name && self.user_sid == if helper { "S-1-5-18" } else { "S-1-5-19" }, "HELPER_PEER_ROLE" ); ensure!( self.service_sid == service_sid(name)? && digest(&self.binary_sha256), "HELPER_PEER_PIN" ); ensure!( self.binary == Path::new(if helper { r"C:\Program Files\RustDiscovery\rmm-helper-windows.exe" } else { r"C:\Program Files\RustDiscovery\rmm-agent-windows.exe" }), "HELPER_FIXED_IMAGE" ); Ok(()) } fn command(&self) -> String { if self.service_name == HELPER_SERVICE { format!("\"{}\" --service", self.binary.display()) } else if self.service_name == crate::SERVICE_NAME { format!( "\"{}\" --service --config \"C:\\ProgramData\\RustDiscovery\\config.json\"", self.binary.display() ) } else { format!("\"{}\"", self.binary.display()) } } } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Pin { pub schema_version: u32, pub binding: Binding, pub policy_sha256: String, pub agent: PeerPin, pub helper: PeerPin, } impl Pin { pub fn validate(&self) -> Result<()> { ensure!( self.schema_version == 1 && digest(&self.policy_sha256), "HELPER_PIN_PROFILE" ); self.agent.validate(false)?; self.helper.validate(true)?; Ok(()) } } #[derive(Clone, Serialize, Deserialize)] #[serde(tag = "operation", rename_all = "snake_case", deny_unknown_fields)] pub enum Operation { TimeBegin { generation: u64, }, TimeComplete { generation: u64, response_bytes: Vec, }, /// Deny-only transport/context fence. It cannot qualify a clock or lease. TimeClose { generation: u64, }, Probe {}, Snapshot { generation: u64, }, Apply { response: SignedResponse, request_bytes: Vec, }, Execute { generation: u64, request: Request, }, Abandon { anchor: Box, request: Request, intent_id: Uuid, intent_sha256: String, }, } impl Operation { fn time_only(&self) -> bool { matches!( self, Self::TimeBegin { .. } | Self::TimeComplete { .. } | Self::TimeClose { .. } ) } } #[derive(Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Call { pub schema_version: u32, pub challenge: Uuid, pub binding: Binding, pub policy_sha256: String, pub operation: Operation, } impl Call { pub fn new(pin: &Pin, operation: Operation) -> Self { Self { schema_version: 1, challenge: Uuid::new_v4(), binding: pin.binding.clone(), policy_sha256: pin.policy_sha256.clone(), operation, } } } #[derive(Debug, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] pub enum ReplyBody { TimeChallenge { request: rmm_time_attestation::Request, }, TimeCompleted {}, TimeClosed {}, Probe { clock_qualified: bool, ready: bool, ledger: FileIdentity, lock: FileIdentity, }, Snapshot { snapshot: Snapshot, }, Applied { snapshot: Snapshot, unlocked_grants: Vec, ready: bool, no_start_anchor: Option>, }, Executed { outcome: Outcome, }, Abandoned { outcome: Outcome, }, Denied { code: String, }, } #[derive(Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Reply { pub schema_version: u32, pub challenge: Uuid, pub binding_sha256: String, pub policy_sha256: String, pub helper_binary_sha256: String, pub body: ReplyBody, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct FileIdentity { pub volume_serial: u64, pub file_id: [u8; 16], } pub fn digest(s: &str) -> bool { s.len() == 64 && s.bytes() .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) } pub fn binding_hash(b: &Binding) -> Result { Ok(hash(&serde_json::to_vec(b)?)) } pub fn wide(s: impl AsRef) -> Vec { s.as_ref().encode_wide().chain(Some(0)).collect() } fn owned(raw: HANDLE) -> Result { if raw.is_null() || raw == INVALID_HANDLE_VALUE { return Err(api_failure("HELPER_HANDLE")); } Ok(unsafe { OwnedHandle::from_raw_handle(raw) }) } fn sid_text(sid: PSID) -> Result { let mut text = ptr::null_mut(); ensure!( unsafe { ConvertSidToStringSidW(sid, &mut text) } != 0, "HELPER_SID_TEXT" ); let mut n = 0; unsafe { while n < 256 && *text.add(n) != 0 { n += 1; } }; let result = if n < 256 { String::from_utf16(unsafe { std::slice::from_raw_parts(text, n) })? } else { String::new() }; unsafe { LocalFree(text.cast()); } ensure!(!result.is_empty(), "HELPER_SID_SIZE"); Ok(result) } pub fn service_sid(name: &str) -> Result { let name = wide(format!("NT SERVICE\\{name}")); let mut length = 0; let mut domain_length = 0; let mut use_type = 0; unsafe { LookupAccountNameW( ptr::null(), name.as_ptr(), ptr::null_mut(), &mut length, ptr::null_mut(), &mut domain_length, &mut use_type, ); } ensure!( (1..=256).contains(&length) && domain_length <= 256, "HELPER_SERVICE_SID_SIZE" ); let mut sid = vec![0usize; (length as usize).div_ceil(size_of::())]; let mut domain = vec![0u16; domain_length as usize]; ensure!( unsafe { LookupAccountNameW( ptr::null(), name.as_ptr(), sid.as_mut_ptr().cast(), &mut length, domain.as_mut_ptr(), &mut domain_length, &mut use_type, ) } != 0, "HELPER_SERVICE_SID" ); sid_text(sid.as_mut_ptr().cast()) } fn token_information(token: HANDLE, class: TOKEN_INFORMATION_CLASS) -> Result> { let mut needed = 0; unsafe { GetTokenInformation(token, class, ptr::null_mut(), 0, &mut needed); } ensure!((1..=65536).contains(&needed), "HELPER_TOKEN_SIZE"); let mut data = vec![0usize; (needed as usize).div_ceil(size_of::())]; ensure!( unsafe { GetTokenInformation(token, class, data.as_mut_ptr().cast(), needed, &mut needed) } != 0, "HELPER_TOKEN_INFORMATION" ); Ok(data) } pub fn verify_token(token: HANDLE, user: &str, service: &str) -> Result<()> { let u = token_information(token, TokenUser)?; ensure!( sid_text(unsafe { (*u.as_ptr().cast::()).User.Sid })? == user, "HELPER_TOKEN_USER" ); let groups = token_information(token, TokenGroups)?; let g = unsafe { &*groups.as_ptr().cast::() }; let count = g.GroupCount as usize; let offset = std::mem::offset_of!(TOKEN_GROUPS, Groups); ensure!( count <= 1024 && offset + count * size_of::() <= groups.len() * size_of::(), "HELPER_TOKEN_GROUPS_SIZE" ); let rows = unsafe { std::slice::from_raw_parts(g.Groups.as_ptr(), count) }; let mut found = false; for row in rows { let sid = sid_text(row.Sid)?; ensure!( user != "S-1-5-19" || sid != "S-1-5-32-544" || row.Attributes & 0x0000_0004 == 0, "HELPER_NETWORK_AGENT_ADMIN_FORBIDDEN" ); // TOKEN_GROUPS SE_GROUP_ENABLED and SE_GROUP_USE_FOR_DENY_ONLY (winnt.h). if row.Attributes & 0x0000_0004 != 0 && row.Attributes & 0x0000_0010 == 0 && sid == service { found = true; } } ensure!(found, "HELPER_SERVICE_SID_NOT_ENABLED"); Ok(()) } pub fn require_self(peer: &PeerPin) -> Result<()> { let mut thread = ptr::null_mut(); if unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, 1, &mut thread) } != 0 { let _ = owned(thread)?; anyhow::bail!("HELPER_IMPERSONATED_SELF"); } ensure!( unsafe { GetLastError() } == ERROR_NO_TOKEN, "HELPER_THREAD_TOKEN_UNVERIFIED" ); let mut token = ptr::null_mut(); ensure!( unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } != 0, "HELPER_SELF_TOKEN" ); let token = owned(token)?; verify_token(token.as_raw_handle(), &peer.user_sid, &peer.service_sid) } fn check_acl( handle: HANDLE, readers: &[String], writers: &[String], writer_mask: Option, ) -> Result<()> { let mut owner = ptr::null_mut(); let mut acl = ptr::null_mut(); let mut descriptor = ptr::null_mut(); ensure!( unsafe { GetSecurityInfo( handle, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, &mut owner, ptr::null_mut(), &mut acl, ptr::null_mut(), &mut descriptor, ) } == 0, "HELPER_PATH_SECURITY" ); let result = (|| { ensure!(!owner.is_null() && !acl.is_null(), "HELPER_NULL_DACL"); let owner = sid_text(owner)?; ensure!( matches!(owner.as_str(), "S-1-5-18" | "S-1-5-32-544"), "HELPER_PATH_OWNER" ); ensure!(unsafe { (*acl).AceCount } > 0, "HELPER_EMPTY_DACL"); for n in 0..unsafe { (*acl).AceCount } { let mut ace = ptr::null_mut(); ensure!( unsafe { GetAce(acl, n.into(), &mut ace) } != 0, "HELPER_PATH_ACE" ); let ace = unsafe { &*ace.cast::() }; ensure!( ace.Header.AceType == 0 && ace.Header.AceSize as usize >= size_of::(), "HELPER_PATH_ACE_TYPE" ); let sid = sid_text(ptr::addr_of!(ace.SidStart).cast_mut().cast())?; let privileged = matches!(sid.as_str(), "S-1-5-18" | "S-1-5-32-544") || writers.contains(&sid); if writers.contains(&sid) && !matches!(sid.as_str(), "S-1-5-18" | "S-1-5-32-544") { ensure!( writer_mask.is_none_or(|mask| ace.Mask & !mask == 0), "HELPER_EXCESSIVE_WRITER_RIGHTS" ); } ensure!( privileged || (readers.contains(&sid) && ace.Mask & !READ_MASK == 0), "HELPER_PATH_WRITABLE_OR_FOREIGN" ); } Ok(()) })(); unsafe { LocalFree(descriptor.cast()); } result } pub struct PinnedFile { pub file: File, pub identity: FileIdentity, pub path: PathBuf, readers: Vec, writers: Vec, directory: bool, writer_mask: Option, } impl PinnedFile { pub fn open( path: &Path, directory: bool, readers: &[String], writers: &[String], write: bool, ) -> Result { Self::open_impl(path, directory, readers, writers, write, false) } /// Pin and check the object without opening a write-capable handle. pub fn open_read_shared( path: &Path, directory: bool, readers: &[String], writers: &[String], ) -> Result { Self::open_impl(path, directory, readers, writers, false, true) } pub(crate) fn limit_writer_rights(&mut self, mask: u32) -> Result<()> { self.writer_mask = Some(mask); self.check() } fn open_impl( path: &Path, directory: bool, readers: &[String], writers: &[String], write: bool, share_write: bool, ) -> Result { ensure!( path.is_absolute() && !path.to_string_lossy().starts_with(r"\\") && !path.to_string_lossy().contains("..") && !path.as_os_str().encode_wide().any(|c| c == 0), "HELPER_LOCAL_ABSOLUTE_PATH" ); for ancestor in path.ancestors().skip(1) { let handle = owned(unsafe { CreateFileW( wide(ancestor).as_ptr(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, ptr::null(), OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, ptr::null_mut(), ) })?; let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() }; ensure!( unsafe { GetFileInformationByHandle(handle.as_raw_handle(), &mut info) } != 0 && info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0, "HELPER_REPARSE_ANCESTOR" ); } let raw = unsafe { CreateFileW( wide(path).as_ptr(), if write { GENERIC_READ | GENERIC_WRITE } else { GENERIC_READ }, FILE_SHARE_READ | if write || share_write { FILE_SHARE_WRITE } else { 0 }, ptr::null(), OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | if directory { FILE_FLAG_BACKUP_SEMANTICS } else { 0 }, ptr::null_mut(), ) }; let handle = owned(raw)?; let file: File = handle.into(); let mut value = Self { identity: file_identity(&file)?, file, path: path.into(), readers: readers.into(), writers: writers.into(), directory, writer_mask: None, }; value.check()?; Ok(value) } pub fn check(&mut self) -> Result<()> { let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() }; ensure!( unsafe { GetFileInformationByHandle(self.file.as_raw_handle(), &mut info) } != 0, "HELPER_FILE_INFORMATION" ); ensure!( info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0 && (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0) == self.directory, "HELPER_FILE_TYPE" ); ensure!( file_identity(&self.file)? == self.identity, "HELPER_FILE_ID_CHANGED" ); check_acl( self.file.as_raw_handle(), &self.readers, &self.writers, self.writer_mask, )?; let raw = unsafe { CreateFileW( wide(&self.path).as_ptr(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, ptr::null(), OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | if self.directory { FILE_FLAG_BACKUP_SEMANTICS } else { 0 }, ptr::null_mut(), ) }; let check = owned(raw)?; ensure!( file_identity(&check)? == self.identity, "HELPER_PATH_REPLACED" ); Ok(()) } pub fn sha256(&mut self) -> Result { use std::io::{Seek, SeekFrom}; ensure!( !self.directory && self.file.metadata()?.len() <= 128 * 1024 * 1024, "HELPER_IMAGE_SIZE" ); self.file.seek(SeekFrom::Start(0))?; let mut h = sha2::Sha256::new(); use sha2::Digest; let mut buf = [0u8; 65536]; loop { let n = self.file.read(&mut buf)?; if n == 0 { break; } h.update(&buf[..n]); } Ok(h.finalize().iter().map(|b| format!("{b:02x}")).collect()) } } pub fn file_identity(handle: &impl AsRawHandle) -> Result { let mut id: FILE_ID_INFO = unsafe { zeroed() }; ensure!( unsafe { GetFileInformationByHandleEx( handle.as_raw_handle(), FileIdInfo, (&mut id as *mut FILE_ID_INFO).cast(), size_of::() as u32, ) } != 0, "HELPER_FILE_ID" ); Ok(FileIdentity { volume_serial: id.VolumeSerialNumber, file_id: id.FileId.Identifier, }) } struct ServiceHandle(SC_HANDLE); impl Drop for ServiceHandle { fn drop(&mut self) { unsafe { CloseServiceHandle(self.0); } } } fn service_status(pin: &PeerPin) -> Result { let manager = ServiceHandle(unsafe { OpenSCManagerW(ptr::null(), ptr::null(), SC_MANAGER_CONNECT) }); ensure!(!manager.0.is_null(), "HELPER_SCM_MANAGER"); let service = ServiceHandle(unsafe { OpenServiceW( manager.0, wide(&pin.service_name).as_ptr(), SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG, ) }); ensure!(!service.0.is_null(), "HELPER_SCM_SERVICE"); let mut needed = 0; unsafe { QueryServiceConfigW(service.0, ptr::null_mut(), 0, &mut needed); }; ensure!((1..=32768).contains(&needed), "HELPER_SCM_CONFIG_SIZE"); let mut config = vec![0usize; (needed as usize).div_ceil(size_of::())]; ensure!( unsafe { QueryServiceConfigW(service.0, config.as_mut_ptr().cast(), needed, &mut needed) } != 0, "HELPER_SCM_CONFIG" ); let c = unsafe { &*config.as_ptr().cast::() }; ensure!( c.dwServiceType == SERVICE_WIN32_OWN_PROCESS && unsafe { utf16_pointer(c.lpBinaryPathName) }? == pin.command(), "HELPER_SCM_IMAGE_BINDING" ); let mut status: SERVICE_STATUS_PROCESS = unsafe { zeroed() }; ensure!( unsafe { QueryServiceStatusEx( service.0, SC_STATUS_PROCESS_INFO, (&mut status as *mut SERVICE_STATUS_PROCESS).cast(), size_of::() as u32, &mut needed, ) } != 0 && status.dwCurrentState == SERVICE_RUNNING && status.dwProcessId > 0, "HELPER_SCM_NOT_RUNNING" ); Ok(status.dwProcessId) } /// # Safety /// `value` must point into a held successful Windows API result with a valid /// NUL-terminated UTF16 string; the owning result must outlive this call. pub unsafe fn utf16_pointer(value: *const u16) -> Result { ensure!(!value.is_null(), "HELPER_STRING_POINTER"); let mut n = 0; while n < 32768 && unsafe { *value.add(n) } != 0 { n += 1; } ensure!(n < 32768, "HELPER_STRING_BOUND"); Ok(String::from_utf16(unsafe { std::slice::from_raw_parts(value, n) })?) } fn creation(handle: HANDLE) -> Result { let (mut c, mut e, mut k, mut u) = unsafe { (zeroed(), zeroed(), zeroed(), zeroed()) }; ensure!( unsafe { GetProcessTimes(handle, &mut c, &mut e, &mut k, &mut u) } != 0, "HELPER_PROCESS_TIME" ); Ok((u64::from(c.dwHighDateTime) << 32) | u64::from(c.dwLowDateTime)) } pub struct PeerProof { process: OwnedHandle, creation: u64, pin: PeerPin, _image: PinnedFile, _image_parent: PinnedFile, pid: u32, identity: ProcessIdentity, } #[derive(Clone, Debug, Serialize)] pub(crate) struct ProcessIdentity { pub pid: u32, pub creation_ticks: u64, pub user_sid: String, pub service_sid: String, pub image: PathBuf, pub image_sha256: String, pub image_file: FileIdentity, } impl ProcessIdentity { pub(crate) fn validate(&self, pin: &PeerPin, expected_pid: u32) -> Result<()> { ensure!( self.pid == expected_pid && expected_pid > 0 && self.creation_ticks > 0, "HELPER_PROCESS_IDENTITY" ); ensure!( self.user_sid == pin.user_sid && self.service_sid == pin.service_sid, "HELPER_PROCESS_TOKEN_IDENTITY" ); ensure!( self.image == pin.binary && self.image_sha256 == pin.binary_sha256, "HELPER_PROCESS_IMAGE_IDENTITY" ); Ok(()) } } impl PeerProof { fn capture(pipe: HANDLE, pin: &PeerPin, client: bool) -> Result { let mut pid = 0; ensure!( unsafe { if client { GetNamedPipeClientProcessId(pipe, &mut pid) } else { GetNamedPipeServerProcessId(pipe, &mut pid) } } != 0 && pid > 0, "HELPER_PIPE_SCM_PID" ); Self::for_service(pin, pid) } /// Internal fixture admission shares the exact same live-process proof as /// both pipe peers. The caller supplies the PID read from its held SCM handle. pub(crate) fn for_service(pin: &PeerPin, pid: u32) -> Result { ensure!(pid == service_status(pin)?, "HELPER_PIPE_SCM_PID"); let process = owned(unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, 0, pid) })?; let born = creation(process.as_raw_handle())?; let mut token = ptr::null_mut(); ensure!( unsafe { OpenProcessToken(process.as_raw_handle(), TOKEN_QUERY, &mut token) } != 0, "HELPER_PEER_TOKEN_QUERY" ); let token = owned(token)?; verify_token(token.as_raw_handle(), &pin.user_sid, &pin.service_sid)?; let actual_user = token_information(token.as_raw_handle(), TokenUser)?; let actual_user = sid_text(unsafe { (*actual_user.as_ptr().cast::()).User.Sid })?; 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, "HELPER_PROCESS_IMAGE" ); let image_name = String::from_utf16(&image[..length as usize])?; ensure!( Path::new(&image_name) == pin.binary, "HELPER_PROCESS_IMAGE_BINDING" ); let image_parent = PinnedFile::open( pin.binary.parent().context("HELPER_IMAGE_PARENT")?, true, &[ service_sid(crate::SERVICE_NAME)?, service_sid(HELPER_SERVICE)?, pin.service_sid.clone(), ], &[], false, )?; let mut image = PinnedFile::open( &pin.binary, false, &[ pin.service_sid.clone(), service_sid(crate::SERVICE_NAME)?, service_sid(HELPER_SERVICE)?, ], &[], false, )?; let actual_hash = image.sha256()?; ensure!(actual_hash == pin.binary_sha256, "HELPER_BINARY_HASH"); let identity = ProcessIdentity { pid, creation_ticks: born, user_sid: actual_user, service_sid: pin.service_sid.clone(), image: image_name.into(), image_sha256: actual_hash, image_file: image.identity, }; identity.validate(pin, pid)?; let mut result = Self { process, creation: born, pin: pin.clone(), _image: image, _image_parent: image_parent, pid, identity, }; result.check()?; Ok(result) } pub fn check(&mut self) -> Result<()> { ensure!( unsafe { WaitForSingleObject(self.process.as_raw_handle(), 0) } == WAIT_TIMEOUT && creation(self.process.as_raw_handle())? == self.creation && service_status(&self.pin)? == self.pid, "HELPER_PEER_RESTARTED" ); let mut token = ptr::null_mut(); ensure!( unsafe { OpenProcessToken(self.process.as_raw_handle(), TOKEN_QUERY, &mut token) } != 0, "HELPER_PEER_TOKEN_RECHECK" ); let token = owned(token)?; verify_token( token.as_raw_handle(), &self.pin.user_sid, &self.pin.service_sid, )?; self._image_parent.check()?; self._image.check() } pub(crate) fn identity(&self) -> &ProcessIdentity { &self.identity } pub(crate) fn exited(&self) -> Result { ensure!( creation(self.process.as_raw_handle())? == self.creation, "HELPER_PROCESS_IDENTITY" ); let state = unsafe { WaitForSingleObject(self.process.as_raw_handle(), 0) }; ensure!( matches!(state, WAIT_OBJECT_0 | WAIT_TIMEOUT), "HELPER_PROCESS_EXIT_QUERY" ); Ok(state == WAIT_OBJECT_0) } } struct Descriptor(*mut c_void); impl Descriptor { fn from(s: &str) -> Result { let mut descriptor = ptr::null_mut(); ensure!( unsafe { ConvertStringSecurityDescriptorToSecurityDescriptorW( wide(s).as_ptr(), 1, &mut descriptor, ptr::null_mut(), ) } != 0, "HELPER_DESCRIPTOR" ); Ok(Self(descriptor)) } } impl Drop for Descriptor { fn drop(&mut self) { unsafe { LocalFree(self.0); } } } /// Read-only visibility into these TWO OWN objects; never grant SeDebug or token duplication. pub fn publish_self_query_rights(agent_sid: &str, helper_sid: &str) -> Result<()> { ensure!( agent_sid == service_sid(crate::SERVICE_NAME)? && helper_sid == service_sid(HELPER_SERVICE)?, "HELPER_QUERY_RIGHTS_ROLE" ); let mut token = ptr::null_mut(); ensure!( unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | WRITE_DAC, &mut token) } != 0, "HELPER_SELF_TOKEN_DACL" ); let token = owned(token)?; verify_token(token.as_raw_handle(), "S-1-5-18", helper_sid)?; for (handle, rights) in [ ( unsafe { GetCurrentProcess() }, PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, ), (token.as_raw_handle(), TOKEN_QUERY), ] { let d = Descriptor::from(&format!( "O:SYG:SYD:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;{helper_sid})(A;;0x{rights:08x};;;{agent_sid})" ))?; ensure!( unsafe { SetKernelObjectSecurity(handle, DACL_SECURITY_INFORMATION, d.0) } != 0, "HELPER_OWN_QUERY_DACL" ); } Ok(()) } fn pipe_descriptor(agent: &str, helper: &str) -> Result { ensure!( agent == service_sid(crate::SERVICE_NAME)? && helper == service_sid(HELPER_SERVICE)?, "HELPER_PIPE_SID_BINDING" ); Descriptor::from(&format!( "O:SYG:SYD:P(D;;GA;;;NU)(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;{helper})(A;;0x{CLIENT_PIPE_RIGHTS:08x};;;{agent})" )) } struct IoEvent { event: OwnedHandle, overlapped: OVERLAPPED, } impl IoEvent { 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) -> Result { let left = deadline.saturating_duration_since(Instant::now()); let milliseconds = u32::try_from(left.as_millis().max(1)).unwrap_or(u32::MAX - 1); if unsafe { WaitForSingleObject(self.event.as_raw_handle(), milliseconds) } != WAIT_OBJECT_0 { unsafe { CancelIoEx(pipe, &self.overlapped); } // Never free an OVERLAPPED/buffer still owned by the kernel. A failed // bounded cancellation is terminal for this process; no unwind. if unsafe { WaitForSingleObject(self.event.as_raw_handle(), 1000) } != WAIT_OBJECT_0 { std::process::abort(); } let mut count = 0; if unsafe { GetOverlappedResult(pipe, &self.overlapped, &mut count, 0) } == 0 && unsafe { GetLastError() } == ERROR_IO_INCOMPLETE { std::process::abort(); } anyhow::bail!("HELPER_PIPE_TIMEOUT"); } let mut count = 0; let complete = unsafe { GetOverlappedResult(pipe, &self.overlapped, &mut count, 0) }; if complete == 0 { let error = api_failure("HELPER_PIPE_IO"); if error .downcast_ref::() .is_some_and(|v| v.0 == ERROR_IO_INCOMPLETE) { std::process::abort(); } return Err(error); } Ok(count) } fn completed(&self, pipe: HANDLE) -> Result { let mut count = 0; if unsafe { GetOverlappedResult(pipe, &self.overlapped, &mut count, 0) } == 0 { let error = api_failure("HELPER_PIPE_IO"); if error .downcast_ref::() .is_some_and(|v| v.0 == ERROR_IO_INCOMPLETE) { std::process::abort(); } return Err(error); } Ok(count) } } fn transfer(pipe: HANDLE, bytes: &mut [u8], write: bool, deadline: Instant) -> Result<()> { let mut offset = 0; while offset < bytes.len() { ensure!(Instant::now() < deadline, "HELPER_PIPE_TIMEOUT"); let mut operation = IoEvent::new()?; let part = &mut bytes[offset..]; let ok = unsafe { if write { WriteFile( pipe, part.as_ptr(), part.len().try_into()?, ptr::null_mut(), &mut operation.overlapped, ) } else { ReadFile( pipe, part.as_mut_ptr(), part.len().try_into()?, ptr::null_mut(), &mut operation.overlapped, ) } }; let count = if ok != 0 { // ReadFile/WriteFile are always OVERLAPPED here. Their direct // byte-counter is unspecified for async handles, even on TRUE. // Obtain completion bytes from this exact held OVERLAPPED instead. operation.completed(pipe)? } else { let error = unsafe { GetLastError() }; if error != ERROR_IO_PENDING { return Err(anyhow::anyhow!("HELPER_PIPE_IO").context(CapturedWin32(error))); } operation.wait(pipe, deadline)? }; ensure!(count > 0 && count as usize <= part.len(), "HELPER_PIPE_EOF"); offset += count as usize; } Ok(()) } struct LimitedJson(Vec); impl Write for LimitedJson { fn write(&mut self, bytes: &[u8]) -> std::io::Result { if bytes.len() > FRAME_LIMIT - self.0.len() { return Err(std::io::Error::other("HELPER_FRAME_CAPACITY")); } self.0.extend_from_slice(bytes); Ok(bytes.len()) } fn flush(&mut self) -> std::io::Result<()> { Ok(()) } } fn encode(value: &impl Serialize) -> Result> { let mut writer = LimitedJson(Vec::with_capacity(FRAME_LIMIT)); serde_json::to_writer(&mut writer, value)?; ensure!(!writer.0.is_empty(), "HELPER_FRAME_EMPTY"); Ok(writer.0) } fn frame_header(len: usize) -> Result<[u8; FRAME_HEADER_LEN]> { ensure!((1..=FRAME_LIMIT).contains(&len), "HELPER_FRAME_LENGTH"); let mut header = [0; FRAME_HEADER_LEN]; header[..8].copy_from_slice(&FRAME_TAG); header[8..].copy_from_slice(&u32::try_from(len)?.to_be_bytes()); Ok(header) } fn send_bytes(pipe: HANDLE, bytes: &mut [u8], deadline: Instant) -> Result<()> { let mut header = frame_header(bytes.len())?; transfer(pipe, &mut header, true, deadline)?; transfer(pipe, bytes, true, deadline) } fn send(pipe: HANDLE, value: &impl Serialize, deadline: Instant) -> Result<()> { send_bytes(pipe, &mut encode(value)?, deadline) } fn frame_length(header: [u8; FRAME_HEADER_LEN]) -> Result { ensure!(header[..8] == FRAME_TAG, "HELPER_FRAME_VERSION"); let len = u32::from_be_bytes(header[8..].try_into()?) as usize; ensure!((1..=FRAME_LIMIT).contains(&len), "HELPER_FRAME_LENGTH"); Ok(len) } fn length(pipe: HANDLE, deadline: Instant) -> Result { let mut header = [0u8; FRAME_HEADER_LEN]; transfer(pipe, &mut header, false, deadline)?; frame_length(header) } fn body_bytes(pipe: HANDLE, len: usize, deadline: Instant) -> Result> { ensure!((1..=FRAME_LIMIT).contains(&len), "HELPER_FRAME_LENGTH"); let mut bytes = vec![0u8; len]; transfer(pipe, &mut bytes, false, deadline)?; Ok(bytes) } fn body(pipe: HANDLE, len: usize, deadline: Instant) -> Result { Ok(serde_json::from_slice(&body_bytes(pipe, len, deadline)?)?) } // This fixed-size receipt only acknowledges receipt of these transport bytes. // It never acknowledges durable evidence, clears state, or permits an effect. fn drain_receipt(challenge: Uuid, reply_bytes: &[u8]) -> [u8; DRAIN_RECEIPT_LEN] { let mut receipt = [0; DRAIN_RECEIPT_LEN]; receipt[..8].copy_from_slice(&DRAIN_TAG); receipt[8..24].copy_from_slice(challenge.as_bytes()); receipt[24..].copy_from_slice(&Sha256::digest(reply_bytes)); receipt } fn verify_drain_receipt( receipt: &[u8; DRAIN_RECEIPT_LEN], challenge: Uuid, reply_bytes: &[u8], ) -> Result<()> { ensure!( *receipt == drain_receipt(challenge, reply_bytes), "HELPER_DRAIN_RECEIPT" ); Ok(()) } pub struct Server { pipe: OwnedHandle, pin: Pin, time_only: bool, } pub struct Received { pub call: Call, pub peer: PeerProof, } impl Server { pub fn bind(pin: Pin) -> Result { Self::bind_fixed(pin, false) } pub fn bind_time(pin: Pin) -> Result { Self::bind_fixed(pin, true) } fn bind_fixed(pin: Pin, time_only: bool) -> Result { pin.validate()?; require_self(&pin.helper)?; let descriptor = pipe_descriptor(&pin.agent.service_sid, &pin.helper.service_sid)?; let security = SECURITY_ATTRIBUTES { nLength: size_of::() as u32, lpSecurityDescriptor: descriptor.0, bInheritHandle: 0, }; let pipe = owned(unsafe { CreateNamedPipeW( wide(if time_only { TIME_PIPE_NAME } else { PIPE_NAME }).as_ptr(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS, 1, 65536, 65536, 1000, &security, ) })?; Ok(Self { pipe, pin, time_only, }) } pub fn receive(&self) -> Result> { let pipe = self.pipe.as_raw_handle(); let mut connect = IoEvent::new().context(Stage::ServerConnect)?; let connected = unsafe { ConnectNamedPipe(pipe, &mut connect.overlapped) }; if connected == 0 { let error = unsafe { GetLastError() }; if error == ERROR_IO_PENDING { if let Err(error) = connect.wait(pipe, Instant::now() + Duration::from_millis(250)) { if diagnostic(&error).code == "HELPER_PIPE_TIMEOUT" { unsafe { DisconnectNamedPipe(pipe); }; return Ok(None); } return Err(error).context(Stage::ServerConnect); } } else { if error != ERROR_PIPE_CONNECTED { return Err( anyhow::anyhow!("HELPER_PIPE_CONNECT").context(CapturedWin32(error)) ) .context(Stage::ServerConnect); } } } let deadline = Instant::now() + Duration::from_secs(5); let len = length(pipe, deadline).context(Stage::ServerReadHeader)?; let mut peer = PeerProof::capture(pipe, &self.pin.agent, true).context(Stage::ServerClientPeer)?; if unsafe { ImpersonateNamedPipeClient(pipe) } == 0 { return Err(api_failure("HELPER_PIPE_IMPERSONATION")).context(Stage::ServerImpersonate); } let auth = (|| { let mut token = ptr::null_mut(); if unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, 1, &mut token) } == 0 { return Err(api_failure("HELPER_PIPE_IMPERSONATED_TOKEN")); } let token = owned(token)?; verify_token( token.as_raw_handle(), &self.pin.agent.user_sid, &self.pin.agent.service_sid, ) })(); if unsafe { RevertToSelf() } == 0 { std::process::abort(); } auth.context(Stage::ServerVerifyToken)?; require_self(&self.pin.helper).context(Stage::ServerVerifyToken)?; let call: Call = body(pipe, len, deadline).context(Stage::ServerReadBody)?; ensure!( call.operation.time_only() == self.time_only, "HELPER_PIPE_OPERATION_SCOPE" ); if !(call.schema_version == 1 && !call.challenge.is_nil() && call.policy_sha256 == self.pin.policy_sha256 && binding_hash(&call.binding)? == binding_hash(&self.pin.binding)?) { return Err(anyhow::anyhow!("HELPER_CALL_BINDING")).context(Stage::ServerCallBinding); } peer.check().context(Stage::ServerRecheckPeer)?; Ok(Some(Received { call, peer })) } pub fn reply(&self, value: &Reply, peer: &mut PeerProof) -> Result<()> { // Do not disconnect after WriteFile merely copied bytes into a pipe // buffer. Wait for a receipt from the same fully pinned peer within // the original reply deadline, without an unbounded FlushFileBuffers. let deadline = Instant::now() + Duration::from_secs(5); peer.check().context(Stage::ServerRecheckPeer)?; let mut bytes = encode(value).context(Stage::ServerReply)?; send_bytes(self.pipe.as_raw_handle(), &mut bytes, deadline).context(Stage::ServerReply)?; let mut receipt = [0; DRAIN_RECEIPT_LEN]; transfer(self.pipe.as_raw_handle(), &mut receipt, false, deadline) .context(Stage::ServerDrainReceipt)?; verify_drain_receipt(&receipt, value.challenge, &bytes) .context(Stage::ServerDrainReceipt)?; peer.check().context(Stage::ServerRecheckPeer)?; if Instant::now() >= deadline { return Err(anyhow::anyhow!("HELPER_PIPE_TIMEOUT")).context(Stage::ServerDrainReceipt); } Ok(()) } pub fn disconnect(&self) { unsafe { DisconnectNamedPipe(self.pipe.as_raw_handle()); } } } /// Blocking SDK call; run on the agent's bounded blocking worker, never heartbeat reactor. pub fn exchange(pin: &Pin, call: &Call, timeout: Duration) -> Result { exchange_fixed(pin, call, timeout, false) } pub fn exchange_time(pin: &Pin, call: &Call, timeout: Duration) -> Result { exchange_fixed(pin, call, timeout, true) } fn exchange_fixed(pin: &Pin, call: &Call, timeout: Duration, time_only: bool) -> Result { ensure!( call.operation.time_only() == time_only, "HELPER_PIPE_OPERATION_SCOPE" ); pin.validate()?; require_self(&pin.agent).context(Stage::ClientSelfRole)?; ensure!( (Duration::from_secs(1)..=Duration::from_secs(125)).contains(&timeout), "HELPER_CALL_TIMEOUT_BOUND" ); let deadline = Instant::now() + timeout; let pipe = owned(unsafe { CreateFileW( wide(if time_only { TIME_PIPE_NAME } else { PIPE_NAME }).as_ptr(), CLIENT_PIPE_RIGHTS, 0, ptr::null(), OPEN_EXISTING, FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, ptr::null_mut(), ) }) .context("HELPER_PIPE_UNAVAILABLE_OR_BUSY") .context(Stage::ClientOpenPipe)?; let mut peer = PeerProof::capture(pipe.as_raw_handle(), &pin.helper, false) .context(Stage::ClientHelperPeer)?; send(pipe.as_raw_handle(), call, deadline).context(Stage::ClientSendFrame)?; let len = length(pipe.as_raw_handle(), deadline).context(Stage::ClientReadReply)?; let reply_bytes = body_bytes(pipe.as_raw_handle(), len, deadline).context(Stage::ClientReadReply)?; let reply: Reply = serde_json::from_slice(&reply_bytes).context(Stage::ClientReadReply)?; peer.check().context(Stage::ClientHelperPeer)?; if !(reply.schema_version == 1 && reply.challenge == call.challenge && reply.binding_sha256 == binding_hash(&pin.binding)? && reply.policy_sha256 == pin.policy_sha256 && reply.helper_binary_sha256 == pin.helper.binary_sha256) { return Err(anyhow::anyhow!("HELPER_REPLY_BINDING")).context(Stage::ClientReplyBinding); } if !matches!( (&call.operation, &reply.body), (_, ReplyBody::Denied { .. }) | (Operation::Probe { .. }, ReplyBody::Probe { .. }) | (Operation::Snapshot { .. }, ReplyBody::Snapshot { .. }) | (Operation::Apply { .. }, ReplyBody::Applied { .. }) | (Operation::Execute { .. }, ReplyBody::Executed { .. }) | (Operation::Abandon { .. }, ReplyBody::Abandoned { .. }) | (Operation::TimeBegin { .. }, ReplyBody::TimeChallenge { .. }) | ( Operation::TimeComplete { .. }, ReplyBody::TimeCompleted { .. } ) | (Operation::TimeClose { .. }, ReplyBody::TimeClosed { .. }) ) { return Err(anyhow::anyhow!("HELPER_REPLY_OPERATION")).context(Stage::ClientReplyBinding); } // Only a complete, authenticated, bound and operation-checked reply gets // this receipt. Hash the received bytes, never a JSON re-serialization. let mut receipt = drain_receipt(call.challenge, &reply_bytes); transfer(pipe.as_raw_handle(), &mut receipt, true, deadline) .context(Stage::ClientDrainReceipt)?; Ok(reply) } #[cfg(test)] mod tests { use super::*; #[test] fn pipe_client_rights_cannot_create_an_instance() { assert_eq!(CLIENT_PIPE_RIGHTS & 4, 0); assert_eq!( CLIENT_PIPE_RIGHTS & (GENERIC_WRITE | GENERIC_ALL | WRITE_DAC | WRITE_OWNER | DELETE), 0 ); } #[test] fn serialization_refuses_oversized_frame() { assert!(encode(&vec![255u8; FRAME_LIMIT]).is_err()); assert!(encode(&vec![1u8; 32]).is_ok()); } #[test] fn untrusted_lengths_are_rejected_before_body_allocation() { for n in [0, (FRAME_LIMIT + 1) as u32, u32::MAX] { let mut header = [0; FRAME_HEADER_LEN]; header[..8].copy_from_slice(&FRAME_TAG); header[8..].copy_from_slice(&n.to_be_bytes()); assert!(frame_length(header).is_err()); assert!(frame_header(n as usize).is_err()); } let header = frame_header(FRAME_LIMIT).unwrap(); assert_eq!(frame_length(header).unwrap(), FRAME_LIMIT); // Neither a v1 length prefix nor another framing version is accepted. let mut old = [0; FRAME_HEADER_LEN]; old[..4].copy_from_slice(&1u32.to_be_bytes()); assert!(frame_length(old).is_err()); let mut foreign = header; foreign[7] = b'1'; assert!(frame_length(foreign).is_err()); } #[test] fn protocol_does_not_accept_a_shell_operation() { let valid = serde_json::from_str::(r#"{"operation":"probe"}"#).unwrap(); assert_eq!( serde_json::to_string(&valid).unwrap(), r#"{"operation":"probe"}"# ); assert!( serde_json::from_str::(r#"{"operation":"shell","command":"whoami"}"#) .is_err() ); assert!( serde_json::from_str::(r#"{"operation":"probe","ready":true}"#).is_err() ); let caller = anyhow::anyhow!("caller-payload-private-marker").context(Stage::ServerReadBody); let encoded = serde_json::to_string(&diagnostic(&caller)).unwrap(); assert!(!encoded.contains("caller-payload-private-marker")); assert_eq!(diagnostic(&caller).stage, "server_read_body"); assert_eq!(diagnostic(&caller).code, "UNCLASSIFIED_IO_OR_CODEC"); let remote = remote_denial(Stage::ClientReplyBinding, "caller-payload-private-marker"); assert_eq!(diagnostic(&remote).code, "UNCLASSIFIED_REMOTE_DENIAL"); let challenge = Uuid::from_u128(1); let raw = br#"{"a":1,"b":2}"#; let receipt = drain_receipt(challenge, raw); assert!(verify_drain_receipt(&receipt, challenge, raw).is_ok()); // Same JSON meaning, different exact bytes must not drain this reply. assert!(verify_drain_receipt(&receipt, challenge, br#"{"b":2,"a":1}"#).is_err()); assert!(verify_drain_receipt(&receipt, Uuid::from_u128(2), raw).is_err()); for offset in [0, 7, 8, 23, 24, DRAIN_RECEIPT_LEN - 1] { let mut changed = receipt; changed[offset] ^= 1; let error = verify_drain_receipt(&changed, challenge, raw) .unwrap_err() .context(Stage::ServerDrainReceipt); assert_eq!(diagnostic(&error).code, "HELPER_DRAIN_RECEIPT"); assert_eq!(diagnostic(&error).stage, "server_drain_receipt"); } } #[test] fn reconfigured_service_cannot_adopt_an_old_running_identity() { let pin = PeerPin { service_name: "RmmDiscoveryFixtureTest".into(), service_sid: "S-1-5-80-123".into(), user_sid: "S-1-5-19".into(), binary: PathBuf::from(r"C:\Program Files\RustDiscoveryFixtures\fixture.exe"), binary_sha256: "a".repeat(64), }; let actual = ProcessIdentity { pid: 42, creation_ticks: 1234, user_sid: pin.user_sid.clone(), service_sid: pin.service_sid.clone(), image: pin.binary.clone(), image_sha256: pin.binary_sha256.clone(), image_file: FileIdentity { volume_serial: 1, file_id: [1; 16], }, }; assert!(actual.validate(&pin, 42).is_ok()); // The configuration can now match the allowlist while the actual old // process still has SYSTEM, another executable, or another service SID. for old in [ ProcessIdentity { user_sid: "S-1-5-18".into(), ..actual.clone() }, ProcessIdentity { image: PathBuf::from(r"C:\Windows\System32\other.exe"), ..actual.clone() }, ProcessIdentity { service_sid: "S-1-5-80-999".into(), ..actual.clone() }, ProcessIdentity { pid: 43, ..actual.clone() }, ] { assert!(old.validate(&pin, 42).is_err()); } } }