Qualify Windows IPC client runtime and prepare bounded native providers
Rust development slice / linux (push) Failing after 7s

This commit is contained in:
2026-11-14 03:53:48 +01:00
parent 2bf0183e68
commit 9d6a6f0eb6
24 changed files with 3880 additions and 30 deletions
+48 -3
View File
@@ -11,13 +11,58 @@ fn main() {
Ok("x86_64"),
"Windows clock RPC is qualified only for x86-64"
);
let out = PathBuf::from(env::var_os("OUT_DIR").unwrap());
let idl = env::current_dir().unwrap().join("native/w32time.idl");
if env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") {
// MIDL and CL come from the explicitly selected native x64 SDK/MSVC
// environment. `win64` means IA64 in MIDL: AMD64 must be explicit.
println!("cargo:rerun-if-env-changed=RMM_MIDL_EXE");
let midl = env::var_os("RMM_MIDL_EXE").expect("Select the native SDK's verified midl.exe");
assert!(
Command::new(midl)
.current_dir(&out)
.args([
"/nologo",
"/env",
"amd64",
"/Oicf",
"/robust",
"/Zp8",
"/client",
"stub",
"/server",
"none",
"/h",
"w32time.h",
"/cstub",
"w32time_c.c",
])
.arg(&idl)
.status()
.expect("Install native Microsoft SDK MIDL; no generated-stub fallback")
.success(),
"Native Microsoft MIDL clock stub generation failed"
);
// Keep RPC's __try/__except entirely inside native C. Existing C ABI
// assertions remain active; never substitute C++/Rust catch_unwind.
cc::Build::new()
.flag("/std:c11")
.flag("/Zp8")
.warnings_into_errors(true)
.include(&out)
.file(out.join("w32time_c.c"))
.file("native/clock_rpc.c")
.file("native/clock_endpoints.c")
.compile("rmm_clock_rpc");
println!("cargo:rustc-link-lib=rpcrt4");
println!("cargo:rustc-link-lib=advapi32");
return;
}
assert_eq!(
env::var("CARGO_CFG_TARGET_ENV").as_deref(),
Ok("gnu"),
"Windows clock RPC currently requires the qualified GNU/clang toolchain"
"Windows clock RPC supports native MSVC or the qualified GNU/clang toolchain"
);
let out = PathBuf::from(env::var_os("OUT_DIR").unwrap());
let idl = env::current_dir().unwrap().join("native/w32time.idl");
for args in [
vec!["-h", "-H", "w32time.h"],
vec!["-c", "-o", "w32time_c.c"],
@@ -161,9 +161,10 @@ mod service {
std::thread::sleep(Duration::from_millis(750));
STAGE.store(31, Ordering::SeqCst);
let second = clock.report();
let identity_controls = super::clock::identity_controls();
STAGE.store(40, Ordering::SeqCst);
let data = serde_json::to_vec_pretty(
&serde_json::json!({"schema":1,"case_id":case,"service_name":NAME,"token_sid":"S-1-5-19","elevated":token.elevation_flag!=0,"token":token,"endpoints":endpoints,"named_pipe_diagnostic":pipe,"source":"MS-W32T:4.1:Opnum6:ncalrpc:SID19:MUTUAL_AUTH:WINNT:PKT_PRIVACY","read_only":true,"samples":[first,second]}),
&serde_json::json!({"schema":1,"case_id":case,"service_name":NAME,"token_sid":"S-1-5-19","elevated":token.elevation_flag!=0,"token":token,"endpoints":endpoints,"named_pipe_diagnostic":pipe,"identity_controls":identity_controls,"source":"MS-W32T:4.1:Opnum6:ncalrpc:SID19:W32Time:V5_descriptor:MUTUAL_AUTH:WINNT:PKT_PRIVACY","read_only":true,"samples":[first,second]}),
)?;
ensure!(data.len() < 16384, "READINESS_REPORT_SIZE");
STAGE.store(41, Ordering::SeqCst);
@@ -258,6 +259,6 @@ fn main() -> anyhow::Result<()> {
fn main() {
println!(
"{}",
serde_json::to_string(&serde_json::json!({"clock":clock::NativeClock::new().report(),"endpoints":clock::endpoint_report(),"named_pipe_diagnostic":clock::named_pipe_diagnostic()})).unwrap()
serde_json::to_string(&serde_json::json!({"clock":clock::NativeClock::new().report(),"endpoints":clock::endpoint_report(),"named_pipe_diagnostic":clock::named_pipe_diagnostic(),"identity_controls":clock::identity_controls()})).unwrap()
);
}
+52 -4
View File
@@ -5,11 +5,32 @@
#include <windows.h>
#include <rpc.h>
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include "w32time.h"
/* Documented public SDK API; older MinGW headers omit its declaration. */
int RPC_ENTRY RpcExceptionFilter(unsigned long exception_code);
/* Older MinGW headers stop at V3. This is the documented x64 V5 SDK layout,
* not a fallback to an older authentication contract. MSVC also checks it
* directly against its native SDK declaration. Windows x64 is the only target.
* https://learn.microsoft.com/windows/win32/api/rpcdce/ns-rpcdce-rpc_security_qos_v5_w
*/
typedef struct {
unsigned long Version, Capabilities, IdentityTracking, ImpersonationType;
unsigned long AdditionalSecurityInfoType;
union { RPC_HTTP_TRANSPORT_CREDENTIALS_W *HttpCredentials; } u;
void *Sid;
unsigned int EffectiveOnly;
void *ServerSecurityDescriptor;
} RmmRpcQosV5;
_Static_assert(sizeof(RmmRpcQosV5) == 56, "x64 RPC QOS V5 ABI");
_Static_assert(offsetof(RmmRpcQosV5, Sid) == offsetof(RPC_SECURITY_QOS_V3_W, Sid), "SDK QOS prefix ABI");
_Static_assert(offsetof(RmmRpcQosV5, ServerSecurityDescriptor) == 48, "x64 server descriptor ABI");
#ifdef _MSC_VER
_Static_assert(sizeof(RmmRpcQosV5) == sizeof(RPC_SECURITY_QOS_V5_W), "native SDK QOS V5 ABI");
_Static_assert(offsetof(RmmRpcQosV5, ServerSecurityDescriptor) == offsetof(RPC_SECURITY_QOS_V5_W, ServerSecurityDescriptor), "native SDK descriptor ABI");
#endif
typedef struct Allocation { struct Allocation *next; size_t size; } Allocation;
typedef struct { Allocation *head; size_t total; } Arena;
@@ -106,7 +127,7 @@ uint32_t rmm_clock_query(RmmClockStatus *out) {
/* Kernel-authenticated ALPC only. No automatic fallback to named pipes.
* The expected SID is fixed locally, never adopted from endpoint metadata.
*/
uint32_t rmm_clock_alpc_query(RmmClockStatus *out) {
static uint32_t alpc_query(RmmClockStatus *out, unsigned control) {
RPC_IF_ID id = {0};
RPC_EP_INQ_HANDLE inquiry = NULL;
RPC_STATUS result;
@@ -132,15 +153,39 @@ uint32_t rmm_clock_alpc_query(RmmClockStatus *out) {
if (result) {RpcBindingFree(&binding);break;}
if (local) {
_Alignas(8) BYTE expected_sid[SECURITY_MAX_SID_SIZE];
_Alignas(8) BYTE service_sid[SECURITY_MAX_SID_SIZE];
_Alignas(8) BYTE acl_buffer[sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + SECURITY_MAX_SID_SIZE];
SECURITY_DESCRIPTOR descriptor;
WCHAR domain[64];
DWORD domain_size = sizeof(domain) / sizeof(domain[0]);
DWORD service_sid_size = sizeof(service_sid);
SID_NAME_USE sid_type;
DWORD sid_size = sizeof(expected_sid);
RPC_SECURITY_QOS_V3_W qos = {0};
if (!CreateWellKnownSid(WinLocalServiceSid, NULL, expected_sid, &sid_size)) result = GetLastError();
RmmRpcQosV5 qos = {0};
/* An account-only SID19 binding also accepts other LocalService
* processes, including our network agent. The client-owned V5
* descriptor therefore requires the separate W32Time service SID.
* No descriptor/identity is obtained from endpoint metadata.
* Controls are fixed read-only diagnostics, never production modes.
*/
if (!CreateWellKnownSid(control == 1 ? WinLocalSystemSid : WinLocalServiceSid,
NULL, expected_sid, &sid_size)) result = GetLastError();
if (!result && !LookupAccountNameW(NULL,
control == 2 ? L"NT SERVICE\\RmmDiscoveryWindows" : L"NT SERVICE\\W32Time",
service_sid, &service_sid_size, domain, &domain_size, &sid_type)) result = GetLastError();
if (!result && (!IsValidSid(service_sid) || service_sid_size > sizeof(service_sid))) result = ERROR_INVALID_SID;
if (!result && !InitializeAcl((PACL)acl_buffer, sizeof(acl_buffer), ACL_REVISION)) result = GetLastError();
if (!result && !AddAccessAllowedAce((PACL)acl_buffer, ACL_REVISION, GENERIC_ALL, service_sid)) result = GetLastError();
if (!result && !InitializeSecurityDescriptor(&descriptor, SECURITY_DESCRIPTOR_REVISION)) result = GetLastError();
if (!result && !SetSecurityDescriptorDacl(&descriptor, TRUE, (PACL)acl_buffer, FALSE)) result = GetLastError();
if (!result) {
qos.Version = RPC_C_SECURITY_QOS_VERSION_3;
qos.Version = 5; /* RPC_C_SECURITY_QOS_VERSION_5 */
qos.Capabilities = RPC_C_QOS_CAPABILITIES_MUTUAL_AUTH;
qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC;
qos.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY;
qos.Sid = expected_sid;
qos.EffectiveOnly = TRUE;
qos.ServerSecurityDescriptor = &descriptor;
result = RpcBindingSetAuthInfoExW(binding, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
RPC_C_AUTHN_WINNT, NULL, RPC_C_AUTHZ_NONE, (RPC_SECURITY_QOS *)&qos);
if (!result) result = invoke_status(binding, out);
@@ -154,3 +199,6 @@ uint32_t rmm_clock_alpc_query(RmmClockStatus *out) {
RpcMgmtEpEltInqDone(&inquiry);
return result == RPC_X_NO_MORE_ENTRIES ? EPT_S_NOT_REGISTERED : result;
}
uint32_t rmm_clock_alpc_query(RmmClockStatus *out) { return alpc_query(out, 0); }
uint32_t rmm_clock_wrong_account(RmmClockStatus *out) { return alpc_query(out, 1); }
uint32_t rmm_clock_wrong_service(RmmClockStatus *out) { return alpc_query(out, 2); }
+55 -2
View File
@@ -8,7 +8,8 @@ use anyhow::{Result, anyhow, ensure};
use chrono::{DateTime, Utc};
use serde::Serialize;
use std::sync::Mutex;
/// Flip only after native SID-bound ALPC, readiness and fail-closed qualification.
/// Flip only after native account AND service-bound ALPC, positive readiness,
/// wrong-account/wrong-service denial and fail-closed qualification.
pub const ADAPTER_QUALIFIED: bool = false;
const SECOND: u64 = 10_000_000;
const MAX_AGE: u64 = 3600 * SECOND;
@@ -191,7 +192,7 @@ impl NativeClock {
transport: if self.diagnostic {
"ncacn_np:W32TIME_ALT:diagnostic_only"
} else {
"ncalrpc:SID19:mutual_auth"
"ncalrpc:SID19:W32Time:V5_descriptor:mutual_auth"
},
status: None,
query_ticks: ticks,
@@ -258,6 +259,38 @@ pub fn named_pipe_diagnostic() -> ClockReport {
}
.report()
}
/// Read-only negative controls for the separate native readiness program.
/// Neither control can produce clock authority, even if the OS accepts it.
/// Rejection without a successful genuine status query is not identity proof.
#[derive(Debug, Serialize)]
pub struct IdentityControls {
pub wrong_account_rpc_code: u32,
pub wrong_service_rpc_code: u32,
pub both_access_denied: bool,
pub diagnostic_only: bool,
}
pub fn identity_controls() -> IdentityControls {
#[cfg(windows)]
let codes = {
static WORKER: std::sync::OnceLock<Mutex<RpcWorker>> = std::sync::OnceLock::new();
let worker = WORKER.get_or_init(|| Mutex::new(RpcWorker::new(raw_control)));
match worker.try_lock() {
Ok(mut worker) => (
worker.call(true, std::time::Duration::from_secs(1)).0,
worker.call(false, std::time::Duration::from_secs(1)).0,
),
Err(_) => (170, 170),
}
};
#[cfg(not(windows))]
let codes = (50, 50);
IdentityControls {
wrong_account_rpc_code: codes.0,
wrong_service_rpc_code: codes.1,
both_access_denied: codes == (5, 5),
diagnostic_only: true,
}
}
impl rmm_agent_core::reconcile::SyncClock for NativeClock {
fn now(&self) -> Result<DateTime<Utc>> {
NativeClock::now(self)
@@ -300,6 +333,26 @@ fn raw_query(diagnostic: bool) -> (u32, Status) {
};
(code, status)
}
#[cfg(windows)]
fn raw_control(wrong_account: bool) -> (u32, Status) {
#[link(name = "rmm_clock_rpc", kind = "static")]
#[link(name = "rpcrt4")]
#[link(name = "advapi32")]
unsafe extern "C" {
fn rmm_clock_wrong_account(status: *mut Status) -> u32;
fn rmm_clock_wrong_service(status: *mut Status) -> u32;
}
let mut status = Status::default();
// SAFETY: fixed C ABI, fixed two local negative identities, contained SEH.
let code = unsafe {
if wrong_account {
rmm_clock_wrong_account(&mut status)
} else {
rmm_clock_wrong_service(&mut status)
}
};
(code, status)
}
#[cfg(any(windows, test))]
type RpcReply = std::sync::mpsc::SyncSender<(u32, Status)>;
#[cfg(any(windows, test))]
+528
View File
@@ -0,0 +1,528 @@
//! Bounded, local, fixture-only live Event Log query; not wired into any job.
//!
//! EvtQuery/EvtRender have no per-call timeout. The monotonic deadline below is
//! cooperative between Win32 calls; the eventual executor must also supervise
//! its process. This module never starts another worker or advances a bookmark.
//! API contracts: https://learn.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtquery
//! https://learn.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtnext
//! https://learn.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtrender
//! https://learn.microsoft.com/en-us/windows/win32/api/winevt/ne-winevt-evt_system_property_id
use anyhow::{Result, ensure};
use chrono::{DateTime, SecondsFormat, Utc};
use serde::{Deserialize, Serialize};
use std::sync::atomic::AtomicBool;
pub const CHANNEL: &str = "Application";
pub const PROVIDER: &str = "RustDiscovery-MVP-Test";
const MAX_BYTES: usize = 256 * 1024;
#[cfg(any(windows, test))]
const REPORT_RESERVE: usize = 256;
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Query {
pub channel: String,
pub provider: String,
pub start_utc: DateTime<Utc>,
pub end_utc: DateTime<Utc>,
pub max_events: u32,
pub max_output_bytes: u32,
pub timeout_ms: u32,
}
impl Query {
fn xpath(&self) -> Result<String> {
ensure!(
self.channel == CHANNEL && self.provider == PROVIDER,
"EVENT_LOG_SOURCE_DENIED"
);
ensure!(
self.start_utc.timestamp() >= 0
&& self.end_utc > self.start_utc
&& self.end_utc - self.start_utc <= chrono::Duration::hours(24),
"EVENT_LOG_WINDOW_INVALID"
);
ensure!(
(1..=1000).contains(&self.max_events)
&& (1024..=MAX_BYTES as u32).contains(&self.max_output_bytes)
&& (1..=5000).contains(&self.timeout_ms),
"EVENT_LOG_LIMIT_INVALID"
);
// Only canonical UTC timestamps enter this fixed expression. Neither a
// caller-supplied XPath, a remote session nor a log-file path exists.
Ok(format!(
"*[System[Provider[@Name='{PROVIDER}'] and TimeCreated[@SystemTime>='{}' and @SystemTime<'{}']]]",
self.start_utc.to_rfc3339_opts(SecondsFormat::Nanos, true),
self.end_utc.to_rfc3339_opts(SecondsFormat::Nanos, true)
))
}
}
#[derive(Debug, Serialize)]
pub struct Event {
pub channel: String,
pub provider: String,
pub record_id: u64,
pub event_id: u16,
pub created_utc: DateTime<Utc>,
/// Exact bounded XML from EvtRenderEventXml, including fixture EventData;
/// no localized publisher DLL/message formatting is performed.
pub xml: String,
}
#[derive(Debug, Serialize)]
pub struct Report {
pub channel: String,
pub provider: String,
pub start_utc: DateTime<Utc>,
pub end_utc: DateTime<Utc>,
pub quality: &'static str,
pub completeness: &'static str,
pub truncated: bool,
pub error_code: Option<&'static str>,
pub win32_error: Option<u32>,
pub events: Vec<Event>,
pub bookmark_updated: bool,
pub deadline_enforcement: &'static str,
}
#[cfg(any(windows, test))]
impl Report {
fn new(q: &Query) -> Self {
Self {
channel: q.channel.clone(),
provider: q.provider.clone(),
start_utc: q.start_utc,
end_utc: q.end_utc,
quality: "valid",
completeness: "partial",
truncated: false,
error_code: None,
win32_error: None,
events: Vec::new(),
bookmark_updated: false,
deadline_enforcement: "cooperative_between_win32_calls",
}
}
fn stop(&mut self, code: &'static str, win32: Option<u32>) {
self.truncated = true;
self.error_code = Some(code);
self.win32_error = win32;
self.completeness = if self.events.is_empty() {
"unknown"
} else {
"partial"
};
if win32 == Some(5) {
self.quality = "permission_denied";
} else if win32.is_some() {
self.quality = "error";
}
}
fn push(&mut self, event: Event, limit: usize) -> Result<bool> {
self.events.push(event);
if serde_json::to_vec(self)?.len() + REPORT_RESERVE > limit {
self.events.pop();
self.stop("EVENT_LOG_BYTE_LIMIT", None);
return Ok(false);
}
Ok(true)
}
}
/// Reads only the fixed local fixture source. No persistent state is modified.
pub fn query(q: &Query, cancelled: &AtomicBool) -> Result<Report> {
let xpath = q.xpath()?;
#[cfg(windows)]
{
windows::query(q, &xpath, cancelled)
}
#[cfg(not(windows))]
{
let _ = (xpath, cancelled);
anyhow::bail!("EVENT_LOG_WINDOWS_ONLY")
}
}
#[cfg(windows)]
mod windows {
use super::*;
use anyhow::Context;
use std::{
mem::size_of,
ptr,
sync::atomic::Ordering,
time::{Duration, Instant},
};
use windows_sys::Win32::{
Foundation::{
ERROR_ACCESS_DENIED, ERROR_INSUFFICIENT_BUFFER, ERROR_NO_MORE_ITEMS, ERROR_TIMEOUT,
GetLastError,
},
System::EventLog::*,
};
struct Handle(EVT_HANDLE);
impl Drop for Handle {
fn drop(&mut self) {
if self.0 != 0 {
unsafe {
EvtClose(self.0);
}
}
}
}
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(Some(0)).collect()
}
fn stopped(report: &mut Report, cancelled: &AtomicBool, until: Instant) -> bool {
if cancelled.load(Ordering::SeqCst) {
report.stop("EVENT_LOG_CANCELLED", None);
true
} else if Instant::now() >= until {
report.stop("EVENT_LOG_TIME_LIMIT", None);
true
} else {
false
}
}
fn failure(report: &mut Report, error: u32) {
report.stop(
if error == ERROR_ACCESS_DENIED {
"EVENT_LOG_PERMISSION_DENIED"
} else {
"EVENT_LOG_API_ERROR"
},
Some(error),
);
}
// u64 storage provides the alignment required by EVT_VARIANT. All returned
// pointers are read while this owning allocation remains alive.
fn render(
context: EVT_HANDLE,
event: EVT_HANDLE,
flags: u32,
cap: usize,
until: Instant,
cancelled: &AtomicBool,
) -> Result<(Vec<u64>, usize, u32)> {
ensure!(
!cancelled.load(Ordering::SeqCst) && Instant::now() < until,
"EVENT_LOG_TIME_OR_CANCELLED"
);
let mut used = 0;
let mut count = 0;
let first = unsafe {
EvtRender(
context,
event,
flags,
0,
ptr::null_mut(),
&mut used,
&mut count,
)
};
let error = if first == 0 {
unsafe { GetLastError() }
} else {
0
};
ensure!(
!cancelled.load(Ordering::SeqCst) && Instant::now() < until,
"EVENT_LOG_TIME_OR_CANCELLED"
);
if first == 0 && error != ERROR_INSUFFICIENT_BUFFER {
return Err(std::io::Error::from_raw_os_error(error as i32).into());
}
ensure!(first == 0 && used > 0, "EVENT_LOG_RENDER_PROBE");
if used as usize > cap {
return Err(std::io::Error::from_raw_os_error(ERROR_INSUFFICIENT_BUFFER as i32).into());
}
let mut buffer = vec![0u64; (used as usize).div_ceil(8)];
let allocated = buffer.len() * 8;
ensure!(
!cancelled.load(Ordering::SeqCst) && Instant::now() < until,
"EVENT_LOG_TIME_OR_CANCELLED"
);
let ok = unsafe {
EvtRender(
context,
event,
flags,
allocated as u32,
buffer.as_mut_ptr().cast(),
&mut used,
&mut count,
)
};
let error = if ok == 0 {
unsafe { GetLastError() }
} else {
0
};
ensure!(
!cancelled.load(Ordering::SeqCst) && Instant::now() < until,
"EVENT_LOG_TIME_OR_CANCELLED"
);
if ok == 0 {
return Err(std::io::Error::from_raw_os_error(error as i32).into());
}
ensure!(used as usize <= allocated, "EVENT_LOG_RENDER_SIZE");
Ok((buffer, used as usize, count))
}
fn string(value: &EVT_VARIANT, buffer: &[u64], used: usize) -> Result<String> {
ensure!(
value.Type == EvtVarTypeString as u32,
"EVENT_LOG_PROPERTY_TYPE"
);
let pointer = unsafe { value.Anonymous.StringVal };
let address = pointer as usize;
let base = buffer.as_ptr() as usize;
ensure!(
address >= base && address < base + used && address.is_multiple_of(2),
"EVENT_LOG_PROPERTY_POINTER"
);
let length = (base + used - address) / 2;
let units = unsafe { std::slice::from_raw_parts(pointer, length) };
let end = units
.iter()
.position(|x| *x == 0)
.context("EVENT_LOG_PROPERTY_TERMINATOR")?;
ensure!(end <= 256, "EVENT_LOG_PROPERTY_LIMIT");
Ok(String::from_utf16(&units[..end])?)
}
fn read_event(
context: EVT_HANDLE,
event: EVT_HANDLE,
q: &Query,
until: Instant,
cancelled: &AtomicBool,
) -> Result<Event> {
let (buffer, used, count) = render(
context,
event,
EvtRenderEventValues,
16 * 1024,
until,
cancelled,
)?;
ensure!(
count == EvtSystemPropertyIdEND as u32
&& used >= count as usize * size_of::<EVT_VARIANT>(),
"EVENT_LOG_PROPERTY_COUNT"
);
let values = unsafe {
std::slice::from_raw_parts(buffer.as_ptr().cast::<EVT_VARIANT>(), count as usize)
};
let provider = string(&values[EvtSystemProviderName as usize], &buffer, used)?;
let channel = string(&values[EvtSystemChannel as usize], &buffer, used)?;
ensure!(
provider == PROVIDER && channel == CHANNEL,
"EVENT_LOG_SOURCE_MISMATCH"
);
let record = &values[EvtSystemEventRecordId as usize];
let time = &values[EvtSystemTimeCreated as usize];
let id = &values[EvtSystemEventID as usize];
ensure!(
record.Type == EvtVarTypeUInt64 as u32
&& time.Type == EvtVarTypeFileTime as u32
&& id.Type == EvtVarTypeUInt16 as u32,
"EVENT_LOG_PROPERTY_TYPE"
);
let record_id = unsafe { record.Anonymous.UInt64Val };
let ticks = unsafe { time.Anonymous.FileTimeVal };
let unix_ticks = ticks
.checked_sub(116_444_736_000_000_000)
.context("EVENT_LOG_TIMESTAMP")?;
let created_utc = DateTime::from_timestamp(
i64::try_from(unix_ticks / 10_000_000)?,
((unix_ticks % 10_000_000) * 100) as u32,
)
.context("EVENT_LOG_TIMESTAMP")?;
ensure!(
record_id > 0 && created_utc >= q.start_utc && created_utc < q.end_utc,
"EVENT_LOG_RECORD_WINDOW"
);
let (xml, bytes, _) = render(
0,
event,
EvtRenderEventXml,
(q.max_output_bytes as usize).min(64 * 1024),
until,
cancelled,
)?;
ensure!(bytes >= 2 && bytes.is_multiple_of(2), "EVENT_LOG_XML_SIZE");
let units = unsafe { std::slice::from_raw_parts(xml.as_ptr().cast::<u16>(), bytes / 2) };
ensure!(
units.last() == Some(&0) && !units[..units.len() - 1].contains(&0),
"EVENT_LOG_XML_TERMINATOR"
);
Ok(Event {
channel,
provider,
record_id,
event_id: unsafe { id.Anonymous.UInt16Val },
created_utc,
xml: String::from_utf16(&units[..units.len() - 1])?,
})
}
pub(super) fn query(q: &Query, xpath: &str, cancelled: &AtomicBool) -> Result<Report> {
let mut report = Report::new(q);
let until = Instant::now() + Duration::from_millis(q.timeout_ms as u64);
if stopped(&mut report, cancelled, until) {
return Ok(report);
}
let channel = wide(CHANNEL);
let expression = wide(xpath);
let handle = Handle(unsafe {
EvtQuery(
0,
channel.as_ptr(),
expression.as_ptr(),
EvtQueryChannelPath | EvtQueryForwardDirection,
)
});
if handle.0 == 0 {
failure(&mut report, unsafe { GetLastError() });
return Ok(report);
}
if stopped(&mut report, cancelled, until) {
return Ok(report);
}
let context =
Handle(unsafe { EvtCreateRenderContext(0, ptr::null(), EvtRenderContextSystem) });
if context.0 == 0 {
failure(&mut report, unsafe { GetLastError() });
return Ok(report);
}
loop {
if stopped(&mut report, cancelled, until) {
break;
}
if report.events.len() >= q.max_events as usize {
report.stop("EVENT_LOG_EVENT_LIMIT", None);
break;
}
let mut event = 0;
let mut returned = 0;
let timeout = until
.saturating_duration_since(Instant::now())
.as_millis()
.min(100) as u32;
let ok = unsafe { EvtNext(handle.0, 1, &mut event, timeout, 0, &mut returned) };
let error = if ok == 0 {
unsafe { GetLastError() }
} else {
0
};
let event = Handle(event);
if stopped(&mut report, cancelled, until) {
break;
}
if ok == 0 {
if error == ERROR_NO_MORE_ITEMS {
report.completeness = "complete";
break;
}
if error == ERROR_TIMEOUT {
continue;
}
failure(&mut report, error);
break;
}
ensure!(returned == 1 && event.0 != 0, "EVENT_LOG_NEXT_COUNT");
let record = read_event(context.0, event.0, q, until, cancelled);
if stopped(&mut report, cancelled, until) {
break;
}
match record {
Ok(record) => {
if !report.push(record, q.max_output_bytes as usize)? {
break;
}
}
Err(error) => {
if let Some(code) = error
.downcast_ref::<std::io::Error>()
.and_then(std::io::Error::raw_os_error)
{
if code as u32 == ERROR_INSUFFICIENT_BUFFER {
report.stop("EVENT_LOG_EVENT_SIZE_LIMIT", None)
} else {
failure(&mut report, code as u32)
}
} else {
report.quality = "error";
report.stop("EVENT_LOG_RENDER_OR_RECORD_INVALID", None)
}
break;
}
}
}
ensure!(
serde_json::to_vec(&report)?.len() <= q.max_output_bytes as usize,
"EVENT_LOG_REPORT_LIMIT"
);
Ok(report)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn request() -> Query {
let start_utc = DateTime::from_timestamp(1_700_000_000, 0).unwrap();
Query {
channel: CHANNEL.into(),
provider: PROVIDER.into(),
start_utc,
end_utc: start_utc + chrono::Duration::minutes(5),
max_events: 1000,
max_output_bytes: 4096,
timeout_ms: 1000,
}
}
#[test]
fn only_fixed_source_window_and_finite_limits_are_queryable() {
let q = request();
let expression = q.xpath().unwrap();
assert!(expression.len() < 512);
assert!(expression.contains(PROVIDER));
for case in 0..7 {
let mut q = request();
match case {
0 => q.channel = "Security".into(),
1 => q.provider = "' or 1=1".into(),
2 => q.end_utc = q.start_utc,
3 => q.end_utc = q.start_utc + chrono::Duration::hours(25),
4 => q.max_events = 1001,
5 => q.max_output_bytes = MAX_BYTES as u32 + 1,
_ => q.timeout_ms = 5001,
};
assert!(q.xpath().is_err());
}
}
#[test]
fn serialized_byte_budget_includes_xml_escaping_and_metadata() {
let q = request();
let mut report = Report::new(&q);
assert!(
!report
.push(
Event {
channel: CHANNEL.into(),
provider: PROVIDER.into(),
record_id: 1,
event_id: 1,
created_utc: q.start_utc,
xml: "\"\\".repeat(2048)
},
q.max_output_bytes as usize
)
.unwrap()
);
assert!(report.events.is_empty());
assert!(report.truncated);
assert_eq!(report.error_code, Some("EVENT_LOG_BYTE_LIMIT"));
assert!(serde_json::to_vec(&report).unwrap().len() <= q.max_output_bytes as usize);
assert!(!report.bookmark_updated);
}
}
+223
View File
@@ -0,0 +1,223 @@
//! Optional passive helper control client. No SYSTEM action capability is
//! advertised here. Each actual IPC runs on one bounded blocking lane.
use crate::{helper_ipc as ipc, native};
use anyhow::{Context, Result, ensure};
use rmm_agent_core::{auth::Binding, helper_reconcile::Snapshot, reconcile::HelperSnapshot};
use rmm_protocol::{SyncAttempt, SyncResponse};
use serde_json::json;
use std::{
io::{Read, Write},
path::Path,
sync::Arc,
time::Duration,
};
use tokio::sync::Semaphore;
pub const PIN_PATH: &str = r"C:\ProgramData\RustDiscoverySystem\agent-pin.json";
const PUBLIC_ROOT: &str = r"C:\ProgramData\RustDiscoverySystem";
const PROBE_FILE: &str = "helper-probe.json";
#[derive(Clone)]
pub struct Client {
pin: ipc::Pin,
lane: Arc<Semaphore>,
}
impl Client {
/// Missing pin is deliberately passive. A present but invalid pin is refused;
/// no endpoint/key/policy is discovered from the pipe itself.
pub fn discover(
agent_id: &str,
asset_id: &str,
binding: Option<&Binding>,
lane: Arc<Semaphore>,
) -> Result<Option<Self>> {
if !Path::new(PIN_PATH).try_exists()? {
return Ok(None);
}
let readers = [
ipc::service_sid(crate::SERVICE_NAME)?,
ipc::service_sid(ipc::HELPER_SERVICE)?,
];
let _root = ipc::PinnedFile::open(Path::new(PUBLIC_ROOT), true, &readers, &[], false)?;
let mut file = ipc::PinnedFile::open(Path::new(PIN_PATH), false, &readers, &[], false)?;
ensure!(file.file.metadata()?.len() <= 16384, "HELPER_PIN_SIZE");
let mut bytes = Vec::new();
file.file.read_to_end(&mut bytes)?;
let pin: ipc::Pin = serde_json::from_slice(&bytes)?;
pin.validate()?;
ensure!(
pin.binding.agent_id.to_string() == agent_id
&& pin.binding.asset_id.to_string() == asset_id
&& pin.binding.enrollment_generation
== binding.map_or(1, |b| b.enrollment_generation),
"HELPER_ENROLLMENT_PIN_MISMATCH"
);
if let Some(binding) = binding {
ensure!(
ipc::binding_hash(binding)? == ipc::binding_hash(&pin.binding)?,
"HELPER_JOB_BINDING_MISMATCH"
);
}
Ok(Some(Self { pin, lane }))
}
pub async fn refresh(
agent_id: String,
asset_id: String,
binding: Option<Binding>,
lane: Arc<Semaphore>,
state: std::path::PathBuf,
) -> Result<Option<Self>> {
let permit = lane
.clone()
.try_acquire_owned()
.context("HELPER_CONTROL_BUSY")?;
tokio::task::spawn_blocking(move || {
let _permit = permit;
let result=(|| {
let client=Self::discover(&agent_id,&asset_id,binding.as_ref(),lane)?;
if let Some(client)=&client {client.probe_blocking(&state)?;}
Ok(client)
})();
if result.is_err() || matches!(&result,Ok(None)) && state.join(PROBE_FILE).try_exists()? {
write_current_probe(&state,&json!({"schema_version":1,"source":"actual_local_service_runtime","agent_process_id":std::process::id(),"agent_id":agent_id,"asset_id":asset_id,"observed_at":chrono::Utc::now(),"authenticated_pipe_exchange":false,"system_capability_advertised":false,"helper_ready":false,"no_jobs":true,"code":"HELPER_NOT_AVAILABLE"}))?;
}
result
})
.await?
}
fn check_pin(&self) -> Result<()> {
let current = Self::discover(
&self.pin.binding.agent_id.to_string(),
&self.pin.binding.asset_id.to_string(),
Some(&self.pin.binding),
self.lane.clone(),
)?
.context("HELPER_PIN_REMOVED")?;
ensure!(
serde_json::to_vec(&current.pin)? == serde_json::to_vec(&self.pin)?,
"HELPER_PIN_CHANGED"
);
Ok(())
}
pub fn pin_hash(&self) -> &str {
&self.pin.policy_sha256
}
async fn call(&self, operation: ipc::Operation) -> Result<ipc::Reply> {
let permit = self
.lane
.clone()
.try_acquire_owned()
.context("HELPER_CONTROL_BUSY")?;
let client = self.clone();
tokio::task::spawn_blocking(move || {
let _permit = permit;
client.check_pin()?;
let call = ipc::Call::new(&client.pin, operation);
let reply = ipc::exchange(&client.pin, &call, Duration::from_secs(5))?;
client.check_pin()?;
Ok(reply)
})
.await?
}
fn probe_blocking(&self, state: &Path) -> Result<()> {
self.check_pin()?;
let pin = &self.pin;
let call = ipc::Call::new(pin, ipc::Operation::Probe {});
let reply = ipc::exchange(pin, &call, Duration::from_secs(5))?;
let ipc::ReplyBody::Probe {
clock_qualified,
ready,
ledger,
lock,
} = reply.body
else {
anyhow::bail!("HELPER_PROBE_DENIED");
};
let value = json!({"schema_version":1,"source":"actual_local_service_runtime","agent_process_id":std::process::id(),"agent_service":crate::SERVICE_NAME,"agent_id":pin.binding.agent_id,"asset_id":pin.binding.asset_id,"challenge":reply.challenge,"observed_at":chrono::Utc::now(),"helper_service":ipc::HELPER_SERVICE,"verified_helper_user_sid":pin.helper.user_sid,"verified_helper_service_sid":pin.helper.service_sid,"helper_binary_sha256":reply.helper_binary_sha256,"policy_sha256":reply.policy_sha256,"authenticated_pipe_exchange":true,"client_service_pid_verified_by_helper":true,"ledger_file_id":ledger,"executor_lock_file_id":lock,"helper_clock_qualified":clock_qualified,"helper_ready":ready,"system_capability_advertised":false,"no_jobs":true});
self.check_pin()?;
write_current_probe(state, &value)
}
pub async fn snapshot(&self, generation: u64, boot: uuid::Uuid) -> Result<HelperSnapshot> {
let reply = self.call(ipc::Operation::Snapshot { generation }).await?;
let ipc::ReplyBody::Snapshot { snapshot } = reply.body else {
anyhow::bail!("HELPER_SNAPSHOT_DENIED");
};
ensure!(snapshot.boot_id == boot, "HELPER_BOOT_MISMATCH");
Ok(map_snapshot(&snapshot))
}
pub async fn apply(
&self,
response: &SyncResponse,
request_bytes: Vec<u8>,
boot: uuid::Uuid,
) -> Result<HelperSnapshot> {
let reply = self
.call(ipc::Operation::Apply {
response: rmm_agent_core::helper_reconcile::SignedResponse {
decision_bytes: response.decision_bytes.clone(),
signature: response.signature.clone(),
},
request_bytes,
})
.await?;
let ipc::ReplyBody::Applied { snapshot, .. } = reply.body else {
anyhow::bail!("HELPER_APPLY_DENIED");
};
ensure!(snapshot.boot_id == boot, "HELPER_BOOT_MISMATCH");
Ok(map_snapshot(&snapshot))
}
}
fn map_snapshot(s: &Snapshot) -> HelperSnapshot {
HelperSnapshot {
journal_id: s.journal_id,
checkpoint: s.checkpoint,
previous_decision_id: s.previous_decision_id,
attempts: s
.attempts
.iter()
.map(|a| SyncAttempt {
job_id: a.job_id.to_string(),
attempt_id: a.attempt_id.to_string(),
job_payload_hash: a.job_payload_hash.clone(),
grant_id: a.grant_id.to_string(),
consumption: a.consumption.clone(),
state: a.state.clone(),
revision: a.revision,
original_boot_id: a.original_boot_id.to_string(),
outcome_sha256: a.outcome_sha256.clone(),
outcome_bytes: a.outcome_bytes.clone(),
..Default::default()
})
.collect(),
}
}
fn write_current_probe(state: &Path, value: &serde_json::Value) -> Result<()> {
native::private_path(state, true)?;
let path = state.join(PROBE_FILE);
if path.try_exists()? {
native::private_path(&path, false)?;
}
let bytes = serde_json::to_vec(value)?;
ensure!(bytes.len() <= 8192, "HELPER_PROBE_REPORT_LIMIT");
// One fixed create-only staging file bounds even interrupted-report state.
// A leftover from a killed process is refused; it is never overwritten.
let temporary = state.join(".helper-probe.pending");
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&temporary)?;
let written = (|| {
native::private_path(&temporary, false)?;
file.write_all(&bytes)?;
file.sync_all()?;
Ok::<_, anyhow::Error>(())
})();
drop(file);
let result = written.and_then(|()| {
std::fs::rename(&temporary, &path)?;
native::private_path(&path, false)
});
if result.is_err() {
// Only our successfully create_new-opened staging file is eligible.
let _ = std::fs::remove_file(&temporary);
}
result
}
+11 -9
View File
@@ -1,14 +1,5 @@
//! First Windows slice: passive observations and durable telemetry only.
//! No executor, startgrant consumer or privileged helper is advertised.
pub mod journal;
#[cfg(windows)]
pub mod native;
#[cfg(windows)]
pub mod inventory;
#[cfg(windows)]
pub mod service;
#[cfg(windows)]
pub mod process;
#[cfg(windows)]
pub mod actions;
#[cfg(windows)]
@@ -16,7 +7,18 @@ pub mod clock;
#[cfg(all(windows, feature = "system-helper"))]
pub mod helper_ipc;
#[cfg(all(windows, feature = "system-helper"))]
pub mod helper_runtime;
#[cfg(all(windows, feature = "system-helper"))]
pub mod helper_system;
#[cfg(windows)]
pub mod inventory;
pub mod journal;
#[cfg(windows)]
pub mod native;
#[cfg(windows)]
pub mod process;
#[cfg(windows)]
pub mod service;
pub const SERVICE_NAME: &str = "RmmDiscoveryWindows";
pub const CAPABILITIES: &[&str] = &["windows.base/1", "heartbeat/1"];
+758
View File
@@ -0,0 +1,758 @@
//! Unwired fixture-only MSI provider. This module confers no authorization.
//! Caller must authenticate its SYSTEM helper, validate signed job/grant+local
//! recipe policy, hold the device/package conflict lock and durably consume the
//! attempt before start(). Cache population is a separate verified RMM artifact
//! operation: this module has no network, URL, UNC, transform or free arguments.
//!
//! Only first install/exact noop of v1.0.0 is implemented. Upgrade and EXE are
//! separate deliveries, not guessed modes of this MSI executor.
//! MSI metadata APIs are synchronous. The caller owns the outer observation
//! deadline; a poll timeout is not a promise that Windows Installer stopped.
//! Do not put this controller in a kill-on-close process-tree executor.
//! https://learn.microsoft.com/en-us/windows/win32/api/msi/nf-msi-msigetproductinfoexw
//! https://learn.microsoft.com/en-us/windows/win32/msi/standard-installer-command-line-options
//! https://learn.microsoft.com/en-us/windows/win32/msi/reboot
//! https://learn.microsoft.com/en-us/windows/win32/msi/error-codes
#[cfg(windows)]
use anyhow::{Result, ensure};
#[cfg(windows)]
use rmm_domain::windows_execution::ResolvedWindowsMsi;
use serde::Serialize;
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Snapshot {
pub product_state: Option<String>,
pub product_version: Option<String>,
pub payload_sha256: Option<String>,
pub payload_bytes: Option<u64>,
}
impl Snapshot {
#[cfg(windows)]
fn desired(&self, r: &ResolvedWindowsMsi) -> bool {
let p = &r.recipe.postcondition;
self.product_state.as_deref() == Some("5")
&& self.product_version.as_deref() == Some(&p.product_version)
&& self.payload_sha256.as_deref() == Some(&p.payload_sha256)
&& self.payload_bytes == Some(p.payload_bytes)
}
#[cfg(any(windows, test))]
fn absent(&self) -> bool {
self.product_state.is_none()
&& self.product_version.is_none()
&& self.payload_sha256.is_none()
&& self.payload_bytes.is_none()
}
}
#[derive(Debug, Serialize)]
pub struct Observation {
pub recipe_sha256: String,
pub artifact_sha256: String,
pub process_id: Option<u32>,
pub state: &'static str,
pub code: &'static str,
pub exit_code: Option<u32>,
pub postconditions_passed: bool,
pub already_desired: bool,
pub installer_process_started: bool,
/// None when no transaction-level observation exists; spawning msiexec is
/// not itself evidence that the Windows Installer service began a change.
pub transaction_started: Option<bool>,
/// Only the installer's own exit semantics; ambient host reboot state is
/// not inferred from an MSI process exit or from an exact no-op.
pub installer_reboot_required: Option<bool>,
pub reboot_initiated: bool,
pub before: Snapshot,
pub after: Option<Snapshot>,
pub automatic_retry: bool,
}
#[cfg(any(windows, test))]
fn classification(
exit: u32,
postconditions: bool,
) -> (&'static str, &'static str, Option<bool>, bool) {
match exit {
0 | 3010 if postconditions => (
"succeeded",
"MSI_POSTCONDITIONS_VERIFIED",
Some(exit == 3010),
false,
),
0 | 3010 => (
"failed",
"MSI_POSTCONDITIONS_FAILED",
Some(exit == 3010),
false,
),
1641 => (
"unknown",
"MSI_UNEXPECTED_REBOOT_INITIATED",
Some(true),
true,
),
1618 => ("failed", "MSI_ANOTHER_INSTALLATION_RUNNING", None, false),
_ => ("unknown", "MSI_FAILURE_EFFECT_UNRESOLVED", None, false),
}
}
/// Contract and locally protected policy must agree, independently of the job.
/// The policy hash must come from the helper's protected settings, never a field
/// copied back out of the job being checked.
#[cfg(windows)]
fn validate(r: &ResolvedWindowsMsi, allowed_recipe_sha256: &str) -> Result<()> {
ensure!(
r.validate() && r.recipe_sha256 == allowed_recipe_sha256,
"MSI_RECIPE_NOT_ALLOWED"
);
Ok(())
}
#[cfg(windows)]
mod windows {
use super::*;
use rmm_domain::windows_execution::{MSI_PAYLOAD, MSI_PRODUCT_CODE};
use sha2::{Digest, Sha256};
use std::{
fs::{File, OpenOptions},
io::{Read, Seek, SeekFrom},
mem::{size_of, zeroed},
os::windows::{
ffi::OsStrExt,
fs::OpenOptionsExt,
io::{AsRawHandle, FromRawHandle},
},
path::{Path, PathBuf},
process::{Child, Command, Stdio},
ptr,
sync::atomic::{AtomicBool, Ordering},
time::{Duration, Instant},
};
use windows_sys::Win32::{
Foundation::*,
Security::{Authorization::*, *},
Storage::FileSystem::*,
System::{
ApplicationInstallationAndServicing::*, SystemInformation::GetSystemWindowsDirectoryW,
},
};
const CACHE: &str = r"C:\ProgramData\RustDiscoverySystem\cache";
const FIXTURES: &str = r"C:\Program Files\RustDiscoveryFixtures";
const TRUSTED_INSTALLER: &str =
"S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";
fn wide(s: impl AsRef<std::ffi::OsStr>) -> Vec<u16> {
s.as_ref().encode_wide().chain(Some(0)).collect()
}
fn sid(sid: PSID) -> Result<String> {
let mut raw = ptr::null_mut();
ensure!(
unsafe { ConvertSidToStringSidW(sid, &mut raw) } != 0,
"MSI_SID"
);
let result = (|| {
let mut n = 0;
while n < 192 && unsafe { *raw.add(n) } != 0 {
n += 1
}
ensure!(n < 192, "MSI_SID_LIMIT");
Ok(String::from_utf16(unsafe {
std::slice::from_raw_parts(raw, n)
})?)
})();
unsafe {
LocalFree(raw.cast());
}
result
}
fn acl(file: &File, system_binary: bool) -> Result<()> {
let mut owner = ptr::null_mut();
let mut dacl = ptr::null_mut();
let mut descriptor = ptr::null_mut();
ensure!(
unsafe {
GetSecurityInfo(
file.as_raw_handle(),
SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
&mut owner,
ptr::null_mut(),
&mut dacl,
ptr::null_mut(),
&mut descriptor,
)
} == 0,
"MSI_FILE_ACL"
);
let result = (|| {
ensure!(
!owner.is_null() && !dacl.is_null() && unsafe { (*dacl).AceCount } > 0,
"MSI_NULL_DACL"
);
let privileged = |s: &str| {
s == "S-1-5-18" || s == "S-1-5-32-544" || (system_binary && s == TRUSTED_INSTALLER)
};
ensure!(privileged(&sid(owner)?), "MSI_FILE_OWNER");
for i in 0..unsafe { (*dacl).AceCount } {
let mut raw = ptr::null_mut();
ensure!(
unsafe { GetAce(dacl, i.into(), &mut raw) } != 0,
"MSI_FILE_ACE"
);
let ace = unsafe { &*raw.cast::<ACCESS_ALLOWED_ACE>() };
ensure!(
ace.Header.AceType == 0
&& ace.Header.AceSize as usize >= size_of::<ACCESS_ALLOWED_ACE>(),
"MSI_ACE_TYPE"
);
if ace.Header.AceFlags & INHERIT_ONLY_ACE as u8 != 0 {
continue;
}
let who = sid(ptr::addr_of!(ace.SidStart).cast_mut().cast())?;
ensure!(
privileged(&who)
|| ace.Mask & !(0x0012_00a9 | GENERIC_READ | GENERIC_EXECUTE) == 0,
"MSI_WRITABLE_BY_UNTRUSTED_PRINCIPAL"
);
}
Ok(())
})();
unsafe {
LocalFree(descriptor.cast());
}
result
}
fn information(file: &File, directory: bool) -> Result<BY_HANDLE_FILE_INFORMATION> {
let mut i: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() };
ensure!(
unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut i) } != 0
&& i.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0
&& (i.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0) == directory,
"MSI_REGULAR_PATH"
);
Ok(i)
}
fn id(i: &BY_HANDLE_FILE_INFORMATION) -> (u32, u32, u32) {
(i.dwVolumeSerialNumber, i.nFileIndexHigh, i.nFileIndexLow)
}
struct Held {
file: File,
path: PathBuf,
identity: (u32, u32, u32),
_ancestors: Vec<File>,
system_binary: bool,
}
impl Held {
fn open(path: &Path, system_binary: bool) -> Result<Self> {
ensure!(
path.is_absolute()
&& !path.to_string_lossy().starts_with(r"\\")
&& !path.to_string_lossy().contains(".."),
"MSI_LOCAL_PATH"
);
let mut ancestors = Vec::new();
for parent in path.ancestors().skip(1) {
let raw = unsafe {
CreateFileW(
wide(parent).as_ptr(),
FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_WRITE,
ptr::null(),
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
ptr::null_mut(),
)
};
ensure!(raw != INVALID_HANDLE_VALUE, "MSI_ANCESTOR_OPEN");
let file = unsafe { File::from_raw_handle(raw) };
information(&file, true)?;
ancestors.push(file);
}
let file = OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?;
let i = information(&file, false)?;
ensure!(system_binary || i.nNumberOfLinks == 1, "MSI_HARDLINK");
acl(&file, system_binary)?;
Ok(Self {
file,
path: path.into(),
identity: id(&i),
_ancestors: ancestors,
system_binary,
})
}
fn check(&self) -> Result<()> {
ensure!(
id(&information(&self.file, false)?) == self.identity,
"MSI_HELD_ID"
);
acl(&self.file, self.system_binary)?;
let again = Self::open(&self.path, self.system_binary)?;
ensure!(again.identity == self.identity, "MSI_PATH_REPLACED");
Ok(())
}
fn hash(&mut self, max: u64) -> Result<(String, u64)> {
self.check()?;
let len = self.file.metadata()?.len();
ensure!(len > 0 && len <= max, "MSI_FILE_LENGTH");
self.file.seek(SeekFrom::Start(0))?;
let mut sha = Sha256::new();
let mut count = 0u64;
let mut buffer = [0u8; 8192];
loop {
let n = self.file.read(&mut buffer)?;
if n == 0 {
break;
}
count += n as u64;
ensure!(count <= max, "MSI_FILE_GROWTH");
sha.update(&buffer[..n]);
}
ensure!(count == len, "MSI_FILE_CHANGED");
self.check()?;
Ok((format!("{:x}", sha.finalize()), count))
}
}
struct Msi(u32);
impl Drop for Msi {
fn drop(&mut self) {
if self.0 != 0 {
unsafe {
MsiCloseHandle(self.0);
}
}
}
}
fn msi_text(db: u32, query: &str) -> Result<String> {
let mut view = 0;
ensure!(
unsafe { MsiDatabaseOpenViewW(db, wide(query).as_ptr(), &mut view) } == 0,
"MSI_DATABASE_VIEW"
);
let view = Msi(view);
ensure!(
unsafe { MsiViewExecute(view.0, 0) } == 0,
"MSI_DATABASE_EXECUTE"
);
let mut record = 0;
ensure!(
unsafe { MsiViewFetch(view.0, &mut record) } == 0,
"MSI_DATABASE_ROW"
);
let record = Msi(record);
let mut text = [0u16; 256];
let mut len = 255;
ensure!(
unsafe { MsiRecordGetStringW(record.0, 1, text.as_mut_ptr(), &mut len) } == 0
&& len < 256,
"MSI_DATABASE_STRING"
);
let mut extra = 0;
let code = unsafe { MsiViewFetch(view.0, &mut extra) };
let _extra = Msi(extra);
ensure!(code == ERROR_NO_MORE_ITEMS, "MSI_DATABASE_NOT_UNIQUE");
Ok(String::from_utf16(&text[..len as usize])?)
}
fn no_custom_actions(db: u32) -> Result<()> {
let mut view = 0;
ensure!(
unsafe {
MsiDatabaseOpenViewW(
db,
wide("SELECT `Name` FROM `_Tables` WHERE `Name`='CustomAction'").as_ptr(),
&mut view,
)
} == 0,
"MSI_TABLE_LIST"
);
let view = Msi(view);
ensure!(unsafe { MsiViewExecute(view.0, 0) } == 0, "MSI_TABLE_QUERY");
let mut record = 0;
let code = unsafe { MsiViewFetch(view.0, &mut record) };
let _record = Msi(record);
if code == ERROR_NO_MORE_ITEMS {
return Ok(());
}
ensure!(code == 0, "MSI_TABLE_FETCH");
let mut actions = 0;
ensure!(
unsafe {
MsiDatabaseOpenViewW(
db,
wide("SELECT `Action` FROM `CustomAction`").as_ptr(),
&mut actions,
)
} == 0,
"MSI_CUSTOM_ACTION_QUERY"
);
let actions = Msi(actions);
ensure!(
unsafe { MsiViewExecute(actions.0, 0) } == 0,
"MSI_CUSTOM_ACTION_EXECUTE"
);
let mut action = 0;
let code = unsafe { MsiViewFetch(actions.0, &mut action) };
let _action = Msi(action);
ensure!(code == ERROR_NO_MORE_ITEMS, "MSI_CUSTOM_ACTIONS_DENIED");
Ok(())
}
fn inspect_archive(file: &mut Held, r: &ResolvedWindowsMsi) -> Result<()> {
let (sha, len) = file.hash(262144)?;
ensure!(
sha == r.recipe.artifact.sha256 && len == r.recipe.artifact.bytes,
"MSI_ARTIFACT_HASH"
);
let mut db = 0;
ensure!(
unsafe { MsiOpenDatabaseW(wide(&file.path).as_ptr(), MSIDBOPEN_READONLY, &mut db) }
== 0,
"MSI_DATABASE_OPEN"
);
let db = Msi(db);
no_custom_actions(db.0)?;
let cabinet = msi_text(db.0, "SELECT `Cabinet` FROM `Media`")?;
ensure!(
cabinet.starts_with('#')
&& cabinet.len() > 1
&& cabinet.len() <= 128
&& cabinet[1..]
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b)),
"MSI_EMBEDDED_CABINET_REQUIRED"
);
for (field, value) in [
("ProductCode", MSI_PRODUCT_CODE),
(
"ProductVersion",
r.recipe.postcondition.product_version.as_str(),
),
("ALLUSERS", "1"),
("UpgradeCode", r.recipe.upgrade_code.as_str()),
] {
ensure!(
msi_text(
db.0,
&format!("SELECT `Value` FROM `Property` WHERE `Property`='{field}'")
)? == value,
"MSI_DATABASE_PROPERTY"
);
}
let mut summary = 0;
ensure!(
unsafe { MsiGetSummaryInformationW(db.0, ptr::null(), 0, &mut summary) } == 0,
"MSI_SUMMARY"
);
let summary = Msi(summary);
let mut kind = 0;
let mut value = 0;
let mut time: FILETIME = unsafe { zeroed() };
let mut text = [0u16; 256];
let mut len = 255;
ensure!(
unsafe {
MsiSummaryInfoGetPropertyW(
summary.0,
7,
&mut kind,
&mut value,
&mut time,
text.as_mut_ptr(),
&mut len,
)
} == 0
&& kind == 30
&& len < 256,
"MSI_ARCHITECTURE_SUMMARY"
);
ensure!(
String::from_utf16(&text[..len as usize])?.starts_with("x64;"),
"MSI_NOT_X64"
);
file.check()?;
Ok(())
}
fn property(name: &str) -> Result<Option<String>> {
let mut value = [0u16; 256];
let mut len = 255;
let code = unsafe {
MsiGetProductInfoExW(
wide(MSI_PRODUCT_CODE).as_ptr(),
ptr::null(),
MSIINSTALLCONTEXT_MACHINE,
wide(name).as_ptr(),
value.as_mut_ptr(),
&mut len,
)
};
if code == ERROR_UNKNOWN_PRODUCT {
return Ok(None);
}
ensure!(code == 0 && len < 256, "MSI_MACHINE_PRODUCT_QUERY");
Ok(Some(String::from_utf16(&value[..len as usize])?))
}
pub fn snapshot() -> Result<Snapshot> {
let product_state = property("State")?;
let product_version = if product_state.as_deref() == Some("5") {
property("VersionString")?
} else {
None
};
let (payload_sha256, payload_bytes) = match std::fs::symlink_metadata(MSI_PAYLOAD) {
Ok(_) => {
let mut file = Held::open(Path::new(MSI_PAYLOAD), false)?;
let (sha, len) = file.hash(65536)?;
(Some(sha), Some(len))
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => (None, None),
Err(e) => return Err(e.into()),
};
Ok(Snapshot {
product_state,
product_version,
payload_sha256,
payload_bytes,
})
}
fn system_root() -> Result<PathBuf> {
let mut value = [0u16; 32768];
let len = unsafe { GetSystemWindowsDirectoryW(value.as_mut_ptr(), value.len() as u32) };
ensure!(len > 0 && (len as usize) < value.len(), "MSI_SYSTEM_ROOT");
Ok(PathBuf::from(String::from_utf16(&value[..len as usize])?))
}
pub struct Prepared {
recipe: ResolvedWindowsMsi,
archive: Held,
msiexec: Held,
_roots: Vec<File>,
before: Snapshot,
system_root: PathBuf,
}
impl Prepared {
pub fn prepare(r: &ResolvedWindowsMsi, allowed_recipe_sha256: &str) -> Result<Self> {
validate(r, allowed_recipe_sha256)?;
let mut roots = Vec::new();
for path in [CACHE, FIXTURES] {
let file = OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?;
information(&file, true)?;
acl(&file, false)?;
roots.push(file);
}
let mut archive = Held::open(
&Path::new(CACHE).join(format!("{}.msi", r.recipe.artifact.sha256)),
false,
)?;
inspect_archive(&mut archive, r)?;
let system_root = system_root()?;
let msiexec = Held::open(&system_root.join("System32").join("msiexec.exe"), true)?;
let before = snapshot()?;
ensure!(
before.absent() || before.desired(r),
"MSI_EXISTING_PRODUCT_OR_PAYLOAD_CONFLICT"
);
Ok(Self {
recipe: r.clone(),
archive,
msiexec,
_roots: roots,
before,
system_root,
})
}
/// Called only after durable original-grant consumption. No change of
/// config, privilege, policy, clock, reboot or foreign process occurs.
pub fn start(
mut self,
timeout: Duration,
cancelled: &AtomicBool,
check_effect_fence: impl FnOnce() -> Result<()>,
) -> Result<Run> {
ensure!(
timeout >= Duration::from_secs(1)
&& timeout <= Duration::from_secs(300)
&& !cancelled.load(Ordering::SeqCst),
"MSI_START_LIMIT_OR_CANCELLED"
);
inspect_archive(&mut self.archive, &self.recipe)?;
self.msiexec.check()?;
let before = snapshot()?;
ensure!(before == self.before, "MSI_BASELINE_CHANGED");
if before.desired(&self.recipe) {
return Ok(Run::Noop(Box::new(Observation {
recipe_sha256: self.recipe.recipe_sha256.clone(),
artifact_sha256: self.recipe.recipe.artifact.sha256.clone(),
process_id: None,
state: "succeeded",
code: "MSI_ALREADY_DESIRED",
exit_code: None,
postconditions_passed: true,
already_desired: true,
installer_process_started: false,
transaction_started: Some(false),
installer_reboot_required: None,
reboot_initiated: false,
before: before.clone(),
after: Some(before),
automatic_retry: false,
})));
}
ensure!(before.absent(), "MSI_INSTALL_BASELINE_CONFLICT");
use std::os::windows::process::CommandExt;
check_effect_fence()?;
ensure!(
!cancelled.load(Ordering::SeqCst),
"MSI_CANCELLED_BEFORE_START"
);
let began = Instant::now();
let child = Command::new(&self.msiexec.path)
.args([
std::ffi::OsStr::new("/i"),
self.archive.path.as_os_str(),
std::ffi::OsStr::new("/qn"),
std::ffi::OsStr::new("/norestart"),
std::ffi::OsStr::new("REBOOT=ReallySuppress"),
std::ffi::OsStr::new("ALLUSERS=1"),
])
.env_clear()
.env("SystemRoot", &self.system_root)
.current_dir(CACHE)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.creation_flags(0x08000000)
.spawn()?;
Ok(Run::Installer(Box::new(Installer {
prepared: self,
child,
began,
timeout,
})))
}
}
pub enum Run {
Noop(Box<Observation>),
Installer(Box<Installer>),
}
pub struct Installer {
prepared: Prepared,
child: Child,
began: Instant,
timeout: Duration,
}
impl Installer {
pub fn process_id(&self) -> u32 {
self.child.id()
}
/// Poll the SAME process only. Timeout/cancel neither kills msiexec nor
/// the system installer service. Caller retains/fences this attempt;
/// another poll is evidence gathering, never a second start.
pub fn poll(&mut self, cancelled: &AtomicBool) -> Result<Option<Observation>> {
let exit = self.child.try_wait()?;
let code = if let Some(status) = exit {
status.code().map(|n| n as u32)
} else {
None
};
if exit.is_none()
&& !cancelled.load(Ordering::SeqCst)
&& self.began.elapsed() < self.timeout
{
return Ok(None);
}
let mut after = None;
let (state, error, reboot, initiated) = if let Some(code) = code {
after = snapshot().ok();
if after.is_none() && matches!(code, 0 | 3010) {
(
"unknown",
"MSI_POSTCONDITION_QUERY_FAILED",
Some(code == 3010),
false,
)
} else {
classification(
code,
after
.as_ref()
.is_some_and(|s| s.desired(&self.prepared.recipe)),
)
}
} else {
(
"unknown",
if cancelled.load(Ordering::SeqCst) {
"MSI_CANCELLED_EFFECT_UNRESOLVED"
} else {
"MSI_TIMEOUT_EFFECT_UNRESOLVED"
},
None,
false,
)
};
Ok(Some(Observation {
recipe_sha256: self.prepared.recipe.recipe_sha256.clone(),
artifact_sha256: self.prepared.recipe.recipe.artifact.sha256.clone(),
process_id: Some(self.child.id()),
state,
code: error,
exit_code: code,
postconditions_passed: state == "succeeded",
already_desired: false,
installer_process_started: true,
transaction_started: if code == Some(1618) {
Some(false)
} else {
None
},
installer_reboot_required: reboot,
reboot_initiated: initiated,
before: self.prepared.before.clone(),
after,
automatic_retry: false,
}))
}
}
}
#[cfg(windows)]
pub use windows::{Installer, Prepared, Run, snapshot};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exit_code_never_substitutes_for_independent_postconditions_or_reboot_authority() {
assert_eq!(
classification(0, true),
(
"succeeded",
"MSI_POSTCONDITIONS_VERIFIED",
Some(false),
false
)
);
assert_eq!(classification(3010, true).2, Some(true));
assert_eq!(classification(0, false).0, "failed");
assert_eq!(
classification(1641, true),
(
"unknown",
"MSI_UNEXPECTED_REBOOT_INITIATED",
Some(true),
true
)
);
assert_eq!(
classification(1618, false).1,
"MSI_ANOTHER_INSTALLATION_RUNNING"
);
assert_eq!(classification(1603, false).0, "unknown");
let advertised = Snapshot {
product_state: Some("1".into()),
product_version: None,
payload_sha256: None,
payload_bytes: None,
};
assert!(!advertised.absent());
}
}
+222 -7
View File
@@ -337,6 +337,30 @@ fn open_ledger(directory: &Path, binding: &Binding) -> Result<(Connection, fs::F
}
Ok((db, file))
}
#[cfg(feature = "system-helper")]
enum HelperControl {
Snapshot(
u64,
tokio::task::JoinHandle<Result<reconcile::HelperSnapshot>>,
),
Apply(
u64,
tokio::task::JoinHandle<Result<reconcile::HelperSnapshot>>,
),
}
#[cfg(feature = "system-helper")]
impl HelperControl {
fn finished(&self) -> bool {
match self {
Self::Snapshot(_, t) | Self::Apply(_, t) => t.is_finished(),
}
}
fn abort(self) {
match self {
Self::Snapshot(_, t) | Self::Apply(_, t) => t.abort(),
}
}
}
struct Agent {
config: Config,
identity: EnrollmentResponse,
@@ -351,6 +375,23 @@ struct Agent {
clock: JobClock,
sync: Option<reconcile::ClientSync>,
prepared: bool,
#[cfg(feature = "system-helper")]
prepared_request: Option<Vec<u8>>,
#[cfg(feature = "system-helper")]
helper_lane: Arc<tokio::sync::Semaphore>,
#[cfg(feature = "system-helper")]
helper: Option<rmm_agent_windows::helper_runtime::Client>,
#[cfg(feature = "system-helper")]
helper_probe:
Option<tokio::task::JoinHandle<Result<Option<rmm_agent_windows::helper_runtime::Client>>>>,
#[cfg(feature = "system-helper")]
helper_probe_at: Instant,
#[cfg(feature = "system-helper")]
helper_control: Option<HelperControl>,
#[cfg(feature = "system-helper")]
helper_checked: bool,
#[cfg(feature = "system-helper")]
helper_refused: bool,
fence: Arc<EffectFence>,
completed_tx: tokio::sync::mpsc::Sender<Completion>,
completed_rx: tokio::sync::mpsc::Receiver<Completion>,
@@ -364,8 +405,110 @@ impl Agent {
sync.close();
}
self.prepared = false;
#[cfg(feature = "system-helper")]
{
self.prepared_request = None;
if let Some(control) = self.helper_control.take() {
control.abort();
}
}
self.deferred_permit = None;
}
fn helper_control_pending(&self) -> bool {
#[cfg(feature = "system-helper")]
{
self.helper_control.is_some()
|| self.helper_probe.is_some()
|| !self.helper_checked
|| self.helper_refused
}
#[cfg(not(feature = "system-helper"))]
{
false
}
}
#[cfg(feature = "system-helper")]
async fn poll_helper(
&mut self,
channel: &crate::wire_channel::Handle,
generation: u64,
) -> Result<()> {
if self
.helper_control
.as_ref()
.is_some_and(HelperControl::finished)
{
match self
.helper_control
.take()
.context("HELPER_CONTROL_REQUIRED")?
{
HelperControl::Snapshot(expected, task) => {
ensure!(expected == generation, "HELPER_CHANNEL_CHANGED");
let snapshot = task.await??;
self.send_sync(channel, generation, Some(&snapshot)).await?;
}
HelperControl::Apply(expected, task) => {
ensure!(expected == generation, "HELPER_CHANNEL_CHANGED");
let snapshot = task.await??;
self.sync
.as_mut()
.context("SYNC_NOT_CONFIGURED")?
.confirm_helper(&snapshot)?;
self.open_fence(generation)?;
}
}
}
if self
.helper_probe
.as_ref()
.is_some_and(|task| task.is_finished())
{
let result = self
.helper_probe
.take()
.context("HELPER_PROBE_REQUIRED")?
.await?;
self.helper_probe_at = Instant::now();
self.helper_checked = true;
match result {
Ok(client) => {
self.helper_refused = false;
if self.helper.as_ref().map(|c| c.pin_hash())
!= client.as_ref().map(|c| c.pin_hash())
{
self.close_gate();
}
self.helper = client;
}
Err(error) => {
self.helper_refused = true;
self.helper = None;
self.close_gate();
return Err(error);
}
}
}
if self.helper_probe.is_none()
&& self.helper_control.is_none()
&& !self.prepared
&& self.running.is_none()
&& self.helper_probe_at.elapsed() >= Duration::from_secs(30)
{
let agent = self.identity.agent_id.clone();
let asset = self.identity.asset_id.clone();
let binding = self.binding.clone();
let lane = self.helper_lane.clone();
let state = self.config.state_directory.clone();
self.helper_probe = Some(tokio::spawn(async move {
rmm_agent_windows::helper_runtime::Client::refresh(
agent, asset, binding, lane, state,
)
.await
}));
}
Ok(())
}
fn channel(&self, generation: u64) -> Result<reconcile::Channel> {
Ok(reconcile::Channel {
connection_generation: generation,
@@ -374,6 +517,7 @@ impl Agent {
}
fn ready(&self, generation: u64) -> bool {
self.config.enable_jobs
&& !self.helper_control_pending()
&& self.channel(generation).is_ok_and(|channel| {
self.sync
.as_ref()
@@ -461,15 +605,38 @@ impl Agent {
generation: u64,
) -> Result<()> {
self.fence.close();
ensure!(!self.helper_control_pending(), "HELPER_CONTROL_NOT_SETTLED");
#[cfg(feature = "system-helper")]
if let Some(helper) = self.helper.clone() {
ensure!(self.helper_control.is_none(), "HELPER_CONTROL_PENDING");
let boot = self.channel(generation)?.boot_id;
self.helper_control = Some(HelperControl::Snapshot(
generation,
tokio::spawn(async move { helper.snapshot(generation, boot).await }),
));
return Ok(());
}
self.send_sync(channel, generation, None).await
}
async fn send_sync(
&mut self,
channel: &crate::wire_channel::Handle,
generation: u64,
helper: Option<&reconcile::HelperSnapshot>,
) -> Result<()> {
let context = self.channel(generation)?;
let sync = self.sync.as_mut().context("SYNC_NOT_CONFIGURED")?;
let prepared = sync.prepare(
self.journal.connection_mut(),
self.ledger.as_ref().context("LEDGER_REQUIRED")?,
context,
None,
helper,
&self.clock,
)?;
#[cfg(feature = "system-helper")]
{
self.prepared_request = Some(prepared.request.encode_to_vec());
}
self.prepared = true;
channel.send(&prepared.envelope).await?;
Ok(())
@@ -479,14 +646,44 @@ impl Agent {
self.prepared = false;
let sync = self.sync.as_mut().context("SYNC_NOT_CONFIGURED")?;
let applied = sync.apply(self.journal.connection_mut(), &response, &self.clock)?;
ensure!(
applied.helper_instruction.is_none(),
"WINDOWS_HELPER_NOT_CONFIGURED"
);
sync.apply_consumption(
self.ledger.as_mut().context("LEDGER_REQUIRED")?,
&self.clock,
)?;
if let Some(instruction) = applied.helper_instruction {
#[cfg(feature = "system-helper")]
{
ensure!(self.helper_control.is_none(), "HELPER_CONTROL_PENDING");
let helper = self
.helper
.clone()
.context("WINDOWS_HELPER_NOT_CONFIGURED")?;
let request = self
.prepared_request
.take()
.context("ORIGINAL_SYNC_REQUEST_REQUIRED")?;
let boot = self.channel(generation)?.boot_id;
self.helper_control = Some(HelperControl::Apply(
generation,
tokio::spawn(async move {
helper.apply(&instruction.response, request, boot).await
}),
));
return Ok(());
}
#[cfg(not(feature = "system-helper"))]
{
let _ = instruction;
anyhow::bail!("WINDOWS_HELPER_NOT_CONFIGURED");
}
}
#[cfg(feature = "system-helper")]
{
self.prepared_request = None;
}
self.open_fence(generation)
}
fn open_fence(&self, generation: u64) -> Result<()> {
if self.ready(generation) {
let deadline = self
.sync
@@ -797,6 +994,8 @@ impl Agent {
tokio::select! {
Some(completion)=self.completed_rx.recv()=>{self.completed(generation,completion)?;needs_sync=true;},
_=tick.tick()=>{
#[cfg(feature = "system-helper")]
if !stop.load(Ordering::SeqCst) && self.poll_helper(&channel,generation).await.is_err() {self.close_gate();needs_sync=self.sync.is_some();}
if !stop.load(Ordering::SeqCst) && let Some((pending_generation,permit))=self.deferred_permit.take() {
ensure!(pending_generation==generation,"PENDING_PERMIT_GENERATION");self.permit(generation,permit)?;
}
@@ -809,7 +1008,7 @@ impl Agent {
if !stop.load(Ordering::SeqCst) && !busy {
if capabilities_at.elapsed()>=Duration::from_secs(60) {capabilities_at=Instant::now();if advertised!=self.capabilities(){return Ok(());}}
if self.prepared && sync_at.elapsed()>=Duration::from_secs(20){self.close_gate();needs_sync=true;}
if self.sync.is_some() && !self.prepared && (needs_sync || sync_at.elapsed()>=Duration::from_secs(40) || !self.ready(generation)) {
if self.sync.is_some() && !self.prepared && !self.helper_control_pending() && (needs_sync || sync_at.elapsed()>=Duration::from_secs(40) || !self.ready(generation)) {
if self.start_sync(&channel,generation).await.is_err(){self.close_gate();needs_sync=true;}else{needs_sync=false;}sync_at=Instant::now();
}
if !needs_sync && !self.prepared && self.ready(generation) && jobs::events(self.journal.connection())?.is_empty() && self.journal.count()?==0 {
@@ -936,7 +1135,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
ensure!(!config.enable_jobs || binding.is_some(),"ENABLED_JOBS_REQUIRE_BINDING");
let (ledger,ledger_file)=match &binding {Some(binding)=>{let (db,file)=open_ledger(&config.state_directory,binding)?;(Some(db),Some(file))},None=>(None,None)};
let clock=JobClock{native:Arc::new(rmm_agent_windows::clock::NativeClock::new()),enabled:config.enable_jobs};
let sync=if config.enable_jobs {binding.clone().map(reconcile::ClientSync::new)} else {None};
let sync=if config.enable_jobs {binding.clone().map(|binding|reconcile::ClientSync::new(binding).with_helper_identity(reconcile::HelperIdentity::System))} else {None};
let (completed_tx,completed_rx)=tokio::sync::mpsc::channel(1);
let mut agent = Agent {
config,
@@ -946,6 +1145,22 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
boot,
instance: Uuid::new_v4().to_string(),
started: Instant::now(), binding, ledger, _ledger_file:ledger_file, clock, sync,
#[cfg(feature="system-helper")]
prepared_request:None,
#[cfg(feature="system-helper")]
helper_lane:Arc::new(tokio::sync::Semaphore::new(1)),
#[cfg(feature="system-helper")]
helper:None,
#[cfg(feature="system-helper")]
helper_probe:None,
#[cfg(feature="system-helper")]
helper_probe_at:Instant::now()-Duration::from_secs(30),
#[cfg(feature="system-helper")]
helper_control:None,
#[cfg(feature="system-helper")]
helper_checked:false,
#[cfg(feature="system-helper")]
helper_refused:false,
prepared:false,fence:Arc::new(EffectFence::default()),completed_tx,completed_rx,running:None,deferred_permit:None,
};
agent.recover_interrupted()?;
+159
View File
@@ -0,0 +1,159 @@
//! Unexported Windows MSI fixture contract. No legacy Linux codec is changed.
//! This version supports first installation or independently proven exact noop;
//! an upgrade requires a separate reviewed recipe with explicit predecessor
//! products/UpgradeCode semantics. No implicit REINSTALL flags are inferred.
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use uuid::Uuid;
pub const MSI_RECIPE_ID: &str = "rmm-windows-msi-fixture-install-1.0";
pub const MSI_PRODUCT_CODE: &str = "{3F070B4B-9C08-4D65-BD41-13D81B884AEC}";
pub const MSI_UPGRADE_CODE: &str = "{C9BF1FB8-E31D-4BD7-BA0D-AB46539BBBAA}";
pub const MSI_VERSION: &str = "1.0.0";
pub const MSI_PAYLOAD: &str = r"C:\Program Files\RustDiscoveryFixtures\msi-payload.txt";
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Architecture {
X64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InstallContext {
Machine,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MsiCommandProfile {
FixtureQuietNoRebootV1,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MsiArtifact {
pub artifact_id: Uuid,
pub sha256: String,
pub bytes: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MsiPostcondition {
pub product_code: String,
pub product_version: String,
pub payload_path: String,
pub payload_sha256: String,
pub payload_bytes: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WindowsMsiRecipe {
pub schema_version: u32,
pub recipe_id: String,
pub recipe_version: String,
pub platform: String,
pub upgrade_code: String,
pub architecture: Architecture,
pub context: InstallContext,
pub command_profile: MsiCommandProfile,
pub artifact: MsiArtifact,
pub postcondition: MsiPostcondition,
pub no_reboot: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ResolvedWindowsMsi {
pub recipe: WindowsMsiRecipe,
/// SHA256 of exactly serde_json::to_vec(recipe), not a self-reference.
pub recipe_sha256: String,
}
pub fn digest(value: &str) -> bool {
value.len() == 64
&& value
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
impl WindowsMsiRecipe {
pub fn validate(&self) -> bool {
self.schema_version == 1
&& self.recipe_id == MSI_RECIPE_ID
&& self.recipe_version == "1"
&& self.platform == "windows"
&& self.upgrade_code == MSI_UPGRADE_CODE
&& self.no_reboot
&& !self.artifact.artifact_id.is_nil()
&& digest(&self.artifact.sha256)
&& (1..=262144).contains(&self.artifact.bytes)
&& self.postcondition.product_code == MSI_PRODUCT_CODE
&& self.postcondition.product_version == MSI_VERSION
&& self.postcondition.payload_path == MSI_PAYLOAD
&& digest(&self.postcondition.payload_sha256)
&& (1..=65536).contains(&self.postcondition.payload_bytes)
}
pub fn sha256(&self) -> Result<String, serde_json::Error> {
Ok(format!("{:x}", Sha256::digest(serde_json::to_vec(self)?)))
}
}
impl ResolvedWindowsMsi {
pub fn validate(&self) -> bool {
self.recipe.validate()
&& digest(&self.recipe_sha256)
&& self
.recipe
.sha256()
.is_ok_and(|sha| sha == self.recipe_sha256)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn recipe() -> WindowsMsiRecipe {
WindowsMsiRecipe {
schema_version: 1,
recipe_id: MSI_RECIPE_ID.into(),
recipe_version: "1".into(),
platform: "windows".into(),
upgrade_code: MSI_UPGRADE_CODE.into(),
architecture: Architecture::X64,
context: InstallContext::Machine,
command_profile: MsiCommandProfile::FixtureQuietNoRebootV1,
artifact: MsiArtifact {
artifact_id: Uuid::new_v4(),
sha256: "ab".repeat(32),
bytes: 1234,
},
postcondition: MsiPostcondition {
product_code: MSI_PRODUCT_CODE.into(),
product_version: MSI_VERSION.into(),
payload_path: MSI_PAYLOAD.into(),
payload_sha256: "cd".repeat(32),
payload_bytes: 20,
},
no_reboot: true,
}
}
#[test]
fn immutable_fixture_recipe_rejects_reboot_url_transform_and_implicit_upgrade() {
let recipe = recipe();
let bound = ResolvedWindowsMsi {
recipe_sha256: recipe.sha256().unwrap(),
recipe: recipe.clone(),
};
assert!(bound.validate());
let mut changed = bound.clone();
changed.recipe.artifact.bytes += 1;
assert!(!changed.validate());
for case in 0..6 {
let mut r = recipe.clone();
match case {
0 => r.no_reboot = false,
1 => r.postcondition.product_code = Uuid::new_v4().to_string(),
2 => r.postcondition.product_version = "1.1.0".into(),
3 => r.postcondition.payload_path = r"\\server\share\payload".into(),
4 => r.artifact.bytes = 262145,
_ => r.platform = "linux".into(),
};
assert!(!r.validate());
}
let mut value = serde_json::to_value(recipe).unwrap();
value["transforms"] = serde_json::json!(["unapproved.mst"]);
assert!(serde_json::from_value::<WindowsMsiRecipe>(value).is_err());
}
}