Qualify Windows system delegation and crash-safe mirror adapter on native VM
Rust development slice / linux (push) Failing after 6s

This commit is contained in:
2026-11-14 07:43:36 +01:00
parent 655572aa5b
commit 4aff116b84
13 changed files with 3115 additions and 115 deletions
+336 -74
View File
@@ -3,7 +3,7 @@
use anyhow::{Context, Result, ensure};
use rmm_agent_core::{
auth::{Binding, Outcome, Request},
helper_reconcile::{SignedResponse, Snapshot},
helper_reconcile::{NoStartAnchor, SignedResponse, Snapshot},
};
use rmm_domain::jobs::hash;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
@@ -34,6 +34,176 @@ 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,
ClientReport,
ServerConnect,
ServerReadHeader,
ServerClientPeer,
ServerImpersonate,
ServerVerifyToken,
ServerReadBody,
ServerCallBinding,
ServerRecheckPeer,
ServerReply,
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::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::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<u32>,
}
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_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::<Diagnostic>() {
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::<Stage>()
.copied()
.unwrap_or(Stage::Unclassified)
.name(),
code,
win32: error.downcast_ref::<CapturedWin32>().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 {
@@ -118,6 +288,12 @@ pub enum Operation {
generation: u64,
request: Request,
},
Abandon {
anchor: Box<NoStartAnchor>,
request: Request,
intent_id: Uuid,
intent_sha256: String,
},
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
@@ -155,10 +331,14 @@ pub enum ReplyBody {
snapshot: Snapshot,
unlocked_grants: Vec<Uuid>,
ready: bool,
no_start_anchor: Option<Box<NoStartAnchor>>,
},
Executed {
outcome: Outcome,
},
Abandoned {
outcome: Outcome,
},
Denied {
code: String,
},
@@ -191,10 +371,9 @@ pub fn wide(s: impl AsRef<std::ffi::OsStr>) -> Vec<u16> {
s.as_ref().encode_wide().chain(Some(0)).collect()
}
fn owned(raw: HANDLE) -> Result<OwnedHandle> {
ensure!(
!raw.is_null() && raw != INVALID_HANDLE_VALUE,
"HELPER_HANDLE"
);
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<String> {
@@ -323,7 +502,12 @@ pub fn require_self(peer: &PeerPin) -> Result<()> {
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]) -> Result<()> {
fn check_acl(
handle: HANDLE,
readers: &[String],
writers: &[String],
writer_mask: Option<u32>,
) -> Result<()> {
let mut owner = ptr::null_mut();
let mut acl = ptr::null_mut();
let mut descriptor = ptr::null_mut();
@@ -365,6 +549,12 @@ fn check_acl(handle: HANDLE, readers: &[String], writers: &[String]) -> Result<(
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"
@@ -384,6 +574,7 @@ pub struct PinnedFile {
readers: Vec<String>,
writers: Vec<String>,
directory: bool,
writer_mask: Option<u32>,
}
impl PinnedFile {
pub fn open(
@@ -392,6 +583,28 @@ impl PinnedFile {
readers: &[String],
writers: &[String],
write: bool,
) -> Result<Self> {
Self::open_impl(path, directory, readers, writers, write, false)
}
pub(crate) fn open_read_shared(
path: &Path,
directory: bool,
readers: &[String],
writers: &[String],
) -> Result<Self> {
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<Self> {
ensure!(
path.is_absolute()
@@ -427,7 +640,12 @@ impl PinnedFile {
} else {
GENERIC_READ
},
FILE_SHARE_READ | if write { FILE_SHARE_WRITE } else { 0 },
FILE_SHARE_READ
| if write || share_write {
FILE_SHARE_WRITE
} else {
0
},
ptr::null(),
OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT
@@ -448,6 +666,7 @@ impl PinnedFile {
readers: readers.into(),
writers: writers.into(),
directory,
writer_mask: None,
};
value.check()?;
Ok(value)
@@ -467,7 +686,12 @@ impl PinnedFile {
file_identity(&self.file)? == self.identity,
"HELPER_FILE_ID_CHANGED"
);
check_acl(self.file.as_raw_handle(), &self.readers, &self.writers)?;
check_acl(
self.file.as_raw_handle(),
&self.readers,
&self.writers,
self.writer_mask,
)?;
let raw = unsafe {
CreateFileW(
wide(&self.path).as_ptr(),
@@ -877,10 +1101,30 @@ impl IoEvent {
}
let mut count = 0;
let complete = unsafe { GetOverlappedResult(pipe, &self.overlapped, &mut count, 0) };
if complete == 0 && unsafe { GetLastError() } == ERROR_IO_INCOMPLETE {
std::process::abort();
if complete == 0 {
let error = api_failure("HELPER_PIPE_IO");
if error
.downcast_ref::<CapturedWin32>()
.is_some_and(|v| v.0 == ERROR_IO_INCOMPLETE)
{
std::process::abort();
}
return Err(error);
}
Ok(count)
}
fn completed(&self, pipe: HANDLE) -> Result<u32> {
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::<CapturedWin32>()
.is_some_and(|v| v.0 == ERROR_IO_INCOMPLETE)
{
std::process::abort();
}
return Err(error);
}
ensure!(complete != 0, "HELPER_PIPE_IO");
Ok(count)
}
}
@@ -890,14 +1134,13 @@ fn transfer(pipe: HANDLE, bytes: &mut [u8], write: bool, deadline: Instant) -> R
ensure!(Instant::now() < deadline, "HELPER_PIPE_TIMEOUT");
let mut operation = IoEvent::new()?;
let part = &mut bytes[offset..];
let mut done = 0;
let ok = unsafe {
if write {
WriteFile(
pipe,
part.as_ptr(),
part.len().try_into()?,
&mut done,
ptr::null_mut(),
&mut operation.overlapped,
)
} else {
@@ -905,18 +1148,21 @@ fn transfer(pipe: HANDLE, bytes: &mut [u8], write: bool, deadline: Instant) -> R
pipe,
part.as_mut_ptr(),
part.len().try_into()?,
&mut done,
ptr::null_mut(),
&mut operation.overlapped,
)
}
};
let count = if ok != 0 {
done
// 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 {
ensure!(
unsafe { GetLastError() } == ERROR_IO_PENDING,
"HELPER_PIPE_IO"
);
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");
@@ -1000,37 +1246,42 @@ impl Server {
}
pub fn receive(&self) -> Result<Option<Received>> {
let pipe = self.pipe.as_raw_handle();
let mut connect = IoEvent::new()?;
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 connect
.wait(pipe, Instant::now() + Duration::from_millis(250))
.is_err()
if let Err(error) = connect.wait(pipe, Instant::now() + Duration::from_millis(250))
{
unsafe {
DisconnectNamedPipe(pipe);
if diagnostic(&error).code == "HELPER_PIPE_TIMEOUT" {
unsafe {
DisconnectNamedPipe(pipe);
};
return Ok(None);
}
return Ok(None);
return Err(error).context(Stage::ServerConnect);
}
} else {
ensure!(error == ERROR_PIPE_CONNECTED, "HELPER_PIPE_CONNECT");
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)?;
let mut peer = PeerProof::capture(pipe, &self.pin.agent, true)?;
ensure!(
unsafe { ImpersonateNamedPipeClient(pipe) } != 0,
"HELPER_PIPE_IMPERSONATION"
);
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();
ensure!(
unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, 1, &mut token) } != 0,
"HELPER_PIPE_IMPERSONATED_TOKEN"
);
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(),
@@ -1041,17 +1292,17 @@ impl Server {
if unsafe { RevertToSelf() } == 0 {
std::process::abort();
}
auth?;
require_self(&self.pin.helper)?;
let call: Call = body(pipe, len, deadline)?;
ensure!(
call.schema_version == 1
&& !call.challenge.is_nil()
&& call.policy_sha256 == self.pin.policy_sha256
&& binding_hash(&call.binding)? == binding_hash(&self.pin.binding)?,
"HELPER_CALL_BINDING"
);
peer.check()?;
auth.context(Stage::ServerVerifyToken)?;
require_self(&self.pin.helper).context(Stage::ServerVerifyToken)?;
let call: Call = body(pipe, len, deadline).context(Stage::ServerReadBody)?;
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) -> Result<()> {
@@ -1060,6 +1311,7 @@ impl Server {
value,
Instant::now() + Duration::from_secs(5),
)
.context(Stage::ServerReply)
}
pub fn disconnect(&self) {
unsafe {
@@ -1070,7 +1322,7 @@ impl Server {
/// Blocking SDK call; run on the agent's bounded blocking worker, never heartbeat reactor.
pub fn exchange(pin: &Pin, call: &Call, timeout: Duration) -> Result<Reply> {
pin.validate()?;
require_self(&pin.agent)?;
require_self(&pin.agent).context(Stage::ClientSelfRole)?;
ensure!(
(Duration::from_secs(1)..=Duration::from_secs(125)).contains(&timeout),
"HELPER_CALL_TIMEOUT_BOUND"
@@ -1087,31 +1339,33 @@ pub fn exchange(pin: &Pin, call: &Call, timeout: Duration) -> Result<Reply> {
ptr::null_mut(),
)
})
.context("HELPER_PIPE_UNAVAILABLE_OR_BUSY")?;
let mut peer = PeerProof::capture(pipe.as_raw_handle(), &pin.helper, false)?;
send(pipe.as_raw_handle(), call, deadline)?;
let len = length(pipe.as_raw_handle(), deadline)?;
let reply: Reply = body(pipe.as_raw_handle(), len, deadline)?;
peer.check()?;
ensure!(
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,
"HELPER_REPLY_BINDING"
);
ensure!(
matches!(
(&call.operation, &reply.body),
(_, ReplyBody::Denied { .. })
| (Operation::Probe { .. }, ReplyBody::Probe { .. })
| (Operation::Snapshot { .. }, ReplyBody::Snapshot { .. })
| (Operation::Apply { .. }, ReplyBody::Applied { .. })
| (Operation::Execute { .. }, ReplyBody::Executed { .. })
),
"HELPER_REPLY_OPERATION"
);
.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: Reply = body(pipe.as_raw_handle(), len, deadline).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 { .. })
) {
return Err(anyhow::anyhow!("HELPER_REPLY_OPERATION")).context(Stage::ClientReplyBinding);
}
Ok(reply)
}
@@ -1155,6 +1409,14 @@ mod tests {
assert!(
serde_json::from_str::<Operation>(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");
}
#[test]
fn reconfigured_service_cannot_adopt_an_old_running_identity() {