Preserve Windows runtime state and qualify native guarded adapters
Rust development slice / linux (push) Failing after 7s

This commit is contained in:
2026-11-14 02:39:39 +01:00
parent 74736483df
commit 500cb7a33e
26 changed files with 6606 additions and 44 deletions
+9
View File
@@ -4,6 +4,15 @@ version.workspace = true
edition.workspace = true
license.workspace = true
[features]
default = []
system-helper = []
[[bin]]
name = "rmm-helper-windows"
path = "src/bin/rmm-helper-windows.rs"
required-features = ["system-helper"]
[dependencies]
anyhow.workspace = true
chrono.workspace = true
+51
View File
@@ -0,0 +1,51 @@
use std::{env, path::PathBuf, process::Command};
fn main() {
println!("cargo:rerun-if-changed=native/w32time.idl");
println!("cargo:rerun-if-changed=native/clock_rpc.c");
println!("cargo:rerun-if-changed=native/clock_endpoints.c");
if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
assert_eq!(
env::var("CARGO_CFG_TARGET_ARCH").as_deref(),
Ok("x86_64"),
"Windows clock RPC is qualified only for x86-64"
);
assert_eq!(
env::var("CARGO_CFG_TARGET_ENV").as_deref(),
Ok("gnu"),
"Windows clock RPC currently requires 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"],
] {
assert!(
Command::new("x86_64-w64-mingw32-widl")
.current_dir(&out)
.args(["--win64", "-Oif"])
.args(args)
.arg(&idl)
.status()
.expect("Install mingw-w64-tools for the generated read-only RPC stub")
.success(),
"WIDL clock stub generation failed"
);
}
// Clang implements x64 Windows SEH in the C boundary. MinGW GCC's __try
// spelling is not sufficient; do not let an RPC exception unwind into Rust.
cc::Build::new()
.compiler("clang")
.flag("--target=x86_64-w64-windows-gnu")
.flag("-fms-extensions")
.flag("-Werror")
.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");
}
@@ -0,0 +1,263 @@
//! Temporary, read-only readiness service. Separate from the permanent agent;
//! no network/RMM jobs, no clock setting, no W32Time ACL/service changes.
#[path = "../src/clock.rs"]
mod clock;
#[cfg(windows)]
mod service {
use anyhow::{Result, ensure};
use std::{
io::Write,
mem::{size_of, zeroed},
path::PathBuf,
ptr,
sync::{
OnceLock,
atomic::{AtomicUsize, Ordering},
},
time::Duration,
};
use windows_sys::Win32::{
Foundation::CloseHandle,
Security::*,
System::{
Services::*,
Threading::{GetCurrentProcess, OpenProcessToken},
},
};
const NAME: &str = "RmmWindowsClockReadiness";
static CASE: OnceLock<uuid::Uuid> = OnceLock::new();
static HANDLE: AtomicUsize = AtomicUsize::new(0);
static STAGE: AtomicUsize = AtomicUsize::new(0);
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(Some(0)).collect()
}
#[derive(serde::Serialize)]
struct TokenEvidence {
user_sid: &'static str,
elevation_flag: u32,
elevation_type: i32,
administrator_member: bool,
system_user: bool,
}
fn token() -> Result<TokenEvidence> {
STAGE.store(10, Ordering::SeqCst);
let mut handle = ptr::null_mut();
ensure!(
unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut handle) } != 0,
"READINESS_TOKEN"
);
let result = (|| {
STAGE.store(11, Ordering::SeqCst);
let mut size = 0;
unsafe {
GetTokenInformation(handle, TokenUser, ptr::null_mut(), 0, &mut size);
}
ensure!(size > 0 && size <= 4096, "READINESS_TOKEN_SIZE");
let mut user = vec![0usize; (size as usize).div_ceil(size_of::<usize>())];
ensure!(
unsafe {
GetTokenInformation(
handle,
TokenUser,
user.as_mut_ptr().cast(),
size,
&mut size,
)
} != 0,
"READINESS_TOKEN_USER"
);
STAGE.store(12, Ordering::SeqCst);
let info = unsafe { &*user.as_ptr().cast::<TOKEN_USER>() };
ensure!(
unsafe { IsWellKnownSid(info.User.Sid, WinLocalServiceSid) } != 0,
"READINESS_NOT_LOCAL_SERVICE"
);
STAGE.store(13, Ordering::SeqCst);
let mut elevation: TOKEN_ELEVATION = unsafe { zeroed() };
ensure!(
unsafe {
GetTokenInformation(
handle,
TokenElevation,
(&mut elevation as *mut TOKEN_ELEVATION).cast(),
size_of::<TOKEN_ELEVATION>() as u32,
&mut size,
)
} != 0,
"READINESS_ELEVATED"
);
STAGE.store(14, Ordering::SeqCst);
let mut elevation_type: TOKEN_ELEVATION_TYPE = 0;
ensure!(
unsafe {
GetTokenInformation(
handle,
TokenElevationType,
(&mut elevation_type as *mut TOKEN_ELEVATION_TYPE).cast(),
size_of::<TOKEN_ELEVATION_TYPE>() as u32,
&mut size,
)
} != 0,
"READINESS_ELEVATION_TYPE"
);
let mut admin_sid = [0u64; 9];
let mut admin_size = 72;
ensure!(
unsafe {
CreateWellKnownSid(
WinBuiltinAdministratorsSid,
ptr::null_mut(),
admin_sid.as_mut_ptr().cast(),
&mut admin_size,
)
} != 0,
"READINESS_ADMIN_SID"
);
let mut admin = 0;
ensure!(
unsafe {
CheckTokenMembership(ptr::null_mut(), admin_sid.as_mut_ptr().cast(), &mut admin)
} != 0,
"READINESS_ADMIN_CHECK"
);
Ok(TokenEvidence {
user_sid: "S-1-5-19",
elevation_flag: elevation.TokenIsElevated,
elevation_type,
administrator_member: admin != 0,
system_user: unsafe { IsWellKnownSid(info.User.Sid, WinLocalSystemSid) } != 0,
})
})();
unsafe {
CloseHandle(handle);
}
result
}
fn run() -> Result<()> {
let token = token()?;
STAGE.store(20, Ordering::SeqCst);
let case = CASE.get().unwrap();
let root =
PathBuf::from(r"C:\ProgramData\RustDiscoveryClockReadiness").join(case.to_string());
ensure!(root.is_dir() && !root.is_symlink(), "READINESS_ROOT");
// Preserve the actual token proof before entering foreign RPC code.
let mut token_file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(root.join("token.json"))?;
token_file.write_all(&serde_json::to_vec(&token)?)?;
token_file.sync_all()?;
let endpoints = super::clock::endpoint_report();
let mut endpoint_file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(root.join("endpoints.json"))?;
endpoint_file.write_all(&serde_json::to_vec(&endpoints)?)?;
endpoint_file.sync_all()?;
let clock = super::clock::NativeClock::new();
STAGE.store(30, Ordering::SeqCst);
let pipe = super::clock::named_pipe_diagnostic();
let first = clock.report();
std::thread::sleep(Duration::from_millis(750));
STAGE.store(31, Ordering::SeqCst);
let second = clock.report();
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]}),
)?;
ensure!(data.len() < 16384, "READINESS_REPORT_SIZE");
STAGE.store(41, Ordering::SeqCst);
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(root.join("result.json"))?;
STAGE.store(42, Ordering::SeqCst);
file.write_all(&data)?;
STAGE.store(43, Ordering::SeqCst);
file.sync_all()?;
STAGE.store(44, Ordering::SeqCst);
Ok(())
}
fn status(state: u32, error: u32) {
let handle = HANDLE.load(Ordering::SeqCst) as SERVICE_STATUS_HANDLE;
if handle.is_null() {
return;
}
let value = SERVICE_STATUS {
dwServiceType: SERVICE_WIN32_OWN_PROCESS,
dwCurrentState: state,
dwControlsAccepted: 0,
dwWin32ExitCode: error,
dwServiceSpecificExitCode: if error == 1066 {
STAGE.load(Ordering::SeqCst) as u32
} else {
0
},
dwCheckPoint: 0,
dwWaitHint: 10000,
};
unsafe {
SetServiceStatus(handle, &value);
}
}
unsafe extern "system" fn control(
_: u32,
_: u32,
_: *mut std::ffi::c_void,
_: *mut std::ffi::c_void,
) -> u32 {
0
}
unsafe extern "system" fn main(_: u32, _: *mut *mut u16) {
let name = wide(NAME);
let handle =
unsafe { RegisterServiceCtrlHandlerExW(name.as_ptr(), Some(control), ptr::null_mut()) };
if handle.is_null() {
return;
}
HANDLE.store(handle as usize, Ordering::SeqCst);
status(SERVICE_RUNNING, 0);
let result = run();
if result.is_ok() {
std::thread::sleep(Duration::from_secs(2));
}
status(SERVICE_STOPPED, if result.is_ok() { 0 } else { 1066 });
}
pub fn dispatch() -> Result<()> {
let args: Vec<_> = std::env::args().collect();
ensure!(
args.len() == 3 && args[1] == "--service",
"READINESS_SERVICE_ONLY"
);
let case = uuid::Uuid::parse_str(&args[2])?;
ensure!(case.get_version_num() == 4, "READINESS_CASE_UUID");
CASE.set(case).unwrap();
let mut name = wide(NAME);
let table = [
SERVICE_TABLE_ENTRYW {
lpServiceName: name.as_mut_ptr(),
lpServiceProc: Some(main),
},
SERVICE_TABLE_ENTRYW {
lpServiceName: ptr::null_mut(),
lpServiceProc: None,
},
];
ensure!(
unsafe { StartServiceCtrlDispatcherW(table.as_ptr()) } != 0,
"READINESS_SCM"
);
Ok(())
}
}
#[cfg(windows)]
fn main() -> anyhow::Result<()> {
service::dispatch()
}
#[cfg(not(windows))]
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()
);
}
@@ -0,0 +1,117 @@
//! Fixed guest read-only persistence witness. No keys, job, grants or clock query.
#[cfg(windows)]
fn main() -> anyhow::Result<()> {
use anyhow::ensure;
use serde_json::json;
use sha2::{Digest, Sha256};
use std::{fs, os::windows::io::AsRawHandle, path::Path};
use windows_sys::Win32::Storage::FileSystem::{
BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle,
};
let state = Path::new(r"C:\ProgramData\RustDiscovery\state");
rmm_agent_windows::native::private_path(state, true)?;
let path = state.join("telemetry.sqlite");
rmm_agent_windows::native::private_path(&path, false)?;
let file = fs::File::open(&path)?;
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: live read-only file handle and correctly sized writable structure.
ensure!(
unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } != 0,
"DATABASE_FILE_ID"
);
let db =
rusqlite::Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;
db.execute_batch("BEGIN DEFERRED")?;
ensure!(
db.query_row("PRAGMA integrity_check", [], |r| r.get::<_, String>(0))? == "ok",
"JOURNAL_INTEGRITY"
);
let sequence: i64 =
db.query_row("SELECT value FROM metadata WHERE key='sequence'", [], |r| {
r.get(0)
})?;
let agent: String = db.query_row("SELECT agent FROM identity", [], |r| r.get(0))?;
ensure!(
agent == "63ea15b2-0643-403d-b5b4-cba1288dbea3" && sequence >= 0,
"FIXED_EXISTING_IDENTITY"
);
let identity: Vec<String> = db
.prepare("SELECT agent FROM identity ORDER BY agent")?
.query_map([], |r| r.get(0))?
.collect::<rusqlite::Result<_>>()?;
let metadata: Vec<(String, i64)> = db
.prepare("SELECT key,value FROM metadata ORDER BY key")?
.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?
.collect::<rusqlite::Result<_>>()?;
let mut events = Vec::new();
for row in db
.prepare("SELECT id,payload FROM events ORDER BY id")?
.query_map([], |r| {
Ok((r.get::<_, String>(0)?, r.get::<_, Vec<u8>>(1)?))
})?
{
let (id, bytes) = row?;
ensure!(
events.len() < 8 && bytes.len() <= 512 * 1024,
"LEGACY_EVENT_LIMIT"
);
events.push(json!({"id":id,"payload_sha256":format!("{:x}",Sha256::digest(&bytes)),"bytes":bytes.len()}));
}
let schema:Vec<(String,String,String)>=db.prepare("SELECT type,name,sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' ORDER BY type,name")?.query_map([],|r|Ok((r.get(0)?,r.get(1)?,r.get::<_,Option<String>>(2)?.unwrap_or_default())))?.collect::<rusqlite::Result<_>>()?;
ensure!(schema.len() <= 64, "SCHEMA_LIMIT");
let mut counts = serde_json::Map::new();
for table in [
"job_attempts",
"job_events",
"reconcile_requests",
"reconcile_results",
"reconcile_receipts",
"reconcile_outcomes",
] {
if schema
.iter()
.any(|(kind, name, _)| kind == "table" && name == table)
{
let count: i64 =
db.query_row(&format!("SELECT count(*) FROM {table}"), [], |r| r.get(0))?;
counts.insert(table.into(), json!(count));
}
}
let counter = if schema.iter().any(|(_, name, _)| name == "counter") {
Some(db.query_row("SELECT seq FROM counter WHERE id=1", [], |r| {
r.get::<_, i64>(0)
})?)
} else {
None
};
if let Some(counter) = counter {
ensure!(counter == sequence, "COUNTER_ALIAS");
}
let page_size: i64 = db.query_row("PRAGMA page_size", [], |r| r.get(0))?;
let page_count: i64 = db.query_row("PRAGMA page_count", [], |r| r.get(0))?;
ensure!(
page_size == 4096 && page_count > 0 && page_count <= 262144,
"FINITE_FILE_BUDGET"
);
db.execute_batch("ROLLBACK")?;
let hash = |value: &serde_json::Value| -> anyhow::Result<String> {
Ok(format!("{:x}", Sha256::digest(serde_json::to_vec(value)?)))
};
let value = json!({"read_only":true,"integrity":"ok","agent_id":agent,"sequence":sequence,
"pending_inventory_events":events.len(),"legacy_events":events,"identity_sha256":hash(&json!(identity))?,
"metadata_sha256":hash(&json!(metadata))?,"events_sha256":hash(&json!(events))?,
"schema":schema,"core_counts":counts,"counter":counter,"page_size":page_size,"page_count":page_count,
"database_file_id":{"volume":info.dwVolumeSerialNumber,"high":info.nFileIndexHigh,"low":info.nFileIndexLow},
"database_creation":{"high":info.ftCreationTime.dwHighDateTime,"low":info.ftCreationTime.dwLowDateTime},
"consumption_exists":state.join("consumption.sqlite").try_exists()?,"jobs_directory_exists":state.join("jobs").try_exists()?,
"private_key_read":false,"clock_queried":false,"jobs_created":false});
let encoded = serde_json::to_string(&value)?;
ensure!(encoded.len() <= 32768, "WITNESS_OUTPUT_LIMIT");
println!("{encoded}");
Ok(())
}
#[cfg(not(windows))]
fn main() {
eprintln!("Native Windows-only read-only state witness");
std::process::exit(1);
}
@@ -0,0 +1,49 @@
/* Read-only local endpoint discovery for precisely the MS-W32T interface.
* No status invocation, no endpoint names/annotations leave this boundary.
*/
#define _WIN32_WINNT 0x0a00
#include <windows.h>
#include <rpc.h>
#include <stdint.h>
#include <string.h>
typedef struct {
uint32_t result, scanned, named_pipe, alpc, other, truncated;
} RmmClockEndpoints;
uint32_t rmm_clock_endpoints(RmmClockEndpoints *out) {
RPC_IF_ID interface_id = {0};
RPC_EP_INQ_HANDLE inquiry = NULL;
RPC_STATUS result;
memset(out, 0, sizeof(*out));
result = UuidFromStringW((RPC_WSTR)L"8fb6d884-2388-11d0-8c35-00c04fda2795", &interface_id.Uuid);
if (result) return out->result = result;
interface_id.VersMajor = 4; interface_id.VersMinor = 1;
result = RpcMgmtEpEltInqBegin(NULL, RPC_C_EP_MATCH_BY_IF, &interface_id,
RPC_C_VERS_EXACT, NULL, &inquiry);
if (result) return out->result = result;
for (unsigned i = 0; i < 16; ++i) {
RPC_BINDING_HANDLE binding = NULL;
RPC_IF_ID actual = {0};
UUID object = {0};
RPC_WSTR annotation = NULL, text = NULL, protocol = NULL;
result = RpcMgmtEpEltInqNextW(inquiry, &actual, &binding, &object, &annotation);
if (annotation) RpcStringFreeW(&annotation);
if (result == RPC_X_NO_MORE_ENTRIES) { result = 0; break; }
if (result) break;
++out->scanned;
result = RpcBindingToStringBindingW(binding, &text);
if (!result) result = RpcStringBindingParseW(text, NULL, &protocol, NULL, NULL, NULL);
if (!result) {
if (!wcscmp((wchar_t *)protocol, L"ncalrpc")) ++out->alpc;
else if (!wcscmp((wchar_t *)protocol, L"ncacn_np")) ++out->named_pipe;
else ++out->other;
}
if (protocol) RpcStringFreeW(&protocol);
if (text) RpcStringFreeW(&text);
RpcBindingFree(&binding);
if (result) break;
if (i == 15) out->truncated = 1;
}
RpcMgmtEpEltInqDone(&inquiry);
return out->result = result;
}
+156
View File
@@ -0,0 +1,156 @@
/* Only the authenticated local MS-W32T status operation is reachable here.
* NDR code is generated by WIDL; SEH must terminate inside C, never in Rust.
*/
#define _WIN32_WINNT 0x0a00
#include <windows.h>
#include <rpc.h>
#include <stdint.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);
typedef struct Allocation { struct Allocation *next; size_t size; } Allocation;
typedef struct { Allocation *head; size_t total; } Arena;
/* Explicit Windows TLS also works on threads created by SCM. Clang static TLS
* in the mixed Rust/MinGW PE did not initialize such a thread's storage. */
static INIT_ONCE arena_once = INIT_ONCE_STATIC_INIT;
static DWORD arena_index = TLS_OUT_OF_INDEXES;
static BOOL CALLBACK initialize_arena(PINIT_ONCE once, PVOID parameter, PVOID *context) {
(void)once; (void)parameter; (void)context;
arena_index = TlsAlloc();
return arena_index != TLS_OUT_OF_INDEXES;
}
void *__RPC_USER MIDL_user_allocate(size_t size) {
Arena *arena = TlsGetValue(arena_index);
if (!arena || size > 65536 || arena->total > 65536 - size) return NULL;
Allocation *p = calloc(1, sizeof(*p) + size);
if (!p) return NULL;
p->size = size; p->next = arena->head; arena->head = p; arena->total += size;
return p + 1;
}
void __RPC_USER MIDL_user_free(void *memory) {
Arena *arena = TlsGetValue(arena_index);
if (!memory || !arena) return;
Allocation **link = &arena->head;
while (*link && (*link + 1) != memory) link = &(*link)->next;
if (*link) { Allocation *p = *link; *link = p->next; arena->total -= p->size; free(p); }
}
static void release_allocations(Arena *arena) {
while (arena->head) MIDL_user_free(arena->head + 1);
}
/* Stable numeric ABI, no returned peer/source strings or remotely sized data. */
typedef struct {
uint32_t leap, stratum, state, flags, last_result, size;
uint64_t last_sync, sync_age;
int64_t root_delay;
uint64_t root_dispersion;
int64_t phase;
} RmmClockStatus;
_Static_assert(sizeof(RmmClockStatus) == 64, "Rust numeric clock ABI");
_Static_assert(sizeof(RMM_W32TIME_STATUS) == 120, "MS-W32T x64 structure ABI");
static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out) {
RMM_W32TIME_STATUS *status = NULL;
unsigned long result = 0;
Arena arena = {0};
if (!result && !InitOnceExecuteOnce(&arena_once, initialize_arena, NULL, NULL)) result = ERROR_NOT_ENOUGH_MEMORY;
if (!result && TlsGetValue(arena_index)) result = ERROR_BUSY;
if (!result && !TlsSetValue(arena_index, &arena)) result = GetLastError();
if (!result) {
RpcTryExcept {
result = RmmW32TimeQueryStatus(binding, &status);
if (!result) {
if (!status || status->ulSize != sizeof(*status) || status->cEntries || status->pEntries)
result = RPC_X_BAD_STUB_DATA;
else {
out->leap = status->eLeapIndicator; out->stratum = status->nStratum;
out->state = status->ulLcState; out->flags = status->ulTSFlags;
out->last_result = status->eLastSyncResult; out->size = status->ulSize;
out->last_sync = status->qwLastSyncTicks; out->sync_age = status->tpTimeLastGoodSync;
out->root_delay = status->toRootDelay; out->root_dispersion = status->tpRootDispersion;
out->phase = status->toSysPhaseOffset;
}
}
} RpcExcept(RpcExceptionFilter(RpcExceptionCode())) {
result = RpcExceptionCode();
} RpcEndExcept
release_allocations(&arena);
TlsSetValue(arena_index, NULL);
}
return result;
}
uint32_t rmm_clock_query(RmmClockStatus *out) {
RPC_WSTR text = NULL;
RPC_BINDING_HANDLE binding = NULL;
RPC_SECURITY_QOS qos = {0};
unsigned long result;
memset(out, 0, sizeof(*out));
result = RpcStringBindingComposeW(NULL, (RPC_WSTR)L"ncacn_np", NULL,
(RPC_WSTR)L"\\pipe\\W32TIME_ALT", NULL, &text);
if (result) return result;
result = RpcBindingFromStringBindingW(text, &binding);
RpcStringFreeW(&text);
if (result) return result;
qos.Version = RPC_C_SECURITY_QOS_VERSION;
qos.Capabilities = RPC_C_QOS_CAPABILITIES_DEFAULT;
qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC;
qos.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY;
result = RpcBindingSetAuthInfoExW(binding, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
RPC_C_AUTHN_WINNT, NULL, RPC_C_AUTHZ_NONE, &qos);
if (!result) result = RpcBindingSetOption(binding, RPC_C_OPT_CALL_TIMEOUT, 1500);
if (!result) result = invoke_status(binding, out);
RpcBindingFree(&binding);
return result;
}
/* 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) {
RPC_IF_ID id = {0};
RPC_EP_INQ_HANDLE inquiry = NULL;
RPC_STATUS result;
memset(out, 0, sizeof(*out));
result = UuidFromStringW((RPC_WSTR)L"8fb6d884-2388-11d0-8c35-00c04fda2795", &id.Uuid);
if (result) return result;
id.VersMajor = 4; id.VersMinor = 1;
result = RpcMgmtEpEltInqBegin(NULL, RPC_C_EP_MATCH_BY_IF, &id, RPC_C_VERS_EXACT, NULL, &inquiry);
if (result) return result;
for (unsigned i=0; i<16; ++i) {
RPC_IF_ID actual = {0};
RPC_BINDING_HANDLE binding = NULL;
UUID object = {0};
RPC_WSTR annotation = NULL, text = NULL, protocol = NULL;
result = RpcMgmtEpEltInqNextW(inquiry, &actual, &binding, &object, &annotation);
if (annotation) RpcStringFreeW(&annotation);
if (result) break;
result = RpcBindingToStringBindingW(binding, &text);
if (!result) result = RpcStringBindingParseW(text, NULL, &protocol, NULL, NULL, NULL);
int local = !result && !wcscmp((wchar_t *)protocol, L"ncalrpc");
if (protocol) RpcStringFreeW(&protocol);
if (text) RpcStringFreeW(&text);
if (result) {RpcBindingFree(&binding);break;}
if (local) {
_Alignas(8) BYTE expected_sid[SECURITY_MAX_SID_SIZE];
DWORD sid_size = sizeof(expected_sid);
RPC_SECURITY_QOS_V3_W qos = {0};
if (!CreateWellKnownSid(WinLocalServiceSid, NULL, expected_sid, &sid_size)) result = GetLastError();
if (!result) {
qos.Version = RPC_C_SECURITY_QOS_VERSION_3;
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;
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);
}
RpcBindingFree(&binding);
break; /* no retry, alternate identity, endpoint or weaker transport */
}
RpcBindingFree(&binding);
result = EPT_S_NOT_REGISTERED;
}
RpcMgmtEpEltInqDone(&inquiry);
return result == RPC_X_NO_MORE_ENTRIES ? EPT_S_NOT_REGISTERED : result;
}
+43
View File
@@ -0,0 +1,43 @@
/* Narrow read-only MS-W32T client, interface v4.1, Opnum6.
* Wire layout derived from Microsoft Open Specifications MS-W32T 2.2.5, 3.1.5.7.
* https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/5793e908-22ef-4cea-962f-fca8a72c485a
* Slots 0..5 preserve the ordinal only. No code calls or exposes these slots;
* they are deliberately NOT definitions of the real mutating RPC operations.
*/
typedef struct {
unsigned long ulSize;
[string, unique] wchar_t *wszName;
[string, unique] wchar_t *wszValue;
[string, unique] wchar_t *wszHelp;
} RMM_W32TIME_ENTRY;
typedef struct {
unsigned long ulSize;
unsigned long eLeapIndicator;
unsigned long nStratum;
long nPollInterval;
unsigned long refidSource;
unsigned hyper qwLastSyncTicks;
hyper toRootDelay;
unsigned hyper tpRootDispersion;
long nClockPrecision;
[string, unique] wchar_t *wszSource;
hyper toSysPhaseOffset;
unsigned long ulLcState;
unsigned long ulTSFlags;
unsigned long ulClockRate;
unsigned long ulNetlogonServiceBits;
unsigned long eLastSyncResult;
unsigned hyper tpTimeLastGoodSync;
unsigned long cEntries;
[size_is(cEntries)] RMM_W32TIME_ENTRY *pEntries;
} RMM_W32TIME_STATUS;
[uuid(8fb6d884-2388-11d0-8c35-00c04fda2795), version(4.1), pointer_default(unique)]
interface RmmW32Time {
unsigned long RmmUnusedSlot0([in] handle_t binding);
unsigned long RmmUnusedSlot1([in] handle_t binding);
unsigned long RmmUnusedSlot2([in] handle_t binding);
unsigned long RmmUnusedSlot3([in] handle_t binding);
unsigned long RmmUnusedSlot4([in] handle_t binding);
unsigned long RmmUnusedSlot5([in] handle_t binding);
unsigned long RmmW32TimeQueryStatus([in] handle_t binding, [out, ref] RMM_W32TIME_STATUS **status);
}
+202
View File
@@ -0,0 +1,202 @@
//! Windows platform effects only. Acceptance, signatures, sync and durable
//! consumption are supplied by the shared core and the runtime, never bypassed.
use anyhow::{Result, ensure};
use rmm_agent_core::auth::Outcome;
use rmm_domain::jobs::{Action, JobPayload, hash};
use std::{
ffi::OsString,
fs::{File, OpenOptions},
io::Write,
os::windows::fs::OpenOptionsExt,
path::{Path, PathBuf},
sync::atomic::AtomicBool,
};
use windows_sys::Win32::{
Storage::FileSystem::{
FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ,
},
System::SystemInformation::GetSystemDirectoryW,
};
pub fn powershell() -> Result<PathBuf> {
let mut buffer = [0u16; 32768];
let length = unsafe { GetSystemDirectoryW(buffer.as_mut_ptr(), buffer.len() as u32) } as usize;
ensure!(length > 0 && length < buffer.len(), "SYSTEM_DIRECTORY");
let executable = PathBuf::from(String::from_utf16(&buffer[..length])?)
.join("WindowsPowerShell/v1.0/powershell.exe");
ensure!(executable.is_file(), "POWERSHELL_51_NOT_AVAILABLE");
Ok(executable)
}
pub fn supported(job: &JobPayload) -> bool {
crate::native::require_local_service().is_ok()
&& job.execution_identity == "agent_service"
&& job.action.validate()
&& match &job.action {
Action::RunScript { interpreter, .. } => {
interpreter == "powershell" && powershell().is_ok()
}
Action::RefreshInventory { scope } => scope == "windows.base",
_ => false,
}
}
pub struct Script {
executable: PathBuf,
path: PathBuf,
/// Denies write/delete replacement while PowerShell opens the approved file.
_file: File,
cwd: PathBuf,
arguments: Vec<OsString>,
}
impl Script {
/// Preparation creates only a protected copy of approved bytes, no child.
/// Only the runtime may call run after committing one-time consumption.
pub fn prepare(job: &JobPayload, directory: &Path, grant: uuid::Uuid) -> Result<Self> {
ensure!(supported(job), "UNSUPPORTED_CAPABILITY");
let Action::RunScript {
interpreter,
script_utf8,
arguments,
..
} = &job.action
else {
anyhow::bail!("SCRIPT_REQUIRED")
};
ensure!(
interpreter == "powershell" && !grant.is_nil(),
"WINDOWS_SCRIPT_BINDING"
);
crate::native::private_path(directory, true)?;
let path = directory.join(format!("{}-{}.ps1", job.attempt_id, grant));
let mut file = OpenOptions::new()
.create_new(true)
.write(true)
.read(true)
.share_mode(FILE_SHARE_READ)
.open(&path)?;
file.write_all(script_utf8.as_bytes())?;
file.sync_all()?;
drop(file);
// Retain a READ handle, not the writer: Windows sharing rules would
// otherwise prevent PowerShell's own read-only file open.
let file = OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(&path)?;
use std::os::windows::fs::MetadataExt;
ensure!(
file.metadata()?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0,
"SCRIPT_REPARSE_POINT"
);
crate::native::private_path(&path, false)?;
// Never add a BOM, prolog or change line endings after the plan hash.
ensure!(
hash(&std::fs::read(&path)?) == hash(script_utf8.as_bytes()),
"SCRIPT_BYTES_CHANGED"
);
let mut args: Vec<OsString> = ["-NoLogo", "-NoProfile", "-NonInteractive", "-File"]
.into_iter()
.map(OsString::from)
.collect();
args.push(path.clone().into_os_string());
args.extend(arguments.iter().map(OsString::from));
Ok(Self {
executable: powershell()?,
path,
_file: file,
cwd: directory.to_path_buf(),
arguments: args,
})
}
pub fn run(self, job: &JobPayload, cancel: &AtomicBool) -> Result<Outcome> {
ensure!(supported(job), "LOCAL_SERVICE_EXECUTOR_NOT_READY");
crate::native::private_path(&self.path, false)?;
let Action::RunScript {
script_utf8,
expected_stdout,
..
} = &job.action
else {
anyhow::bail!("SCRIPT_REQUIRED")
};
ensure!(
std::fs::read(&self.path)? == script_utf8.as_bytes(),
"SCRIPT_BYTES_CHANGED"
);
let output = crate::process::run(
&self.executable,
&self.arguments,
&self.cwd,
job.max_runtime_seconds,
job.max_output_bytes as usize,
cancel,
)?;
let expected = expected_stdout
.as_ref()
.is_none_or(|expected| output.stdout == expected.as_bytes());
let success =
!output.interrupted && output.exit_code == Some(0) && expected && !output.truncated;
let state = if output.interrupted {
"unknown"
} else if success {
"succeeded"
} else {
"failed"
};
let code = if output.interrupted {
if output.cancelled {
"CANCELLED_EFFECT_UNKNOWN"
} else {
"TIMEOUT_EFFECT_UNKNOWN"
}
} else if output.truncated {
"OUTPUT_LIMIT_REACHED"
} else if output.exit_code != Some(0) {
"POWERSHELL_PROCESS_FAILED"
} else if !expected {
"STDOUT_POSTCONDITION_FAILED"
} else {
""
};
Ok(Outcome {
state: state.into(),
stdout: output.stdout,
stderr: output.stderr,
exit_code: output.exit_code,
output_truncated: output.truncated,
reboot_required: false,
error_code: code.into(),
evidence: serde_json::json!({"postconditions_passed":success,"interpreter":"powershell",
"script_sha256":hash(script_utf8.as_bytes()),"execution_sid":"S-1-5-19",
"output_encoding":"raw_native_bytes","comparison":"exact_utf8_bytes",
"execution_policy":"inherited","process_tree_bounded":true,
"cancel_requested":output.cancelled,"termination_does_not_prove_absence_of_effects":output.interrupted}),
})
}
}
pub fn inventory(job: &JobPayload) -> Result<Outcome> {
ensure!(
supported(job)
&& matches!(&job.action, Action::RefreshInventory {scope} if scope=="windows.base"),
"WINDOWS_INVENTORY_BINDING"
);
let data = crate::native::snapshot()?;
let stdout = serde_json::to_vec(&data)?;
ensure!(
stdout.len() <= job.max_output_bytes as usize,
"INVENTORY_OUTPUT_LIMIT"
);
Ok(Outcome {
state: "succeeded".into(),
stdout,
stderr: vec![],
exit_code: None,
output_truncated: false,
reboot_required: false,
error_code: String::new(),
evidence: serde_json::json!({"postconditions_passed":true,"source_id":"windows.base",
"observed_at":chrono::Utc::now(),"completeness":"partial","execution_sid":"S-1-5-19"}),
})
}
@@ -0,0 +1,10 @@
//! Separate SCM binary. The network agent always remains LocalService.
#[cfg(windows)]
fn main() -> anyhow::Result<()> {
rmm_agent_windows::helper_system::dispatch()
}
#[cfg(not(windows))]
fn main() {
eprintln!("Windows SCM helper requires a Windows target");
std::process::exit(1);
}
+516
View File
@@ -0,0 +1,516 @@
//! Read-only trusted clock gate for Windows 11. All MS-W32T time intervals are
//! 100 ns; last_sync alone is a FILETIME (1601 epoch), sync_age is a duration.
//! No W32Time reconfiguration, resync, unauthenticated pipe or server-time anchor.
//! Policy: <=1h successful sync age, SYNC state, stratum1..15, nonalarm leap,
//! <=2s root dispersion + roundtrip/2 + absolute phase + query latency.
//! A >1s wall step or suspend invalidates until a post-discontinuity sync.
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.
pub const ADAPTER_QUALIFIED: bool = false;
const SECOND: u64 = 10_000_000;
const MAX_AGE: u64 = 3600 * SECOND;
const MAX_ERROR: u64 = 2 * SECOND;
const FILETIME_UNIX: u64 = 116_444_736_000_000_000;
#[derive(Clone, Copy, Debug, Default, Serialize)]
#[repr(C)]
pub struct Status {
pub leap: u32,
pub stratum: u32,
pub state: u32,
pub flags: u32,
pub last_result: u32,
pub size: u32,
pub last_sync: u64,
pub sync_age: u64,
pub root_delay: i64,
pub root_dispersion: u64,
pub phase: i64,
}
#[derive(Clone, Copy, Debug, Default, Serialize)]
pub struct Sample {
pub wall: u64,
pub interrupt: u64,
pub unbiased: u64,
}
/// Diagnostic endpoint counts only; never a trusted clock or server identity.
#[derive(Debug, Default, Serialize)]
#[repr(C)]
pub struct EndpointReport {
pub result: u32,
pub scanned: u32,
pub named_pipe: u32,
pub alpc: u32,
pub other: u32,
pub truncated: u32,
}
pub fn endpoint_report() -> EndpointReport {
#[cfg(windows)]
{
#[link(name = "rmm_clock_rpc", kind = "static")]
#[link(name = "rpcrt4")]
unsafe extern "C" {
fn rmm_clock_endpoints(out: *mut EndpointReport) -> u32;
}
let mut report = EndpointReport::default();
// SAFETY: fixed 6*u32 C ABI; bounded exact-interface local enumeration.
unsafe {
rmm_clock_endpoints(&mut report);
}
report
}
#[cfg(not(windows))]
{
EndpointReport {
result: 50,
..EndpointReport::default()
}
}
}
#[derive(Debug, Serialize)]
pub struct ClockReport {
pub trusted: bool,
pub adapter_qualified: bool,
pub reason: String,
pub rpc_code: u32,
pub transport: &'static str,
pub status: Option<Status>,
pub query_ticks: u64,
pub error_bound_ticks: Option<u64>,
pub sample: Sample,
}
#[derive(Default)]
struct Continuity {
previous: Option<Sample>,
require_sync_after: Option<u64>,
}
impl Continuity {
fn observe(&mut self, sample: Sample) -> Result<()> {
if let Some(p) = self.previous {
let wall = sample.wall.checked_sub(p.wall);
let interrupt = sample.interrupt.checked_sub(p.interrupt);
let unbiased = sample.unbiased.checked_sub(p.unbiased);
let continuous = match (wall, interrupt, unbiased) {
(Some(w), Some(i), Some(u)) => w.abs_diff(i) <= SECOND && i.abs_diff(u) <= SECOND,
_ => false,
};
if !continuous {
// A backward step can make the prior wall timestamp too strict;
// require successful sync after the NEW observed wall value.
self.require_sync_after = Some(sample.wall);
self.previous = Some(sample);
return Err(anyhow!("CLOCK_DISCONTINUITY"));
}
}
self.previous = Some(sample);
Ok(())
}
fn validate(&mut self, status: &Status, sample: Sample, query_ticks: u64) -> Result<u64> {
self.observe(sample)?;
let bound = evaluate(status, sample.wall, query_ticks)?;
if let Some(after) = self.require_sync_after {
ensure!(
status.last_sync > after,
"CLOCK_AWAITING_POST_DISCONTINUITY_SYNC"
);
self.require_sync_after = None;
}
Ok(bound)
}
}
fn evaluate(status: &Status, wall: u64, query_ticks: u64) -> Result<u64> {
ensure!(status.size == 120, "CLOCK_UNSUPPORTED_LAYOUT");
ensure!(
status.state == 2
&& status.last_result == 0
&& status.leap <= 2
&& (1..=15).contains(&status.stratum),
"CLOCK_UNSYNCHRONIZED"
);
// MS-W32T hardware flag is reserved/unused, all bits above2 are reserved.
// Authenticated MS-SNTP is reported, not demanded above Linux NTP policy.
ensure!(status.flags & !6 == 0, "CLOCK_UNKNOWN_FLAGS");
ensure!(
status.last_sync > FILETIME_UNIX && status.last_sync <= wall,
"CLOCK_SYNC_TIMESTAMP"
);
ensure!(
wall - status.last_sync <= MAX_AGE && status.sync_age <= MAX_AGE,
"CLOCK_STALE_SYNC"
);
// These independent representations should agree within sampling latency.
ensure!(
(wall - status.last_sync).abs_diff(status.sync_age) <= SECOND.saturating_add(query_ticks),
"CLOCK_INCONSISTENT_SYNC_AGE"
);
ensure!(status.root_delay >= 0, "CLOCK_NEGATIVE_DELAY");
let bound = status
.root_dispersion
.checked_add((status.root_delay as u64).div_ceil(2))
.and_then(|v| v.checked_add(status.phase.unsigned_abs()))
.and_then(|v| v.checked_add(query_ticks))
.ok_or_else(|| anyhow!("CLOCK_UNCERTAINTY_OVERFLOW"))?;
ensure!(
query_ticks <= SECOND && bound <= MAX_ERROR,
"CLOCK_UNCERTAINTY"
);
Ok(bound)
}
pub struct NativeClock {
state: Mutex<Continuity>,
diagnostic: bool,
}
impl Default for NativeClock {
fn default() -> Self {
Self::new()
}
}
impl NativeClock {
pub fn new() -> Self {
Self {
state: Mutex::new(Continuity::default()),
diagnostic: false,
}
}
pub fn report(&self) -> ClockReport {
let before = sample();
let (rpc_code, raw) = query(self.diagnostic);
let after = sample();
let ticks = after
.interrupt
.checked_sub(before.interrupt)
.unwrap_or(u64::MAX);
let mut report = ClockReport {
trusted: false,
adapter_qualified: ADAPTER_QUALIFIED,
reason: "CLOCK_UNTRUSTED".into(),
rpc_code,
transport: if self.diagnostic {
"ncacn_np:W32TIME_ALT:diagnostic_only"
} else {
"ncalrpc:SID19:mutual_auth"
},
status: None,
query_ticks: ticks,
error_bound_ticks: None,
sample: after,
};
let Ok(mut state) = self.state.lock() else {
report.reason = "CLOCK_STATE_POISONED".into();
return report;
};
// Observe both sides even when RPC fails, so errors cannot hide resume.
if let Err(e) = state.observe(before) {
report.reason = e.to_string();
return report;
}
if rpc_code != 0 {
let _ = state.observe(after);
report.reason = match rpc_code {
5 | 1326 | 1747 => "CLOCK_PERMISSION_DENIED",
50 | 1717 | 1722 | 1753 => "CLOCK_UNSUPPORTED",
1818 => "CLOCK_RPC_TIMEOUT",
_ => "CLOCK_RPC_ERROR",
}
.into();
return report;
}
report.status = Some(raw);
match state.validate(&raw, after, ticks) {
Ok(bound) => {
report.trusted = !self.diagnostic;
report.reason = if self.diagnostic {
"CLOCK_SERVER_IDENTITY_UNQUALIFIED"
} else {
"CLOCK_TRUSTED"
}
.into();
report.error_bound_ticks = Some(bound);
}
Err(e) => report.reason = e.to_string(),
}
report
}
pub fn now(&self) -> Result<DateTime<Utc>> {
ensure!(ADAPTER_QUALIFIED, "CLOCK_ADAPTER_UNQUALIFIED");
let report = self.report();
ensure!(report.trusted, "CLOCK_UNTRUSTED: {}", report.reason);
let ticks = report
.sample
.wall
.checked_sub(FILETIME_UNIX)
.ok_or_else(|| anyhow!("CLOCK_TIMESTAMP"))?;
DateTime::from_timestamp(
(ticks / SECOND).try_into()?,
((ticks % SECOND) * 100) as u32,
)
.ok_or_else(|| anyhow!("CLOCK_TIMESTAMP"))
}
}
/// Named-pipe diagnostics can never open the production clock gate.
pub fn named_pipe_diagnostic() -> ClockReport {
NativeClock {
state: Mutex::new(Continuity::default()),
diagnostic: true,
}
.report()
}
impl rmm_agent_core::reconcile::SyncClock for NativeClock {
fn now(&self) -> Result<DateTime<Utc>> {
NativeClock::now(self)
}
}
#[cfg(windows)]
fn sample() -> Sample {
#[link(name = "kernel32")]
unsafe extern "system" {
fn GetSystemTimePreciseAsFileTime(value: *mut u64);
fn QueryInterruptTimePrecise(value: *mut u64);
fn QueryUnbiasedInterruptTimePrecise(value: *mut u64);
}
let mut v = Sample::default();
// SAFETY: three fixed kernel getters writing valid aligned u64 outputs.
unsafe {
GetSystemTimePreciseAsFileTime(&mut v.wall);
QueryInterruptTimePrecise(&mut v.interrupt);
QueryUnbiasedInterruptTimePrecise(&mut v.unbiased);
}
v
}
#[cfg(windows)]
fn raw_query(diagnostic: bool) -> (u32, Status) {
#[link(name = "rmm_clock_rpc", kind = "static")]
#[link(name = "rpcrt4")]
#[link(name = "advapi32")]
unsafe extern "C" {
fn rmm_clock_query(status: *mut Status) -> u32;
fn rmm_clock_alpc_query(status: *mut Status) -> u32;
}
let mut status = Status::default();
// SAFETY: numeric C ABI and contained RPC exceptions, fixed local endpoints.
let code = unsafe {
if diagnostic {
rmm_clock_query(&mut status)
} else {
rmm_clock_alpc_query(&mut status)
}
};
(code, status)
}
#[cfg(any(windows, test))]
type RpcReply = std::sync::mpsc::SyncSender<(u32, Status)>;
#[cfg(any(windows, test))]
type RpcRequest = (bool, RpcReply);
#[cfg(any(windows, test))]
struct RpcWorker {
sender: Option<std::sync::mpsc::SyncSender<RpcRequest>>,
poisoned: bool,
}
#[cfg(any(windows, test))]
impl RpcWorker {
fn new(run: fn(bool) -> (u32, Status)) -> Self {
let (sender, receiver) = std::sync::mpsc::sync_channel::<RpcRequest>(1);
let created = std::thread::Builder::new()
.name("rmm-clock-rpc".into())
.spawn(move || {
while let Ok((mode, reply)) = receiver.recv() {
let _ = reply.send(run(mode));
}
})
.is_ok();
Self {
sender: created.then_some(sender),
poisoned: !created,
}
}
fn call(&mut self, mode: bool, timeout: std::time::Duration) -> (u32, Status) {
if self.poisoned {
return (1818, Status::default());
}
let (reply, receiver) = std::sync::mpsc::sync_channel(1);
let sent = self
.sender
.as_ref()
.is_some_and(|sender| sender.try_send((mode, reply)).is_ok());
if sent && let Ok(value) = receiver.recv_timeout(timeout) {
return value;
}
// No replacement worker or retry, including across NativeClock rebuilds.
// At most one stuck read-only call; the service/telemetry thread returns.
self.poisoned = true;
self.sender = None;
(1818, Status::default())
}
}
#[cfg(windows)]
fn query(diagnostic: bool) -> (u32, Status) {
static WORKER: std::sync::OnceLock<Mutex<RpcWorker>> = std::sync::OnceLock::new();
let worker = WORKER.get_or_init(|| Mutex::new(RpcWorker::new(raw_query)));
match worker.try_lock() {
Ok(mut worker) => worker.call(diagnostic, std::time::Duration::from_secs(1)),
Err(_) => (170, Status::default()),
}
}
#[cfg(not(windows))]
fn sample() -> Sample {
Sample::default()
}
#[cfg(not(windows))]
fn query(_diagnostic: bool) -> (u32, Status) {
(50, Status::default())
}
#[cfg(test)]
mod tests {
use super::*;
fn good() -> (Status, Sample) {
let wall = FILETIME_UNIX + 1_800_000_000 * SECOND;
(
Status {
size: 120,
leap: 0,
stratum: 3,
state: 2,
last_sync: wall - 10 * SECOND,
sync_age: 10 * SECOND,
root_delay: (SECOND / 10) as i64,
root_dispersion: SECOND / 20,
phase: 1000,
..Status::default()
},
Sample {
wall,
interrupt: 100 * SECOND,
unbiased: 100 * SECOND,
},
)
}
#[test]
fn production_clock_stays_closed_until_native_adapter_qualification() {
assert_eq!(
NativeClock::new().now().unwrap_err().to_string(),
"CLOCK_ADAPTER_UNQUALIFIED"
);
}
#[test]
fn timeout_worker_stays_closed_without_a_second_call() {
use std::sync::atomic::{AtomicUsize, Ordering};
static CALLS: AtomicUsize = AtomicUsize::new(0);
fn delayed(_: bool) -> (u32, Status) {
CALLS.fetch_add(1, Ordering::SeqCst);
std::thread::sleep(std::time::Duration::from_millis(30));
(0, Status::default())
}
let mut worker = RpcWorker::new(delayed);
assert_eq!(
worker.call(false, std::time::Duration::from_millis(1)).0,
1818
);
assert_eq!(
worker.call(false, std::time::Duration::from_millis(1)).0,
1818
);
std::thread::sleep(std::time::Duration::from_millis(40));
assert_eq!(CALLS.load(Ordering::SeqCst), 1);
}
#[test]
fn gate_requires_all_status_and_uncertainty_evidence() {
let (s, v) = good();
assert!(evaluate(&s, v.wall, 100).is_ok());
for bad in [
Status { state: 1, ..s },
Status { leap: 3, ..s },
Status {
last_result: 2,
..s
},
Status { stratum: 16, ..s },
Status {
sync_age: MAX_AGE + 1,
..s
},
Status {
root_dispersion: MAX_ERROR,
..s
},
Status {
root_delay: -1,
..s
},
Status { flags: 8, ..s },
Status {
phase: i64::MIN,
..s
},
] {
assert!(evaluate(&bad, v.wall, 100).is_err());
}
}
#[test]
fn suspend_closes_until_actual_post_resume_sync() {
let (s, v) = good();
let mut c = Continuity::default();
assert!(c.validate(&s, v, 1).is_ok());
let r = Sample {
wall: v.wall + 20 * SECOND,
interrupt: v.interrupt + 20 * SECOND,
unbiased: v.unbiased + SECOND,
};
assert!(
c.validate(&s, r, 1)
.unwrap_err()
.to_string()
.contains("DISCONTINUITY")
);
let stale = Status {
sync_age: 30 * SECOND,
..s
};
assert!(c.validate(&stale, r, 1).is_err());
let later = Sample {
wall: r.wall + SECOND,
interrupt: r.interrupt + SECOND,
unbiased: r.unbiased + SECOND,
};
assert!(
c.validate(
&Status {
last_sync: later.wall,
sync_age: 0,
..s
},
later,
1
)
.is_ok()
);
}
#[test]
fn wall_step_and_overflow_fail_closed() {
let (s, v) = good();
let mut c = Continuity::default();
assert!(c.validate(&s, v, 1).is_ok());
assert!(
c.observe(Sample {
wall: v.wall - SECOND,
..v
})
.is_err()
);
assert!(
evaluate(
&Status {
root_dispersion: u64::MAX,
..s
},
v.wall,
100
)
.is_err()
);
assert!(evaluate(&s, v.wall, SECOND + 1).is_err());
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+219
View File
@@ -0,0 +1,219 @@
//! Passive native machine inventory. Never queries Win32_Product or executes
//! uninstall commands; registry entries are evidence, not verified MSI state.
use anyhow::{Result, ensure};
use chrono::Utc;
use serde_json::{Value, json};
use std::{
mem::{size_of, zeroed},
ptr,
time::{Duration, Instant},
};
use windows_sys::Win32::{
Foundation::{ERROR_FILE_NOT_FOUND, ERROR_NO_MORE_ITEMS, ERROR_SUCCESS},
System::{Registry::*, SystemInformation::*},
};
struct Registry(HKEY);
impl Drop for Registry {
fn drop(&mut self) {
unsafe {
RegCloseKey(self.0);
}
}
}
fn open(parent: HKEY, name: &str, flags: u32) -> Result<Registry> {
let mut key = ptr::null_mut();
let name = crate::native::wide(name);
ensure!(
unsafe { RegOpenKeyExW(parent, name.as_ptr(), 0, KEY_READ | flags, &mut key) }
== ERROR_SUCCESS,
"REGISTRY_INVENTORY_ACCESS"
);
Ok(Registry(key))
}
fn text(key: HKEY, name: &str) -> Result<Option<String>> {
let name = crate::native::wide(name);
let mut data = [0u16; 512];
let mut bytes = size_of::<[u16; 512]>() as u32;
let result = unsafe {
RegGetValueW(
key,
ptr::null(),
name.as_ptr(),
RRF_RT_REG_SZ,
ptr::null_mut(),
data.as_mut_ptr().cast(),
&mut bytes,
)
};
if result == ERROR_FILE_NOT_FOUND {
return Ok(None);
}
ensure!(
result == ERROR_SUCCESS
&& bytes >= 2
&& bytes as usize <= size_of::<[u16; 512]>()
&& bytes.is_multiple_of(2),
"REGISTRY_INVENTORY_STRING"
);
let count = bytes as usize / 2;
ensure!(
data[count - 1] == 0 && !data[..count - 1].contains(&0),
"REGISTRY_STRING_TERMINATION"
);
Ok(Some(String::from_utf16(&data[..count - 1])?))
}
fn hardware() -> Result<Value> {
let mut system: SYSTEM_INFO = unsafe { zeroed() };
unsafe {
GetNativeSystemInfo(&mut system);
}
let mut memory: MEMORYSTATUSEX = unsafe { zeroed() };
memory.dwLength = size_of::<MEMORYSTATUSEX>() as u32;
ensure!(
unsafe { GlobalMemoryStatusEx(&mut memory) } != 0
&& system.dwNumberOfProcessors > 0
&& memory.ullTotalPhys > 0
&& memory.ullAvailPhys <= memory.ullTotalPhys
&& memory.dwMemoryLoad <= 100,
"NATIVE_HARDWARE_QUERY"
);
Ok(
json!({"logical_processors_visible":system.dwNumberOfProcessors,
"memory_total_bytes":memory.ullTotalPhys,"memory_available_bytes":memory.ullAvailPhys,
"memory_load_percent":memory.dwMemoryLoad}),
)
}
fn software() -> Result<Value> {
let began = Instant::now();
let mut entries = Vec::new();
let mut errors = 0u32;
let mut scanned = 0u32;
let mut truncated = false;
let mut views = Vec::new();
for (view, label) in [
(KEY_WOW64_64KEY, "machine_registry_64"),
(KEY_WOW64_32KEY, "machine_registry_32"),
] {
views.push(label);
let key = match open(
HKEY_LOCAL_MACHINE,
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
view,
) {
Ok(key) => key,
Err(_) => {
errors += 1;
continue;
}
};
for index in 0..2048 {
if began.elapsed() > Duration::from_millis(250) || entries.len() >= 64 {
truncated = true;
break;
}
let mut name = [0u16; 256];
let mut length = name.len() as u32;
let result = unsafe {
RegEnumKeyExW(
key.0,
index,
name.as_mut_ptr(),
&mut length,
ptr::null(),
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
)
};
if result == ERROR_NO_MORE_ITEMS {
break;
}
scanned += 1;
if result != ERROR_SUCCESS || length as usize >= name.len() {
errors += 1;
continue;
}
let entry = (|| -> Result<Option<Value>> {
let name = String::from_utf16(&name[..length as usize])?;
let child = open(key.0, &name, view)?;
let Some(display) = text(child.0, "DisplayName")?.filter(|v| !v.is_empty()) else {
return Ok(None);
};
// No arbitrary path, username, uninstall string or installer
// execution is inventoried. Missing version stays null.
Ok(Some(
json!({"display_name":display,"version":text(child.0,"DisplayVersion")?,
"publisher":text(child.0,"Publisher")?,"source":label,
"installation_context":"machine","installed_state":"registry_entry_only"}),
))
})();
match entry {
Ok(Some(entry)) => {
entries.push(entry);
if serde_json::to_vec(&entries)?.len() > 12288 {
entries.pop();
truncated = true;
break;
}
}
Ok(None) => {}
Err(_) => errors += 1,
}
if index == 2047 {
truncated = true;
}
}
if truncated {
break;
}
}
ensure!(
errors < 2 || !entries.is_empty(),
"SOFTWARE_REGISTRY_UNAVAILABLE"
);
Ok(
json!({"entries":entries,"scanned_keys":scanned,"read_errors":errors,"truncated":truncated,"views_queried":views,
"scope":"machine_registry_only","per_user_inventory":"unsupported",
"msi_state_verification":"not_collected","appx_inventory":"not_collected"}),
)
}
/// Each provider is isolated. Missing permissions never fabricate an empty,
/// complete software inventory or hide the last valid stored observation.
pub fn observations() -> Vec<Value> {
type Provider = fn() -> Result<Value>;
[
(
"windows.hardware",
"windows.win32:GetNativeSystemInfo+GlobalMemoryStatusEx",
hardware as Provider,
),
(
"windows.software",
"windows.registry:HKLM.Uninstall:64+32",
software as Provider,
),
]
.into_iter()
.map(|(scope, source, collect)| {
let data = collect();
let observed = Utc::now();
match data {
Ok(data) => {
let truncated = data
.get("truncated")
.and_then(Value::as_bool)
.unwrap_or(false);
json!({"scope":scope,"source_id":source,"observed_at":observed,"quality":"valid",
"completeness":"partial","truncated":truncated,"error_code":null,"data":data})
}
Err(_) => json!({"scope":scope,"source_id":source,"observed_at":observed,
"quality":"error","completeness":"unknown","truncated":false,
"error_code":"NATIVE_PROVIDER_UNAVAILABLE","data":null}),
}
})
.collect()
}
+206 -5
View File
@@ -20,12 +20,32 @@ impl Journal {
.open(directory.join("agent.lock"))?;
lock.try_lock_exclusive()?;
let db = Connection::open(directory.join("telemetry.sqlite"))?;
// Bound the existing file without resetting sequence, identity, or
// unacknowledged bytes. Unexpected page sizes fail closed.
rmm_agent_core::ledger::bounded_journal_capacity(&db)?;
db.execute_batch(
"PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON;
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value INTEGER NOT NULL);
INSERT OR IGNORE INTO metadata VALUES('sequence',0);
CREATE TABLE IF NOT EXISTS events(id TEXT PRIMARY KEY,payload BLOB NOT NULL);",
)?;
// Add the shared durable-job schema to the same database; old inventory
// bytes and identity remain in place. Both names reference one sequence
// through atomic, monotonic triggers, including old passive clients.
db.execute_batch("BEGIN IMMEDIATE;
CREATE TABLE IF NOT EXISTS counter(id INTEGER PRIMARY KEY CHECK(id=1),seq INTEGER NOT NULL CHECK(seq>=0));
INSERT OR IGNORE INTO counter SELECT 1,value FROM metadata WHERE key='sequence';
CREATE TRIGGER IF NOT EXISTS counter_monotonic BEFORE UPDATE OF seq ON counter WHEN NEW.seq<OLD.seq BEGIN SELECT RAISE(ABORT,'SEQUENCE_ROLLBACK'); END;
CREATE TRIGGER IF NOT EXISTS metadata_monotonic BEFORE UPDATE OF value ON metadata WHEN NEW.key='sequence' AND NEW.value<OLD.value BEGIN SELECT RAISE(ABORT,'SEQUENCE_ROLLBACK'); END;
CREATE TRIGGER IF NOT EXISTS counter_to_metadata AFTER UPDATE OF seq ON counter WHEN NEW.seq!=(SELECT value FROM metadata WHERE key='sequence') BEGIN UPDATE metadata SET value=NEW.seq WHERE key='sequence'; END;
CREATE TRIGGER IF NOT EXISTS metadata_to_counter AFTER UPDATE OF value ON metadata WHEN NEW.key='sequence' AND NEW.value!=(SELECT seq FROM counter WHERE id=1) BEGIN UPDATE counter SET seq=NEW.value WHERE id=1; END;
CREATE TABLE IF NOT EXISTS job_attempts(job TEXT NOT NULL,attempt TEXT NOT NULL,offer BLOB NOT NULL,state TEXT NOT NULL,revision INTEGER NOT NULL DEFAULT 0,grant_id TEXT NOT NULL DEFAULT '',cancel_requested INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(job,attempt));
CREATE TABLE IF NOT EXISTS job_events(id TEXT PRIMARY KEY,payload BLOB NOT NULL CHECK(length(payload)<=1048576));
CREATE TABLE IF NOT EXISTS safety(key TEXT PRIMARY KEY,value TEXT NOT NULL);
COMMIT;")?;
let consistent: bool = db.query_row("SELECT seq>=0 AND seq=(SELECT value FROM metadata WHERE key='sequence') FROM counter WHERE id=1", [], |r|r.get(0))?;
ensure!(consistent, "JOURNAL_SEQUENCE_DIVERGED");
rmm_agent_core::reconcile::initialize(&db)?;
ensure!(
db.query_row("PRAGMA integrity_check", [], |r| r.get::<_, String>(0))? == "ok",
"JOURNAL_INTEGRITY"
@@ -34,17 +54,20 @@ impl Journal {
}
pub fn next_sequence(&mut self) -> Result<u64> {
let tx = self.db.transaction()?;
let sequence: i64 =
tx.query_row("SELECT value FROM metadata WHERE key='sequence'", [], |r| {
r.get(0)
})?;
let sequence: i64 = tx.query_row("SELECT seq FROM counter WHERE id=1", [], |r| r.get(0))?;
let next = sequence
.checked_add(1)
.ok_or_else(|| anyhow::anyhow!("SEQUENCE_EXHAUSTED"))?;
tx.execute("UPDATE metadata SET value=?1 WHERE key='sequence'", [next])?;
tx.execute("UPDATE counter SET seq=?1 WHERE id=1", [next])?;
tx.commit()?;
Ok(u64::try_from(next)?)
}
pub fn connection(&self) -> &Connection {
&self.db
}
pub fn connection_mut(&mut self) -> &mut Connection {
&mut self.db
}
pub fn save(&self, envelope: &Envelope) -> Result<()> {
// This slice never deletes a durable event to make room for telemetry.
// At the fixed cap it stops collecting until concrete ACKs release room.
@@ -135,4 +158,182 @@ mod tests {
drop(j);
std::fs::remove_dir_all(directory).unwrap();
}
#[test]
fn bounded_existing_journal_preserves_identity_sequence_and_unacked_bytes() {
let directory =
std::env::temp_dir().join(format!("rmm-windows-capacity-{}", uuid::Uuid::new_v4()));
std::fs::create_dir(&directory).unwrap();
let mut journal = Journal::open(&directory).unwrap();
journal.pin_identity("preserved-device").unwrap();
let sequence = journal.next_sequence().unwrap();
let envelope = Envelope {
message_id: uuid::Uuid::new_v4().to_string(),
sequence,
payload: Some(rmm_protocol::Payload::InventorySnapshot(Default::default())),
..Default::default()
};
journal.save(&envelope).unwrap();
let original: Vec<u8> = journal
.db
.query_row(
"SELECT payload FROM events WHERE id=?1",
[&envelope.message_id],
|r| r.get(0),
)
.unwrap();
// Simulate an earlier lower bound; reopening changes only the budget.
journal
.db
.execute_batch("PRAGMA max_page_count=65536")
.unwrap();
drop(journal);
let mut journal = Journal::open(&directory).unwrap();
assert_eq!(
journal
.db
.query_row("PRAGMA max_page_count", [], |r| r.get::<_, u32>(0))
.unwrap(),
262144
);
assert_eq!(
journal
.db
.query_row("PRAGMA page_size", [], |r| r.get::<_, u32>(0))
.unwrap(),
4096
);
journal.pin_identity("preserved-device").unwrap();
assert_eq!(journal.next_sequence().unwrap(), sequence + 1);
// Core checkpoints and the old passive counter cannot diverge.
journal
.db
.execute("UPDATE counter SET seq=seq+1 WHERE id=1", [])
.unwrap();
assert_eq!(
journal
.db
.query_row("SELECT value FROM metadata WHERE key='sequence'", [], |r| r
.get::<_, i64>(0))
.unwrap(),
sequence as i64 + 2
);
journal
.db
.execute("UPDATE metadata SET value=value+1 WHERE key='sequence'", [])
.unwrap();
assert_eq!(
journal
.db
.query_row("SELECT seq FROM counter WHERE id=1", [], |r| r
.get::<_, i64>(0))
.unwrap(),
sequence as i64 + 3
);
assert!(
journal
.db
.execute("UPDATE counter SET seq=0 WHERE id=1", [])
.is_err()
);
assert!(
journal
.db
.execute("UPDATE metadata SET value=0 WHERE key='sequence'", [])
.is_err()
);
assert_eq!(
journal
.db
.query_row(
"SELECT payload FROM events WHERE id=?1",
[&envelope.message_id],
|r| r.get::<_, Vec<u8>>(0)
)
.unwrap(),
original
);
journal.ack("different-message-id").unwrap();
assert_eq!(journal.count().unwrap(), 1);
drop(journal);
std::fs::remove_dir_all(directory).unwrap();
}
#[test]
fn unsupported_page_size_is_refused_without_mutating_existing_data() {
let directory =
std::env::temp_dir().join(format!("rmm-windows-page-size-{}", uuid::Uuid::new_v4()));
std::fs::create_dir(&directory).unwrap();
let path = directory.join("telemetry.sqlite");
let db = Connection::open(&path).unwrap();
db.execute_batch("PRAGMA page_size=8192; CREATE TABLE retained(value BLOB); INSERT INTO retained VALUES(x'010203');").unwrap();
drop(db);
let error = Journal::open(&directory).err().expect("must refuse");
assert_eq!(error.to_string(), "JOURNAL_PAGE_SIZE_UNSUPPORTED");
let db = Connection::open(&path).unwrap();
assert_eq!(
db.query_row("SELECT value FROM retained", [], |r| r.get::<_, Vec<u8>>(0))
.unwrap(),
vec![1, 2, 3]
);
drop(db);
std::fs::remove_dir_all(directory).unwrap();
}
#[test]
fn migrates_original_passive_schema_without_rewriting_pending_envelopes() {
let directory =
std::env::temp_dir().join(format!("rmm-windows-migrate-{}", uuid::Uuid::new_v4()));
std::fs::create_dir(&directory).unwrap();
let db = Connection::open(directory.join("telemetry.sqlite")).unwrap();
db.execute_batch("CREATE TABLE metadata(key TEXT PRIMARY KEY,value INTEGER NOT NULL); INSERT INTO metadata VALUES('sequence',42); CREATE TABLE events(id TEXT PRIMARY KEY,payload BLOB NOT NULL); CREATE TABLE identity(agent TEXT PRIMARY KEY); INSERT INTO identity VALUES('original-device');").unwrap();
let envelope = Envelope {
message_id: uuid::Uuid::new_v4().to_string(),
sequence: 42,
payload: Some(rmm_protocol::Payload::InventorySnapshot(Default::default())),
..Default::default()
};
let bytes = envelope.encode_to_vec();
db.execute(
"INSERT INTO events VALUES(?1,?2)",
params![envelope.message_id, bytes],
)
.unwrap();
drop(db);
let mut journal = Journal::open(&directory).unwrap();
journal.pin_identity("original-device").unwrap();
assert_eq!(journal.next_sequence().unwrap(), 43);
assert_eq!(journal.events().unwrap()[0].encode_to_vec(), bytes);
assert_eq!(
journal
.connection()
.query_row("SELECT count(*) FROM job_attempts", [], |r| r
.get::<_, i64>(0))
.unwrap(),
0
);
let journal_id: String = journal
.connection()
.query_row(
"SELECT journal_id FROM reconcile_meta WHERE id=1",
[],
|r| r.get(0),
)
.unwrap();
drop(journal);
let journal = Journal::open(&directory).unwrap();
assert_eq!(
journal
.connection()
.query_row(
"SELECT journal_id FROM reconcile_meta WHERE id=1",
[],
|r| r.get::<_, String>(0)
)
.unwrap(),
journal_id
);
drop(journal);
std::fs::remove_dir_all(directory).unwrap();
}
}
+12
View File
@@ -4,7 +4,19 @@ 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)]
pub mod clock;
#[cfg(all(windows, feature = "system-helper"))]
pub mod helper_ipc;
#[cfg(all(windows, feature = "system-helper"))]
pub mod helper_system;
pub const SERVICE_NAME: &str = "RmmDiscoveryWindows";
pub const CAPABILITIES: &[&str] = &["windows.base/1", "heartbeat/1"];
+110 -9
View File
@@ -37,6 +37,90 @@ fn sid_string(sid: *mut c_void) -> Result<String> {
}
Ok(result)
}
/// Verify the actual SCM process token; an administrator probe cannot stand in
/// for this check. No account switching or SYSTEM fallback exists.
pub fn require_local_service() -> Result<()> {
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
let mut token = ptr::null_mut();
ensure!(
unsafe { OpenProcessToken(GetCurrentProcess(), Security::TOKEN_QUERY, &mut token) } != 0,
"SERVICE_TOKEN_REQUIRED"
);
let token = unsafe { OwnedHandle::from_raw_handle(token) };
// Native structures require alignment, even though GetTokenInformation
// accepts a void pointer. Allocate pointer-aligned storage, with fixed cap.
let mut storage = vec![0usize; 256];
let mut size = 0;
ensure!(
unsafe {
Security::GetTokenInformation(
token.as_raw_handle(),
Security::TokenUser,
storage.as_mut_ptr().cast(),
(storage.len() * std::mem::size_of::<usize>()) as u32,
&mut size,
)
} != 0,
"SERVICE_TOKEN_USER"
);
let user = unsafe { &*storage.as_ptr().cast::<Security::TOKEN_USER>() };
ensure!(
sid_string(user.User.Sid)? == "S-1-5-19",
"LOCAL_SERVICE_REQUIRED"
);
// A native SCM probe showed LocalService's unfiltered service token reports
// TokenElevation=1, type=Default, while SID19 has no enabled administrator
// membership. UAC elevation alone is not an account/administrator check.
// Reject thread impersonation before querying effective membership.
use windows_sys::Win32::{
Foundation::{ERROR_NO_TOKEN, GetLastError},
System::Threading::{GetCurrentThread, OpenThreadToken},
};
let mut thread_token = ptr::null_mut();
if unsafe {
OpenThreadToken(
GetCurrentThread(),
Security::TOKEN_QUERY,
1,
&mut thread_token,
)
} != 0
{
let _thread_token = unsafe { OwnedHandle::from_raw_handle(thread_token) };
anyhow::bail!("IMPERSONATED_EXECUTOR_FORBIDDEN");
}
ensure!(
unsafe { GetLastError() } == ERROR_NO_TOKEN,
"THREAD_TOKEN_UNVERIFIED"
);
let mut admin_sid = [0usize; 16];
let mut admin_size = std::mem::size_of_val(&admin_sid) as u32;
ensure!(
unsafe {
Security::CreateWellKnownSid(
Security::WinBuiltinAdministratorsSid,
ptr::null_mut(),
admin_sid.as_mut_ptr().cast(),
&mut admin_size,
)
} != 0,
"ADMINISTRATOR_SID_QUERY"
);
let mut admin_member = 0;
ensure!(
unsafe {
Security::CheckTokenMembership(
ptr::null_mut(),
admin_sid.as_mut_ptr().cast(),
&mut admin_member,
)
} != 0
&& admin_member == 0,
"ADMINISTRATOR_EXECUTOR_FORBIDDEN"
);
Ok(())
}
pub fn service_sid() -> Result<String> {
let account = wide(format!("NT SERVICE\\{}", crate::SERVICE_NAME));
let mut sid_len = 0;
@@ -191,15 +275,19 @@ pub fn snapshot() -> Result<Value> {
let build = registry_string("CurrentBuildNumber")?;
let os = format!("{product}; DisplayVersion={display}; Build={build}");
let completed = Utc::now();
Ok(
json!({"os":os,"hostname":hostname,"architecture":std::env::consts::ARCH,"root_total_bytes":total,"root_available_bytes":available,"root_available_inodes":null,
"collection_started_at":started,"collection_completed_at":completed,
"observations":[
{"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build}},
{"scope":"windows.volumes","source_id":"windows.win32:GetDiskFreeSpaceExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"system_volume_total_bytes":total,"system_volume_available_bytes":available}},
{"scope":"windows.inodes","source_id":"windows.win32","observed_at":completed,"quality":"unsupported","completeness":"unknown","truncated":false,"error_code":"NOT_APPLICABLE","data":null}
]}),
)
let mut snapshot = json!({"os":os,"hostname":hostname,"architecture":std::env::consts::ARCH,"root_total_bytes":total,"root_available_bytes":available,"root_available_inodes":null,
"collection_started_at":started,"collection_completed_at":completed,
"observations":[
{"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build}},
{"scope":"windows.volumes","source_id":"windows.win32:GetDiskFreeSpaceExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"system_volume_total_bytes":total,"system_volume_available_bytes":available}},
{"scope":"windows.inodes","source_id":"windows.win32","observed_at":completed,"quality":"unsupported","completeness":"unknown","truncated":false,"error_code":"NOT_APPLICABLE","data":null}
]});
snapshot["observations"]
.as_array_mut()
.context("INVENTORY_OBSERVATIONS")?
.extend(crate::inventory::observations());
snapshot["collection_completed_at"] = json!(Utc::now());
Ok(snapshot)
}
pub async fn boot_id() -> Result<String> {
// Fixed passive query only. Never interpolates a job or caller-supplied code.
@@ -235,6 +323,19 @@ mod tests {
assert!(v["root_total_bytes"].as_u64().unwrap() > 0);
assert!(v["root_available_inodes"].is_null());
assert!(!v["hostname"].as_str().unwrap().is_empty());
let hardware = v["observations"]
.as_array()
.unwrap()
.iter()
.find(|o| o["scope"] == "windows.hardware")
.unwrap();
assert!(hardware["data"]["memory_total_bytes"].as_u64().unwrap() > 0);
assert!(
hardware["data"]["logical_processors_visible"]
.as_u64()
.unwrap()
> 0
);
assert!(
v["observations"]
.as_array()
+406
View File
@@ -0,0 +1,406 @@
//! Bounded Windows child process trees. No authorization is conferred here.
//! The caller must commit the verified grant/attempt consumption before run.
//! Job and handle lists are applied atomically by CreateProcessW (Windows 10+).
use anyhow::{Result, ensure};
use std::{
ffi::{OsStr, OsString},
mem::{size_of, size_of_val, zeroed},
os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle},
path::Path,
ptr,
sync::atomic::{AtomicBool, Ordering},
time::{Duration, Instant},
};
use windows_sys::Win32::{
Foundation::{
ERROR_BROKEN_PIPE, GetLastError, HANDLE, HANDLE_FLAG_INHERIT, STILL_ACTIVE,
SetHandleInformation,
},
Security::SECURITY_ATTRIBUTES,
Storage::FileSystem::ReadFile,
System::{
JobObjects::*,
Pipes::{CreatePipe, PeekNamedPipe},
Threading::*,
},
};
pub struct Output {
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
pub exit_code: Option<i32>,
pub truncated: bool,
/// A killed process can already have affected the machine: never retry it.
pub interrupted: bool,
pub cancelled: bool,
}
/// Windows CRT quoting, not shell escaping. PowerShell receives -File followed
/// by individual arguments; none are evaluated as a generated command string.
pub fn quote(arg: &OsStr) -> Result<Vec<u16>> {
use std::os::windows::ffi::OsStrExt;
let input: Vec<u16> = arg.encode_wide().collect();
ensure!(!input.contains(&0), "ARGUMENT_NUL");
let mut out = vec![b'"' as u16];
let mut slashes = 0;
for ch in input {
if ch == b'\\' as u16 {
slashes += 1;
continue;
}
out.extend(std::iter::repeat_n(
b'\\' as u16,
slashes * if ch == b'"' as u16 { 2 } else { 1 },
));
if ch == b'"' as u16 {
out.push(b'\\' as u16);
}
out.push(ch);
slashes = 0;
}
out.extend(std::iter::repeat_n(b'\\' as u16, slashes * 2));
out.push(b'"' as u16);
Ok(out)
}
fn owned(raw: HANDLE) -> Result<OwnedHandle> {
ensure!(!raw.is_null() && raw != -1isize as HANDLE, "PROCESS_HANDLE");
// SAFETY: successful creating API transfers this unique, live handle.
Ok(unsafe { OwnedHandle::from_raw_handle(raw) })
}
fn pipe() -> Result<(OwnedHandle, OwnedHandle)> {
let mut read = ptr::null_mut();
let mut write = ptr::null_mut();
let security = SECURITY_ATTRIBUTES {
nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: ptr::null_mut(),
bInheritHandle: 1,
};
// SAFETY: initialized output pointers and fixed-size security descriptor.
ensure!(
unsafe { CreatePipe(&mut read, &mut write, &security, 8192) } != 0,
"PROCESS_PIPE"
);
let read = owned(read)?;
let write = owned(write)?;
ensure!(
unsafe { SetHandleInformation(read.as_raw_handle(), HANDLE_FLAG_INHERIT, 0) } != 0,
"PIPE_READ_NOT_INHERITED"
);
Ok((read, write))
}
struct Attributes {
storage: Vec<usize>,
}
impl Attributes {
fn new() -> Result<Self> {
let mut bytes = 0;
unsafe {
InitializeProcThreadAttributeList(ptr::null_mut(), 2, 0, &mut bytes);
}
ensure!(bytes > 0 && bytes < 65536, "PROCESS_ATTRIBUTES_SIZE");
let mut storage = vec![0usize; bytes.div_ceil(size_of::<usize>())];
ensure!(
unsafe {
InitializeProcThreadAttributeList(storage.as_mut_ptr().cast(), 2, 0, &mut bytes)
} != 0,
"PROCESS_ATTRIBUTES"
);
Ok(Self { storage })
}
fn pointer(&mut self) -> LPPROC_THREAD_ATTRIBUTE_LIST {
self.storage.as_mut_ptr().cast()
}
fn set(&mut self, attribute: u32, handles: &[HANDLE]) -> Result<()> {
ensure!(
unsafe {
UpdateProcThreadAttribute(
self.pointer(),
0,
attribute as usize,
handles.as_ptr().cast(),
std::mem::size_of_val(handles),
ptr::null_mut(),
ptr::null(),
)
} != 0,
"PROCESS_ATTRIBUTE_BINDING"
);
Ok(())
}
}
impl Drop for Attributes {
fn drop(&mut self) {
unsafe {
DeleteProcThreadAttributeList(self.pointer());
}
}
}
fn drain(
pipe: &OwnedHandle,
output: &mut Vec<u8>,
remaining: &mut usize,
truncated: &mut bool,
) -> Result<()> {
// One bounded read per stream/iteration avoids starvation by a noisy child.
let mut available = 0;
if unsafe {
PeekNamedPipe(
pipe.as_raw_handle(),
ptr::null_mut(),
0,
ptr::null_mut(),
&mut available,
ptr::null_mut(),
)
} == 0
{
ensure!(
unsafe { GetLastError() } == ERROR_BROKEN_PIPE,
"PROCESS_PIPE_PEEK"
);
return Ok(());
}
if available == 0 {
return Ok(());
}
let mut buffer = [0u8; 16384];
let mut read = 0;
ensure!(
unsafe {
ReadFile(
pipe.as_raw_handle(),
buffer.as_mut_ptr(),
available.min(buffer.len() as u32),
&mut read,
ptr::null_mut(),
)
} != 0,
"PROCESS_PIPE_READ"
);
let keep = (*remaining).min(read as usize);
output.extend_from_slice(&buffer[..keep]);
*remaining -= keep;
*truncated |= keep < read as usize;
Ok(())
}
pub fn run(
executable: &Path,
arguments: &[OsString],
cwd: &Path,
seconds: u32,
max_bytes: usize,
cancel: &AtomicBool,
) -> Result<Output> {
ensure!(
executable.is_absolute() && cwd.is_absolute() && seconds > 0 && max_bytes <= 512 * 1024,
"PROCESS_LIMITS"
);
let (stdout, out_write) = pipe()?;
let (stderr, err_write) = pipe()?;
let (stdin, in_write) = pipe()?;
// The child reads immediate EOF. Only its read handle is inheritable.
ensure!(
unsafe {
SetHandleInformation(
stdin.as_raw_handle(),
HANDLE_FLAG_INHERIT,
HANDLE_FLAG_INHERIT,
)
} != 0,
"STDIN_INHERITANCE"
);
drop(in_write);
let job = owned(unsafe { CreateJobObjectW(ptr::null(), ptr::null()) })?;
let mut limits: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { zeroed() };
limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
ensure!(
unsafe {
SetInformationJobObject(
job.as_raw_handle(),
JobObjectExtendedLimitInformation,
ptr::addr_of!(limits).cast(),
size_of_val(&limits) as u32,
)
} != 0,
"PROCESS_JOB_LIMITS"
);
let jobs = [job.as_raw_handle()];
let inherited = [
stdin.as_raw_handle(),
out_write.as_raw_handle(),
err_write.as_raw_handle(),
];
let mut attributes = Attributes::new()?;
attributes.set(PROC_THREAD_ATTRIBUTE_JOB_LIST, &jobs)?;
attributes.set(PROC_THREAD_ATTRIBUTE_HANDLE_LIST, &inherited)?;
let mut startup: STARTUPINFOEXW = unsafe { zeroed() };
startup.StartupInfo.cb = size_of::<STARTUPINFOEXW>() as u32;
startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
startup.StartupInfo.hStdInput = stdin.as_raw_handle();
startup.StartupInfo.hStdOutput = out_write.as_raw_handle();
startup.StartupInfo.hStdError = err_write.as_raw_handle();
startup.lpAttributeList = attributes.pointer();
let mut command = quote(executable.as_os_str())?;
for arg in arguments {
command.push(b' ' as u16);
command.extend(quote(arg)?);
}
ensure!(command.len() < 32766, "PROCESS_ARGUMENT_LIMIT");
command.push(0);
let application = crate::native::wide(executable);
let directory = crate::native::wide(cwd);
let mut system_buffer = [0u16; 32768];
let system_length = unsafe {
windows_sys::Win32::System::SystemInformation::GetSystemWindowsDirectoryW(
system_buffer.as_mut_ptr(),
system_buffer.len() as u32,
)
} as usize;
ensure!(
system_length > 0 && system_length < system_buffer.len(),
"SYSTEM_ROOT"
);
let system = std::path::PathBuf::from(String::from_utf16(&system_buffer[..system_length])?);
// Minimal environment: no inherited tokens, proxy secrets, device paths,
// PSModulePath overrides, user profile or caller-controlled executable PATH.
let mut environment = Vec::new();
for value in [
format!("PATH={}\\System32;{}", system.display(), system.display()),
format!("SystemRoot={}", system.display()),
format!("TEMP={}", cwd.display()),
format!("TMP={}", cwd.display()),
format!("windir={}", system.display()),
] {
environment.extend(crate::native::wide(value));
}
environment.push(0);
let mut process: PROCESS_INFORMATION = unsafe { zeroed() };
ensure!(
unsafe {
CreateProcessW(
application.as_ptr(),
command.as_mut_ptr(),
ptr::null(),
ptr::null(),
1,
EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT,
environment.as_ptr().cast(),
directory.as_ptr(),
&startup.StartupInfo,
&mut process,
)
} != 0,
"PROCESS_CREATION_REFUSED"
);
let process_handle = owned(process.hProcess)?;
let _thread = owned(process.hThread)?;
// Handles not explicitly listed (including job, DB and keys) are never inherited.
drop(attributes);
drop(stdin);
drop(out_write);
drop(err_write);
let mut result = Output {
stdout: Vec::new(),
stderr: Vec::new(),
exit_code: None,
truncated: false,
interrupted: false,
cancelled: false,
};
let began = Instant::now();
let mut remaining = max_bytes;
loop {
drain(
&stdout,
&mut result.stdout,
&mut remaining,
&mut result.truncated,
)?;
drain(
&stderr,
&mut result.stderr,
&mut remaining,
&mut result.truncated,
)?;
let mut accounting: JOBOBJECT_BASIC_ACCOUNTING_INFORMATION = unsafe { zeroed() };
ensure!(
unsafe {
QueryInformationJobObject(
job.as_raw_handle(),
JobObjectBasicAccountingInformation,
ptr::addr_of_mut!(accounting).cast(),
size_of_val(&accounting) as u32,
ptr::null_mut(),
)
} != 0,
"PROCESS_TREE_STATE"
);
if accounting.ActiveProcesses == 0 {
break;
}
if began.elapsed() >= Duration::from_secs(seconds.into()) || cancel.load(Ordering::SeqCst) {
result.cancelled = cancel.load(Ordering::SeqCst);
result.interrupted = true;
ensure!(
unsafe { TerminateJobObject(job.as_raw_handle(), 1) } != 0,
"PROCESS_TREE_TERMINATION"
);
// This wait proves termination, not absence of effects.
ensure!(
unsafe { WaitForSingleObject(process_handle.as_raw_handle(), 5000) } == 0,
"PROCESS_TERMINATION_UNCONFIRMED"
);
break;
}
std::thread::sleep(Duration::from_millis(5));
}
// No writer can outlive job destruction. Drain the bounded OS pipe buffers.
drop(job);
for _ in 0..8 {
drain(
&stdout,
&mut result.stdout,
&mut remaining,
&mut result.truncated,
)?;
drain(
&stderr,
&mut result.stderr,
&mut remaining,
&mut result.truncated,
)?;
}
let mut code = 0;
ensure!(
unsafe { GetExitCodeProcess(process_handle.as_raw_handle(), &mut code) } != 0
&& code != STILL_ACTIVE as u32,
"PROCESS_EXIT_UNCONFIRMED"
);
result.exit_code = Some(code as i32);
Ok(result)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn arguments_never_become_shell_code_and_trailing_slashes_are_quoted() {
assert_eq!(
String::from_utf16(&quote(OsStr::new("a b\\")).unwrap()).unwrap(),
"\"a b\\\\\""
);
assert_eq!(
String::from_utf16(&quote(OsStr::new("a\"b")).unwrap()).unwrap(),
"\"a\\\"b\""
);
assert_eq!(
String::from_utf16(&quote(OsStr::new("$(Get-Content x); & y")).unwrap()).unwrap(),
"\"$(Get-Content x); & y\""
);
assert!(quote(OsStr::new("a\0b")).is_err());
}
}
+793 -24
View File
@@ -1,14 +1,25 @@
use anyhow::{Result, ensure};
use anyhow::{Context, Result, ensure};
use chrono::Utc;
use prost::Message;
use rcgen::{CertificateParams, DnType, KeyPair};
use rmm_agent_core::{
auth::{Binding, Outcome, Request},
jobs, ledger,
reconcile::{self, SyncClock},
};
use rmm_agent_windows::{CAPABILITIES, journal::Journal, native};
use rmm_domain::jobs::{Action, ExecutionPermitPayload};
use rmm_protocol::*;
use rusqlite::{Connection, OptionalExtension};
use serde::Deserialize;
use sha2::{Digest, Sha256};
use std::{
fs,
path::{Path, PathBuf},
sync::atomic::{AtomicBool, Ordering},
sync::{
Arc,
atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering},
},
time::{Duration, Instant},
};
use uuid::Uuid;
@@ -22,6 +33,11 @@ struct Config {
state_directory: PathBuf,
enrollment_token_file: PathBuf,
transport: String,
#[serde(default)]
job_binding_file: Option<PathBuf>,
// False until the independent LocalService clock qualification is complete.
#[serde(default)]
enable_jobs: bool,
}
fn create_private(path: &Path, bytes: &[u8]) -> Result<()> {
use std::io::Write;
@@ -105,6 +121,222 @@ async fn enrollment(config: &Config, ca: &[u8]) -> Result<EnrollmentResponse> {
fs::remove_file(&config.enrollment_token_file)?;
Ok(identity)
}
#[derive(Clone)]
struct JobClock {
native: Arc<rmm_agent_windows::clock::NativeClock>,
enabled: bool,
}
impl SyncClock for JobClock {
fn now(&self) -> Result<chrono::DateTime<Utc>> {
ensure!(self.enabled, "WINDOWS_JOBS_NOT_ENABLED");
self.native.now()
}
}
#[derive(Default)]
struct EffectFence {
generation: AtomicU64,
deadline: AtomicI64,
}
impl EffectFence {
fn close(&self) {
self.generation.store(0, Ordering::SeqCst);
}
fn allows(&self, generation: u64, clock: &impl SyncClock) -> bool {
self.generation.load(Ordering::SeqCst) == generation
&& generation > 0
&& clock.now().is_ok_and(|now| {
(now + chrono::Duration::seconds(2)).timestamp_millis()
< self.deadline.load(Ordering::SeqCst)
})
}
}
type Completion = (JobOffer, ExecutionPermitPayload, Outcome);
struct Running {
offer: JobOffer,
grant: ExecutionPermitPayload,
cancel: Arc<AtomicBool>,
worker: tokio::task::JoinHandle<()>,
}
fn verified_window(
binding: &Binding,
request: &Request,
clock: &impl SyncClock,
) -> Result<(rmm_domain::jobs::JobPayload, ExecutionPermitPayload)> {
let now = clock.now()?;
// The entire qualified <=2s clock interval must lie inside the grant window.
let result = binding.verify(request, now - chrono::Duration::seconds(2))?;
binding.verify(request, now + chrono::Duration::seconds(2))?;
Ok(result)
}
fn readonly_binding(path: &Path) -> Result<Binding> {
use std::ptr;
use windows_sys::Win32::{
Foundation::LocalFree,
Security::{
self, ACCESS_ALLOWED_ACE, ACL,
Authorization::{ConvertSidToStringSidW, GetNamedSecurityInfoW, SE_FILE_OBJECT},
DACL_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION,
},
};
unsafe fn sid(sid: Security::PSID) -> Result<String> {
let mut raw = ptr::null_mut();
ensure!(
unsafe { ConvertSidToStringSidW(sid, &mut raw) } != 0,
"BINDING_SID"
);
let mut len = 0;
while unsafe { *raw.add(len) } != 0 {
len += 1;
ensure!(len < 256, "BINDING_SID_LIMIT");
}
let value = String::from_utf16(unsafe { std::slice::from_raw_parts(raw, len) })?;
unsafe {
LocalFree(raw.cast());
}
Ok(value)
}
ensure!(path.is_absolute(), "ABSOLUTE_JOB_BINDING_REQUIRED");
// The immediate configuration directory must also deny agent replacement.
for (item, directory) in [
(path, false),
(path.parent().context("BINDING_PARENT")?, true),
] {
native::private_path(item, directory)?;
let mut owner = ptr::null_mut();
let mut dacl: *mut ACL = ptr::null_mut();
let mut descriptor = ptr::null_mut();
let status = unsafe {
GetNamedSecurityInfoW(
native::wide(item).as_ptr(),
SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
&mut owner,
ptr::null_mut(),
&mut dacl,
ptr::null_mut(),
&mut descriptor,
)
};
ensure!(status == 0, "BINDING_SECURITY");
let check = (|| -> Result<()> {
ensure!(!owner.is_null() && !dacl.is_null(), "BINDING_NULL_SECURITY");
ensure!(
matches!(unsafe { sid(owner) }?.as_str(), "S-1-5-18" | "S-1-5-32-544"),
"BINDING_ADMIN_OWNER_REQUIRED"
);
for index in 0..unsafe { (*dacl).AceCount } {
let mut raw = ptr::null_mut();
ensure!(
unsafe { Security::GetAce(dacl, u32::from(index), &mut raw) } != 0,
"BINDING_ACE"
);
let ace = unsafe { &*raw.cast::<ACCESS_ALLOWED_ACE>() };
ensure!(
ace.Header.AceType == 0
&& usize::from(ace.Header.AceSize)
>= std::mem::size_of::<ACCESS_ALLOWED_ACE>(),
"BINDING_ACE_TYPE"
);
let who = unsafe { sid(ptr::addr_of!(ace.SidStart).cast_mut().cast()) }?;
if !matches!(who.as_str(), "S-1-5-18" | "S-1-5-32-544") {
// Generic write/all, owner/DACL/delete and all file/directory mutation bits.
ensure!(ace.Mask & 0x500d_0156 == 0, "BINDING_AGENT_WRITE_FORBIDDEN");
}
}
Ok(())
})();
unsafe {
LocalFree(descriptor.cast());
}
check?;
}
let binding: Binding = serde_json::from_slice(&protected_read(path, 8192)?)?;
ensure!(
!binding.tenant_id.is_nil()
&& !binding.agent_id.is_nil()
&& !binding.asset_id.is_nil()
&& binding.enrollment_generation > 0
&& binding.assignment_version > 0
&& binding.public_key_hex.len() == 64
&& binding
.public_key_hex
.bytes()
.all(|b| b.is_ascii_hexdigit()),
"JOB_BINDING_PROFILE"
);
Ok(binding)
}
fn import_legacy_inventory(journal: &mut Journal) -> Result<()> {
let original = {
let mut q = journal
.connection()
.prepare("SELECT id,payload FROM events ORDER BY rowid")?;
q.query_map([], |r| {
Ok((r.get::<_, String>(0)?, r.get::<_, Vec<u8>>(1)?))
})?
.collect::<rusqlite::Result<Vec<_>>>()?
};
let tx = journal.connection_mut().transaction()?;
for (id, bytes) in original {
let envelope = Envelope::decode(bytes.as_slice())?;
ensure!(
envelope.message_id == id
&& matches!(envelope.payload, Some(Payload::InventorySnapshot(_))),
"LEGACY_INVENTORY_BINDING"
);
let old: Option<Vec<u8>> = tx
.query_row("SELECT payload FROM job_events WHERE id=?1", [&id], |r| {
r.get(0)
})
.optional()?;
ensure!(
old.as_ref().is_none_or(|old| old == &bytes),
"LEGACY_INVENTORY_CONFLICT"
);
// Copy original bytes/ID, never decode/re-encode or discard pending telemetry.
tx.execute(
"INSERT OR IGNORE INTO job_events(id,payload) VALUES(?1,?2)",
rusqlite::params![id, bytes],
)?;
}
// Core ACK/Sync deletion and the old queue advance in the SAME transaction.
tx.execute_batch("CREATE TRIGGER IF NOT EXISTS windows_legacy_inventory_ack AFTER DELETE ON job_events BEGIN DELETE FROM events WHERE id=OLD.id AND payload=OLD.payload; END;")?;
tx.commit()?;
Ok(())
}
fn open_ledger(directory: &Path, binding: &Binding) -> Result<(Connection, fs::File)> {
use std::os::windows::fs::OpenOptionsExt;
use windows_sys::Win32::Storage::FileSystem::{FILE_SHARE_READ, FILE_SHARE_WRITE};
let path = directory.join("consumption.sqlite");
let file = fs::OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
.open(&path)?;
native::private_path(&path, false)?;
let db = Connection::open(&path)?;
ledger::initialize_ledger(&db)?;
db.execute_batch("CREATE TABLE IF NOT EXISTS windows_binding(identity TEXT NOT NULL);")?;
let identity = format!(
"{}:{}:{}:{}:{}",
binding.tenant_id,
binding.asset_id,
binding.agent_id,
binding.enrollment_generation,
binding.assignment_version
);
let old: Option<String> = db
.query_row("SELECT identity FROM windows_binding", [], |r| r.get(0))
.optional()?;
if let Some(old) = old {
ensure!(old == identity, "LEDGER_IDENTITY_MISMATCH");
} else {
db.execute("INSERT INTO windows_binding VALUES(?1)", [identity])?;
}
Ok((db, file))
}
struct Agent {
config: Config,
identity: EnrollmentResponse,
@@ -113,15 +345,347 @@ struct Agent {
boot: String,
instance: String,
started: Instant,
binding: Option<Binding>,
ledger: Option<Connection>,
_ledger_file: Option<fs::File>,
clock: JobClock,
sync: Option<reconcile::ClientSync>,
prepared: bool,
fence: Arc<EffectFence>,
completed_tx: tokio::sync::mpsc::Sender<Completion>,
completed_rx: tokio::sync::mpsc::Receiver<Completion>,
running: Option<Running>,
deferred_permit: Option<(u64, ExecutionPermit)>,
}
impl Agent {
fn close_gate(&mut self) {
self.fence.close();
if let Some(sync) = &mut self.sync {
sync.close();
}
self.prepared = false;
self.deferred_permit = None;
}
fn channel(&self, generation: u64) -> Result<reconcile::Channel> {
Ok(reconcile::Channel {
connection_generation: generation,
boot_id: Uuid::parse_str(&self.boot)?,
})
}
fn ready(&self, generation: u64) -> bool {
self.config.enable_jobs
&& self.channel(generation).is_ok_and(|channel| {
self.sync
.as_ref()
.is_some_and(|sync| sync.can_start(&channel, false, &self.clock))
})
}
fn capabilities(&self) -> Vec<String> {
let mut caps: Vec<String> = CAPABILITIES.iter().map(|c| c.to_string()).collect();
if self.config.enable_jobs
&& self.binding.is_some()
&& native::require_local_service().is_ok()
&& self.clock.now().is_ok()
{
caps.extend(["rmm.sync.v1", "refresh_inventory"].map(str::to_string));
if rmm_agent_windows::actions::powershell().is_ok() {
caps.extend(["run_script", "script.powershell/1"].map(str::to_string));
}
}
caps
}
fn record(
&mut self,
generation: u64,
offer: &JobOffer,
grant: &str,
outcome: Outcome,
) -> Result<()> {
let mut envelope = self.envelope(generation, Payload::JobResult(JobResult::default()))?;
let tx = self.journal.connection_mut().transaction()?;
let revision = jobs::transition(&tx, offer, &outcome.state, grant)?;
envelope.payload = Some(Payload::JobResult(jobs::result(
offer, revision, grant, outcome,
)));
jobs::event(&tx, &envelope)?;
tx.commit()?;
Ok(())
}
fn recover_interrupted(&mut self) -> Result<()> {
let Some(binding) = self.binding.clone() else {
return Ok(());
};
let interrupted = jobs::interrupted(
self.journal.connection(),
self.ledger.as_ref().context("LEDGER_REQUIRED")?,
&binding,
)?;
for (offer, grant) in interrupted {
if grant.is_empty() {
jobs::interrupted_request(self.journal.connection(), &offer)?;
} else {
let outcome = jobs::recover_interrupted_outcome(
self.ledger.as_ref().context("LEDGER_REQUIRED")?,
&binding,
&offer,
&grant,
)?
.unwrap_or_else(|| Outcome::unknown("AGENT_PROCESS_INTERRUPTED"));
// Replay original durable evidence only. Normal signed Sync,
// never startup, releases the previously consumed attempt.
self.record(0, &offer, &grant, outcome)?;
}
}
Ok(())
}
async fn replay(
&mut self,
channel: &crate::wire_channel::Handle,
generation: u64,
) -> Result<()> {
let events = jobs::events(self.journal.connection())?;
let passive = self.journal.events()?;
tokio::time::timeout(Duration::from_secs(2), async {
for mut event in events.into_iter().chain(passive).take(8) {
event.connection_generation = generation;
channel.send(&event).await?;
}
Ok::<_, anyhow::Error>(())
})
.await??;
Ok(())
}
async fn start_sync(
&mut self,
channel: &crate::wire_channel::Handle,
generation: u64,
) -> Result<()> {
self.fence.close();
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,
&self.clock,
)?;
self.prepared = true;
channel.send(&prepared.envelope).await?;
Ok(())
}
fn apply_sync(&mut self, generation: u64, response: SyncResponse) -> Result<()> {
ensure!(self.prepared, "UNSOLICITED_SYNC_RESPONSE");
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 self.ready(generation) {
let deadline = self
.sync
.as_ref()
.and_then(|sync| sync.validity_deadline())
.context("SIGNED_LEASE_REQUIRED")?;
self.fence
.deadline
.store(deadline.timestamp_millis(), Ordering::SeqCst);
self.fence.generation.store(generation, Ordering::SeqCst);
}
Ok(())
}
fn completed(&mut self, generation: u64, (offer, grant, outcome): Completion) -> Result<()> {
let running = self
.running
.as_ref()
.context("UNSOLICITED_EXECUTOR_COMPLETION")?;
ensure!(
running.offer.job_id == offer.job_id
&& running.offer.attempt_id == offer.attempt_id
&& running.grant == grant,
"EXECUTOR_COMPLETION_BINDING"
);
ledger::persist_outcome(
self.ledger.as_ref().context("LEDGER_REQUIRED")?,
&grant,
&outcome,
)?;
self.record(
generation,
&offer,
&grant.grant_id.to_string(),
outcome.clone(),
)?;
ledger::finish(
self.ledger.as_ref().context("LEDGER_REQUIRED")?,
&grant,
&outcome,
)?;
self.running = None;
Ok(())
}
fn permit(&mut self, generation: u64, permit: ExecutionPermit) -> Result<()> {
if let Some((old_generation, old)) = &self.deferred_permit {
ensure!(
*old_generation == generation && *old == permit,
"PENDING_PERMIT_CONFLICT"
);
return Ok(());
}
let offer = jobs::requesting(self.journal.connection())?.context("UNSOLICITED_PERMIT")?;
if !permit.denial_code.is_empty() {
self.record(
generation,
&offer,
"",
Outcome::unknown("PERMIT_DENIED_RECONCILIATION_REQUIRED"),
)?;
return Ok(());
}
ensure!(
self.ready(generation) && self.running.is_none(),
"FENCED_SYNC_REQUIRED"
);
let binding = self
.binding
.as_ref()
.context("JOB_BINDING_REQUIRED")?
.clone();
let request = jobs::permit_request(&offer, &permit)?;
let now = self.clock.now()?;
// Authenticate before interpreting timing. A freshly issued grant may
// need two seconds before the full uncertainty interval is inside it.
let (_, authenticated) = binding.verify(&request, now + chrono::Duration::seconds(2))?;
if now - chrono::Duration::seconds(2) < authenticated.not_before {
self.deferred_permit = Some((generation, permit));
return Ok(());
}
let (job, grant) = verified_window(&binding, &request, &self.clock)?;
ensure!(
rmm_agent_windows::actions::supported(&job),
"UNSUPPORTED_CAPABILITY"
);
let started_at = self.clock.now()?;
let ledger = self.ledger.as_mut().context("LEDGER_REQUIRED")?;
ledger::begin_execution(
ledger,
&grant,
&request,
Uuid::parse_str(&self.boot)?,
started_at,
)?;
let cancelled: bool = self.journal.connection().query_row(
"SELECT cancel_requested FROM job_attempts WHERE job=?1 AND attempt=?2",
rusqlite::params![offer.job_id, offer.attempt_id],
|r| r.get(0),
)?;
if cancelled {
let outcome = jobs::no_start("cancelled", "CANCELLED_BEFORE_EFFECT");
ledger::persist_outcome(
self.ledger.as_ref().context("LEDGER_REQUIRED")?,
&grant,
&outcome,
)?;
self.record(
generation,
&offer,
&grant.grant_id.to_string(),
outcome.clone(),
)?;
ledger::finish(
self.ledger.as_ref().context("LEDGER_REQUIRED")?,
&grant,
&outcome,
)?;
return Ok(());
}
let mut started = self.envelope(
generation,
Payload::JobStateChanged(JobStateChanged::default()),
)?;
let tx = self.journal.connection_mut().transaction()?;
let revision = jobs::transition(&tx, &offer, "running", &grant.grant_id.to_string())?;
started.payload = Some(Payload::JobStateChanged(JobStateChanged {
job_id: offer.job_id.clone(),
attempt_id: offer.attempt_id.clone(),
revision,
state: "running".into(),
grant_id: grant.grant_id.to_string(),
}));
jobs::event(&tx, &started)?;
tx.commit()?;
let cancelled = Arc::new(AtomicBool::new(false));
let worker_cancel = cancelled.clone();
let clock = self.clock.clone();
let fence = self.fence.clone();
let completed = self.completed_tx.clone();
let directory = self.config.state_directory.join("jobs");
let work_offer = offer.clone();
let work_grant = grant.clone();
let worker = tokio::task::spawn_blocking(move || {
let outcome = (|| -> Result<Outcome> {
if !fence.allows(generation, &clock)
|| verified_window(&binding, &request, &clock).is_err()
{
return Ok(jobs::no_start(
"failed",
"START_WINDOW_OR_CLOCK_INVALID_BEFORE_EFFECT",
));
}
let script = if matches!(job.action, Action::RunScript { .. }) {
match rmm_agent_windows::actions::Script::prepare(
&job,
&directory,
work_grant.grant_id,
) {
Ok(script) => Some(script),
Err(_) => return Ok(jobs::no_start("failed", "SCRIPT_PREPARATION_FAILED")),
}
} else {
None
};
// File creation, pool scheduling and fsync never extend a start window.
if worker_cancel.load(Ordering::SeqCst) {
return Ok(jobs::no_start("cancelled", "CANCELLED_BEFORE_EFFECT"));
}
if !fence.allows(generation, &clock)
|| verified_window(&binding, &request, &clock).is_err()
{
return Ok(jobs::no_start(
"failed",
"START_WINDOW_OR_CLOCK_INVALID_BEFORE_EFFECT",
));
}
if let Some(script) = script {
script.run(&job, &worker_cancel)
} else {
rmm_agent_windows::actions::inventory(&job)
}
})()
.unwrap_or_else(|_| Outcome::unknown("WINDOWS_EXECUTOR_EFFECT_UNKNOWN"));
let _ = completed.blocking_send((work_offer, work_grant, outcome));
});
self.running = Some(Running {
offer,
grant,
cancel: cancelled,
worker,
});
Ok(())
}
fn envelope(&mut self, generation: u64, payload: Payload) -> Result<Envelope> {
Ok(Envelope {
protocol_major: 1,
protocol_minor: 0,
message_id: Uuid::new_v4().to_string(),
agent_id: self.identity.agent_id.clone(),
enrollment_generation: 1,
enrollment_generation: self.binding.as_ref().map_or(1, |b| b.enrollment_generation),
connection_generation: generation,
boot_id: self.boot.clone(),
sequence: self.journal.next_sequence()?,
@@ -130,7 +694,7 @@ impl Agent {
})
}
fn queue_inventory(&mut self, generation: u64) -> Result<()> {
if self.journal.count()? > 0 {
if self.journal.count()? > 0 || !jobs::events(self.journal.connection())?.is_empty() {
return Ok(());
}
let data = serde_json::to_vec(&native::snapshot()?)?;
@@ -148,14 +712,26 @@ impl Agent {
completeness: "partial".into(),
}),
)?;
self.journal.save(&envelope)
if self.binding.is_some() {
jobs::event(self.journal.connection(), &envelope)
} else {
self.journal.save(&envelope)
}
}
async fn session(&mut self, stop: &AtomicBool) -> Result<()> {
self.close_gate();
let result = self.session_inner(stop).await;
self.close_gate();
result
}
async fn session_inner(&mut self, stop: &AtomicBool) -> Result<()> {
self.boot = native::boot_id().await?;
let advertised = self.capabilities();
let hello = self.envelope(
0,
Payload::ClientHello(ClientHello {
agent_version: env!("CARGO_PKG_VERSION").into(),
capabilities: CAPABILITIES.iter().map(|v| v.to_string()).collect(),
capabilities: advertised.clone(),
}),
)?;
let identity = crate::certificate_rotation::DeviceIdentity {
@@ -180,7 +756,8 @@ impl Agent {
let reply = tokio::time::timeout(Duration::from_secs(20), channel.receive()).await??;
ensure!(
reply.agent_id == self.identity.agent_id
&& reply.enrollment_generation == 1
&& reply.enrollment_generation
== self.binding.as_ref().map_or(1, |b| b.enrollment_generation)
&& reply.protocol_major == 1
&& reply.protocol_minor == 0,
"SERVER_HELLO_BINDING"
@@ -194,26 +771,96 @@ impl Agent {
"SERVER_LIMITS"
);
self.queue_inventory(generation)?;
self.replay(&channel, generation).await?;
let mut needs_sync = self.sync.is_some();
if self.sync.is_some() && self.running.is_none() {
if self.start_sync(&channel, generation).await.is_err() {
self.close_gate();
} else {
needs_sync = false;
}
}
let mut sync_at = Instant::now();
let mut capabilities_at = Instant::now();
let mut replay = Instant::now() - Duration::from_secs(10);
let mut inventory = Instant::now();
let mut heartbeat = Instant::now() - Duration::from_secs(60);
let mut heartbeat_after = Duration::from_secs(30);
let mut tick = tokio::time::interval(Duration::from_secs(1));
while !stop.load(Ordering::SeqCst) {
while !stop.load(Ordering::SeqCst) || self.running.is_some() {
if stop.load(Ordering::SeqCst) {
self.close_gate();
if let Some(running) = &self.running {
running.cancel.store(true, Ordering::SeqCst);
}
}
tokio::select! {
_=tick.tick()=>{},
Some(completion)=self.completed_rx.recv()=>{self.completed(generation,completion)?;needs_sync=true;},
_=tick.tick()=>{
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)?;
}
if self.running.as_ref().is_some_and(|r|r.worker.is_finished()) {
if let Ok(completion)=self.completed_rx.try_recv(){self.completed(generation,completion)?;}
else {let running=self.running.as_ref().context("RUNNING_REQUIRED")?;self.completed(generation,(running.offer.clone(),running.grant.clone(),Outcome::unknown("EXECUTOR_THREAD_INTERRUPTED")))?;}
needs_sync=true;
}
let busy=self.running.is_some() || self.journal.connection().query_row("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN ('requesting','running','verifying'))",[],|r|r.get::<_,bool>(0))?;
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.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 {
let now=self.clock.now()?;
if let Some(offer)=jobs::next_at(self.journal.connection(),now)? {
let job=self.binding.as_ref().context("JOB_BINDING_REQUIRED")?.job(&offer.payload_bytes)?;
if now>=job.start_before {self.record(generation,&offer,"",jobs::no_start("expired","START_DEADLINE_EXPIRED"))?;needs_sync=true;}
else if now-chrono::Duration::seconds(2)>=job.not_before {
jobs::reserve_request(self.journal.connection(),&offer)?;
let request=self.envelope(generation,Payload::ExecutionPermitRequest(ExecutionPermitRequest{job_id:offer.job_id,attempt_id:offer.attempt_id,job_payload_hash:offer.job_payload_hash,assignment_version:job.assignment_version}))?;
channel.send(&request).await?;
}
}
}
}
},
message=channel.receive()=>{
let message=message?;
ensure!(message.agent_id==self.identity.agent_id && message.enrollment_generation==1 && message.protocol_major==1 && message.protocol_minor==0 && message.connection_generation==generation,"SERVER_ENVELOPE_BINDING");
ensure!(message.agent_id==self.identity.agent_id && message.enrollment_generation==self.binding.as_ref().map_or(1,|b|b.enrollment_generation) && message.protocol_major==1 && message.protocol_minor==0 && message.connection_generation==generation,"SERVER_ENVELOPE_BINDING");
match message.payload {
Some(Payload::Ack(ack))=>self.journal.ack(&ack.message_id)?,
// There is deliberately no acceptance/start path. A stale
// or malicious offer cannot activate an unimplemented job.
Some(Payload::JobOffer(_)|Payload::ExecutionPermit(_))=>anyhow::bail!("UNSUPPORTED_EXECUTION_CAPABILITY"),
Some(Payload::Ack(ack))=>{
let pending:Option<Vec<u8>>=self.journal.connection().query_row("SELECT payload FROM job_events WHERE id=?1",[&ack.message_id],|r|r.get(0)).optional()?;
if let Some(bytes)=pending && matches!(Envelope::decode(bytes.as_slice())?.payload,Some(Payload::InventorySnapshot(_)|Payload::JobResult(_))){needs_sync=true;}
self.journal.ack(&ack.message_id)?;jobs::ack(self.journal.connection_mut(),&ack.message_id)?;
},
Some(Payload::SyncResponse(response))=>{if self.apply_sync(generation,response).is_err(){self.close_gate();needs_sync=true;}sync_at=Instant::now();},
Some(Payload::JobOffer(offer))=>{
ensure!(self.config.enable_jobs,"UNSUPPORTED_EXECUTION_CAPABILITY");
let binding=self.binding.as_ref().context("JOB_BINDING_REQUIRED")?.clone();
let accepted=self.envelope(generation,Payload::JobAccepted(JobAccepted{job_id:offer.job_id.clone(),attempt_id:offer.attempt_id.clone(),job_payload_hash:offer.job_payload_hash.clone(),journal_proof:rmm_domain::jobs::hash(&offer.encode_to_vec())}))?;
let tx=self.journal.connection_mut().transaction()?;
let fresh=jobs::accept(&tx,&binding,&offer,rmm_agent_windows::actions::supported)?;
jobs::event(&tx,&accepted)?;tx.commit()?;needs_sync|=fresh;
},
Some(Payload::ExecutionPermit(permit))=>self.permit(generation,permit)?,
Some(Payload::CancelRequest(cancel))=>{
let row:Option<(Vec<u8>,String,String)>=self.journal.connection().query_row("SELECT offer,state,grant_id FROM job_attempts WHERE job=?1 AND attempt=?2",rusqlite::params![cancel.job_id,cancel.attempt_id],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?))).optional()?;
if let Some((bytes,state,grant))=row {
self.journal.connection().execute("UPDATE job_attempts SET cancel_requested=1 WHERE job=?1 AND attempt=?2",rusqlite::params![cancel.job_id,cancel.attempt_id])?;
if let Some(running)=&self.running && running.offer.job_id==cancel.job_id && running.offer.attempt_id==cancel.attempt_id {running.cancel.store(true,Ordering::SeqCst);}
if state=="accepted" {self.record(generation,&JobOffer::decode(bytes.as_slice())?,&grant,jobs::no_start("cancelled","CANCELLED_BEFORE_START"))?;needs_sync=true;}
}
let ack=self.envelope(generation,Payload::Ack(Ack{message_id:message.message_id}))?;channel.send(&ack).await?;
},
_=>anyhow::bail!("UNSUPPORTED_SERVER_MESSAGE")
}
}
}
if stop.load(Ordering::SeqCst) {
continue;
}
if heartbeat.elapsed() >= heartbeat_after {
let payload = Payload::Heartbeat(Heartbeat {
instance_id: self.instance.clone(),
@@ -235,13 +882,10 @@ impl Agent {
heartbeat_after = Duration::from_millis(rand::random_range(27000..33000));
}
if replay.elapsed() >= Duration::from_secs(5) {
for mut event in self.journal.events()? {
event.connection_generation = generation;
channel.send(&event).await?;
}
self.replay(&channel, generation).await?;
replay = Instant::now();
}
if inventory.elapsed() >= Duration::from_secs(86400) {
if !stop.load(Ordering::SeqCst) && inventory.elapsed() >= Duration::from_secs(86400) {
self.queue_inventory(generation)?;
inventory = Instant::now();
}
@@ -258,6 +902,11 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
let path = Path::new(&arguments[2]);
ensure!(path.is_absolute(), "ABSOLUTE_CONFIG_REQUIRED");
let config: Config = serde_json::from_slice(&protected_read(path, 32768)?)?;
native::require_local_service()?;
ensure!(
config.state_directory.is_absolute(),
"ABSOLUTE_STATE_REQUIRED"
);
native::private_path(&config.state_directory, true)?;
ensure!(
crate::https_channel::server_name()? == config.server_name,
@@ -266,7 +915,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
let ca = protected_read(&config.ca_file, 32768)?;
for child in fs::read_dir(&config.state_directory)? {
let child = child?;
native::private_path(&child.path(), false)?;
native::private_path(&child.path(), child.file_type()?.is_dir())?;
}
let journal = Journal::open(&config.state_directory)?;
let runtime = tokio::runtime::Builder::new_multi_thread()
@@ -275,8 +924,20 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
.build()?;
runtime.block_on(async move {
let identity = enrollment(&config, &ca).await?;
let mut journal=journal;
journal.pin_identity(&identity.agent_id)?;
let boot = native::boot_id().await?;
let binding=config.job_binding_file.as_deref().map(readonly_binding).transpose()?;
if let Some(binding)=&binding {
ensure!(binding.agent_id.to_string()==identity.agent_id && binding.asset_id.to_string()==identity.asset_id,"ENROLLMENT_JOB_BINDING_MISMATCH");
native::private_path(&config.state_directory.join("jobs"),true)?;
import_legacy_inventory(&mut journal)?;
}
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 (completed_tx,completed_rx)=tokio::sync::mpsc::channel(1);
let mut agent = Agent {
config,
identity,
@@ -284,10 +945,23 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
journal,
boot,
instance: Uuid::new_v4().to_string(),
started: Instant::now(),
started: Instant::now(), binding, ledger, _ledger_file:ledger_file, clock, sync,
prepared:false,fence:Arc::new(EffectFence::default()),completed_tx,completed_rx,running:None,deferred_permit:None,
};
agent.recover_interrupted()?;
let mut backoff = 1;
while !stop.load(Ordering::SeqCst) {
while !stop.load(Ordering::SeqCst) || agent.running.is_some() {
if stop.load(Ordering::SeqCst) {
agent.close_gate();
if let Some(running)=&agent.running {running.cancel.store(true,Ordering::SeqCst);}
if let Ok(completion)=agent.completed_rx.try_recv(){agent.completed(0,completion)?;}
if agent.running.as_ref().is_some_and(|r|r.worker.is_finished()) {
let running=agent.running.as_ref().context("RUNNING_REQUIRED")?;
agent.completed(0,(running.offer.clone(),running.grant.clone(),Outcome::unknown("EXECUTOR_THREAD_INTERRUPTED")))?;
}
if agent.running.is_some() {tokio::select!{Some(completion)=agent.completed_rx.recv()=>agent.completed(0,completion)?,_=tokio::time::sleep(Duration::from_millis(250))=>{}}}
continue;
}
let start = Instant::now();
let _ = agent.session(stop).await;
if start.elapsed() > Duration::from_secs(60) {
@@ -296,7 +970,15 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
let delay = crate::https_channel::retry_delay(backoff);
backoff = (backoff + 1).min(6);
let until = Instant::now() + delay;
while !stop.load(Ordering::SeqCst) && Instant::now() < until {
while Instant::now() < until && (!stop.load(Ordering::SeqCst) || agent.running.is_some()) {
if stop.load(Ordering::SeqCst) {
agent.close_gate();if let Some(running)=&agent.running {running.cancel.store(true,Ordering::SeqCst);}
}
if let Ok(completion)=agent.completed_rx.try_recv(){agent.completed(0,completion)?;}
if agent.running.as_ref().is_some_and(|r|r.worker.is_finished()) {
let running=agent.running.as_ref().context("RUNNING_REQUIRED")?;
agent.completed(0,(running.offer.clone(),running.grant.clone(),Outcome::unknown("EXECUTOR_THREAD_INTERRUPTED")))?;
}
tokio::time::sleep(Duration::from_millis(250)).await;
}
}
@@ -307,7 +989,7 @@ pub fn main() -> Result<()> {
let args: Vec<String> = std::env::args().skip(1).collect();
if args == ["--help"] {
println!(
"Development Windows passive service. --service --config ABSOLUTE_PATH. No job executor or approval bypass."
"Development Windows service. --service --config ABSOLUTE_PATH. Jobs disabled by default; require qualified clock, provisioned signing binding, signed Sync and WebUI-authorized grant. No approval bypass."
);
return Ok(());
}
@@ -341,3 +1023,90 @@ pub fn main() -> Result<()> {
);
rmm_agent_windows::service::dispatch(service_run)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn old_passive_configuration_cannot_enable_jobs_or_read_the_clock() {
let config:Config=serde_json::from_value(serde_json::json!({"server_name":"example.invalid","connect_address":"127.0.0.1:443","ca_file":"C:/fixture/ca.pem","state_directory":"C:/fixture/state","enrollment_token_file":"C:/fixture/token","transport":"auto"})).unwrap();
assert!(!config.enable_jobs);
assert!(config.job_binding_file.is_none());
let clock = JobClock {
native: Arc::new(rmm_agent_windows::clock::NativeClock::new()),
enabled: config.enable_jobs,
};
assert_eq!(
clock.now().unwrap_err().to_string(),
"WINDOWS_JOBS_NOT_ENABLED"
);
}
#[test]
fn legacy_inventory_keeps_original_bytes_until_concrete_core_ack() {
let directory =
std::env::temp_dir().join(format!("windows-runtime-import-{}", Uuid::new_v4()));
fs::create_dir(&directory).unwrap();
let mut journal = Journal::open(&directory).unwrap();
journal.pin_identity("retained").unwrap();
let sequence = journal.next_sequence().unwrap();
let envelope = Envelope {
message_id: Uuid::new_v4().to_string(),
sequence,
payload: Some(Payload::InventorySnapshot(InventorySnapshot::default())),
..Default::default()
};
journal.save(&envelope).unwrap();
let mut original = envelope.encode_to_vec();
original.extend([0xf8, 0x07, 0x01]); // Unknown additive protobuf field must remain byte-exact.
journal
.connection()
.execute(
"UPDATE events SET payload=?1 WHERE id=?2",
rusqlite::params![&original, &envelope.message_id],
)
.unwrap();
import_legacy_inventory(&mut journal).unwrap();
for table in ["events", "job_events"] {
let bytes: Vec<u8> = journal
.connection()
.query_row(
&format!("SELECT payload FROM {table} WHERE id=?1"),
[&envelope.message_id],
|r| r.get(0),
)
.unwrap();
assert_eq!(bytes, original);
}
jobs::ack(journal.connection_mut(), &Uuid::new_v4().to_string()).unwrap();
assert_eq!(journal.count().unwrap(), 1);
import_legacy_inventory(&mut journal).unwrap(); // Exact same-ID copy is idempotent.
assert_eq!(journal.next_sequence().unwrap(), sequence + 1);
jobs::ack(journal.connection_mut(), &envelope.message_id).unwrap();
assert_eq!(journal.count().unwrap(), 0);
assert!(jobs::events(journal.connection()).unwrap().is_empty());
drop(journal);
fs::remove_dir_all(directory).unwrap();
}
#[test]
fn worker_fence_requires_same_generation_and_entire_clock_interval() {
struct Clock(chrono::DateTime<Utc>);
impl SyncClock for Clock {
fn now(&self) -> Result<chrono::DateTime<Utc>> {
Ok(self.0)
}
}
let now = Utc::now();
let fence = EffectFence::default();
fence.deadline.store(
(now + chrono::Duration::seconds(3)).timestamp_millis(),
Ordering::SeqCst,
);
assert!(!fence.allows(1, &Clock(now)));
fence.generation.store(1, Ordering::SeqCst);
assert!(fence.allows(1, &Clock(now)));
assert!(!fence.allows(2, &Clock(now)));
assert!(!fence.allows(1, &Clock(now + chrono::Duration::seconds(1))));
fence.close();
assert!(!fence.allows(1, &Clock(now)));
}
}