From 500cb7a33ee8424713a09ddafe43a7c2d6090f4f Mon Sep 17 00:00:00 2001 From: Kevin Janssen Date: Sat, 14 Nov 2026 02:39:39 +0100 Subject: [PATCH] Preserve Windows runtime state and qualify native guarded adapters --- crates/agent-windows/Cargo.toml | 9 + crates/agent-windows/build.rs | 51 + .../agent-windows/examples/clock_readiness.rs | 263 ++++ .../agent-windows/examples/runtime_state.rs | 117 ++ crates/agent-windows/native/clock_endpoints.c | 49 + crates/agent-windows/native/clock_rpc.c | 156 +++ crates/agent-windows/native/w32time.idl | 43 + crates/agent-windows/src/actions.rs | 202 +++ .../src/bin/rmm-helper-windows.rs | 10 + crates/agent-windows/src/clock.rs | 516 +++++++ crates/agent-windows/src/helper_ipc.rs | 1204 +++++++++++++++++ crates/agent-windows/src/helper_system.rs | 1173 ++++++++++++++++ crates/agent-windows/src/inventory.rs | 219 +++ crates/agent-windows/src/journal.rs | 211 ++- crates/agent-windows/src/lib.rs | 12 + crates/agent-windows/src/native.rs | 119 +- crates/agent-windows/src/process.rs | 406 ++++++ crates/agent-windows/src/runtime.rs | 817 ++++++++++- deploy/windows/client_bootstrap.py | 4 +- deploy/windows/clock_readiness.py | 208 +++ deploy/windows/runtime_upgrade.py | 493 +++++++ docs/handover.md | 17 + docs/implementation-status.md | 53 + docs/windows-clock-readiness.md | 229 ++++ docs/windows-gates.md | 8 +- tests/windows_clock_readiness.py | 61 + 26 files changed, 6606 insertions(+), 44 deletions(-) create mode 100644 crates/agent-windows/build.rs create mode 100644 crates/agent-windows/examples/clock_readiness.rs create mode 100644 crates/agent-windows/examples/runtime_state.rs create mode 100644 crates/agent-windows/native/clock_endpoints.c create mode 100644 crates/agent-windows/native/clock_rpc.c create mode 100644 crates/agent-windows/native/w32time.idl create mode 100644 crates/agent-windows/src/actions.rs create mode 100644 crates/agent-windows/src/bin/rmm-helper-windows.rs create mode 100644 crates/agent-windows/src/clock.rs create mode 100644 crates/agent-windows/src/helper_ipc.rs create mode 100644 crates/agent-windows/src/helper_system.rs create mode 100644 crates/agent-windows/src/inventory.rs create mode 100644 crates/agent-windows/src/process.rs create mode 100644 deploy/windows/clock_readiness.py create mode 100644 deploy/windows/runtime_upgrade.py create mode 100644 docs/windows-clock-readiness.md create mode 100644 tests/windows_clock_readiness.py diff --git a/crates/agent-windows/Cargo.toml b/crates/agent-windows/Cargo.toml index 97efd3b..f7e2edc 100644 --- a/crates/agent-windows/Cargo.toml +++ b/crates/agent-windows/Cargo.toml @@ -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 diff --git a/crates/agent-windows/build.rs b/crates/agent-windows/build.rs new file mode 100644 index 0000000..67662b9 --- /dev/null +++ b/crates/agent-windows/build.rs @@ -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"); +} diff --git a/crates/agent-windows/examples/clock_readiness.rs b/crates/agent-windows/examples/clock_readiness.rs new file mode 100644 index 0000000..ad9d72c --- /dev/null +++ b/crates/agent-windows/examples/clock_readiness.rs @@ -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 = OnceLock::new(); + static HANDLE: AtomicUsize = AtomicUsize::new(0); + static STAGE: AtomicUsize = AtomicUsize::new(0); + fn wide(s: &str) -> Vec { + 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 { + 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::())]; + 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::() }; + 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::() 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::() 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() + ); +} diff --git a/crates/agent-windows/examples/runtime_state.rs b/crates/agent-windows/examples/runtime_state.rs new file mode 100644 index 0000000..ddec8b7 --- /dev/null +++ b/crates/agent-windows/examples/runtime_state.rs @@ -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 = db + .prepare("SELECT agent FROM identity ORDER BY agent")? + .query_map([], |r| r.get(0))? + .collect::>()?; + 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::>()?; + 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>(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>(2)?.unwrap_or_default())))?.collect::>()?; + 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 { + 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); +} diff --git a/crates/agent-windows/native/clock_endpoints.c b/crates/agent-windows/native/clock_endpoints.c new file mode 100644 index 0000000..d9f9dbc --- /dev/null +++ b/crates/agent-windows/native/clock_endpoints.c @@ -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 +#include +#include +#include + +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; +} diff --git a/crates/agent-windows/native/clock_rpc.c b/crates/agent-windows/native/clock_rpc.c new file mode 100644 index 0000000..7367b42 --- /dev/null +++ b/crates/agent-windows/native/clock_rpc.c @@ -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 +#include +#include +#include +#include +#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; +} diff --git a/crates/agent-windows/native/w32time.idl b/crates/agent-windows/native/w32time.idl new file mode 100644 index 0000000..cfb4eac --- /dev/null +++ b/crates/agent-windows/native/w32time.idl @@ -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); +} diff --git a/crates/agent-windows/src/actions.rs b/crates/agent-windows/src/actions.rs new file mode 100644 index 0000000..5734572 --- /dev/null +++ b/crates/agent-windows/src/actions.rs @@ -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 { + 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, +} +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 { + 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 = ["-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 { + 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 { + 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"}), + }) +} diff --git a/crates/agent-windows/src/bin/rmm-helper-windows.rs b/crates/agent-windows/src/bin/rmm-helper-windows.rs new file mode 100644 index 0000000..5635313 --- /dev/null +++ b/crates/agent-windows/src/bin/rmm-helper-windows.rs @@ -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); +} diff --git a/crates/agent-windows/src/clock.rs b/crates/agent-windows/src/clock.rs new file mode 100644 index 0000000..ce89cb2 --- /dev/null +++ b/crates/agent-windows/src/clock.rs @@ -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, + pub query_ticks: u64, + pub error_bound_ticks: Option, + pub sample: Sample, +} +#[derive(Default)] +struct Continuity { + previous: Option, + require_sync_after: Option, +} +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 { + 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 { + 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, + 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> { + 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> { + 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>, + poisoned: bool, +} +#[cfg(any(windows, test))] +impl RpcWorker { + fn new(run: fn(bool) -> (u32, Status)) -> Self { + let (sender, receiver) = std::sync::mpsc::sync_channel::(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> = 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()); + } +} diff --git a/crates/agent-windows/src/helper_ipc.rs b/crates/agent-windows/src/helper_ipc.rs new file mode 100644 index 0000000..43438c4 --- /dev/null +++ b/crates/agent-windows/src/helper_ipc.rs @@ -0,0 +1,1204 @@ +//! Local, mutually pinned SYSTEM-helper pipe. This transport never approves jobs. +//! No generic write rights on the pipe: FILE_APPEND_DATA also creates instances. +use anyhow::{Context, Result, ensure}; +use rmm_agent_core::{ + auth::{Binding, Outcome, Request}, + helper_reconcile::{SignedResponse, Snapshot}, +}; +use rmm_domain::jobs::hash; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; +use std::{ + ffi::c_void, + fs::File, + io::{Read, Write}, + mem::{size_of, zeroed}, + os::windows::{ + ffi::OsStrExt, + io::{AsRawHandle, FromRawHandle, OwnedHandle}, + }, + path::{Path, PathBuf}, + ptr, + time::{Duration, Instant}, +}; +use uuid::Uuid; +use windows_sys::Win32::{ + Foundation::*, + Security::{Authorization::*, *}, + Storage::FileSystem::*, + System::{IO::*, Pipes::*, Services::*, Threading::*}, +}; + +pub const HELPER_SERVICE: &str = "RmmDiscoverySystemHelper"; +pub const PIPE_NAME: &str = r"\\.\pipe\RustDiscovery-System-v1"; +pub const FRAME_LIMIT: usize = 1024 * 1024; +pub const CLIENT_PIPE_RIGHTS: u32 = 0x0012_0083; // data R/W, attributes R, RC, synchronize; no bit4 +const READ_MASK: u32 = 0x0012_00a9; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PeerPin { + pub service_name: String, + pub service_sid: String, + pub user_sid: String, + pub binary: PathBuf, + pub binary_sha256: String, +} +impl PeerPin { + pub fn validate(&self, helper: bool) -> Result<()> { + let name = if helper { + HELPER_SERVICE + } else { + crate::SERVICE_NAME + }; + ensure!( + self.service_name == name + && self.user_sid == if helper { "S-1-5-18" } else { "S-1-5-19" }, + "HELPER_PEER_ROLE" + ); + ensure!( + self.service_sid == service_sid(name)? && digest(&self.binary_sha256), + "HELPER_PEER_PIN" + ); + ensure!( + self.binary + == Path::new(if helper { + r"C:\Program Files\RustDiscovery\rmm-helper-windows.exe" + } else { + r"C:\Program Files\RustDiscovery\rmm-agent-windows.exe" + }), + "HELPER_FIXED_IMAGE" + ); + Ok(()) + } + fn command(&self) -> String { + if self.service_name == HELPER_SERVICE { + format!("\"{}\" --service", self.binary.display()) + } else if self.service_name == crate::SERVICE_NAME { + format!( + "\"{}\" --service --config \"C:\\ProgramData\\RustDiscovery\\config.json\"", + self.binary.display() + ) + } else { + format!("\"{}\"", self.binary.display()) + } + } +} +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Pin { + pub schema_version: u32, + pub binding: Binding, + pub policy_sha256: String, + pub agent: PeerPin, + pub helper: PeerPin, +} +impl Pin { + pub fn validate(&self) -> Result<()> { + ensure!( + self.schema_version == 1 && digest(&self.policy_sha256), + "HELPER_PIN_PROFILE" + ); + self.agent.validate(false)?; + self.helper.validate(true)?; + Ok(()) + } +} +#[derive(Clone, Serialize, Deserialize)] +#[serde(tag = "operation", rename_all = "snake_case", deny_unknown_fields)] +pub enum Operation { + Probe {}, + Snapshot { + generation: u64, + }, + Apply { + response: SignedResponse, + request_bytes: Vec, + }, + Execute { + generation: u64, + request: Request, + }, +} +#[derive(Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Call { + pub schema_version: u32, + pub challenge: Uuid, + pub binding: Binding, + pub policy_sha256: String, + pub operation: Operation, +} +impl Call { + pub fn new(pin: &Pin, operation: Operation) -> Self { + Self { + schema_version: 1, + challenge: Uuid::new_v4(), + binding: pin.binding.clone(), + policy_sha256: pin.policy_sha256.clone(), + operation, + } + } +} +#[derive(Debug, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum ReplyBody { + Probe { + clock_qualified: bool, + ready: bool, + ledger: FileIdentity, + lock: FileIdentity, + }, + Snapshot { + snapshot: Snapshot, + }, + Applied { + snapshot: Snapshot, + unlocked_grants: Vec, + ready: bool, + }, + Executed { + outcome: Outcome, + }, + Denied { + code: String, + }, +} +#[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Reply { + pub schema_version: u32, + pub challenge: Uuid, + pub binding_sha256: String, + pub policy_sha256: String, + pub helper_binary_sha256: String, + pub body: ReplyBody, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct FileIdentity { + pub volume_serial: u64, + pub file_id: [u8; 16], +} +pub fn digest(s: &str) -> bool { + s.len() == 64 + && s.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} +pub fn binding_hash(b: &Binding) -> Result { + Ok(hash(&serde_json::to_vec(b)?)) +} +pub fn wide(s: impl AsRef) -> Vec { + s.as_ref().encode_wide().chain(Some(0)).collect() +} +fn owned(raw: HANDLE) -> Result { + ensure!( + !raw.is_null() && raw != INVALID_HANDLE_VALUE, + "HELPER_HANDLE" + ); + Ok(unsafe { OwnedHandle::from_raw_handle(raw) }) +} +fn sid_text(sid: PSID) -> Result { + let mut text = ptr::null_mut(); + ensure!( + unsafe { ConvertSidToStringSidW(sid, &mut text) } != 0, + "HELPER_SID_TEXT" + ); + let mut n = 0; + unsafe { + while n < 256 && *text.add(n) != 0 { + n += 1; + } + }; + let result = if n < 256 { + String::from_utf16(unsafe { std::slice::from_raw_parts(text, n) })? + } else { + String::new() + }; + unsafe { + LocalFree(text.cast()); + } + ensure!(!result.is_empty(), "HELPER_SID_SIZE"); + Ok(result) +} +pub fn service_sid(name: &str) -> Result { + let name = wide(format!("NT SERVICE\\{name}")); + let mut length = 0; + let mut domain_length = 0; + let mut use_type = 0; + unsafe { + LookupAccountNameW( + ptr::null(), + name.as_ptr(), + ptr::null_mut(), + &mut length, + ptr::null_mut(), + &mut domain_length, + &mut use_type, + ); + } + ensure!( + (1..=256).contains(&length) && domain_length <= 256, + "HELPER_SERVICE_SID_SIZE" + ); + let mut sid = vec![0usize; (length as usize).div_ceil(size_of::())]; + let mut domain = vec![0u16; domain_length as usize]; + ensure!( + unsafe { + LookupAccountNameW( + ptr::null(), + name.as_ptr(), + sid.as_mut_ptr().cast(), + &mut length, + domain.as_mut_ptr(), + &mut domain_length, + &mut use_type, + ) + } != 0, + "HELPER_SERVICE_SID" + ); + sid_text(sid.as_mut_ptr().cast()) +} +fn token_information(token: HANDLE, class: TOKEN_INFORMATION_CLASS) -> Result> { + let mut needed = 0; + unsafe { + GetTokenInformation(token, class, ptr::null_mut(), 0, &mut needed); + } + ensure!((1..=65536).contains(&needed), "HELPER_TOKEN_SIZE"); + let mut data = vec![0usize; (needed as usize).div_ceil(size_of::())]; + ensure!( + unsafe { GetTokenInformation(token, class, data.as_mut_ptr().cast(), needed, &mut needed) } + != 0, + "HELPER_TOKEN_INFORMATION" + ); + Ok(data) +} +pub fn verify_token(token: HANDLE, user: &str, service: &str) -> Result<()> { + let u = token_information(token, TokenUser)?; + ensure!( + sid_text(unsafe { (*u.as_ptr().cast::()).User.Sid })? == user, + "HELPER_TOKEN_USER" + ); + let groups = token_information(token, TokenGroups)?; + let g = unsafe { &*groups.as_ptr().cast::() }; + let count = g.GroupCount as usize; + let offset = std::mem::offset_of!(TOKEN_GROUPS, Groups); + ensure!( + count <= 1024 + && offset + count * size_of::() + <= groups.len() * size_of::(), + "HELPER_TOKEN_GROUPS_SIZE" + ); + let rows = unsafe { std::slice::from_raw_parts(g.Groups.as_ptr(), count) }; + let mut found = false; + for row in rows { + let sid = sid_text(row.Sid)?; + ensure!( + user != "S-1-5-19" || sid != "S-1-5-32-544" || row.Attributes & 0x0000_0004 == 0, + "HELPER_NETWORK_AGENT_ADMIN_FORBIDDEN" + ); + // TOKEN_GROUPS SE_GROUP_ENABLED and SE_GROUP_USE_FOR_DENY_ONLY (winnt.h). + if row.Attributes & 0x0000_0004 != 0 && row.Attributes & 0x0000_0010 == 0 && sid == service + { + found = true; + } + } + ensure!(found, "HELPER_SERVICE_SID_NOT_ENABLED"); + Ok(()) +} +pub fn require_self(peer: &PeerPin) -> Result<()> { + let mut thread = ptr::null_mut(); + if unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, 1, &mut thread) } != 0 { + let _ = owned(thread)?; + anyhow::bail!("HELPER_IMPERSONATED_SELF"); + } + ensure!( + unsafe { GetLastError() } == ERROR_NO_TOKEN, + "HELPER_THREAD_TOKEN_UNVERIFIED" + ); + let mut token = ptr::null_mut(); + ensure!( + unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } != 0, + "HELPER_SELF_TOKEN" + ); + let token = owned(token)?; + verify_token(token.as_raw_handle(), &peer.user_sid, &peer.service_sid) +} +fn check_acl(handle: HANDLE, readers: &[String], writers: &[String]) -> Result<()> { + let mut owner = ptr::null_mut(); + let mut acl = ptr::null_mut(); + let mut descriptor = ptr::null_mut(); + ensure!( + unsafe { + GetSecurityInfo( + handle, + SE_FILE_OBJECT, + OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, + &mut owner, + ptr::null_mut(), + &mut acl, + ptr::null_mut(), + &mut descriptor, + ) + } == 0, + "HELPER_PATH_SECURITY" + ); + let result = (|| { + ensure!(!owner.is_null() && !acl.is_null(), "HELPER_NULL_DACL"); + let owner = sid_text(owner)?; + ensure!( + matches!(owner.as_str(), "S-1-5-18" | "S-1-5-32-544"), + "HELPER_PATH_OWNER" + ); + ensure!(unsafe { (*acl).AceCount } > 0, "HELPER_EMPTY_DACL"); + for n in 0..unsafe { (*acl).AceCount } { + let mut ace = ptr::null_mut(); + ensure!( + unsafe { GetAce(acl, n.into(), &mut ace) } != 0, + "HELPER_PATH_ACE" + ); + let ace = unsafe { &*ace.cast::() }; + ensure!( + ace.Header.AceType == 0 + && ace.Header.AceSize as usize >= size_of::(), + "HELPER_PATH_ACE_TYPE" + ); + let sid = sid_text(ptr::addr_of!(ace.SidStart).cast_mut().cast())?; + let privileged = + matches!(sid.as_str(), "S-1-5-18" | "S-1-5-32-544") || writers.contains(&sid); + ensure!( + privileged || (readers.contains(&sid) && ace.Mask & !READ_MASK == 0), + "HELPER_PATH_WRITABLE_OR_FOREIGN" + ); + } + Ok(()) + })(); + unsafe { + LocalFree(descriptor.cast()); + } + result +} +pub struct PinnedFile { + pub file: File, + pub identity: FileIdentity, + pub path: PathBuf, + readers: Vec, + writers: Vec, + directory: bool, +} +impl PinnedFile { + pub fn open( + path: &Path, + directory: bool, + readers: &[String], + writers: &[String], + write: bool, + ) -> Result { + ensure!( + path.is_absolute() + && !path.to_string_lossy().starts_with(r"\\") + && !path.to_string_lossy().contains("..") + && !path.as_os_str().encode_wide().any(|c| c == 0), + "HELPER_LOCAL_ABSOLUTE_PATH" + ); + for ancestor in path.ancestors().skip(1) { + let handle = owned(unsafe { + CreateFileW( + wide(ancestor).as_ptr(), + FILE_READ_ATTRIBUTES, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + ptr::null(), + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, + ptr::null_mut(), + ) + })?; + let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() }; + ensure!( + unsafe { GetFileInformationByHandle(handle.as_raw_handle(), &mut info) } != 0 + && info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0, + "HELPER_REPARSE_ANCESTOR" + ); + } + let raw = unsafe { + CreateFileW( + wide(path).as_ptr(), + if write { + GENERIC_READ | GENERIC_WRITE + } else { + GENERIC_READ + }, + FILE_SHARE_READ | if write { FILE_SHARE_WRITE } else { 0 }, + ptr::null(), + OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT + | if directory { + FILE_FLAG_BACKUP_SEMANTICS + } else { + 0 + }, + ptr::null_mut(), + ) + }; + let handle = owned(raw)?; + let file: File = handle.into(); + let mut value = Self { + identity: file_identity(&file)?, + file, + path: path.into(), + readers: readers.into(), + writers: writers.into(), + directory, + }; + value.check()?; + Ok(value) + } + pub fn check(&mut self) -> Result<()> { + let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() }; + ensure!( + unsafe { GetFileInformationByHandle(self.file.as_raw_handle(), &mut info) } != 0, + "HELPER_FILE_INFORMATION" + ); + ensure!( + info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0 + && (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0) == self.directory, + "HELPER_FILE_TYPE" + ); + ensure!( + file_identity(&self.file)? == self.identity, + "HELPER_FILE_ID_CHANGED" + ); + check_acl(self.file.as_raw_handle(), &self.readers, &self.writers)?; + let raw = unsafe { + CreateFileW( + wide(&self.path).as_ptr(), + FILE_READ_ATTRIBUTES, + FILE_SHARE_READ | FILE_SHARE_WRITE, + ptr::null(), + OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT + | if self.directory { + FILE_FLAG_BACKUP_SEMANTICS + } else { + 0 + }, + ptr::null_mut(), + ) + }; + let check = owned(raw)?; + ensure!( + file_identity(&check)? == self.identity, + "HELPER_PATH_REPLACED" + ); + Ok(()) + } + pub fn sha256(&mut self) -> Result { + use std::io::{Seek, SeekFrom}; + ensure!( + !self.directory && self.file.metadata()?.len() <= 128 * 1024 * 1024, + "HELPER_IMAGE_SIZE" + ); + self.file.seek(SeekFrom::Start(0))?; + let mut h = sha2::Sha256::new(); + use sha2::Digest; + let mut buf = [0u8; 65536]; + loop { + let n = self.file.read(&mut buf)?; + if n == 0 { + break; + } + h.update(&buf[..n]); + } + Ok(h.finalize().iter().map(|b| format!("{b:02x}")).collect()) + } +} +pub fn file_identity(handle: &impl AsRawHandle) -> Result { + let mut id: FILE_ID_INFO = unsafe { zeroed() }; + ensure!( + unsafe { + GetFileInformationByHandleEx( + handle.as_raw_handle(), + FileIdInfo, + (&mut id as *mut FILE_ID_INFO).cast(), + size_of::() as u32, + ) + } != 0, + "HELPER_FILE_ID" + ); + Ok(FileIdentity { + volume_serial: id.VolumeSerialNumber, + file_id: id.FileId.Identifier, + }) +} + +struct ServiceHandle(SC_HANDLE); +impl Drop for ServiceHandle { + fn drop(&mut self) { + unsafe { + CloseServiceHandle(self.0); + } + } +} +fn service_status(pin: &PeerPin) -> Result { + let manager = + ServiceHandle(unsafe { OpenSCManagerW(ptr::null(), ptr::null(), SC_MANAGER_CONNECT) }); + ensure!(!manager.0.is_null(), "HELPER_SCM_MANAGER"); + let service = ServiceHandle(unsafe { + OpenServiceW( + manager.0, + wide(&pin.service_name).as_ptr(), + SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG, + ) + }); + ensure!(!service.0.is_null(), "HELPER_SCM_SERVICE"); + let mut needed = 0; + unsafe { + QueryServiceConfigW(service.0, ptr::null_mut(), 0, &mut needed); + }; + ensure!((1..=32768).contains(&needed), "HELPER_SCM_CONFIG_SIZE"); + let mut config = vec![0usize; (needed as usize).div_ceil(size_of::())]; + ensure!( + unsafe { QueryServiceConfigW(service.0, config.as_mut_ptr().cast(), needed, &mut needed) } + != 0, + "HELPER_SCM_CONFIG" + ); + let c = unsafe { &*config.as_ptr().cast::() }; + ensure!( + c.dwServiceType == SERVICE_WIN32_OWN_PROCESS + && unsafe { utf16_pointer(c.lpBinaryPathName) }? == pin.command(), + "HELPER_SCM_IMAGE_BINDING" + ); + let mut status: SERVICE_STATUS_PROCESS = unsafe { zeroed() }; + ensure!( + unsafe { + QueryServiceStatusEx( + service.0, + SC_STATUS_PROCESS_INFO, + (&mut status as *mut SERVICE_STATUS_PROCESS).cast(), + size_of::() as u32, + &mut needed, + ) + } != 0 + && status.dwCurrentState == SERVICE_RUNNING + && status.dwProcessId > 0, + "HELPER_SCM_NOT_RUNNING" + ); + Ok(status.dwProcessId) +} +/// # Safety +/// `value` must point into a held successful Windows API result with a valid +/// NUL-terminated UTF16 string; the owning result must outlive this call. +pub unsafe fn utf16_pointer(value: *const u16) -> Result { + ensure!(!value.is_null(), "HELPER_STRING_POINTER"); + let mut n = 0; + while n < 32768 && unsafe { *value.add(n) } != 0 { + n += 1; + } + ensure!(n < 32768, "HELPER_STRING_BOUND"); + Ok(String::from_utf16(unsafe { + std::slice::from_raw_parts(value, n) + })?) +} +fn creation(handle: HANDLE) -> Result { + let (mut c, mut e, mut k, mut u) = unsafe { (zeroed(), zeroed(), zeroed(), zeroed()) }; + ensure!( + unsafe { GetProcessTimes(handle, &mut c, &mut e, &mut k, &mut u) } != 0, + "HELPER_PROCESS_TIME" + ); + Ok((u64::from(c.dwHighDateTime) << 32) | u64::from(c.dwLowDateTime)) +} +pub struct PeerProof { + process: OwnedHandle, + creation: u64, + pin: PeerPin, + _image: PinnedFile, + _image_parent: PinnedFile, + pid: u32, + identity: ProcessIdentity, +} +#[derive(Clone, Debug, Serialize)] +pub(crate) struct ProcessIdentity { + pub pid: u32, + pub creation_ticks: u64, + pub user_sid: String, + pub service_sid: String, + pub image: PathBuf, + pub image_sha256: String, + pub image_file: FileIdentity, +} +impl ProcessIdentity { + pub(crate) fn validate(&self, pin: &PeerPin, expected_pid: u32) -> Result<()> { + ensure!( + self.pid == expected_pid && expected_pid > 0 && self.creation_ticks > 0, + "HELPER_PROCESS_IDENTITY" + ); + ensure!( + self.user_sid == pin.user_sid && self.service_sid == pin.service_sid, + "HELPER_PROCESS_TOKEN_IDENTITY" + ); + ensure!( + self.image == pin.binary && self.image_sha256 == pin.binary_sha256, + "HELPER_PROCESS_IMAGE_IDENTITY" + ); + Ok(()) + } +} +impl PeerProof { + fn capture(pipe: HANDLE, pin: &PeerPin, client: bool) -> Result { + let mut pid = 0; + ensure!( + unsafe { + if client { + GetNamedPipeClientProcessId(pipe, &mut pid) + } else { + GetNamedPipeServerProcessId(pipe, &mut pid) + } + } != 0 + && pid > 0, + "HELPER_PIPE_SCM_PID" + ); + Self::for_service(pin, pid) + } + /// Internal fixture admission shares the exact same live-process proof as + /// both pipe peers. The caller supplies the PID read from its held SCM handle. + pub(crate) fn for_service(pin: &PeerPin, pid: u32) -> Result { + ensure!(pid == service_status(pin)?, "HELPER_PIPE_SCM_PID"); + let process = + owned(unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, 0, pid) })?; + let born = creation(process.as_raw_handle())?; + let mut token = ptr::null_mut(); + ensure!( + unsafe { OpenProcessToken(process.as_raw_handle(), TOKEN_QUERY, &mut token) } != 0, + "HELPER_PEER_TOKEN_QUERY" + ); + let token = owned(token)?; + verify_token(token.as_raw_handle(), &pin.user_sid, &pin.service_sid)?; + let actual_user = token_information(token.as_raw_handle(), TokenUser)?; + let actual_user = + sid_text(unsafe { (*actual_user.as_ptr().cast::()).User.Sid })?; + let mut image = vec![0u16; 32768]; + let mut length = image.len() as u32; + ensure!( + unsafe { + QueryFullProcessImageNameW( + process.as_raw_handle(), + 0, + image.as_mut_ptr(), + &mut length, + ) + } != 0, + "HELPER_PROCESS_IMAGE" + ); + let image_name = String::from_utf16(&image[..length as usize])?; + ensure!( + Path::new(&image_name) == pin.binary, + "HELPER_PROCESS_IMAGE_BINDING" + ); + let image_parent = PinnedFile::open( + pin.binary.parent().context("HELPER_IMAGE_PARENT")?, + true, + &[ + service_sid(crate::SERVICE_NAME)?, + service_sid(HELPER_SERVICE)?, + pin.service_sid.clone(), + ], + &[], + false, + )?; + let mut image = PinnedFile::open( + &pin.binary, + false, + &[ + pin.service_sid.clone(), + service_sid(crate::SERVICE_NAME)?, + service_sid(HELPER_SERVICE)?, + ], + &[], + false, + )?; + let actual_hash = image.sha256()?; + ensure!(actual_hash == pin.binary_sha256, "HELPER_BINARY_HASH"); + let identity = ProcessIdentity { + pid, + creation_ticks: born, + user_sid: actual_user, + service_sid: pin.service_sid.clone(), + image: image_name.into(), + image_sha256: actual_hash, + image_file: image.identity, + }; + identity.validate(pin, pid)?; + let mut result = Self { + process, + creation: born, + pin: pin.clone(), + _image: image, + _image_parent: image_parent, + pid, + identity, + }; + result.check()?; + Ok(result) + } + pub fn check(&mut self) -> Result<()> { + ensure!( + unsafe { WaitForSingleObject(self.process.as_raw_handle(), 0) } == WAIT_TIMEOUT + && creation(self.process.as_raw_handle())? == self.creation + && service_status(&self.pin)? == self.pid, + "HELPER_PEER_RESTARTED" + ); + let mut token = ptr::null_mut(); + ensure!( + unsafe { OpenProcessToken(self.process.as_raw_handle(), TOKEN_QUERY, &mut token) } != 0, + "HELPER_PEER_TOKEN_RECHECK" + ); + let token = owned(token)?; + verify_token( + token.as_raw_handle(), + &self.pin.user_sid, + &self.pin.service_sid, + )?; + self._image_parent.check()?; + self._image.check() + } + pub(crate) fn identity(&self) -> &ProcessIdentity { + &self.identity + } + pub(crate) fn exited(&self) -> Result { + ensure!( + creation(self.process.as_raw_handle())? == self.creation, + "HELPER_PROCESS_IDENTITY" + ); + let state = unsafe { WaitForSingleObject(self.process.as_raw_handle(), 0) }; + ensure!( + matches!(state, WAIT_OBJECT_0 | WAIT_TIMEOUT), + "HELPER_PROCESS_EXIT_QUERY" + ); + Ok(state == WAIT_OBJECT_0) + } +} + +struct Descriptor(*mut c_void); +impl Descriptor { + fn from(s: &str) -> Result { + let mut descriptor = ptr::null_mut(); + ensure!( + unsafe { + ConvertStringSecurityDescriptorToSecurityDescriptorW( + wide(s).as_ptr(), + 1, + &mut descriptor, + ptr::null_mut(), + ) + } != 0, + "HELPER_DESCRIPTOR" + ); + Ok(Self(descriptor)) + } +} +impl Drop for Descriptor { + fn drop(&mut self) { + unsafe { + LocalFree(self.0); + } + } +} +/// Read-only visibility into these TWO OWN objects; never grant SeDebug or token duplication. +pub fn publish_self_query_rights(agent_sid: &str, helper_sid: &str) -> Result<()> { + ensure!( + agent_sid == service_sid(crate::SERVICE_NAME)? + && helper_sid == service_sid(HELPER_SERVICE)?, + "HELPER_QUERY_RIGHTS_ROLE" + ); + let mut token = ptr::null_mut(); + ensure!( + unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | WRITE_DAC, &mut token) } != 0, + "HELPER_SELF_TOKEN_DACL" + ); + let token = owned(token)?; + verify_token(token.as_raw_handle(), "S-1-5-18", helper_sid)?; + for (handle, rights) in [ + ( + unsafe { GetCurrentProcess() }, + PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, + ), + (token.as_raw_handle(), TOKEN_QUERY), + ] { + let d = Descriptor::from(&format!( + "O:SYG:SYD:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;{helper_sid})(A;;0x{rights:08x};;;{agent_sid})" + ))?; + ensure!( + unsafe { SetKernelObjectSecurity(handle, DACL_SECURITY_INFORMATION, d.0) } != 0, + "HELPER_OWN_QUERY_DACL" + ); + } + Ok(()) +} +fn pipe_descriptor(agent: &str, helper: &str) -> Result { + ensure!( + agent == service_sid(crate::SERVICE_NAME)? && helper == service_sid(HELPER_SERVICE)?, + "HELPER_PIPE_SID_BINDING" + ); + Descriptor::from(&format!( + "O:SYG:SYD:P(D;;GA;;;NU)(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;{helper})(A;;0x{CLIENT_PIPE_RIGHTS:08x};;;{agent})" + )) +} + +struct IoEvent { + event: OwnedHandle, + overlapped: OVERLAPPED, +} +impl IoEvent { + fn new() -> Result { + let event = owned(unsafe { CreateEventW(ptr::null(), 1, 0, ptr::null()) })?; + let mut overlapped: OVERLAPPED = unsafe { zeroed() }; + overlapped.hEvent = event.as_raw_handle(); + Ok(Self { event, overlapped }) + } + fn wait(&mut self, pipe: HANDLE, deadline: Instant) -> Result { + let left = deadline.saturating_duration_since(Instant::now()); + let milliseconds = u32::try_from(left.as_millis().max(1)).unwrap_or(u32::MAX - 1); + if unsafe { WaitForSingleObject(self.event.as_raw_handle(), milliseconds) } != WAIT_OBJECT_0 + { + unsafe { + CancelIoEx(pipe, &self.overlapped); + } + // Never free an OVERLAPPED/buffer still owned by the kernel. A failed + // bounded cancellation is terminal for this process; no unwind. + if unsafe { WaitForSingleObject(self.event.as_raw_handle(), 1000) } != WAIT_OBJECT_0 { + std::process::abort(); + } + let mut count = 0; + if unsafe { GetOverlappedResult(pipe, &self.overlapped, &mut count, 0) } == 0 + && unsafe { GetLastError() } == ERROR_IO_INCOMPLETE + { + std::process::abort(); + } + anyhow::bail!("HELPER_PIPE_TIMEOUT"); + } + let mut count = 0; + let complete = unsafe { GetOverlappedResult(pipe, &self.overlapped, &mut count, 0) }; + if complete == 0 && unsafe { GetLastError() } == ERROR_IO_INCOMPLETE { + std::process::abort(); + } + ensure!(complete != 0, "HELPER_PIPE_IO"); + Ok(count) + } +} +fn transfer(pipe: HANDLE, bytes: &mut [u8], write: bool, deadline: Instant) -> Result<()> { + let mut offset = 0; + while offset < bytes.len() { + ensure!(Instant::now() < deadline, "HELPER_PIPE_TIMEOUT"); + let mut operation = IoEvent::new()?; + let part = &mut bytes[offset..]; + let mut done = 0; + let ok = unsafe { + if write { + WriteFile( + pipe, + part.as_ptr(), + part.len().try_into()?, + &mut done, + &mut operation.overlapped, + ) + } else { + ReadFile( + pipe, + part.as_mut_ptr(), + part.len().try_into()?, + &mut done, + &mut operation.overlapped, + ) + } + }; + let count = if ok != 0 { + done + } else { + ensure!( + unsafe { GetLastError() } == ERROR_IO_PENDING, + "HELPER_PIPE_IO" + ); + operation.wait(pipe, deadline)? + }; + ensure!(count > 0 && count as usize <= part.len(), "HELPER_PIPE_EOF"); + offset += count as usize; + } + Ok(()) +} +struct LimitedJson(Vec); +impl Write for LimitedJson { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + if bytes.len() > FRAME_LIMIT - self.0.len() { + return Err(std::io::Error::other("HELPER_FRAME_CAPACITY")); + } + self.0.extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} +fn encode(value: &impl Serialize) -> Result> { + let mut writer = LimitedJson(Vec::with_capacity(FRAME_LIMIT)); + serde_json::to_writer(&mut writer, value)?; + ensure!(!writer.0.is_empty(), "HELPER_FRAME_EMPTY"); + Ok(writer.0) +} +fn send(pipe: HANDLE, value: &impl Serialize, deadline: Instant) -> Result<()> { + let mut bytes = encode(value)?; + let mut header = u32::try_from(bytes.len())?.to_be_bytes(); + transfer(pipe, &mut header, true, deadline)?; + transfer(pipe, &mut bytes, true, deadline) +} +fn frame_length(header: [u8; 4]) -> Result { + let len = u32::from_be_bytes(header) as usize; + ensure!((1..=FRAME_LIMIT).contains(&len), "HELPER_FRAME_LENGTH"); + Ok(len) +} +fn length(pipe: HANDLE, deadline: Instant) -> Result { + let mut header = [0u8; 4]; + transfer(pipe, &mut header, false, deadline)?; + frame_length(header) +} +fn body(pipe: HANDLE, len: usize, deadline: Instant) -> Result { + ensure!((1..=FRAME_LIMIT).contains(&len), "HELPER_FRAME_LENGTH"); + let mut bytes = vec![0u8; len]; + transfer(pipe, &mut bytes, false, deadline)?; + Ok(serde_json::from_slice(&bytes)?) +} + +pub struct Server { + pipe: OwnedHandle, + pin: Pin, +} +pub struct Received { + pub call: Call, + pub peer: PeerProof, +} +impl Server { + pub fn bind(pin: Pin) -> Result { + pin.validate()?; + require_self(&pin.helper)?; + let descriptor = pipe_descriptor(&pin.agent.service_sid, &pin.helper.service_sid)?; + let security = SECURITY_ATTRIBUTES { + nLength: size_of::() as u32, + lpSecurityDescriptor: descriptor.0, + bInheritHandle: 0, + }; + let pipe = owned(unsafe { + CreateNamedPipeW( + wide(PIPE_NAME).as_ptr(), + PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE, + PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS, + 1, + 65536, + 65536, + 1000, + &security, + ) + })?; + Ok(Self { pipe, pin }) + } + pub fn receive(&self) -> Result> { + let pipe = self.pipe.as_raw_handle(); + let mut connect = IoEvent::new()?; + let connected = unsafe { ConnectNamedPipe(pipe, &mut connect.overlapped) }; + if connected == 0 { + let error = unsafe { GetLastError() }; + if error == ERROR_IO_PENDING { + if connect + .wait(pipe, Instant::now() + Duration::from_millis(250)) + .is_err() + { + unsafe { + DisconnectNamedPipe(pipe); + } + return Ok(None); + } + } else { + ensure!(error == ERROR_PIPE_CONNECTED, "HELPER_PIPE_CONNECT"); + } + } + let deadline = Instant::now() + Duration::from_secs(5); + let len = length(pipe, deadline)?; + let mut peer = PeerProof::capture(pipe, &self.pin.agent, true)?; + ensure!( + unsafe { ImpersonateNamedPipeClient(pipe) } != 0, + "HELPER_PIPE_IMPERSONATION" + ); + let auth = (|| { + let mut token = ptr::null_mut(); + ensure!( + unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, 1, &mut token) } != 0, + "HELPER_PIPE_IMPERSONATED_TOKEN" + ); + let token = owned(token)?; + verify_token( + token.as_raw_handle(), + &self.pin.agent.user_sid, + &self.pin.agent.service_sid, + ) + })(); + if unsafe { RevertToSelf() } == 0 { + std::process::abort(); + } + auth?; + require_self(&self.pin.helper)?; + let call: Call = body(pipe, len, deadline)?; + ensure!( + call.schema_version == 1 + && !call.challenge.is_nil() + && call.policy_sha256 == self.pin.policy_sha256 + && binding_hash(&call.binding)? == binding_hash(&self.pin.binding)?, + "HELPER_CALL_BINDING" + ); + peer.check()?; + Ok(Some(Received { call, peer })) + } + pub fn reply(&self, value: &Reply) -> Result<()> { + send( + self.pipe.as_raw_handle(), + value, + Instant::now() + Duration::from_secs(5), + ) + } + pub fn disconnect(&self) { + unsafe { + DisconnectNamedPipe(self.pipe.as_raw_handle()); + } + } +} +/// Blocking SDK call; run on the agent's bounded blocking worker, never heartbeat reactor. +pub fn exchange(pin: &Pin, call: &Call, timeout: Duration) -> Result { + pin.validate()?; + require_self(&pin.agent)?; + ensure!( + (Duration::from_secs(1)..=Duration::from_secs(125)).contains(&timeout), + "HELPER_CALL_TIMEOUT_BOUND" + ); + let deadline = Instant::now() + timeout; + let pipe = owned(unsafe { + CreateFileW( + wide(PIPE_NAME).as_ptr(), + CLIENT_PIPE_RIGHTS, + 0, + ptr::null(), + OPEN_EXISTING, + FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, + ptr::null_mut(), + ) + }) + .context("HELPER_PIPE_UNAVAILABLE_OR_BUSY")?; + let mut peer = PeerProof::capture(pipe.as_raw_handle(), &pin.helper, false)?; + send(pipe.as_raw_handle(), call, deadline)?; + let len = length(pipe.as_raw_handle(), deadline)?; + let reply: Reply = body(pipe.as_raw_handle(), len, deadline)?; + peer.check()?; + ensure!( + reply.schema_version == 1 + && reply.challenge == call.challenge + && reply.binding_sha256 == binding_hash(&pin.binding)? + && reply.policy_sha256 == pin.policy_sha256 + && reply.helper_binary_sha256 == pin.helper.binary_sha256, + "HELPER_REPLY_BINDING" + ); + ensure!( + matches!( + (&call.operation, &reply.body), + (_, ReplyBody::Denied { .. }) + | (Operation::Probe { .. }, ReplyBody::Probe { .. }) + | (Operation::Snapshot { .. }, ReplyBody::Snapshot { .. }) + | (Operation::Apply { .. }, ReplyBody::Applied { .. }) + | (Operation::Execute { .. }, ReplyBody::Executed { .. }) + ), + "HELPER_REPLY_OPERATION" + ); + Ok(reply) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn pipe_client_rights_cannot_create_an_instance() { + assert_eq!(CLIENT_PIPE_RIGHTS & 4, 0); + assert_eq!( + CLIENT_PIPE_RIGHTS & (GENERIC_WRITE | GENERIC_ALL | WRITE_DAC | WRITE_OWNER | DELETE), + 0 + ); + } + #[test] + fn serialization_refuses_oversized_frame() { + assert!(encode(&vec![255u8; FRAME_LIMIT]).is_err()); + assert!(encode(&vec![1u8; 32]).is_ok()); + } + #[test] + fn untrusted_lengths_are_rejected_before_body_allocation() { + for n in [0, (FRAME_LIMIT + 1) as u32, u32::MAX] { + assert!(frame_length(n.to_be_bytes()).is_err()); + } + assert_eq!( + frame_length((FRAME_LIMIT as u32).to_be_bytes()).unwrap(), + FRAME_LIMIT + ); + } + #[test] + fn protocol_does_not_accept_a_shell_operation() { + let valid = serde_json::from_str::(r#"{"operation":"probe"}"#).unwrap(); + assert_eq!( + serde_json::to_string(&valid).unwrap(), + r#"{"operation":"probe"}"# + ); + assert!( + serde_json::from_str::(r#"{"operation":"shell","command":"whoami"}"#) + .is_err() + ); + assert!( + serde_json::from_str::(r#"{"operation":"probe","ready":true}"#).is_err() + ); + } + #[test] + fn reconfigured_service_cannot_adopt_an_old_running_identity() { + let pin = PeerPin { + service_name: "RmmDiscoveryFixtureTest".into(), + service_sid: "S-1-5-80-123".into(), + user_sid: "S-1-5-19".into(), + binary: PathBuf::from(r"C:\Program Files\RustDiscoveryFixtures\fixture.exe"), + binary_sha256: "a".repeat(64), + }; + let actual = ProcessIdentity { + pid: 42, + creation_ticks: 1234, + user_sid: pin.user_sid.clone(), + service_sid: pin.service_sid.clone(), + image: pin.binary.clone(), + image_sha256: pin.binary_sha256.clone(), + image_file: FileIdentity { + volume_serial: 1, + file_id: [1; 16], + }, + }; + assert!(actual.validate(&pin, 42).is_ok()); + // The configuration can now match the allowlist while the actual old + // process still has SYSTEM, another executable, or another service SID. + for old in [ + ProcessIdentity { + user_sid: "S-1-5-18".into(), + ..actual.clone() + }, + ProcessIdentity { + image: PathBuf::from(r"C:\Windows\System32\other.exe"), + ..actual.clone() + }, + ProcessIdentity { + service_sid: "S-1-5-80-999".into(), + ..actual.clone() + }, + ProcessIdentity { + pid: 43, + ..actual.clone() + }, + ] { + assert!(old.validate(&pin, 42).is_err()); + } + } +} diff --git a/crates/agent-windows/src/helper_system.rs b/crates/agent-windows/src/helper_system.rs new file mode 100644 index 0000000..4582329 --- /dev/null +++ b/crates/agent-windows/src/helper_system.rs @@ -0,0 +1,1173 @@ +//! SYSTEM service with an independent signed-sync gate and durable ledger. +//! Only fixed, policy-pinned SCM state changes exist; no arbitrary SYSTEM CLI. +//! +//! Bootstrap contract (not performed by this module): install exactly +//! `RmmDiscoverySystemHelper` as an OWN_PROCESS LocalSystem service with its +//! unrestricted service SID, image `"...\\rmm-helper-windows.exe" --service`. +//! Both peers keep their fixed names and binary hashes in `helper.json`. +//! The public root/settings are owned by SYSTEM or Administrators, grant only +//! those principals write access, and permit agent/helper service SIDs read. +//! `state` MUST have a separately protected SYSTEM/Administrators/helper-SID-only +//! ACL: no inherited agent reader. Files inherit that private ACL. This service +//! never installs itself, repairs ACLs, changes its account, resets a ledger, or +//! starts a fixture at bootstrap. `enable_effects=false`, `allow_reboot=false` +//! is the intended initial profile; clock qualification remains a separate gate. +//! A fixture is exactly OWN_PROCESS/LocalService with an unrestricted service +//! SID and a quoted argument-free pinned EXE. Dependencies/load-order groups +//! must be empty; recovery is empty/SC_ACTION_NONE with no command/reboot text. +//! These are read-only admission checks, never implicit configuration repairs. +use crate::{ + clock::NativeClock, + helper_ipc::{self as ipc, Call, Operation, PeerPin, Pin, PinnedFile, Reply, ReplyBody}, +}; +use anyhow::{Context, Result, ensure}; +use fs2::FileExt; +use rmm_agent_core::{ + auth::{Binding, HelperIdentity, Outcome, Request}, + crypto::DalekVerifier, + helper_reconcile::{BootSource, ExecutorLedgerGuard, HelperSync}, + ledger, +}; +use rmm_domain::jobs::{Action, ExecutionPermitPayload, JobPayload, hash}; +use rusqlite::{Connection, OptionalExtension}; +use serde::{Deserialize, Serialize}; +use std::{ + fs::OpenOptions, + mem::{size_of, zeroed}, + path::{Path, PathBuf}, + ptr, + sync::{ + OnceLock, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, + time::{Duration, Instant}, +}; +use uuid::Uuid; +use windows_sys::Win32::{Foundation::*, System::Services::*}; + +pub const CONFIG_PATH: &str = r"C:\ProgramData\RustDiscoverySystem\helper.json"; +pub const STATE_ROOT: &str = r"C:\ProgramData\RustDiscoverySystem\state"; +const PUBLIC_ROOT: &str = r"C:\ProgramData\RustDiscoverySystem"; +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ServiceRule { + pub name: String, + pub binary: PathBuf, + pub binary_sha256: String, +} +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Settings { + pub schema_version: u32, + pub binding: Binding, + pub agent: PeerPin, + pub helper: PeerPin, + pub allowed_services: Vec, + pub max_runtime_seconds: u32, + pub enable_effects: bool, + pub allow_reboot: bool, +} +impl Settings { + pub fn validate(&self) -> Result<()> { + ensure!( + self.schema_version == 1 + && !self.allow_reboot + && (1..=120).contains(&self.max_runtime_seconds) + && self.allowed_services.len() <= 16, + "SYSTEM_POLICY_PROFILE" + ); + self.agent.validate(false)?; + self.helper.validate(true)?; + ensure!( + !self.binding.tenant_id.is_nil() + && !self.binding.agent_id.is_nil() + && !self.binding.asset_id.is_nil() + && self.binding.enrollment_generation > 0 + && self.binding.assignment_version > 0, + "SYSTEM_POLICY_BINDING" + ); + use rmm_agent_core::crypto::Ed25519Verifier; + let raw = decode_key(&self.binding.public_key_hex)?; + ensure!(DalekVerifier.validate_key(&raw)?, "SYSTEM_SIGNING_KEY"); + let mut names = std::collections::BTreeSet::new(); + for rule in &self.allowed_services { + ensure!( + rule.name.starts_with("RmmDiscoveryFixture") + && rule.name.len() <= 128 + && rule + .name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') + && names.insert(rule.name.to_ascii_lowercase()), + "SYSTEM_SERVICE_ALLOWLIST" + ); + ensure!( + !rule.name.eq_ignore_ascii_case(crate::SERVICE_NAME) + && !rule.name.eq_ignore_ascii_case(ipc::HELPER_SERVICE), + "SYSTEM_SELF_CONTROL_DENIED" + ); + ensure!( + rule.binary.parent() == Some(Path::new(r"C:\Program Files\RustDiscoveryFixtures")) + && rule + .binary + .extension() + .is_some_and(|x| x.eq_ignore_ascii_case("exe")) + && rule.binary.file_name().is_some_and(|n| n + .to_str() + .is_some_and(|n| n.len() <= 200 + && n.bytes() + .all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b)))) + && ipc::digest(&rule.binary_sha256), + "SYSTEM_FIXTURE_IMAGE" + ); + } + Ok(()) + } + pub fn policy_sha256(&self) -> Result { + Ok(hash(&serde_json::to_vec(self)?)) + } + pub fn pin(&self) -> Result { + self.validate()?; + Ok(Pin { + schema_version: 1, + binding: self.binding.clone(), + policy_sha256: self.policy_sha256()?, + agent: self.agent.clone(), + helper: self.helper.clone(), + }) + } +} +fn decode_key(s: &str) -> Result> { + ensure!( + s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit()), + "SYSTEM_KEY_SIZE" + ); + (0..32) + .map(|i| Ok(u8::from_str_radix(&s[i * 2..i * 2 + 2], 16)?)) + .collect() +} +pub fn read_settings() -> Result<(Settings, Vec)> { + let agent = ipc::service_sid(crate::SERVICE_NAME)?; + let helper = ipc::service_sid(ipc::HELPER_SERVICE)?; + let readers = vec![agent, helper]; + let root = PinnedFile::open(Path::new(PUBLIC_ROOT), true, &readers, &[], false)?; + let mut file = PinnedFile::open(Path::new(CONFIG_PATH), false, &readers, &[], false)?; + ensure!(file.file.metadata()?.len() <= 32768, "SYSTEM_CONFIG_SIZE"); + use std::io::Read; + let mut bytes = Vec::new(); + file.file.read_to_end(&mut bytes)?; + let settings: Settings = serde_json::from_slice(&bytes)?; + settings.validate()?; + Ok((settings, vec![root, file])) +} +struct WindowsBoot(Uuid); +impl BootSource for WindowsBoot { + fn current_boot(&self) -> Result { + Ok(self.0) + } +} +impl WindowsBoot { + fn capture() -> Result { + // The exact existing fixed read-only CIM getter, independently called here. + // No caller values, execution-policy flag, or supplied command are accepted. + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?; + let id = rt.block_on(crate::native::boot_id())?; + let id = Uuid::parse_str(&id)?; + ensure!(!id.is_nil(), "SYSTEM_BOOT_ID"); + Ok(Self(id)) + } +} +pub struct LedgerGuard { + root: PinnedFile, + lock: PinnedFile, + ledger: PinnedFile, +} +impl LedgerGuard { + fn acquire(helper_sid: &str, binding: &Binding) -> Result<(Self, Connection)> { + let root = PinnedFile::open(Path::new(STATE_ROOT), true, &[], &[helper_sid.into()], true)?; + for name in ["executor.lock", "ledger.sqlite"] { + let path = Path::new(STATE_ROOT).join(name); + if !path.exists() { + let _ = OpenOptions::new() + .write(true) + .create_new(true) + .open(&path)?; + } + } + let lock = PinnedFile::open( + &Path::new(STATE_ROOT).join("executor.lock"), + false, + &[], + &[helper_sid.into()], + true, + )?; + lock.file + .try_lock_exclusive() + .context("SYSTEM_EXECUTOR_BUSY")?; + let ledger = PinnedFile::open( + &Path::new(STATE_ROOT).join("ledger.sqlite"), + false, + &[], + &[helper_sid.into()], + true, + )?; + let db = + Connection::open_with_flags(&ledger.path, rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE)?; + db.busy_timeout(Duration::from_millis(250))?; + ledger::initialize_ledger(&db)?; + db.execute_batch("CREATE TABLE IF NOT EXISTS windows_helper_files(id INTEGER PRIMARY KEY CHECK(id=1),ledger BLOB NOT NULL,executor_lock BLOB NOT NULL,binding_sha256 TEXT NOT NULL)")?; + let a = serde_json::to_vec(&ledger.identity)?; + let b = serde_json::to_vec(&lock.identity)?; + let binding_hash = ipc::binding_hash(binding)?; + db.execute( + "INSERT OR IGNORE INTO windows_helper_files(id,ledger,executor_lock,binding_sha256) VALUES(1,?1,?2,?3)", + rusqlite::params![a, b, binding_hash], + )?; + let retained: (Vec, Vec, String) = db.query_row( + "SELECT ledger,executor_lock,binding_sha256 FROM windows_helper_files WHERE id=1", + [], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), + )?; + ensure!( + retained == (a, b, binding_hash), + "SYSTEM_LEDGER_OR_LOCK_REPLACED" + ); + let guard = Self { root, lock, ledger }; + guard.check(&db)?; + Ok((guard, db)) + } + fn check_files(&self) -> Result<()> { + for file in [&self.root, &self.lock, &self.ledger] { + ensure!( + ipc::file_identity(&file.file)? == file.identity, + "SYSTEM_HELD_FILE_CHANGED" + ); + let opened = PinnedFile::open( + &file.path, + file.path == Path::new(STATE_ROOT), + &[], + &[ipc::service_sid(ipc::HELPER_SERVICE)?], + true, + )?; + ensure!( + opened.identity == file.identity, + "SYSTEM_LEDGER_PATH_CHANGED" + ); + } + Ok(()) + } +} +impl ExecutorLedgerGuard for LedgerGuard { + fn check(&self, db: &Connection) -> Result<()> { + self.check_files()?; + let path = db.path().context("SYSTEM_DB_PATH_MISSING")?; + let actual = PinnedFile::open( + Path::new(path), + false, + &[], + &[ipc::service_sid(ipc::HELPER_SERVICE)?], + true, + )?; + ensure!(actual.identity == self.ledger.identity, "SYSTEM_DB_FILE_ID"); + Ok(()) + } +} + +struct ServiceHandle(SC_HANDLE); +impl Drop for ServiceHandle { + fn drop(&mut self) { + unsafe { + CloseServiceHandle(self.0); + } + } +} +#[derive(Clone, Copy, Debug, Serialize)] +struct ServiceState { + state: u32, + pid: u32, + checkpoint: u32, + wait_hint_ms: u32, + win32_exit: u32, + service_exit: u32, +} +fn state(handle: SC_HANDLE) -> Result { + let mut value: SERVICE_STATUS_PROCESS = unsafe { zeroed() }; + let mut needed = 0; + ensure!( + unsafe { + QueryServiceStatusEx( + handle, + SC_STATUS_PROCESS_INFO, + (&mut value as *mut SERVICE_STATUS_PROCESS).cast(), + size_of::() as u32, + &mut needed, + ) + } != 0, + "SYSTEM_SERVICE_STATUS" + ); + Ok(ServiceState { + state: value.dwCurrentState, + pid: value.dwProcessId, + checkpoint: value.dwCheckPoint, + wait_hint_ms: value.dwWaitHint, + win32_exit: value.dwWin32ExitCode, + service_exit: value.dwServiceSpecificExitCode, + }) +} +fn desired_state(value: &str) -> Result { + match value { + "running" => Ok(SERVICE_RUNNING), + "stopped" => Ok(SERVICE_STOPPED), + _ => anyhow::bail!("SYSTEM_SERVICE_STATE_UNAVAILABLE"), + } +} +fn check_runtime(deadline: Instant) -> Result<()> { + ensure!(Instant::now() < deadline, "SYSTEM_SCM_RUNTIME_EXCEEDED"); + Ok(()) +} +#[derive(Clone, Debug)] +struct ServiceConfig { + service_type: u32, + binary: String, + account: String, + dependencies_empty: bool, + load_group_empty: bool, + recovery: RecoveryConfig, + sid_type: u32, +} +#[derive(Clone, Debug)] +struct RecoveryConfig { + actions: Vec, + command_empty: bool, + reboot_text_empty: bool, +} +impl RecoveryConfig { + fn validate(&self) -> Result<()> { + ensure!( + self.command_empty + && self.reboot_text_empty + && self.actions.iter().all(|kind| *kind == SC_ACTION_NONE), + "SYSTEM_UNAPPROVED_SERVICE_RECOVERY" + ); + Ok(()) + } +} +impl ServiceConfig { + fn validate(&self, rule: &ServiceRule) -> Result<()> { + ensure!( + self.service_type == SERVICE_WIN32_OWN_PROCESS + && self.binary == format!("\"{}\"", rule.binary.display()) + && matches!( + self.account.as_str(), + "NT AUTHORITY\\LocalService" | "NT AUTHORITY\\Local Service" + ), + "SYSTEM_FIXTURE_SCM_BINDING" + ); + // StartService may implicitly start dependencies/groups. A fixed-fixture + // grant authorizes exactly this service, so neither is admitted. + ensure!( + self.dependencies_empty && self.load_group_empty, + "SYSTEM_UNAPPROVED_SERVICE_DEPENDENCY" + ); + self.recovery.validate()?; + ensure!( + self.sid_type == SERVICE_SID_TYPE_UNRESTRICTED, + "SYSTEM_FIXTURE_SERVICE_SID_DISABLED" + ); + Ok(()) + } +} +fn query_service_config2(handle: SC_HANDLE, level: u32) -> Result> { + let mut needed = 0; + unsafe { + QueryServiceConfig2W(handle, level, ptr::null_mut(), 0, &mut needed); + } + ensure!((1..=32768).contains(&needed), "SYSTEM_SERVICE_CONFIG2_SIZE"); + let mut bytes = vec![0usize; (needed as usize).div_ceil(size_of::())]; + ensure!( + unsafe { + QueryServiceConfig2W( + handle, + level, + bytes.as_mut_ptr().cast(), + needed, + &mut needed, + ) + } != 0, + "SYSTEM_SERVICE_CONFIG2" + ); + Ok(bytes) +} +fn buffer_empty_string(bytes: &[usize], text: *const u16) -> Result { + if text.is_null() { + return Ok(true); + } + let base = bytes.as_ptr() as usize; + let address = text as usize; + let size = std::mem::size_of_val(bytes); + ensure!( + address >= base && address - base <= size.saturating_sub(2) && address.is_multiple_of(2), + "SYSTEM_CONFIG2_STRING_POINTER" + ); + Ok(unsafe { *text } == 0) +} +fn recovery_config(handle: SC_HANDLE) -> Result { + let bytes = query_service_config2(handle, SERVICE_CONFIG_FAILURE_ACTIONS)?; + ensure!( + std::mem::size_of_val(bytes.as_slice()) >= size_of::(), + "SYSTEM_RECOVERY_STRUCT_SIZE" + ); + let value = unsafe { &*bytes.as_ptr().cast::() }; + ensure!(value.cActions <= 128, "SYSTEM_RECOVERY_ACTION_COUNT"); + let mut actions = Vec::new(); + if value.cActions > 0 { + let base = bytes.as_ptr() as usize; + let address = value.lpsaActions as usize; + let length = value.cActions as usize * size_of::(); + let size = std::mem::size_of_val(bytes.as_slice()); + ensure!( + !value.lpsaActions.is_null() + && address >= base + && length <= size + && address - base <= size - length + && address.is_multiple_of(std::mem::align_of::()), + "SYSTEM_RECOVERY_ACTION_POINTER" + ); + actions.extend( + unsafe { std::slice::from_raw_parts(value.lpsaActions, value.cActions as usize) } + .iter() + .map(|a| a.Type), + ); + } + Ok(RecoveryConfig { + actions, + command_empty: buffer_empty_string(&bytes, value.lpCommand)?, + reboot_text_empty: buffer_empty_string(&bytes, value.lpRebootMsg)?, + }) +} +fn query_service_config(handle: SC_HANDLE) -> Result { + let mut needed = 0; + unsafe { + QueryServiceConfigW(handle, ptr::null_mut(), 0, &mut needed); + } + ensure!((1..=32768).contains(&needed), "SYSTEM_SERVICE_CONFIG_SIZE"); + let mut bytes = vec![0usize; (needed as usize).div_ceil(size_of::())]; + ensure!( + unsafe { QueryServiceConfigW(handle, bytes.as_mut_ptr().cast(), needed, &mut needed) } != 0, + "SYSTEM_SERVICE_CONFIG" + ); + let value = unsafe { &*bytes.as_ptr().cast::() }; + // Microsoft defines NULL or first UTF16 NUL as empty for both fields. + // Do not enumerate or adopt any dependency supplied by configuration. + let sid_info = query_service_config2(handle, SERVICE_CONFIG_SERVICE_SID_INFO)?; + ensure!( + std::mem::size_of_val(sid_info.as_slice()) >= size_of::(), + "SYSTEM_SID_CONFIG_SIZE" + ); + Ok(ServiceConfig { + service_type: value.dwServiceType, + binary: unsafe { ipc::utf16_pointer(value.lpBinaryPathName) }?, + account: unsafe { ipc::utf16_pointer(value.lpServiceStartName) }?, + dependencies_empty: value.lpDependencies.is_null() || unsafe { *value.lpDependencies } == 0, + load_group_empty: value.lpLoadOrderGroup.is_null() + || unsafe { *value.lpLoadOrderGroup } == 0, + recovery: recovery_config(handle)?, + sid_type: unsafe { (*sid_info.as_ptr().cast::()).dwServiceSidType }, + }) +} +struct PreparedService { + handle: ServiceHandle, + _manager: ServiceHandle, + image: PinnedFile, + root: PinnedFile, + rule: ServiceRule, + pin: PeerPin, + running: Option, + wanted: u32, + initial: ServiceState, +} +impl PreparedService { + fn prepare(settings: &Settings, job: &JobPayload) -> Result { + ensure!( + job.execution_identity == "system" + && job.max_runtime_seconds <= settings.max_runtime_seconds, + "SYSTEM_IDENTITY_OR_RUNTIME" + ); + let Action::SetServiceState { + unit, + state: desired, + } = &job.action + else { + anyhow::bail!("SYSTEM_TYPED_SERVICE_ONLY"); + }; + let wanted = desired_state(desired)?; + let rule = settings + .allowed_services + .iter() + .find(|r| r.name == *unit) + .context("SYSTEM_SERVICE_DENIED")? + .clone(); + let sid = ipc::service_sid(&rule.name)?; + let readers = [ + settings.agent.service_sid.clone(), + settings.helper.service_sid.clone(), + sid.clone(), + ]; + let root = PinnedFile::open( + Path::new(r"C:\Program Files\RustDiscoveryFixtures"), + true, + &readers, + &[], + false, + )?; + let mut image = PinnedFile::open(&rule.binary, false, &readers, &[], false)?; + ensure!( + image.sha256()? == rule.binary_sha256, + "SYSTEM_SERVICE_IMAGE_HASH" + ); + let manager = + ServiceHandle(unsafe { OpenSCManagerW(ptr::null(), ptr::null(), SC_MANAGER_CONNECT) }); + ensure!(!manager.0.is_null(), "SYSTEM_SERVICE_MANAGER"); + let handle = ServiceHandle(unsafe { + OpenServiceW( + manager.0, + ipc::wide(unit).as_ptr(), + SERVICE_QUERY_CONFIG + | SERVICE_QUERY_STATUS + | if wanted == SERVICE_RUNNING { + SERVICE_START + } else { + SERVICE_STOP + }, + ) + }); + ensure!(!handle.0.is_null(), "SYSTEM_SERVICE_OPEN"); + query_service_config(handle.0)?.validate(&rule)?; + let initial = state(handle.0)?; + ensure!( + matches!(initial.state, SERVICE_RUNNING | SERVICE_STOPPED), + "SYSTEM_SERVICE_BUSY" + ); + let pin = PeerPin { + service_name: rule.name.clone(), + service_sid: sid, + user_sid: "S-1-5-19".into(), + binary: rule.binary.clone(), + binary_sha256: rule.binary_sha256.clone(), + }; + let running = if initial.state == SERVICE_RUNNING { + Some(ipc::PeerProof::for_service(&pin, initial.pid)?) + } else { + None + }; + Ok(Self { + handle, + _manager: manager, + image, + root, + rule, + pin, + running, + wanted, + initial, + }) + } + fn recheck(&mut self) -> Result { + self.image.check()?; + self.root.check()?; + query_service_config(self.handle.0)?.validate(&self.rule)?; + let before = state(self.handle.0)?; + ensure!( + before.state == self.initial.state && before.pid == self.initial.pid, + "SYSTEM_SERVICE_CHANGED_BEFORE_EFFECT" + ); + if let Some(process) = &mut self.running { + process.check()?; + } + Ok(before) + } + fn execute(&mut self, timeout: Duration, mut authorize: impl FnMut() -> Result<()>) -> Outcome { + let result = (|| -> Result { + let deadline = Instant::now() + timeout; + let before = match self.recheck() { + Ok(value) => value, + Err(error) => { + return Ok(Outcome { + state: "failed".into(), + evidence: serde_json::json!({"postconditions_passed":false,"not_started":true}), + ..Outcome::unknown(&safe_error(&error)) + }); + } + }; + let noop = before.state == self.wanted; + // This callback performs the final BOTH-edge clock/permit check, + // after all potentially slow configuration/process preflights. + if let Err(error) = authorize() { + return Ok(Outcome { + state: "failed".into(), + evidence: serde_json::json!({"postconditions_passed":false,"not_started":true}), + ..Outcome::unknown(&safe_error(&error)) + }); + } + if let Err(error) = check_runtime(deadline) { + return Ok(Outcome { + state: "failed".into(), + evidence: serde_json::json!({"postconditions_passed":false,"not_started":true}), + ..Outcome::unknown(&safe_error(&error)) + }); + } + if !noop { + // SCM's synchronous RPC can block (documented up to30s), and + // cannot be safely cancelled here. Exceedance remains Unknown, + // never success or a claim that effects stopped at the limit. + let ok = unsafe { + if self.wanted == SERVICE_RUNNING { + StartServiceW(self.handle.0, 0, ptr::null()) + } else { + let mut ignored: SERVICE_STATUS = zeroed(); + ControlService(self.handle.0, SERVICE_CONTROL_STOP, &mut ignored) + } + }; + let native_error = if ok == 0 { + Some(unsafe { GetLastError() }) + } else { + None + }; + check_runtime(deadline)?; + if ok == 0 { + return Ok(Outcome { + evidence: serde_json::json!({"postconditions_passed":false,"native_error":native_error,"initial":before}), + ..Outcome::unknown("SYSTEM_SCM_EFFECT_UNCONFIRMED") + }); + } + } + let mut final_state = state(self.handle.0)?; + while final_state.state != self.wanted && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(50)); + final_state = state(self.handle.0)?; + } + if final_state.state != self.wanted { + return Ok(Outcome { + evidence: serde_json::json!({"postconditions_passed":false,"initial":before,"last_status":final_state}), + ..Outcome::unknown("SYSTEM_SERVICE_POSTCONDITION_TIMEOUT") + }); + } + self.image.check()?; + query_service_config(self.handle.0)?.validate(&self.rule)?; + let process_identity = if self.wanted == SERVICE_RUNNING { + if self.running.is_none() { + self.running = Some(ipc::PeerProof::for_service(&self.pin, final_state.pid)?); + } + let process = self.running.as_mut().unwrap(); + process.check()?; + Some(process.identity().clone()) + } else { + if let Some(process) = &self.running { + while !process.exited()? && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(50)); + } + ensure!(process.exited()?, "SYSTEM_STOPPED_PROCESS_STILL_ALIVE"); + } + None + }; + // Re-read after live process proof; a stale SCM config/state is + // never turned into success for an old SYSTEM/other image process. + query_service_config(self.handle.0)?.validate(&self.rule)?; + let confirmed = state(self.handle.0)?; + ensure!( + confirmed.state == self.wanted + && (self.wanted != SERVICE_RUNNING || confirmed.pid == final_state.pid), + "SYSTEM_SERVICE_CHANGED_DURING_POSTCONDITION" + ); + check_runtime(deadline)?; + Ok(Outcome { + state: "succeeded".into(), + stdout: vec![], + stderr: vec![], + exit_code: Some(0), + output_truncated: false, + reboot_required: false, + error_code: String::new(), + evidence: serde_json::json!({"postconditions_passed":true,"provider":"windows.scm/1","service":self.rule.name,"requested_state":self.wanted,"initial":before,"final_status":confirmed,"noop":noop,"fixture_sha256":self.rule.binary_sha256,"fixture_file_id":self.image.identity,"running_process":process_identity,"captured_process_exited":self.wanted==SERVICE_STOPPED&&self.running.is_some()}), + }) + })(); + result.unwrap_or_else(|error| Outcome::unknown(&safe_error(&error))) + } +} + +fn verified_window( + binding: &Binding, + request: &Request, + clock: &impl rmm_agent_core::reconcile::SyncClock, +) -> Result<( + JobPayload, + ExecutionPermitPayload, + chrono::DateTime, +)> { + let now = clock.now()?; + let lower = now + .checked_sub_signed(chrono::Duration::seconds(2)) + .context("SYSTEM_CLOCK_RANGE")?; + let upper = now + .checked_add_signed(chrono::Duration::seconds(2)) + .context("SYSTEM_CLOCK_RANGE")?; + let (job, permit) = binding.verify_with(request, lower, &DalekVerifier)?; + binding.verify_with(request, upper, &DalekVerifier)?; + Ok((job, permit, now)) +} + +pub struct SystemHelper { + settings: Settings, + pin: Pin, + files: Vec, + guard: LedgerGuard, + db: Connection, + clock: NativeClock, + boot: WindowsBoot, + sync: Option>, +} +impl SystemHelper { + pub fn open() -> Result { + let (settings, files) = read_settings()?; + ipc::require_self(&settings.helper)?; + let pin = settings.pin()?; + ipc::publish_self_query_rights(&settings.agent.service_sid, &settings.helper.service_sid)?; + let (guard, db) = LedgerGuard::acquire(&settings.helper.service_sid, &settings.binding)?; + let clock = NativeClock::new(); + let boot = WindowsBoot::capture()?; + let sync = HelperSync::with_verifier(settings.binding.clone(), DalekVerifier, &clock) + .ok() + .map(|s| s.with_helper_identity(HelperIdentity::System)); + Ok(Self { + settings, + pin, + files, + guard, + db, + clock, + boot, + sync, + }) + } + pub fn pin(&self) -> &Pin { + &self.pin + } + fn recheck(&mut self) -> Result<()> { + ipc::require_self(&self.settings.helper)?; + for file in &mut self.files { + file.check()?; + } + self.guard.check(&self.db) + } + fn sync(&mut self) -> Result<&mut HelperSync> { + if self.sync.is_none() { + self.sync = Some( + HelperSync::with_verifier( + self.settings.binding.clone(), + DalekVerifier, + &self.clock, + )? + .with_helper_identity(HelperIdentity::System), + ); + } + self.sync.as_mut().context("SYSTEM_SYNC_CLOSED") + } + pub fn handle(&mut self, call: &Call, peer: &mut ipc::PeerProof) -> Reply { + let result = (|| -> Result { + self.recheck()?; + peer.check()?; + ensure!( + call.schema_version == 1 + && !call.challenge.is_nil() + && ipc::binding_hash(&call.binding)? + == ipc::binding_hash(&self.settings.binding)? + && call.policy_sha256 == self.pin.policy_sha256, + "SYSTEM_CALL_BINDING" + ); + let response: Result = match &call.operation { + Operation::Probe {} => { + let ready = self.settings.enable_effects + && self + .sync + .as_ref() + .and_then(|s| { + s.active_generation().map(|g| { + s.can_start(&self.db, &self.guard, g, &self.clock, &self.boot) + }) + }) + .unwrap_or(false); + Ok(ReplyBody::Probe { + clock_qualified: self.clock.now().is_ok(), + ready, + ledger: self.guard.ledger.identity, + lock: self.guard.lock.identity, + }) + } + Operation::Snapshot { generation } => { + self.sync()?; + let snapshot = self.sync.as_mut().unwrap().snapshot( + &mut self.db, + &self.guard, + *generation, + &self.clock, + &self.boot, + )?; + Ok(ReplyBody::Snapshot { snapshot }) + } + Operation::Apply { + response, + request_bytes, + } => { + self.sync()?; + let value = self.sync.as_mut().unwrap().apply( + &mut self.db, + &self.guard, + response, + request_bytes, + &self.clock, + &self.boot, + )?; + Ok(ReplyBody::Applied { + snapshot: value.snapshot, + unlocked_grants: value.unlocked_grants, + ready: value.ready && self.settings.enable_effects, + }) + } + Operation::Execute { + generation, + request, + } => Ok(ReplyBody::Executed { + outcome: self.execute(*generation, request, peer)?, + }), + }; + let response = response?; + peer.check()?; + Ok(response) + })(); + let body = match result { + Ok(body) => body, + Err(e) => { + if let Some(sync) = &mut self.sync { + sync.close(); + } + ReplyBody::Denied { + code: safe_error(&e), + } + } + }; + Reply { + schema_version: 1, + challenge: call.challenge, + binding_sha256: ipc::binding_hash(&self.settings.binding).expect("validated binding"), + policy_sha256: self.pin.policy_sha256.clone(), + helper_binary_sha256: self.settings.helper.binary_sha256.clone(), + body, + } + } + fn execute( + &mut self, + generation: u64, + request: &Request, + peer: &mut ipc::PeerProof, + ) -> Result { + // Historical signature validation can only return retained evidence. It + // never reopens a start window or authorizes an effect after expiry. + let parsed: ExecutionPermitPayload = serde_json::from_slice(&request.permit_bytes)?; + let (job, permit) = + self.settings + .binding + .verify_with(request, parsed.not_before, &DalekVerifier)?; + ensure!( + job.execution_identity == "system", + "SYSTEM_IDENTITY_REQUIRED" + ); + type Completion = (Option>, Option>); + let old:Option=self.db.query_row("SELECT e.start,COALESCE(c.result,e.outcome) FROM consumed c LEFT JOIN execution_evidence e ON e.grant_id=c.grant_id WHERE c.grant_id=?1",[permit.grant_id.to_string()],|r|Ok((r.get(0)?,r.get(1)?))).optional()?; + if let Some((start, outcome)) = old { + let Some(start) = start else { + return Ok(Outcome::unknown("SYSTEM_PREVIOUS_START_UNRESOLVED")); + }; + let value: serde_json::Value = serde_json::from_slice(&start)?; + let original: Request = serde_json::from_value(value["request"].clone())?; + ensure!( + serde_json::to_vec(&original)? == serde_json::to_vec(request)?, + "SYSTEM_REDELIVERY_REQUEST_CHANGED" + ); + return outcome + .map(|bytes| Ok(serde_json::from_slice(&bytes)?)) + .unwrap_or_else(|| Ok(Outcome::unknown("SYSTEM_PREVIOUS_EFFECT_UNRESOLVED"))); + } + ensure!(self.settings.enable_effects, "SYSTEM_EFFECTS_DISABLED"); + verified_window(&self.settings.binding, request, &self.clock)?; + self.sync()?; + ensure!( + self.sync.as_ref().unwrap().can_start( + &self.db, + &self.guard, + generation, + &self.clock, + &self.boot + ), + "SYSTEM_SIGNED_SYNC_REQUIRED" + ); + let mut provider = PreparedService::prepare(&self.settings, &job)?; + self.recheck()?; + peer.check()?; + ensure!( + self.sync.as_ref().unwrap().can_start( + &self.db, + &self.guard, + generation, + &self.clock, + &self.boot + ), + "SYSTEM_SIGNED_SYNC_REQUIRED" + ); + provider.recheck()?; + let (_, fresh, recorded_at) = + verified_window(&self.settings.binding, request, &self.clock)?; + ensure!(fresh == permit, "SYSTEM_START_REQUEST_CHANGED"); + // Parent core provides atomic request/consumption persistence; never + // dispatch SCM until both exact request and tombstone are durable. + ledger::begin_execution( + &mut self.db, + &permit, + request, + self.boot.current_boot()?, + recorded_at, + )?; + self.sync.as_mut().unwrap().close(); + let outcome = provider.execute(Duration::from_secs(job.max_runtime_seconds.into()), || { + self.recheck()?; + peer.check()?; + verified_window(&self.settings.binding, request, &self.clock)?; + Ok(()) + }); + ledger::persist_outcome(&self.db, &permit, &outcome)?; + self.guard.check(&self.db)?; + ledger::finish(&self.db, &permit, &outcome)?; + Ok(outcome) + } +} +pub fn safe_error(error: &anyhow::Error) -> String { + if error.chain().any(|cause| { + matches!(cause.downcast_ref::(), + Some(rusqlite::Error::SqliteFailure(code,_)) if code.code==rusqlite::ErrorCode::DiskFull) + }) { + return "JOURNAL_STORAGE_CAPACITY_BLOCKED".into(); + } + let text = error.to_string(); + if text.len() <= 96 + && text + .bytes() + .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_') + { + text + } else { + "SYSTEM_VALIDATION_OR_STORAGE_FAILURE".into() + } +} + +static STOP: AtomicBool = AtomicBool::new(false); +static SCM_HANDLE: AtomicUsize = AtomicUsize::new(0); +static START: OnceLock<()> = OnceLock::new(); +fn scm_status(state: u32, error: u32) { + let h = SCM_HANDLE.load(Ordering::SeqCst) as SERVICE_STATUS_HANDLE; + if h.is_null() { + return; + } + let status = SERVICE_STATUS { + dwServiceType: SERVICE_WIN32_OWN_PROCESS, + dwCurrentState: state, + dwControlsAccepted: if state == SERVICE_RUNNING { + SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN + } else { + 0 + }, + dwWin32ExitCode: error, + dwServiceSpecificExitCode: 0, + dwCheckPoint: u32::from(state == SERVICE_START_PENDING || state == SERVICE_STOP_PENDING), + dwWaitHint: if state == SERVICE_STOP_PENDING { + 125000 + } else { + 30000 + }, + }; + unsafe { + SetServiceStatus(h, &status); + } +} +unsafe extern "system" fn control( + code: u32, + _: u32, + _: *mut std::ffi::c_void, + _: *mut std::ffi::c_void, +) -> u32 { + if matches!(code, SERVICE_CONTROL_STOP | SERVICE_CONTROL_SHUTDOWN) { + STOP.store(true, Ordering::SeqCst); + scm_status(SERVICE_STOP_PENDING, 0); + } + 0 +} +unsafe extern "system" fn service_main(_: u32, _: *mut *mut u16) { + let name = ipc::wide(ipc::HELPER_SERVICE); + let handle = + unsafe { RegisterServiceCtrlHandlerExW(name.as_ptr(), Some(control), ptr::null_mut()) }; + if handle.is_null() { + return; + } + SCM_HANDLE.store(handle as usize, Ordering::SeqCst); + scm_status(SERVICE_START_PENDING, 0); + let result = (|| -> Result<()> { + let mut helper = SystemHelper::open()?; + let server = ipc::Server::bind(helper.pin().clone())?; + scm_status(SERVICE_RUNNING, 0); + while !STOP.load(Ordering::SeqCst) { + match server.receive() { + Ok(Some(mut incoming)) => { + let reply = helper.handle(&incoming.call, &mut incoming.peer); + if server.reply(&reply).is_err() + && let Some(sync) = &mut helper.sync + { + sync.close(); + } + server.disconnect(); + } + Ok(None) => {} + Err(_) => { + if let Some(sync) = &mut helper.sync { + sync.close(); + } + server.disconnect(); + } + } + } + Ok(()) + })(); + scm_status(SERVICE_STOPPED, if result.is_ok() { 0 } else { 1066 }); +} +pub fn dispatch() -> Result<()> { + ensure!( + std::env::args().skip(1).collect::>() == ["--service"], + "SYSTEM_SCM_MODE_ONLY" + ); + ensure!(START.set(()).is_ok(), "SYSTEM_SCM_ALREADY_STARTED"); + let mut name = ipc::wide(ipc::HELPER_SERVICE); + let table = [ + SERVICE_TABLE_ENTRYW { + lpServiceName: name.as_mut_ptr(), + lpServiceProc: Some(service_main), + }, + SERVICE_TABLE_ENTRYW { + lpServiceName: ptr::null_mut(), + lpServiceProc: None, + }, + ]; + ensure!( + unsafe { StartServiceCtrlDispatcherW(table.as_ptr()) } != 0, + "SYSTEM_SCM_DISPATCH" + ); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn service_adapter_exposes_only_implemented_states() { + assert_eq!(desired_state("running").unwrap(), SERVICE_RUNNING); + assert_eq!(desired_state("stopped").unwrap(), SERVICE_STOPPED); + for state in ["restarted", "reload", "start;whoami", ""] { + assert!(desired_state(state).is_err()); + } + } + #[test] + fn single_fixture_cannot_start_services_or_groups_as_dependencies() { + let rule = ServiceRule { + name: "RmmDiscoveryFixtureTest".into(), + binary: PathBuf::from(r"C:\Program Files\RustDiscoveryFixtures\fixture.exe"), + binary_sha256: "a".repeat(64), + }; + let view = ServiceConfig { + service_type: SERVICE_WIN32_OWN_PROCESS, + binary: format!("\"{}\"", rule.binary.display()), + account: "NT AUTHORITY\\LocalService".into(), + dependencies_empty: true, + load_group_empty: true, + recovery: RecoveryConfig { + actions: vec![], + command_empty: true, + reboot_text_empty: true, + }, + sid_type: SERVICE_SID_TYPE_UNRESTRICTED, + }; + assert!(view.validate(&rule).is_ok()); + for changed in [ + ServiceConfig { + dependencies_empty: false, + ..view.clone() + }, + ServiceConfig { + load_group_empty: false, + ..view.clone() + }, + ServiceConfig { + account: "LocalSystem".into(), + ..view.clone() + }, + ServiceConfig { + binary: r"C:\Windows\System32\other.exe".into(), + ..view.clone() + }, + ServiceConfig { + sid_type: SERVICE_SID_TYPE_NONE, + ..view.clone() + }, + ] { + assert!(changed.validate(&rule).is_err()); + } + } + #[test] + fn fixture_recovery_cannot_add_commands_reboots_or_restart_attempts() { + let none = RecoveryConfig { + actions: vec![SC_ACTION_NONE], + command_empty: true, + reboot_text_empty: true, + }; + assert!(none.validate().is_ok()); + for kind in [SC_ACTION_RESTART, SC_ACTION_RUN_COMMAND, SC_ACTION_REBOOT] { + assert!( + RecoveryConfig { + actions: vec![kind], + ..none.clone() + } + .validate() + .is_err() + ); + } + assert!( + RecoveryConfig { + command_empty: false, + ..none.clone() + } + .validate() + .is_err() + ); + assert!( + RecoveryConfig { + reboot_text_empty: false, + ..none + } + .validate() + .is_err() + ); + } + #[test] + fn completed_scm_state_cannot_override_elapsed_runtime() { + let expired = Instant::now().checked_sub(Duration::from_secs(1)).unwrap(); + assert!(check_runtime(expired).is_err()); + assert!(check_runtime(Instant::now() + Duration::from_secs(10)).is_ok()); + } +} diff --git a/crates/agent-windows/src/inventory.rs b/crates/agent-windows/src/inventory.rs new file mode 100644 index 0000000..b766f1f --- /dev/null +++ b/crates/agent-windows/src/inventory.rs @@ -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 { + 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> { + 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 { + let mut system: SYSTEM_INFO = unsafe { zeroed() }; + unsafe { + GetNativeSystemInfo(&mut system); + } + let mut memory: MEMORYSTATUSEX = unsafe { zeroed() }; + memory.dwLength = size_of::() 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 { + 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> { + 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 { + type Provider = fn() -> Result; + [ + ( + "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() +} diff --git a/crates/agent-windows/src/journal.rs b/crates/agent-windows/src/journal.rs index 6e3c02e..4c42bc6 100644 --- a/crates/agent-windows/src/journal.rs +++ b/crates/agent-windows/src/journal.rs @@ -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=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 { 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 = 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>(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>(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(); + } } diff --git a/crates/agent-windows/src/lib.rs b/crates/agent-windows/src/lib.rs index 77d6a0c..7d49697 100644 --- a/crates/agent-windows/src/lib.rs +++ b/crates/agent-windows/src/lib.rs @@ -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"]; diff --git a/crates/agent-windows/src/native.rs b/crates/agent-windows/src/native.rs index 97d956a..9c4e0d0 100644 --- a/crates/agent-windows/src/native.rs +++ b/crates/agent-windows/src/native.rs @@ -37,6 +37,90 @@ fn sid_string(sid: *mut c_void) -> Result { } 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::()) as u32, + &mut size, + ) + } != 0, + "SERVICE_TOKEN_USER" + ); + let user = unsafe { &*storage.as_ptr().cast::() }; + 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 { let account = wide(format!("NT SERVICE\\{}", crate::SERVICE_NAME)); let mut sid_len = 0; @@ -191,15 +275,19 @@ pub fn snapshot() -> Result { 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 { // 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() diff --git a/crates/agent-windows/src/process.rs b/crates/agent-windows/src/process.rs new file mode 100644 index 0000000..cfdd377 --- /dev/null +++ b/crates/agent-windows/src/process.rs @@ -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, + pub stderr: Vec, + pub exit_code: Option, + 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> { + use std::os::windows::ffi::OsStrExt; + let input: Vec = 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 { + 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::() 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, +} +impl Attributes { + fn new() -> Result { + 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::())]; + 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, + 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 { + 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::() 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("e(OsStr::new("a b\\")).unwrap()).unwrap(), + "\"a b\\\\\"" + ); + assert_eq!( + String::from_utf16("e(OsStr::new("a\"b")).unwrap()).unwrap(), + "\"a\\\"b\"" + ); + assert_eq!( + String::from_utf16("e(OsStr::new("$(Get-Content x); & y")).unwrap()).unwrap(), + "\"$(Get-Content x); & y\"" + ); + assert!(quote(OsStr::new("a\0b")).is_err()); + } +} diff --git a/crates/agent-windows/src/runtime.rs b/crates/agent-windows/src/runtime.rs index 869f753..0ac3670 100644 --- a/crates/agent-windows/src/runtime.rs +++ b/crates/agent-windows/src/runtime.rs @@ -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, + // 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 { fs::remove_file(&config.enrollment_token_file)?; Ok(identity) } +#[derive(Clone)] +struct JobClock { + native: Arc, + enabled: bool, +} +impl SyncClock for JobClock { + fn now(&self) -> Result> { + 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, + 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 { + 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 { + 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::() }; + ensure!( + ace.Header.AceType == 0 + && usize::from(ace.Header.AceSize) + >= std::mem::size_of::(), + "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>(1)?)) + })? + .collect::>>()? + }; + 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> = 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 = 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, + ledger: Option, + _ledger_file: Option, + clock: JobClock, + sync: Option, + prepared: bool, + fence: Arc, + completed_tx: tokio::sync::mpsc::Sender, + completed_rx: tokio::sync::mpsc::Receiver, + running: Option, + 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 { + 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 { + let mut caps: Vec = 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 { + 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 { 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>=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,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 = 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 = 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); + impl SyncClock for Clock { + fn now(&self) -> Result> { + 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))); + } +} diff --git a/deploy/windows/client_bootstrap.py b/deploy/windows/client_bootstrap.py index 5ab0fac..f0bda0d 100644 --- a/deploy/windows/client_bootstrap.py +++ b/deploy/windows/client_bootstrap.py @@ -45,7 +45,7 @@ def powershell(script, payload=None, timeout=60, remote_signed=False): UPLOAD = r''' $ErrorActionPreference='Stop' $p=([Console]::In.ReadLine() | ConvertFrom-Json) -if ($p.name -notmatch '^((rmm-agent-windows|windows-tests-(lib|bin|acl)|windows-core-(contracts|reconcile|helper-reconcile))\.exe|Install-PassiveClient\.ps1|PassiveStateProbe\.exe|WindowsTlsProbe\.exe)$') {throw 'Artifact allowlist'} +if ($p.name -notmatch '^((rmm-agent-windows|windows-tests-(lib|bin|acl)|windows-core-(contracts|reconcile|helper-reconcile))\.exe|Install-PassiveClient\.ps1|PassiveStateProbe\.exe|WindowsTlsProbe\.exe|RuntimeStateProbe\.exe)$') {throw 'Artifact allowlist'} $root='C:\ProgramData\RustDiscoveryBootstrap' if (!(Test-Path -LiteralPath $root)) { New-Item -ItemType Directory -Path $root | Out-Null @@ -68,7 +68,7 @@ if (Test-Path -LiteralPath $path) {throw 'Artifact already exists'} VERIFY_UPLOAD = r''' $ErrorActionPreference='Stop' $p=([Console]::In.ReadLine() | ConvertFrom-Json) -if ($p.sha256 -notmatch '^[0-9a-f]{64}$' -or $p.name -notmatch '^((rmm-agent-windows|windows-tests-(lib|bin|acl)|windows-core-(contracts|reconcile|helper-reconcile))\.exe|Install-PassiveClient\.ps1|PassiveStateProbe\.exe|WindowsTlsProbe\.exe)$') {throw 'Artifact allowlist'} +if ($p.sha256 -notmatch '^[0-9a-f]{64}$' -or $p.name -notmatch '^((rmm-agent-windows|windows-tests-(lib|bin|acl)|windows-core-(contracts|reconcile|helper-reconcile))\.exe|Install-PassiveClient\.ps1|PassiveStateProbe\.exe|WindowsTlsProbe\.exe|RuntimeStateProbe\.exe)$') {throw 'Artifact allowlist'} $path='C:\ProgramData\RustDiscoveryBootstrap\'+$p.sha256+'\'+$p.name $hash=(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant() if ($hash -cne $p.sha256) {throw 'Artifact hash'} diff --git a/deploy/windows/clock_readiness.py b/deploy/windows/clock_readiness.py new file mode 100644 index 0000000..49ca63c --- /dev/null +++ b/deploy/windows/clock_readiness.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +"""Read-only LocalService W32Time readiness bootstrap; no RMM jobs. + +A lost SSH reply is resumed using readback --id, never by repeating start. +The temporary service is separate from the permanent enrolled Windows agent. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import uuid + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import client_bootstrap as cb + +STATE = cb.EVIDENCE / 'clock-readiness' +ROOT = r'C:\ProgramData\RustDiscoveryClockReadiness' +SERVICE = 'RmmWindowsClockReadiness' + +PREPARE = r'''$ErrorActionPreference='Stop' +$p=([Console]::In.ReadLine()|ConvertFrom-Json) +if($p.sha -notmatch '^[a-f0-9]{64}$' -or $p.name -notin @('WindowsClockReadiness.exe','ClockReadiness.ps1')){throw 'Fixed artifact'} +$root='C:\ProgramData\RustDiscoveryClockReadiness' +function CheckPrivate($path){ + $acl=Get-Acl -LiteralPath $path;$owner=$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value + if($owner -notin @('S-1-5-18','S-1-5-32-544') -or $acl.Access.Count -eq 0){throw 'Artifact owner/DACL'} + foreach($ace in $acl.Access){ + $sid=$ace.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value + if($ace.AccessControlType -ne 'Allow' -or $sid -notin @('S-1-5-18','S-1-5-32-544','S-1-5-19')){throw 'Artifact broad ACL'} + if($sid -eq 'S-1-5-19' -and ([int64]$ace.FileSystemRights -band (-bnot ([int64][Security.AccessControl.FileSystemRights]::ReadAndExecute -bor [int64][Security.AccessControl.FileSystemRights]::Synchronize)))){throw 'Artifact writable by service account'} + } +} +if(!(Test-Path -LiteralPath $root)){ + New-Item -ItemType Directory -Path $root|Out-Null + $a=New-Object Security.AccessControl.DirectorySecurity;$a.SetAccessRuleProtection($true,$false) + foreach($sid in @('S-1-5-18','S-1-5-32-544','S-1-5-19')){ + $rights=if($sid -eq 'S-1-5-19'){'ReadAndExecute'}else{'FullControl'} + $a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),$rights,'ContainerInherit,ObjectInherit','None','Allow'))) + } + $a.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')));Set-Acl -LiteralPath $root -AclObject $a +} +if((Get-Item -LiteralPath $root).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Root reparse'} +CheckPrivate $root +$dir=Join-Path $root $p.sha +if(!(Test-Path -LiteralPath $dir)){New-Item -ItemType Directory -Path $dir|Out-Null} +if((Get-Item -LiteralPath $dir).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Artifact reparse'} +CheckPrivate $dir +$file=Join-Path $dir $p.name +$exists=Test-Path -LiteralPath $file +if($exists -and ((Get-Item -LiteralPath $file).Attributes -band [IO.FileAttributes]::ReparsePoint)){throw 'File reparse'} +if($exists){CheckPrivate $file} +if($exists -and (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.sha){throw 'Artifact immutable'} +[pscustomobject]@{exists=$exists;sha=$p.sha}|ConvertTo-Json -Compress +''' + +SCRIPT = r'''$ErrorActionPreference='Stop' +$p=([Console]::In.ReadLine()|ConvertFrom-Json) +$id=[guid]::ParseExact($p.id,'D').ToString() +if($id -cne $p.id -or $p.binary -notmatch '^[a-f0-9]{64}$' -or $p.source -notmatch '^[a-f0-9]{64}$' -or $p.action -notin @('start','readback')){throw 'Fixed request'} +$root='C:\ProgramData\RustDiscoveryClockReadiness';$name='RmmWindowsClockReadiness' +$case=Join-Path $root $id;$intent=Join-Path $case 'intent.json';$result=Join-Path $case 'result.json' +$exe=Join-Path (Join-Path $root $p.binary) 'WindowsClockReadiness.exe' +$source=Join-Path (Join-Path $root $p.source) 'ClockReadiness.ps1' +foreach($file in @($exe,$source)){ + if((Get-Item -LiteralPath $file).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Reparse'} +} +if((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.binary -or (Get-FileHash -LiteralPath $source -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.source){throw 'Qualified source and binary'} +$command='"'+$exe+'" --service '+$id +function PrivateFile($path){ + $a=New-Object Security.AccessControl.FileSecurity;$a.SetAccessRuleProtection($true,$false) + foreach($sid in @('S-1-5-18','S-1-5-32-544')){$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'FullControl','Allow')))} + $a.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')));Set-Acl -LiteralPath $path -AclObject $a +} +function WriteNew($path,$data){ + $bytes=[Text.Encoding]::UTF8.GetBytes(($data|ConvertTo-Json -Depth 12 -Compress));$f=[IO.File]::Open($path,'CreateNew','Write','None') + try{$f.Write($bytes,0,$bytes.Length);$f.Flush($true)}finally{$f.Dispose()};PrivateFile $path +} +if($p.action -eq 'start'){ + if((Test-Path -LiteralPath $case) -or (Get-Service -Name $name -ErrorAction SilentlyContinue)){throw 'Use retained case readback; never repeat start'} + New-Item -ItemType Directory -Path $case|Out-Null + WriteNew $intent ([ordered]@{id=$id;binary=$p.binary;source=$p.source;command=$command;service=$name;no_jobs=$true}) + New-Service -Name $name -BinaryPathName $command -StartupType Manual -Credential (New-Object Management.Automation.PSCredential('NT AUTHORITY\LocalService',(New-Object Security.SecureString)))|Out-Null + & "$env:WINDIR\System32\sc.exe" sidtype $name unrestricted|Out-Null;if($LASTEXITCODE -ne 0){throw 'Readiness service SID'} + $sid=(New-Object Security.Principal.NTAccount('NT SERVICE\'+$name)).Translate([Security.Principal.SecurityIdentifier]) + $a=Get-Acl -LiteralPath $case;$a.SetAccessRuleProtection($true,$true) + $a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($sid,'ReadAndExecute,Write','ContainerInherit,ObjectInherit','None','Allow')));Set-Acl -LiteralPath $case -AclObject $a + Start-Service -Name $name +} +if(!(Test-Path -LiteralPath $intent)){throw 'Missing durable intent'} +$i=Get-Content -LiteralPath $intent -Raw|ConvertFrom-Json +if($i.id -cne $id -or $i.binary -cne $p.binary -or $i.source -cne $p.source -or $i.command -cne $command -or $i.service -cne $name){throw 'Retained intent mismatch'} +$service=Get-CimInstance Win32_Service -Filter "Name='RmmWindowsClockReadiness'" +if($service -and ($service.PathName -cne $command -or $service.StartName -notin @('NT AUTHORITY\LocalService','NT AUTHORITY\Local Service'))){throw 'Service owner/configuration mismatch'} +$deadline=[DateTime]::UtcNow.AddSeconds(25) +while($service -and $service.State -ne 'Stopped' -and [DateTime]::UtcNow -lt $deadline){Start-Sleep -Milliseconds 250;$service=Get-CimInstance Win32_Service -Filter "Name='RmmWindowsClockReadiness'"} +if($service -and $service.State -ne 'Stopped'){throw 'Readiness still active; retain case and readback'} +$token=$null;$tokenPath=Join-Path $case 'token.json' +if(Test-Path -LiteralPath $tokenPath){ + if((Get-Item -LiteralPath $tokenPath).Length -gt 1024 -or ((Get-Item -LiteralPath $tokenPath).Attributes -band [IO.FileAttributes]::ReparsePoint)){throw 'Token report bound'} + $token=Get-Content -LiteralPath $tokenPath -Raw|ConvertFrom-Json + if($token.user_sid -cne 'S-1-5-19' -or $token.administrator_member -ne $false -or $token.system_user -ne $false){throw 'Token report identity'} + PrivateFile $tokenPath +} +$data=$null +if(Test-Path -LiteralPath $result){ + if((Get-Item -LiteralPath $result).Length -gt 16384 -or ((Get-Item -LiteralPath $result).Attributes -band [IO.FileAttributes]::ReparsePoint)){throw 'Result bound'} + $data=Get-Content -LiteralPath $result -Raw|ConvertFrom-Json + if($data.case_id -cne $id -or $data.token_sid -cne 'S-1-5-19' -or $data.token.user_sid -cne 'S-1-5-19' -or $data.token.administrator_member -ne $false -or $data.token.system_user -ne $false -or $data.token.elevation_flag -notin @(0,1) -or $data.token.elevation_type -notin @(1,2,3) -or $data.elevated -ne ($data.token.elevation_flag -ne 0) -or $data.service_name -cne $name -or $data.read_only -ne $true){throw 'Actual LocalService report'} + PrivateFile $result +} +if($service){ + $cleanup=Join-Path $case 'cleanup-intent.json' + if(!(Test-Path -LiteralPath $cleanup)){WriteNew $cleanup ([ordered]@{id=$id;command=$command;service=$name;remove_only_own_stopped_service=$true})} + else{$c=Get-Content -LiteralPath $cleanup -Raw|ConvertFrom-Json;if($c.id -cne $id -or $c.command -cne $command -or $c.service -cne $name){throw 'Cleanup intent mismatch'}} + & "$env:WINDIR\System32\sc.exe" delete $name|Out-Null;if($LASTEXITCODE -ne 0){throw 'Readiness cleanup'} +} +[pscustomobject]@{id=$id;native_report=$data;partial_token=$token;service_removed=!(Get-Service -Name $name -ErrorAction SilentlyContinue);service_exit_code=if($service){$service.ExitCode}else{$null};service_specific_exit_code=if($service){$service.ServiceSpecificExitCode}else{$null};no_jobs=$true;no_clock_change=$true;no_agent_change=$true}|ConvertTo-Json -Depth 15 -Compress +''' +LAUNCH = r'''$ErrorActionPreference='Stop' +$p=([Console]::In.ReadLine()|ConvertFrom-Json) +if($p.source -notmatch '^[a-f0-9]{64}$'){throw 'Source hash'} +$file='C:\ProgramData\RustDiscoveryClockReadiness\'+$p.source+'\ClockReadiness.ps1' +if((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.source){throw 'Source changed'} +$inputJson=$p|ConvertTo-Json -Compress +$raw=$inputJson|& "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File $file +if($LASTEXITCODE -ne 0){throw 'Readiness source failed'} +$raw +''' + + +def save(folder, name, value): + fd = os.open(folder / name, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, 'w') as out: + json.dump(value, out, indent=2) + out.flush() + os.fsync(out.fileno()) + + +def stage(path, name): + digest = hashlib.sha256(path.read_bytes()).hexdigest() + value = cb.powershell(PREPARE, dict(sha=digest, name=name)) + if not value['exists']: + access = cb.contract.protected_json(cb.ROOT / 'credentials/windows-dev-access.json') + prefix = access['ssh_prefix'] + args = ['sftp'] + [p for p in prefix[1:-1] if p != '-T'] + ['-b', '-', prefix[-1]] + remote = '/C:/ProgramData/RustDiscoveryClockReadiness/' + digest + '/' + name + batch = 'put ' + json.dumps(str(path.resolve())) + ' ' + json.dumps(remote) + '\n' + result = subprocess.run(args, input=batch.encode(), capture_output=True, timeout=120) + if result.returncode: + raise RuntimeError('CLOCK_ARTIFACT_UPLOAD_FAILED') + if not cb.powershell(PREPARE, dict(sha=digest, name=name))['exists']: + raise RuntimeError('CLOCK_ARTIFACT_READBACK_FAILED') + return digest + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('action', choices=('start', 'readback')) + parser.add_argument('--binary', type=Path) + parser.add_argument('--id') + args = parser.parse_args() + os.umask(0o077) + STATE.mkdir(parents=True, exist_ok=True, mode=0o700) + if args.action == 'start': + if args.id or not args.binary or not args.binary.is_file(): + raise RuntimeError('NEW_CASE_BINARY_REQUIRED') + ident = str(uuid.uuid4()) + folder = STATE / ident + folder.mkdir(mode=0o700) + source_path = folder / 'ClockReadiness.ps1' + fd = os.open(source_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, 'w') as out: + out.write(SCRIPT) + intent = dict(id=ident, binary=hashlib.sha256(args.binary.read_bytes()).hexdigest(), source=hashlib.sha256(SCRIPT.encode()).hexdigest(), no_jobs=True) + save(folder, 'intent.json', intent) + print('Retained readiness case ' + ident, flush=True) + stage(args.binary, 'WindowsClockReadiness.exe') + stage(source_path, 'ClockReadiness.ps1') + save(folder, 'start-intent.json', dict(**intent, action='start')) + else: + if not args.id or args.binary: + raise RuntimeError('READBACK_SAME_CASE_REQUIRED') + ident = str(uuid.UUID(args.id)) + folder = STATE / ident + intent = cb.contract.protected_json(folder / 'intent.json') + if intent['source'] != hashlib.sha256(SCRIPT.encode()).hexdigest(): + raise RuntimeError('QUALIFIED_SOURCE_CHANGED') + result = cb.powershell(LAUNCH, dict(**intent, action=args.action), timeout=60) + save(folder, 'readback-' + str(uuid.uuid4()) + '.json', result) + report = result['native_report'] + if not result['service_removed'] or not report or len(report['samples']) != 2: + raise RuntimeError('READINESS_NATIVE_REPORT_INCOMPLETE') + diagnostic = all(s['trusted'] for s in report['samples']) + qualified = all(s.get('adapter_qualified') is True for s in report['samples']) + ready = diagnostic and qualified + completed = dict(native_execution_verified=True, diagnostic_status_ready=diagnostic, adapter_qualified=qualified, clock_ready=ready, **result) + if not (folder / 'result.json').exists(): + save(folder, 'result.json', completed) + elif cb.contract.protected_json(folder / 'result.json')['native_report'] != report: + raise RuntimeError('IMMUTABLE_NATIVE_REPORT_CHANGED') + print(json.dumps(dict(id=ident,native_execution_verified=True,diagnostic_status_ready=diagnostic,adapter_qualified=qualified,clock_ready=ready,reasons=[s['reason'] for s in report['samples']],rpc_codes=[s['rpc_code'] for s in report['samples']],token=report.get('token'),service_removed=True,no_jobs=True))) + + +if __name__ == '__main__': + main() diff --git a/deploy/windows/runtime_upgrade.py b/deploy/windows/runtime_upgrade.py new file mode 100644 index 0000000..5858ccb --- /dev/null +++ b/deploy/windows/runtime_upgrade.py @@ -0,0 +1,493 @@ +#!/usr/bin/env python3 +"""Qualified passive-only Windows runtime replacement, never a Windows RMM job. + +Native test qualification and binary replacement are separate explicit phases. +Only the parent/orchestrator executes native phases after source review. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import time +import uuid + +import client_bootstrap as cb +import activate_auto_transport as activation +import auto_transport_acceptance as auto + +base=auto.base +require=cb.contract.require +STATE=cb.EVIDENCE/'runtime-upgrade' +TARGET='x86_64-pc-windows-gnu' +IMAGE='rust-discovery-windows-clock-full:local' +ACTIVATION='422562e8-18eb-4865-977d-ab2af65f510b' + +TESTS=r''' +$ErrorActionPreference='Stop' +$p=([Console]::In.ReadLine() | ConvertFrom-Json) +if ($p.name -notin @('windows-tests-lib.exe','windows-tests-bin.exe') -or $p.sha256 -notmatch '^[0-9a-f]{64}$') {throw 'Fixed native test artifact'} +$binary='C:\ProgramData\RustDiscoveryBootstrap\'+$p.sha256+'\'+$p.name +if ((Get-FileHash -LiteralPath $binary -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.sha256) {throw 'Exact native test artifact hash'} +function Run-Own([string]$arguments) { + $si=New-Object Diagnostics.ProcessStartInfo;$si.FileName=$binary;$si.Arguments=$arguments + $si.UseShellExecute=$false;$si.CreateNoWindow=$true;$si.RedirectStandardOutput=$true;$si.RedirectStandardError=$true + $proc=New-Object Diagnostics.Process;$proc.StartInfo=$si + if (!$proc.Start()) {throw 'Native selftest start'} + try { + $stdout=$proc.StandardOutput.ReadToEndAsync();$stderr=$proc.StandardError.ReadToEndAsync() + if (!$proc.WaitForExit(120000)) {$proc.Kill();throw 'Native selftest timeout'} + $out=$stdout.Result;$err=$stderr.Result + if ($out.Length -gt 32768 -or $err.Length -gt 32768) {throw 'Bounded native selftest output'} + return [pscustomobject]@{exit_code=$proc.ExitCode;stdout=$out;stderr=$err} + } finally {$proc.Dispose()} +} +$list=Run-Own '--list --format terse' +if ($list.exit_code -ne 0) {throw 'Native selftest listing failed'} +$result=Run-Own '--test-threads=1' +[pscustomobject]@{listed=$list;result=$result;native_windows=$true;execution_context='bootstrap_administrator_unit_tests';rmm_jobs_created=$false;clock_service_changed=$false} | ConvertTo-Json -Depth 6 -Compress +''' + + +UPGRADE=r''' +$ErrorActionPreference='Stop' +$p=$global:RmmRuntimePayload +if ($null -eq $p -or [string]([guid]$p.id) -cne $p.id -or $p.action -notin @('state','enter','finish','rollback')) {throw 'Fixed passive runtime intent'} +foreach($n in @('old_sha256','new_sha256','probe_sha256','config_sha256')) {if ($p.$n -notmatch '^[0-9a-f]{64}$') {throw 'Qualified hash binding'}} +if ($p.old_sha256 -cne '31e360e50b177b4d5729d24e436d4f25aeed7b1a7bd35f2a129841ba1abffd37' -or $p.new_sha256 -ceq $p.old_sha256) {throw 'Known old passive runtime'} +$name='RmmDiscoveryWindows';$root='C:\ProgramData\RustDiscovery';$state=Join-Path $root 'state';$config=Join-Path $root 'config.json' +$binary='C:\Program Files\RustDiscovery\rmm-agent-windows.exe' +$folder='C:\ProgramData\RustDiscoveryBootstrap\runtime-'+$p.id +$active='C:\ProgramData\RustDiscoveryBootstrap\runtime-active-intent.json' +$uploaded='C:\ProgramData\RustDiscoveryBootstrap\'+$p.new_sha256+'\rmm-agent-windows.exe' +$probe='C:\ProgramData\RustDiscoveryBootstrap\'+$p.probe_sha256+'\RuntimeStateProbe.exe' +$sid=(New-Object Security.Principal.NTAccount('NT SERVICE',$name)).Translate([Security.Principal.SecurityIdentifier]).Value +$allowed=@('S-1-5-18','S-1-5-32-544',$sid) +function Check([string]$path,[bool]$directory) { + $item=Get-Item -LiteralPath $path -Force + if ($item.PSIsContainer -ne $directory -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {throw 'Fixed regular path'} + $acl=Get-Acl -LiteralPath $path;$owner=$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value + if ($owner -notin $allowed -and ($directory -or $owner -cne 'S-1-5-19')) {throw 'Protected owner'} + $rules=@($acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if (!$rules.Count) {throw 'Empty DACL'} + foreach($r in $rules) {if ($r.AccessControlType -ne 'Allow' -or $r.IdentityReference.Value -notin $allowed) {throw 'Unexpected DACL'}} +} +function Hash-Bytes([byte[]]$bytes) { + $hash=[Security.Cryptography.SHA256]::Create() + try {return ([BitConverter]::ToString($hash.ComputeHash($bytes))).Replace('-','').ToLowerInvariant()} finally {$hash.Dispose()} +} +function Hash([string]$path) {Check $path $false;return (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()} +function Acl-Hash([string]$path) {return Hash-Bytes ([Text.Encoding]::UTF8.GetBytes((Get-Acl -LiteralPath $path).Sddl))} +function Write-New([string]$path,$value) { + $bytes=[Text.Encoding]::UTF8.GetBytes(($value | ConvertTo-Json -Depth 24 -Compress)) + $file=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read) + try {$file.Write($bytes,0,$bytes.Length);$file.Flush($true)} finally {$file.Dispose()} +} +function Probe { + if ((Hash $probe) -cne $p.probe_sha256) {throw 'Exact readonly witness artifact'} + $si=New-Object Diagnostics.ProcessStartInfo;$si.FileName=$probe;$si.UseShellExecute=$false;$si.CreateNoWindow=$true;$si.RedirectStandardOutput=$true;$si.RedirectStandardError=$true + $proc=New-Object Diagnostics.Process;$proc.StartInfo=$si + if (!$proc.Start()) {throw 'Readonly witness start'} + try { + $stdout=$proc.StandardOutput.ReadToEndAsync();$stderr=$proc.StandardError.ReadToEndAsync() + if (!$proc.WaitForExit(20000)) {$proc.Kill();throw 'Readonly witness timeout'} + if ($proc.ExitCode -ne 0 -or $stdout.Result.Length -gt 32768 -or $stderr.Result.Length) {throw 'Readonly witness refusal'} + return ($stdout.Result | ConvertFrom-Json) + } finally {$proc.Dispose()} +} +function Snapshot([string]$expected) { + foreach($dir in @('C:\Program Files\RustDiscovery',$root,$state)) {Check $dir $true} + Check $config $false + if ((Get-Item -LiteralPath $config).Length -gt 32768 -or (Hash $config) -cne $p.config_sha256) {throw 'Exact immutable auto configuration'} + $cfg=Get-Content -LiteralPath $config -Raw | ConvertFrom-Json + if ((($cfg.PSObject.Properties.Name|Sort-Object)-join ',') -cne 'ca_file,connect_address,enrollment_token_file,server_name,state_directory,transport' -or $cfg.transport -cne 'auto' -or $cfg.server_name -cne 'discovery.ease-technologies.de' -or $cfg.state_directory -cne $state -or $cfg.ca_file -cne (Join-Path $root 'server-ca.pem') -or $cfg.enrollment_token_file -cne (Join-Path $state 'enrollment.token')) {throw 'Original six-field passive configuration'} + if ((Test-Path -LiteralPath $cfg.enrollment_token_file) -or (Test-Path -LiteralPath (Join-Path $root 'binding.json')) -or (Test-Path -LiteralPath (Join-Path $state 'consumption.sqlite')) -or (Test-Path -LiteralPath (Join-Path $state 'jobs'))) {throw 'Passive only: no token binding ledger or jobs directory'} + $svc=Get-CimInstance Win32_Service -Filter "Name='RmmDiscoveryWindows'" -OperationTimeoutSec 10 + $command='"C:\Program Files\RustDiscovery\rmm-agent-windows.exe" --service --config "C:\ProgramData\RustDiscovery\config.json"' + if ($svc.PathName -cne $command -or $svc.StartName -cne 'NT AUTHORITY\LocalService' -or $svc.StartMode -cne 'Auto') {throw 'Unchanged LocalService deployment'} + $owner=$null + if ($svc.State -eq 'Running') { + $process=Get-CimInstance Win32_Process -Filter ('ProcessId='+$svc.ProcessId) -OperationTimeoutSec 10 + $owner=(Invoke-CimMethod -InputObject $process -MethodName GetOwnerSid -OperationTimeoutSec 10).Sid + if ($owner -cne 'S-1-5-19') {throw 'Actual LocalService identity'} + } + $identity=Get-Content -LiteralPath (Join-Path $state 'identity.json') -Raw | ConvertFrom-Json + if ($identity.agent_id -cne '63ea15b2-0643-403d-b5b4-cba1288dbea3' -or $identity.asset_id -cne 'a176520e-8a91-4e93-a78b-8e7620f430e0') {throw 'Original registered identity'} + if ((Hash $binary) -cne $expected) {throw 'Pinned actual binary'} + $public=[ordered]@{};$acls=[ordered]@{} + foreach($pair in @(@('ca',$cfg.ca_file),@('identity',(Join-Path $state 'identity.json')),@('certificate',(Join-Path $state 'device.pem')))) {$public[$pair[0]]=Hash $pair[1];$acls[$pair[0]]=Acl-Hash $pair[1]} + $key=Join-Path $state 'device.key';Check $key $false;$item=Get-Item -LiteralPath $key + $acls.private_key=Acl-Hash $key + return [pscustomobject]@{agent_id=$identity.agent_id;asset_id=$identity.asset_id;binary_sha256=$expected;binary_acl_sha256=(Acl-Hash $binary);config_sha256=(Hash $config);config_acl_sha256=(Acl-Hash $config);public_hashes=$public;identity_acls=$acls;private_key_metadata=[ordered]@{length=$item.Length;creation_ticks=$item.CreationTimeUtc.Ticks;last_write_ticks=$item.LastWriteTimeUtc.Ticks};private_key_read=$false;service=[ordered]@{state=$svc.State;start_name=$svc.StartName;start_mode=$svc.StartMode;path=$svc.PathName;process_id=$svc.ProcessId;owner_sid=$owner};journal=(Probe)} +} +function Preserved($before,$after,[bool]$frozen) { + foreach($field in @('agent_id','asset_id','config_sha256','config_acl_sha256','binary_acl_sha256')) {if ($before.$field -cne $after.$field) {throw 'Preserved deployment metadata'}} + foreach($field in @('public_hashes','identity_acls','private_key_metadata')) {if (($before.$field|ConvertTo-Json -Compress) -cne ($after.$field|ConvertTo-Json -Compress)) {throw 'Preserved identity metadata'}} + foreach($field in @('database_file_id','database_creation')) {if (($before.journal.$field|ConvertTo-Json -Compress) -cne ($after.journal.$field|ConvertTo-Json -Compress)) {throw 'Original database file identity'}} + if ($after.journal.integrity -cne 'ok' -or $after.journal.sequence -lt $before.journal.sequence -or $after.journal.identity_sha256 -cne $before.journal.identity_sha256 -or $after.journal.consumption_exists -or $after.journal.jobs_directory_exists) {throw 'Preserved passive journal'} + if ($frozen) {foreach($field in @('metadata_sha256','events_sha256')) {if ($before.journal.$field -cne $after.journal.$field) {throw 'Stopped original tables changed'}}} + foreach($row in $before.journal.schema) { + $found=$false + foreach($candidate in $after.journal.schema) { + if ($candidate[0] -ceq $row[0] -and $candidate[1] -ceq $row[1]) { + if ($found -or $candidate[2] -cne $row[2]) {throw 'Original schema changed'} + $found=$true + } + } + if (!$found) {throw 'Original schema missing'} + } + foreach($field in $after.journal.core_counts.PSObject.Properties) {if ($field.Value -ne 0) {throw 'Unexpected job or Sync rows'}} +} +function New-Intent { + if ((Test-Path -LiteralPath $folder) -or (Test-Path -LiteralPath $active)) {throw 'Existing native runtime intent: read finish, never repeat enter'} + New-Item -ItemType Directory -Path $folder | Out-Null + $acl=New-Object Security.AccessControl.DirectorySecurity;$acl.SetAccessRuleProtection($true,$false);$acl.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544'))) + foreach($identity in @('S-1-5-18','S-1-5-32-544')) {$acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($identity)),'FullControl','ContainerInherit,ObjectInherit','None','Allow')))} + Set-Acl -LiteralPath $folder -AclObject $acl +} +function Read-Intent { + Check $folder $true + $intent=Get-Content -LiteralPath (Join-Path $folder 'intent.json') -Raw | ConvertFrom-Json + foreach($field in @('id','old_sha256','new_sha256','probe_sha256','config_sha256')) {if ($intent.payload.$field -cne $p.$field) {throw 'Exact existing native intent'}} + return $intent +} +function Stop-Own {Stop-Service -Name $name;(Get-Service -Name $name).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped,[TimeSpan]::FromSeconds(20))} +function Start-Own {Start-Service -Name $name;(Get-Service -Name $name).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running,[TimeSpan]::FromSeconds(20))} +if ($p.action -eq 'state') {Snapshot $p.old_sha256|ConvertTo-Json -Depth 24 -Compress;exit 0} +if ($p.action -eq 'finish') { + $intent=Read-Intent + $restored=Test-Path -LiteralPath (Join-Path $folder 'rollback-intent.json') + $expected=$p.new_sha256;if ($restored) {$expected=$p.old_sha256} + $after=Snapshot $expected;Preserved $intent.before $after $false + if ($after.service.state -cne 'Running') {throw 'Selected runtime not running; no repeated start'} + [pscustomobject]@{read_only=$true;completed=$true;restored=$restored;id=$p.id;native=$after;original=$intent.before;stop_receipt=(Test-Path -LiteralPath (Join-Path $folder 'stopped.json'));entered_receipt=(Test-Path -LiteralPath (Join-Path $folder 'entered.json'));no_jobs=$true;no_clock_change=$true;no_reboot=$true} | ConvertTo-Json -Depth 24 -Compress;exit 0 +} +try { + if ($p.action -eq 'enter') { + $before=Snapshot $p.old_sha256 + if ($before.service.state -cne 'Running' -or $before.journal.pending_inventory_events -ne 0) {throw 'Settled original runtime required'} + if ((Hash $uploaded) -cne $p.new_sha256) {throw 'New qualified binary upload'} + New-Intent + $intent=[pscustomobject]@{payload=$p;before=$before;binary_sddl=(Get-Acl -LiteralPath $binary).Sddl} + Write-New $active @{id=$p.id;old_sha256=$p.old_sha256;new_sha256=$p.new_sha256;no_jobs=$true} + Write-New (Join-Path $folder 'intent.json') $intent + Write-New (Join-Path $folder 'stop-attempt.json') @{stop_once=$true;no_jobs=$true} + Stop-Own + $stopped=Snapshot $p.old_sha256;Preserved $before $stopped $false + if ($stopped.journal.pending_inventory_events -ne 0) {throw 'Unacknowledged legacy inventory: preserve and inspect'} + Write-New (Join-Path $folder 'stopped.json') $stopped + $candidate=Join-Path $folder 'candidate.exe';[IO.File]::Copy($uploaded,$candidate,$false) + if ((Hash $candidate) -cne $p.new_sha256) {throw 'Exact staged candidate'} + [IO.File]::Replace($candidate,$binary,(Join-Path $folder 'original-binary.exe')) + $acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm($intent.binary_sddl);Set-Acl -LiteralPath $binary -AclObject $acl + if ((Hash (Join-Path $folder 'original-binary.exe')) -cne $p.old_sha256) {throw 'Versioned original binary retained'} + $swapped=Snapshot $p.new_sha256;Preserved $stopped $swapped $true + Write-New (Join-Path $folder 'swapped.json') $swapped + Write-New (Join-Path $folder 'start-attempt.json') @{start_once=$true;no_jobs=$true} + Start-Own + $after=Snapshot $p.new_sha256;Preserved $before $after $false + if ($after.service.state -cne 'Running') {throw 'New runtime stopped after start; no automatic retry'} + Write-New (Join-Path $folder 'entered.json') $after + [pscustomobject]@{entered=$true;id=$p.id;native=$after;no_jobs=$true;no_clock_change=$true;no_reboot=$true}|ConvertTo-Json -Depth 24 -Compress + } else { + $intent=Read-Intent + if (Test-Path -LiteralPath (Join-Path $folder 'rollback-intent.json')) {throw 'Rollback already requested; readback only, no repeated start'} + $actual=Hash $binary + if ($actual -cne $p.old_sha256 -and $actual -cne $p.new_sha256) {throw 'Unknown runtime; refuse rollback overwrite'} + $current=Snapshot $actual;Preserved $intent.before $current $false + Write-New (Join-Path $folder 'rollback-intent.json') @{id=$p.id;actual_sha256=$actual;restore_sha256=$p.old_sha256;no_jobs=$true} + if ($current.service.state -eq 'Running') {Stop-Own} elseif ($current.service.state -ne 'Stopped') {throw 'Unexpected service transition'} + if ($actual -cne $p.old_sha256) { + $backup=Join-Path $folder 'original-binary.exe';if ((Hash $backup) -cne $p.old_sha256) {throw 'Exact original backup'} + $candidate=Join-Path $folder 'rollback-candidate.exe';[IO.File]::Copy($backup,$candidate,$false) + [IO.File]::Replace($candidate,$binary,(Join-Path $folder 'rollback-new-binary.exe')) + $acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm($intent.binary_sddl);Set-Acl -LiteralPath $binary -AclObject $acl + } + Write-New (Join-Path $folder 'rollback-start-attempt.json') @{start_once=$true;no_jobs=$true} + Start-Own + $after=Snapshot $p.old_sha256;Preserved $intent.before $after $false + Write-New (Join-Path $folder 'rollback-result.json') $after + [pscustomobject]@{restored=$true;id=$p.id;native=$after;no_jobs=$true;no_reboot=$true}|ConvertTo-Json -Depth 24 -Compress + } +} catch { + if (Test-Path -LiteralPath $folder) {Write-New (Join-Path $folder ('error-'+[guid]::NewGuid().ToString()+'.json')) @{incomplete=$true;error_type=$_.Exception.GetType().FullName;line=$_.InvocationInfo.ScriptLineNumber;no_retry_start=$true}} + throw +} +''' + + +def digest(path):return hashlib.sha256(Path(path).read_bytes()).hexdigest() +def write(folder,name,value): + descriptor=os.open(folder/name,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600) + with os.fdopen(descriptor,'w') as stream:json.dump(value,stream,indent=2);stream.write('\n');stream.flush();os.fsync(stream.fileno()) + + +def source_files(): + names=['Cargo.toml','Cargo.lock','rust-toolchain.toml','crates/agent-windows/Cargo.toml','crates/agent-windows/build.rs'] + for name in ['main','lib','runtime','native','inventory','journal','service','process','actions','clock']: + names.append('crates/agent-windows/src/'+name+'.rs') + names+=['crates/agent-windows/examples/runtime_state.rs'] + names+=['crates/agent/src/'+name+'.rs' for name in ['https_channel','transport','wire_channel']] + for crate in ['agent-core','domain','protocol']: + names.append('crates/'+crate+'/Cargo.toml') + if crate=='agent-core':names.extend('crates/agent-core/src/'+name+'.rs' for name in ['lib','auth','crypto','jobs','ledger','reconcile']) + else:names.extend(str(path.relative_to(cb.ROOT)) for path in sorted((cb.ROOT/'crates'/crate/'src').glob('*.rs'))) + names.extend(str(path.relative_to(cb.ROOT)) for path in sorted((cb.ROOT/'crates/agent-windows/native').glob('*')) if path.is_file()) + names.append('proto/agent.proto') + require(all((cb.ROOT/name).is_file() for name in names),'all default-profile build sources must exist/freeze first') + return {name:digest(cb.ROOT/name) for name in sorted(set(names))} + + +def stable(manifest): + require(manifest['architecture']==TARGET and manifest['default_features'] is True + and manifest['system_helper_feature'] is False,'qualified default unprivileged Windows profile') + require(all((cb.ROOT/name).is_file() and digest(cb.ROOT/name)==sha for name,sha in manifest['source_files'].items()),'qualified source drift') + for item in manifest['artifacts'].values(): + path=Path(item['path']);require(path.is_file() and digest(path)==item['sha256'],'qualified artifact changed') + + +def command(arguments,timeout=300): + result=subprocess.run(arguments,capture_output=True,timeout=timeout) + if result.returncode:raise RuntimeError('LOCAL_BUILD_FAILED_'+str(result.returncode)) + return result.stdout + + +def build(): + """Local cross-build only; source must already have been frozen by owners.""" + os.umask(0o077);STATE.mkdir(mode=0o700,parents=True,exist_ok=True) + folder=STATE/('build-'+str(uuid.uuid4()));folder.mkdir(mode=0o700) + before=source_files();write(folder,'source-before.json',before) + target=cb.ROOT/'devstate/windows-runtime/target';target.mkdir(mode=0o700,parents=True,exist_ok=True) + script='cargo clippy --locked --offline --target '+TARGET+' -p rmm-agent-windows --all-targets -- -D warnings && cargo build --locked --offline --target '+TARGET+' -p rmm-agent-windows --bin rmm-agent-windows --example runtime_state --release && cargo test --locked --offline --target '+TARGET+' -p rmm-agent-windows --lib --bin rmm-agent-windows --no-run --message-format=json' + raw=command(['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,size=512m', + '-v',str(cb.ROOT)+':/src:ro','-v',str(target)+':/target','-e','CARGO_TARGET_DIR=/target','--entrypoint','/bin/sh',IMAGE,'-c',script]) + require(source_files()==before,'source changed during local build; do not qualify') + units={} + for line in raw.decode().splitlines(): + try:item=json.loads(line) + except ValueError:continue + if item.get('reason')=='compiler-artifact' and 'rmm-agent-windows' in item.get('package_id',''): + require('system-helper' not in item.get('features',[]),'system helper excluded from passive qualification') + if item.get('reason')=='compiler-artifact' and item.get('profile',{}).get('test') and item.get('executable'): + kind=item['target']['kind'];key='lib' if 'lib' in kind else 'bin' if 'bin' in kind else None + if key:units[key]=target/Path(item['executable']).relative_to('/target') + require(set(units)=={'lib','bin'},'both actual compiled native test executables') + artifacts={} + for key,path,name,release in [('agent',target/TARGET/'release/rmm-agent-windows.exe','rmm-agent-windows.exe',True), + ('probe',target/TARGET/'release/examples/runtime_state.exe','RuntimeStateProbe.exe',True), + ('lib',units['lib'],'windows-tests-lib.exe',False),('bin',units['bin'],'windows-tests-bin.exe',False)]: + destination=folder/name;shutil.copyfile(path,destination);destination.chmod(0o600) + original_sha=digest(path) + if key in ('lib','bin'): + # Strip only the private delivery copy. Preserve Cargo's original + # linked executable and all prior manifests/native observations. + command(['docker','run','--rm','--network','none','--read-only', + '-v',str(folder.resolve())+':/artifacts', + '--entrypoint','x86_64-w64-mingw32-strip',IMAGE, + '--strip-debug','/artifacts/'+name]) + require(digest(path)==original_sha,'original native unit link preserved') + data=destination.read_bytes();offset=int.from_bytes(data[60:64],'little') + require(data[:2]==b'MZ' and data[offset:offset+6]==b'PE\0\0\x64\x86','native x86-64 PE artifact') + artifacts[key]=dict(path=str(destination.resolve()),name=name,sha256=digest(destination),bytes=len(data),release_build=release) + if key in ('lib','bin'): + artifacts[key].update(debug_stripped=True,original_link_path=str(path.resolve()),original_link_sha256=original_sha) + require(source_files()==before,'source changed during artifact preparation; do not qualify') + manifest=dict(schema_version=1,architecture=TARGET,default_features=True,system_helper_feature=False, + source_files=before,artifacts=artifacts,checks=dict(cross_clippy_D_warnings=True,release_build=True,windows_unit_link=True),native_vm_tested=False) + write(folder,'manifest.json',manifest) + print(json.dumps(dict(manifest=str((folder/'manifest.json').resolve()),artifacts={k:v['sha256'] for k,v in artifacts.items()},native_vm_tested=False))) + + +def upload(item): + pointer=cb.EVIDENCE/(item['name']+'.latest.json') + if pointer.exists() and cb.contract.protected_json(pointer)['sha256']==item['sha256']: + return cb.powershell(cb.VERIFY_UPLOAD,dict(name=item['name'],sha256=item['sha256'])) + return cb.upload(item['path'],item['name']) + + +def qualify(manifest_path): + manifest=cb.contract.protected_json(manifest_path);stable(manifest) + os.umask(0o077);STATE.mkdir(mode=0o700,parents=True,exist_ok=True) + folder=STATE/('qualification-'+str(uuid.uuid4()));folder.mkdir(mode=0o700) + write(folder,'intent.json',dict(manifest_path=str(manifest_path.resolve()),manifest_sha256=digest(manifest_path),source_files=manifest['source_files'],test_runner_sha256=hashlib.sha256(TESTS.encode()).hexdigest())) + before=auto.scopes();flags=auto.status();write(folder,'server-before.json',dict(counts=before,flags=flags)) + reports={} + for key,minimum in [('lib',12),('bin',6)]: + item=manifest['artifacts'][key];upload(item) + report=cb.powershell(TESTS,dict(name=item['name'],sha256=item['sha256']),timeout=150) + write(folder,key+'-native.json',report) + require(report['listed']['exit_code']==report['result']['exit_code']==0,'native unit executable success') + listed=re.findall(r'^(.+): test\r?$',report['listed']['stdout'],re.M) + summary=re.search(r'test result: ok\. (\d+) passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;',report['result']['stdout']) + require(summary and len(listed)>=minimum and int(summary.group(1))==len(listed),'all actually listed native tests passed with zero skipped/filtered') + reports[key]=dict(artifact_sha256=item['sha256'],passed=len(listed),test_names=listed,native_context='bootstrap_administrator_unit_tests') + stable(manifest) + after=auto.scopes();after_flags=auto.status();require(after==before and flags==after_flags and auto.flags_disabled(flags),'native units changed no job counts or server policy/hooks') + write(folder,'result.json',dict(verified=True,completed=True,native_unit_tests=reports,manifest_path=str(manifest_path.resolve()),manifest_sha256=digest(manifest_path),source_files=manifest['source_files'],server_counts=after,server_flags=flags, + no_jobs=True,no_clock_service_changes=True,local_service_runtime_test=False,clock_adapter_qualified=False)) + print(json.dumps(dict(verified=True,qualification=str((folder/'result.json').resolve()),native_tests={k:v['passed'] for k,v in reports.items()},clock_adapter_qualified=False))) + + +PREPARE_SOURCE=base.PREPARE_SCRIPT.replace('TransportAcceptance.ps1','RuntimeUpgrade.ps1') +LAUNCH_SOURCE=base.LAUNCH_SCRIPT.replace('TransportAcceptance.ps1','RuntimeUpgrade.ps1').replace('RmmTransportPayload','RmmRuntimePayload') + + +def stage_source(): + raw=UPGRADE.encode();sha=hashlib.sha256(raw).hexdigest() + value=cb.powershell(PREPARE_SOURCE,dict(sha256=sha)) + if not value['already_uploaded']: + folder=STATE/'source';folder.mkdir(mode=0o700,parents=True,exist_ok=True) + path=folder/(sha+'.ps1') + if not path.exists(): + fd=os.open(path,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600) + with os.fdopen(fd,'wb') as stream:stream.write(raw);stream.flush();os.fsync(stream.fileno()) + require(digest(path)==sha,'fixed staged source bytes') + prefix=cb.contract.protected_json(cb.ROOT/'credentials/windows-dev-access.json')['ssh_prefix'] + arguments=['sftp']+[v for v in prefix[1:-1] if v!='-T']+['-b','-',prefix[-1]] + target='/C:/ProgramData/RustDiscoveryBootstrap/'+sha+'/RuntimeUpgrade.ps1' + result=subprocess.run(arguments,input=('put '+json.dumps(str(path.resolve()))+' '+json.dumps(target)+'\n').encode(),capture_output=True,timeout=60) + require(result.returncode==0,'fixed runtime bootstrap transfer') + require(cb.powershell(PREPARE_SOURCE,dict(sha256=sha))['already_uploaded'],'staged source hash verification') + return sha + + +def remote(intent,action): + require(intent['source_sha256']==hashlib.sha256(UPGRADE.encode()).hexdigest(),'preserved exact runtime bootstrap source') + payload={**intent['remote_payload'],'action':action} + return cb.powershell(LAUNCH_SOURCE,dict(sha256=intent['source_sha256'],payload=payload),timeout=100,remote_signed=True) + + +def manifest_and_qualification(manifest_path,qualification_path): + manifest=cb.contract.protected_json(manifest_path);stable(manifest) + qualified=cb.contract.protected_json(qualification_path) + require(qualified['verified'] is True and qualified['completed'] is True + and qualified['manifest_sha256']==digest(manifest_path) + and qualified['manifest_path']==str(manifest_path.resolve()) + and qualified['source_files']==manifest['source_files'] + and qualified['native_unit_tests']['lib']['artifact_sha256']==manifest['artifacts']['lib']['sha256'] + and qualified['native_unit_tests']['bin']['artifact_sha256']==manifest['artifacts']['bin']['sha256'] + and qualified['native_unit_tests']['lib']['passed']>=12 and qualified['native_unit_tests']['bin']['passed']>=6 + and qualified['no_jobs'] is True and qualified['clock_adapter_qualified'] is False,'source-bound completed native library/bin qualification') + return manifest,qualified + + +def upgrade(manifest_path,qualification_path): + manifest,qualified=manifest_and_qualification(manifest_path,qualification_path) + current=cb.contract.protected_json(activation.CURRENT) + require(current['type']=='rmm.windows.current-transport' and current['case_id']==ACTIVATION + and current['transport']=='auto' and current['binary_sha256']==base.BINARY,'known original native automatic transport index') + derived=activation.transition(ACTIVATION) + require(derived['original_config_sha256']==base.ORIGINAL_CONFIG + and derived['expected_auto_config_sha256']==current['config_sha256'],'independently derived original auto bytes') + os.umask(0o077);STATE.mkdir(mode=0o700,parents=True,exist_ok=True) + ident=str(uuid.uuid4());folder=STATE/ident;folder.mkdir(mode=0o700) + for key in ['agent','probe']:upload(manifest['artifacts'][key]) + source=stage_source() + payload=dict(id=ident,old_sha256=base.BINARY,new_sha256=manifest['artifacts']['agent']['sha256'], + probe_sha256=manifest['artifacts']['probe']['sha256'],config_sha256=current['config_sha256']) + intent=dict(id=ident,type='passive_runtime_upgrade',started_at=cb.contract.now().isoformat(),source_sha256=source, + manifest_path=str(manifest_path.resolve()),manifest_sha256=digest(manifest_path),qualification_path=str(qualification_path.resolve()), + qualification_sha256=digest(qualification_path),remote_payload=payload,config_derivation=derived, + original_transport_index=dict(path=str(activation.CURRENT.resolve()),sha256=digest(activation.CURRENT)), + no_jobs=True,no_binding_or_policy_change=True,no_clock_change=True,no_reboot=True) + write(folder,'intent.json',intent) + before=dict(native=remote(intent,'state'),central=base.observe(ident),counts=auto.scopes(),server=auto.status()) + require(before['counts']==qualified['server_counts'] and before['server']==qualified['server_flags'] + and auto.flags_disabled(before['server']),'unchanged settled job/policy state after qualification') + require(before['native']['service']['state']=='Running' and before['native']['journal']['pending_inventory_events']==0,'settled original service and acknowledged inventory') + write(folder,'before.json',before) + write(folder,'enter-intent.json',dict(id=ident,stop_swap_start_once=True,source_sha256=source)) + try:write(folder,'entered.json',remote(intent,'enter')) + except Exception as error: + write(folder,'enter-reply-incomplete.json',dict(error_type=type(error).__name__,continuation='finish reads only; explicit rollback is separate, never repeat enter')) + raise + print('Passive runtime transition '+ident,flush=True) + finish(ident) + + +def load_case(ident): + ident=str(uuid.UUID(ident));folder=STATE/ident + intent=cb.contract.protected_json(folder/'intent.json') + require(intent['id']==ident and intent['type']=='passive_runtime_upgrade','same retained runtime case') + require(digest(intent['manifest_path'])==intent['manifest_sha256'] and digest(intent['qualification_path'])==intent['qualification_sha256'],'historical qualification files unchanged') + manifest,_=manifest_and_qualification(Path(intent['manifest_path']),Path(intent['qualification_path'])) + return folder,intent,manifest + + +def publish_current(folder,result_name,binary): + result=folder/result_name + value=dict(schema_version=1,type='rmm.windows.current-runtime',case_id=folder.name,agent_id=base.AGENT, + asset_id=base.ASSET,binary_sha256=binary,transport='auto',evidence=dict(path=str(result.resolve()),sha256=digest(result)), + windows_jobs_enabled=False,clock_adapter_qualified=False) + path=cb.EVIDENCE/'current-runtime.json' + if path.exists(): + previous=cb.contract.protected_json(path) + if previous==value:return + require(previous['case_id']==folder.name,'do not overwrite another current runtime transition') + backup=folder/('previous-index-'+str(uuid.uuid4())+'.json');write(folder,backup.name,previous) + temporary=path.with_name('.runtime-'+str(uuid.uuid4())+'.json') + write(temporary.parent,temporary.name,value);os.replace(temporary,path) + + +def finish(ident): + folder,intent,manifest=load_case(ident) + restored=(folder/'rollback-intent.json').exists() + before=cb.contract.protected_json(folder/'before.json') + observed=remote(intent,'finish');write(folder,'finish-readback-'+str(uuid.uuid4())+'.json',observed) + expected=base.BINARY if restored else manifest['artifacts']['agent']['sha256'] + require(observed['completed'] is True and observed['read_only'] is True and observed['restored']==restored and observed['native']['binary_sha256']==expected,'actual retained selected runtime; no second start') + started=cb.contract.protected_json(folder/'rollback-intent.json')['started_at'] if restored else intent['started_at'] + online=base.wait_mode(ident,'wss',cb.contract.timestamp(started),before['central']['device']) + after=remote(intent,'finish');write(folder,'after-readback-'+str(uuid.uuid4())+'.json',after) + native=after['native'];require(native['journal']['pending_inventory_events']==0 and native['journal']['sequence']>before['native']['journal']['sequence'],'actual new process heartbeat sequence and concrete inventory ACK') + device=base.read_device();denied=base.foreign_denied() + require(cb.contract.timestamp(device['observed_at'])>=cb.contract.timestamp(intent['started_at']),'fresh upgraded inventory stored independently') + observations={o['scope']:o for o in device['inventory'].get('observations',[])} + hardware=observations.get('windows.hardware',{}) + if not restored:require(hardware.get('quality')=='valid' and hardware['data']['logical_processors_visible']>0 + and hardware['data']['memory_total_bytes']>0,'actual unprivileged native hardware observation') + counts=auto.scopes();flags=auto.status();require(counts==before['counts'] and flags==before['server'] and auto.flags_disabled(flags),'both target job counts/policy/fault hooks preserved') + stable(manifest) + result_name='rollback-completed.json' if restored else 'result.json' + result=folder/result_name + value=dict(verified=True,completed=True,restored=restored,id=ident,native=native,online=online,stored_inventory=device,foreign_denied=denied, + manifest_path=intent['manifest_path'],manifest_sha256=intent['manifest_sha256'],qualification_sha256=intent['qualification_sha256'], + counts=counts,server=flags,no_jobs=True,no_reboot=True,no_clock_change=True,windows_jobs_enabled=False, + clock_adapter_qualified=False,private_key_read=False,configuration_unchanged=True,transport='auto',preferred_wire='wss') + if result.exists():require(cb.contract.protected_json(result)['verified'] is True,'retain prior successful runtime result') + else:write(folder,result_name,value) + publish_current(folder,result_name,expected) + print(json.dumps(dict(verified=True,id=ident,passive_only=True,clock_adapter_qualified=False,windows_jobs_enabled=False))) + + +def rollback(ident): + folder,intent,_=load_case(ident) + before=cb.contract.protected_json(folder/'before.json') + require(auto.scopes()==before['counts'] and auto.status()==before['server'],'no intervening job/policy changes before explicit rollback') + write(folder,'rollback-intent.json',dict(id=ident,old_binary_sha256=base.BINARY,started_at=cb.contract.now().isoformat(),start_once=True,no_jobs=True)) + try:value=remote(intent,'rollback') + except Exception as error: + write(folder,'rollback-reply-incomplete.json',dict(error_type=type(error).__name__,readback_required=True,no_repeated_start=True));raise + write(folder,'rollback-result.json',value) + require(value['restored'] is True and value['native']['binary_sha256']==base.BINARY,'actual preserved original binary restored') + finish(ident) + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('phase',choices=['build-local','qualify-native','upgrade-passive','finish','rollback']) + parser.add_argument('--manifest',type=Path);parser.add_argument('--qualification',type=Path);parser.add_argument('--id') + args=parser.parse_args() + if args.phase=='build-local':require(not(args.manifest or args.qualification or args.id),'build creates a fresh immutable manifest');build() + elif args.phase=='qualify-native':require(args.manifest and not(args.qualification or args.id),'one qualified local manifest');qualify(args.manifest) + elif args.phase=='upgrade-passive':require(args.manifest and args.qualification and not args.id,'native qualified same manifest, no supplied new case ID');upgrade(args.manifest,args.qualification) + else:require(args.id and not(args.manifest or args.qualification),'same original transition ID only');{'finish':finish,'rollback':rollback}[args.phase](args.id) + + +if __name__=='__main__': + try:main() + except Exception as error: + print('WINDOWS_RUNTIME_UPGRADE_INCOMPLETE:'+type(error).__name__) + raise SystemExit(2) from None diff --git a/docs/handover.md b/docs/handover.md index 618cc99..bfabefb 100644 --- a/docs/handover.md +++ b/docs/handover.md @@ -52,6 +52,23 @@ Zugänge und private Rohbelege bleiben gitignoriert. ## Aktuelle Windowsfortsetzung +Neuester passiver Windowsstand: Agent `f64e8115…`, eigener erhaltender Fall +`c4f9b280-e83d-4b8e-a1c2-1cd103f73eda`, tatsächlicher LocalService/Auto/WSS, +gleiche Identität/Schlüsselmetadaten/ACLs und ursprüngliche Telemetrie-DB. +Neue Hardware-/begrenzte Softwarebeobachtungen, zwei frische Heartbeats und +konkretes Inventar-ACK nachgewiesen. Davor native Default-Unitqualifikation +`3dbfe686-6e91-41e9-a5bc-078f7a4e3e6a`:12+6 tatsächlich bestanden. +Jobs bleiben deaktiviert, Clockadapter fest unqualifiziert, kein Signingbinding, +Verbrauchsledger oder Jobsverzeichnis angelegt. W32Time gestoppt und unverändert; +dessen Start und eine mögliche nur prozessbezogene RemoteSigned-Option wurden +konkret beim Benutzer angefragt, noch nicht genehmigt. SYSTEM-Helperquelle nur +featureisoliert vorbereitet, noch nicht installiert/nativ als Dienst abgenommen. +Nach tatsächlichem Codecfehler wurde die Probevariante strikt korrigiert; +eigener Fall `38b0fe75-f6a5-4ad3-ab2d-7f3acf7e9cbd` bestand alle21 nativen +Unitfixtures, kein tatsächlicher SYSTEM-/Pipepeer-Nachweis. +Details und Grenzen im [Implementierungsstand](implementation-status.md) und +[Clockbericht](windows-clock-readiness.md). Notebook weiterhin nur Entwicklung. + **Fortsetzung 2026-11-14:** Gemeinsamer `rmm-agent-core` und Linuxadapter implementiert. Eigene Core-Unittests zuerst auf Cloud-Linux (25) und danach auf Windows (24) nativ ohne Skip bestanden; Fall diff --git a/docs/implementation-status.md b/docs/implementation-status.md index 50492eb..7d72ca3 100644 --- a/docs/implementation-status.md +++ b/docs/implementation-status.md @@ -1,5 +1,58 @@ # Tatsächlicher Implementierungsstand +## Windows-Laufzeit erhaltend als LocalService aktualisiert — 2026-11-14 + +Zusätzlicher Helper-Quelllauf: zunächst20/21 native Fixtures bestanden; Serde +akzeptierte bei einer intern getaggten Unit-Variante unerwartete Probe-Felder. +Die Variante ist jetzt eine strikt leere Struktur, unverändertes Wireformat +`{"operation":"probe"}`. Der ursprüngliche Negativtest bleibt erhalten. +Neuer Fall `38b0fe75-f6a5-4ad3-ab2d-7f3acf7e9cbd` bestand tatsächlich alle21 +Fixtures einschließlich neun Helperfälle, ohne Skip, als Bootstrapadministrator. +Das qualifiziert Codec-/Guardfixturen, keinen laufenden SYSTEM-Dienst oder +tatsächliche Pipepeers. Die Helperquelle wurde zusätzlich unabhängig auf +Grantintervall, echte SCM-Prozessidentität, Dependencies/Groups, Recoveryaktionen +und Deadline geprüft. Recovery-Command/Reboot/Restart bleiben verweigert; +überschrittene SCM-Laufzeit nach möglicher Wirkung bleibt Unknown. Eine synchrone +SCM-API kann trotzdem blockieren; keine harte Effektabbruchgarantie behauptet. + +Die Default-Laufzeit integriert jetzt den gemeinsamen Jobkern, additive +Telemetrie-/Jobtabellen und monotone Sequenzmigration. Der PowerShell-5.1- +Executor ist implementiert: unveränderte genehmigte Skriptbytes, einzelne +Argumente, begrenzte Rohbytes, atomare Windows-Jobobject-Zuordnung und explizite +Handlevererbung. Maschinenrichtlinien werden nicht verändert; die Ausführungs- +richtlinie wird derzeit geerbt. Timeout/Abbruch kann eine Wirkung hinterlassen +und wird deshalb nicht als erfolgreicher oder sicher wiederholbarer Lauf gewertet. +Dies ist noch kein tatsächlicher Windows-RMM-Jobnachweis. + +Native Qualifikation `3dbfe686-6e91-41e9-a5bc-078f7a4e3e6a`: alle12 Library- +und6 Binarytests ohne Skip bestanden, als Bootstrapadministrator. Ein früherer +Fall bestand bereits12 Tests, verlor danach beim Übertragen der großen zweiten +Testdatei die Antwort und bleibt unvollständig. Neue, vor Hashbildung von +Debuginformationen befreite Testkopien wurden beide erneut tatsächlich geprüft; +Originalartefakte und frühere Berichte blieben erhalten. Cross-Clippy mit +`-D warnings`, Releasebuild und Quellenbindung bestanden. + +Anschließend eigener erhaltender Dienstwechsel +`c4f9b280-e83d-4b8e-a1c2-1cd103f73eda`: Agent `f64e8115…` läuft tatsächlich +als LocalService SID19, automatisch, mit unverändertem `transport=auto` und +bevorzugtem WSS. Geräteidentität, Zertifikat, private Schlüsselmetadaten, +Konfiguration/ACLs und ursprüngliche Telemetrie-DB-Dateiidentität erhalten; +Integrität `ok`, Sequenz steigt, zwei frische Heartbeats und konkretes Inventar- +ACK nachgewiesen. Neue CPU-/Speicher- und begrenzte64-/32-Bit-HKLM-Software- +beobachtungen wurden unabhängig auf dem Server gelesen; explizit Teilinventar, +kein `Win32_Product`, kein vollständiger Patchstatus. Fremder Tenant verweigert. + +Windows bleibt0 Jobs/Outbox/Grants/ungeklärte Wirkungen, Linux30/30/26/0. +Kein Binding, Verbrauchsledger oder Jobsverzeichnis angelegt; keine neue +Ausführungscapability. `enable_jobs=false` und `ADAPTER_QUALIFIED=false` bleiben +geschlossen. Der implementierte Zeitadapter und seine tatsächlichen negativen +Zwischenstände stehen in [Windows-Zeitstatus](windows-clock-readiness.md). +W32Time blieb gestoppt; dessen Start und eine etwaige prozessbezogene +PowerShell-Richtlinie warten auf die jeweils konkrete Benutzerentscheidung. +Die SYSTEM-Helperquelle ist featureisoliert; daraus folgt keine native Helper-, +Pipe- oder Systemaktionsabnahme. Geschützte Belege: +`devstate/windows-client/runtime-upgrade//`. + ## Dauerhafte Outcomes und atomarer Start nativ geprüft — 2026-11-14 Beim Portieren wurde eine bestehende Verfügbarkeitslücke gefunden: Ein Crash diff --git a/docs/windows-clock-readiness.md b/docs/windows-clock-readiness.md new file mode 100644 index 0000000..a827180 --- /dev/null +++ b/docs/windows-clock-readiness.md @@ -0,0 +1,229 @@ +# Windows-Zeitstatus: Adapter und native Readinessprobe + +Stand 2026-11-14. Ergänzung zu [Windows-Jobgrenze](windows-job-boundary.md). +Diese Strecke ändert weder die Windows-Geräteidentität noch die WebUI-Grenze. +Ein Zeitstatusbericht ist keine Jobgenehmigung. `NativeClock::now()` verweigert +aktuell immer mit `CLOCK_ADAPTER_UNQUALIFIED`, unabhängig von einem positiven +Diagnosestatus; `ADAPTER_QUALIFIED=false` bleibt bis zur tatsächlichen nativen +Adapterabnahme im Code fest geschlossen. Der aktuelle RPC-Prototyp ist +noch kein vollständig qualifizierter produktiver Zeitvertrauensnachweis. + +## Vertrag und konservative Genauigkeitspolitik + +`crates/agent-windows/src/clock.rs` enthält eine numerische Statusauswertung und +einen `SyncClock`-Adapter. Ein Stub wird aus dem engen IDL mit WIDL generiert; +der C-Adapter fängt RPC-Ausnahmen mittels Windows-SEH vor der Rust-Grenze ab. +Einziger aufgerufener Statusvertrag ist MS-W32T Interface4.1, Opnum6. Die sechs +vorherigen IDL-Platzhalter erhalten ausschließlich dessen Ordinal; sie werden +niemals aufgerufen und bilden keine mutierenden Produktfunktionen ab. + +Die Zeitintervalle für Verzögerung, Dispersion, Phasenabweichung und Alter sind +100ns-Einheiten. `qwLastSyncTicks` ist dagegen ein UTC-FILETIME seit1601; +`tpTimeLastGoodSync` bezeichnet das verstrichene Alter seit dem letzten guten +Abgleich, kein zweites UTC-Datum: +[Statusstruktur](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/f60ebce0-df96-4c96-b40b-fdbd34a2c936), +[Zeitdienstelemente](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/1da649d7-3edf-4a9a-98c2-907ecacd1633). + +Der technische Default verlangt gemeinsam: + +- `SYNC=2`, letztes Syncergebnis0, Leap0..2 und Stratum1..15; +- letzten erfolgreichen Abgleich höchstens3600s alt, UTC-Zeitstempel nicht in + der Zukunft, beide Altersdarstellungen innerhalb1s plus Abrufdauer konsistent; +- Dispersion + halbe nichtnegative Root-Roundtripverzögerung + absolute + Phasenabweichung + gesamte gemessene Abrufdauer höchstens2s; +- Abrufdauer höchstens1s, bekannte Flags und exaktes x64-Strukturlayout120Byte. + +Negative Root-Verzögerung wird konservativ verweigert, auch wenn einzelne +Zeitquellen solche Werte liefern können. Überlauf, unbekannte Felder, Fehler, +veralteter oder widersprüchlicher Status schließen das Gate. Das separate +MS-SNTP-Authentifizierungsflag wird nicht über die bestehende Linux-NTP-Politik +hinaus verlangt. Die Werte begrenzen die gemeldete technische Unsicherheit; +sie ersetzen keine neue kryptografische Vertrauensentscheidung für Zeitquellen. +[Synczustände](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/b4abb4b0-6d6e-41e4-bd41-d54980d0598a). + +Wallclock und beide präzisen Kernel-Interruptzähler werden vor und nach jedem +Abruf beobachtet. Der unbereinigte Zähler berücksichtigt Schlafzeit, der +unbiased-Zähler schließt sie aus. Eine Differenz oder Wallclockänderung über1s +invalidiert. Ein späterer Status kann erst nach einem tatsächlich erfolgreichen +Abgleich mit UTC-Zeitstempel nach dieser Diskontinuität wieder öffnen. Einfaches +Pollieren des alten Pre-Resume-Status genügt nicht. Es wird kein OS-Suspend oder +Uhrsprung als destruktiver nativer Test ausgelöst: +[Interruptzähler](https://learn.microsoft.com/en-us/windows/win32/api/realtimeapiset/nf-realtimeapiset-queryinterrupttimeprecise), +[Zähler ohne Schlafzeit](https://learn.microsoft.com/en-us/windows/win32/api/realtimeapiset/nf-realtimeapiset-queryunbiasedinterrupttimeprecise). + +## Lokaler RPC und verbleibende Identitätsfrage + +Der erste Readiness-Prototyp benutzt ausschließlich lokalen `ncacn_np` am +festen authentifizierten Endpunkt `\\pipe\\W32TIME_ALT`, WINNT, PacketPrivacy, +Identify und den tatsächlichen Prozesskontext; keine Zugangsdaten und kein +Fallback zum unauthentifizierten W32TIME-Endpunkt. Der NDR-Allocator begrenzt +seine Gesamtdaten auf64KiB. RPC-Timeout1,5s ist ein Paket-Inaktivitätslimit; +zusätzlich verweigert die Auswertung jede tatsächlich über1s dauernde Abfrage. +Ausgaben enthalten nur begrenzte numerische Statusfelder und Fehlercodes, keine +Peer-Namen, Adressen oder Rohdaten. +[MS-W32T-Transport](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/e0803f6b-e175-4b87-ba63-bbcf51175655), +[RPC-Zeitlimit](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/nf-rpcdce-rpcbindingsetoption). + +WINNT mit PacketPrivacy authentifiziert allein noch nicht zuverlässig die +Identität des lokalen Named-Pipe-Servers. NTLM kann auch bei gesetztem +`MUTUAL_AUTH` Erfolg melden, obwohl es keine gegenseitige Authentifizierung +unterstützt. Eine solche Flagänderung ist kein Sicherheitsnachweis. Vor +Produktintegration muss zusätzlich die tatsächliche Serveridentität belastbar +gebunden werden. `RPC_SECURITY_QOS_V3.Sid` ist insbesondere für `ncalrpc` +dokumentiert; ob die aktuelle W32Time-Implementierung einen entsprechend +qualifizierbaren lokalen Endpunkt anbietet, ist offen. Kein automatischer +Wechsel auf einen schwächeren Transport. +[RPC-QoS](https://learn.microsoft.com/en-us/windows/win32/rpc/quality-of-service), +[SID-Vertrag](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/ns-rpcdce-rpc_security_qos_v3_w). + +## Getrennte LocalService-Probe + +`examples/clock_readiness.rs` ist ein eigener kurzlebiger SCM-Dienst +`RmmWindowsClockReadiness`. Er prüft im eigenen nativen Prozess TokenUser +`S-1-5-19`, erfasst das tatsächliche Elevationflag und den Elevationtyp sowie +aktivierte Administratormitgliedschaft und SYSTEM-Identität separat, liest zwei +Zeitstatuswerte und schreibt einen +höchstens16KiB großen Bericht. Keine RMM-Verbindung, kein Agentenstop, keine +Uhrkorrektur und keine Änderung von W32Time-Konfiguration oder System-ACLs. + +`deploy/windows/clock_readiness.py` legt für jeden Versuch einen neuen privaten +Fall mit UUID, Source-/Binaryhash und dauerhaftem Intent vor dem RPC an. +Bootstrapdateien liegen versioniert unter einem eigenen privaten Verzeichnis. +Nur der eigene Readiness-Dienst erhält Schreibrecht auf seinen Ergebnisordner; +das Manifest bleibt Administratoren/SYSTEM vorbehalten. Nach Dienstende werden +Statusbericht und exakte Dienstkonfiguration gelesen und ausschließlich dieser +eng gebundene gestoppte Hilfsdienst entfernt. Ausgelieferte Dateien und private +Belege bleiben für Readback erhalten. Der vorhandene Bootstrap verwendet nur +prozessbezogen `RemoteSigned`, keine Maschinenrichtlinienänderung und keine +entsprechende Erlaubnis für spätere RMM-PowerShell-Jobs. + +Nach unklarer SSH-Antwort ausschließlich `readback --id ` +verwenden. Kein erneutes Starten desselben Falls, kein blinder neuer Start als +Ersatz. `native_execution_verified` weist die tatsächliche LocalService-Probe +nach; `diagnostic_status_ready` bildet den Rohstatus beider Berichte ab; `clock_ready` +verlangt zusätzlich die getrennte Adapterqualifikation. Rohstatus allein kann +niemals produktive Clock-Bereitschaft behaupten. Ein negativer +Status ist ein gültiger Messbeleg und keine Freigabe für Jobcapabilities. Die +oben offene Serveridentitätsbindung bleibt dabei eigenständig erforderlich. +Das rohe Elevationflag wird nicht mit Administratormitgliedschaft gleichgesetzt; +seine tatsächliche Bedeutung für dieses Diensttoken wird erst nativ ermittelt. +[Token-Elevation](https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-token_elevation), +[aktivierte Gruppenmitgliedschaft](https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-checktokenmembership). + +## Tatsächlich lokal ausgeführte Qualifikation + +- WIDL-Generierung und beide C-Objekte Windows-x64 mit Clang-SEH und `-Werror`: + erfolgreich; statische C-Assertions bestätigen120Byte-Status/64Byte-Rust-ABI. +- WindowsGNU-Crossbuild der Readiness-EXE mit Lockfile/offline: erfolgreich. +- Drei Rust-Tests: Status-/Unsicherheitsverweigerung, Suspend mit notwendigem + anschließendem Sync, Wallclockrücksprung/Überlauf: alle bestanden. +- Drei Python-Guards: readback nach verlorener Startantwort ohne erneuten Start, + Sourceänderung verweigert, fehlender nativer Bericht verweigert: bestanden. +- Alle drei PowerShell-Bootstrapfragmente mit PowerShell-Parser geprüft. + +Toolchain lokal im Entwicklungscontainer +`rust-discovery-windows-clock-full:local` aus dem bisherigen gecachten +Windows-Buildimage mit `mingw-w64-tools` und `clang`. `build.rs` verlangt für +Windows derzeit genau x86-64/GNU; MSVC und andere Architekturen sind nicht +qualifiziert. Compiler-/Containerprüfungen ersetzen keine tatsächliche +Windows-Ausführung. Native Ergebnisse werden getrennt im Projekt ergänzt. + +## Native Zwischenstände: keine Clock-Abnahme + +Der Root-Runner hat drei getrennte Fälle durchgeführt und die Belege privat +unter `devstate/windows-client/clock-readiness/` erhalten: + +- `995eb9c1-e1f4-4b17-85b4-5976e9e362e6`: vor Upload/Diensterstellung + verweigert. Die ACL-Prüfung berücksichtigte das automatisch ergänzte reine + Synchronize-Recht nicht. Tatsächlicher Readback: Rootbesitzer Administrators, + nur SYSTEM/Administrators FullControl und LocalService ReadExecute+Synchronize, + kein Hilfsdienst, kein Remote-Fall und keine Dateien. Danach wurde nur dieses + zusätzliche Nichtschreibrecht im engen ACL-Maskenvertrag zugelassen. +- `89b3e688-50ae-4cbd-b519-16a379aa6424`: Hilfsdienststart scheiterte mit + behandeltem1066, kein Ergebnisbericht. Derselbe Fall wurde ausschließlich + gelesen und sein exakt gebundener gestoppter Hilfsdienst entfernt. Ursache + noch nicht durch einen spezifischen Fehlercode belegt. +- `513fb6df-df3b-43a2-bada-a0f7bb939f54`: nach Erweiterung um tatsächliche + Tokenfelder wurde kein Ergebnisbericht erzeugt; Dienstexit1067. Nur die eigene + ApplicationError-Metadatenabfrage belegte Exception `c0000005` im eigenen + `WindowsClockReadiness.exe` um2026-11-13T23:52:57.3579204Z. Auch dieser exakt + gebundene gestoppte Hilfsdienst wurde im Readback entfernt. Das ist ein + tatsächlicher nativer Fehler, kein DLL-/Zugriffs-/Zeitstatus-Erfolgsnachweis. + +Die danach vorbereitete Probe schreibt den begrenzten Tokenbeleg bereits vor dem +RPC dauerhaft und führt numerische SCM-Stufen für behandelte Fehler. Der konkrete Compiler-TLS-Fehler wurde danach lokalisiert und behoben (unten). +Authentifizierte Serveridentitätsbindung bleibt offen; Windows-Jobclock +bleibt unqualifiziert und das Jobgate geschlossen. Die permanenten Agenten, +Geräteidentitäten, Zeitdienste und Cloudserver wurden von diesen ausschließlich +eigenen Readinesshilfsdiensten nicht verändert. + +Der zusätzliche eigene Fehleroffset `0x48b4e4` ließ sich mit der exakten +EXE9be65748… und ImageBase`0x140000000` lokal mittels MinGW-addr2line auf +`release_allocations()` abbilden. Disassembly zeigt dort den Zugriff auf eine +NULL-Compiler-TLS-Basis des SCM-Threads. Der Korrekturbuild ersetzt ausschließlich +diesen `_Thread_local`-Allocatorzustand durch `InitOnceExecuteOnce`/`TlsAlloc` +und eine pro synchronem Aufruf über `TlsSetValue` gebundene, geprüfte Arena. +Aufrufende Threads ohne Arena erhalten keine Allokation; nach Cleanup wird der +Pointer gelöscht. Endpoint, RPC-Authentifizierung und IDL wurden dafür nicht +abgeschwächt. Die begrenzte Tokenprobe wird vorher dauerhaft geschrieben. +Dieser korrigierte Build wurde erfolgreich crossgebaut; die drei Rusttests, +drei Runnerguards und PowerShellparser liefen erneut erfolgreich. Der native Nachweis folgt im nächsten Absatz. + +Native Korrekturprobe `ecf04ebb-23e4-48da-b324-56d98460cd64`, EXE +`4219054b8c51462458ab36fcb0eee3ad5e6905e4725621e6f5103c3e0eca9f4f`: +tatsächlich ausgeführt, zwei Statusabrufe, dauerhafte Token- und Ergebnisberichte, +Hilfsdienst danach entfernt. Beide Abrufe liefern RPC1722 (`CLOCK_UNSUPPORTED`), +keinen Zeitstatus und `clock_ready=false`; gemessene Dauer3,6513ms und0,2029ms. +Damit ist der Compiler-TLS-Absturz für diese Strecke nativ behoben, aber kein +Zeitvertrauen belegt. Das echte Diensttoken besitzt SID`S-1-5-19`, keine aktivierte +Administratormitgliedschaft und keine SYSTEM-Identität, dennoch +`TokenIsElevated=1`/`TokenElevationType=Default(1)`. Der rohe Elevationswert darf +nicht als gleichwertige Administratorzugehörigkeitsprüfung verwendet werden. + +Eine anschließende enge Endpointprobe ist nun implementiert und lokal +crossqualifiziert: ausschließlich lokaler EPM, exakte Clock-UUID/Version4.1, +höchstens16 Einträge, nur aggregierte Transportanzahlen und Fehlercode. Keine +Endpointnamen, Annotationen oder Adressen verlassen die C-Grenze. Diese Probe +führt keinen ALPC-Statusaufruf aus und ersetzt keine Serveridentitätsprüfung. +Der entsprechende neue native Durchlauf ist noch offen. + +## Implementierter nächster Kandidat: ALPC mit fester Server-SID + +`NativeClock::new()` verwendet im aktuellen Quellstand ausschließlich einen +lokal per exakter Interface-UUID/Version gefundenen `ncalrpc`-Endpunkt. Die +verlangte Server-SID wird lokal als LocalService`S-1-5-19` erzeugt und mittels +`RPC_SECURITY_QOS_V3.Sid` und `MUTUAL_AUTH` fest gebunden. WINNT/PacketPrivacy, +Identify und der echte Prozesskontext bleiben erforderlich. Es gibt keinen +Status-Fallback auf Named Pipes und keine Übernahme einer Identität aus der +Endpointliste. Ein fremder registrierter Endpunkt kann so höchstens die +Bereitschaft verhindern. Dieser Vertrag trennt unterschiedliche Windowskonten; +ein Angreifer mit bereits denselben LocalService-Prozessrechten gehört nicht +zu einer neu behaupteten Prozessisolation. Der zuvor dokumentierte Named-Pipe- +Abruf bleibt eine getrennte Diagnose und liefert selbst bei geeignetem Status +immer `trusted=false`/`CLOCK_SERVER_IDENTITY_UNQUALIFIED`. + +Da Windows die synchrone RPC-Timeout-/Cancel-API für `ncalrpc` nicht entsprechend +unterstützt, begrenzt ein einziger prozessweiter RPC-Worker den Aufrufer. Er +verwendet einen Kanal mit Kapazität1 und maximal1s Antwortwartezeit. Ein Timeout +vergiftet diesen Worker dauerhaft: keine Ersatzthreads, kein blindes Wiederholen, +kein Rückfall auf Named Pipes. Selbst bei einem hängenden read-only RPC existiert +höchstens ein solcher Worker; die Agenten-/Telemetriearbeit kehrt mit +`CLOCK_UNTRUSTED` zurück. Rekonstruktion eines `NativeClock`-Objekts setzt diesen +Zustand nicht zurück. Parallelaufrufe bei belegtem Worker werden verweigert. +[RPC-Cancel-Grenzen](https://learn.microsoft.com/en-us/windows/win32/api/rpcdce/nf-rpcdce-rpccancelthreadex). + +Dieser Kandidat wurde erfolgreich für WindowsGNU crossgebaut. Fünf lokale +Rusttests bestehen, einschließlich Timeout und nachfolgend verweigerter zweiter +RPC-Wirkung sowie unverändert geschlossenem Qualifikationsgate; die früheren +drei Clocktests bleiben erhalten. Vier Runnerguards bestehen, zusätzlich +Rohstatusbereitschaft ohne Adapterqualifikation verweigert produktive Bereitschaft. Native Nachweise für +ALPC-Verfügbarkeit, feste SID-Bindung und positive Zeitbereitschaft stehen aus. +Das ist weiterhin keine Windows-Jobclock-Abnahme. + +Ein eigener Bootstrap-Readback des Root-Agenten bestätigte für W32Time +`Stopped`, Startart`Manual`, KontoLocalService`S-1-5-19` und PID0. Die +RPC1722-Werte der korrigierten Probe sind damit konsistent. Der Zeitdienst wurde +für diese Readinessstrecke nicht gestartet oder umkonfiguriert. Ein entsprechender +eng begrenzter Start des bestehenden Dienstes bleibt bis zur hierfür vom +Root-Agenten angefragten Benutzerentscheidung ausgesetzt. Der neue +ALPC-/SID-Kandidat wurde deshalb noch nicht nativ ausgeführt. diff --git a/docs/windows-gates.md b/docs/windows-gates.md index e9f3464..8a359e8 100644 --- a/docs/windows-gates.md +++ b/docs/windows-gates.md @@ -1,6 +1,6 @@ # Windows-Client: Abnahmegates -Stand 2026-11-13, Spezifikation 1.15. Der Windows-11-x64-Gast ist ein eigenes +Stand 2026-11-14, Spezifikation 1.15. Der Windows-11-x64-Gast ist ein eigenes Testgerät. Der Notebook-Host bleibt ausschließlich Entwicklungsrechner; Server ist `discovery.ease-technologies.de`. Das abgeschlossene Linux-MVP bleibt eine eigenständige Abnahme. Dieser Bericht erweitert dessen Umfang nicht. @@ -11,9 +11,9 @@ bleibt eine eigenständige Abnahme. Dieser Bericht erweitert dessen Umfang nicht | Passiver Client | SCM-Dienst, Service-SID/ACLs, Enrollment/mTLS/WSS, Inventar mit Quelle/Zeit, Heartbeats und Mandantentrennung nativ bestanden; sieben native Rusttests. | Bestehende Identität und Telemetriehistorie bei allen weiteren Schritten erhalten. | | HTTPS/Fallback | Explizites HTTPS und automatischer Fallback nach zwei tatsächlichen mTLS-WSS503 unter LocalService nativ bestanden, jeweils mit frischen Heartbeats und Inventar-ACK. Testhooks geschlossen. Anschließend bestehende VM separat dauerhaft auf `auto` gestellt und bevorzugtes WSS erneut mit zwei frischen Heartbeats/ACK geprüft; Identität und ACLs erhalten, 0 Jobs/Grants. | Transportnachweise abgeschlossen; kein automatischer HTTPS→WSS-Switchback nachgewiesen. Installerdefault ebenfalls `auto`, aber keine neue Installationsabnahme. | | TLS-Lifecycle | Falsche CA, falscher Name und abgelaufenes Clientzertifikat mit gültigen Kontrollen nativ als getrennte Admin-TLS-Proben bestanden. Permanente Identität/Dienst unverändert. | Rotation und Widerruf noch gesondert sicher implementieren und prüfen. Permanente Identität nicht widerrufen oder ersetzen. | -| Signierter Jobkern | Gemeinsamer Core und Linuxadapter implementiert; native Core-Unittests zuerst Linux (25), dann Windows (24) bestanden. Bestehender Windows-Dienst bleibt passiv und verweigert Jobs/Grants. | Native Dienstintegration, vertrauenswürdige Uhr, erhaltende Journalmigration und vollständige Startgrenze qualifizieren. Unit-Fixturen ersetzen keinen tatsächlichen Jobnachweis. | -| PowerShell | Noch kein Executor oder freigegebener Interpreter. Server/UI lösen derzeit Linuxvarianten auf. | Exakte Windows-PowerShell-5.1-Bytes, Ausgabeencoding, Prozessgrenzen und unprivilegierte Ausführungsidentität binden. Erst nach vollständigem Antrag und tatsächlichem WebUI-Klick ausführen. | -| Privilegierte Aktionen | Kein Windows-Helper, keine Named-Pipe-Aktionsschnittstelle. | Eigenständiger restriktiver Helper mit geprüfter Pipe-Identität und unabhängiger Signatur-/Plan-/Grantprüfung; keine SYSTEM-Netzwerkkomponente. | +| Signierter Jobkern | Gemeinsamer Core/Helper-Sync und atomare Outcomes nativ zuerst Linux, dann Windows geprüft; letzter Fixturelauf76/54. Default-Windowsdienst mit additiver Journalmigration erhaltend als LocalService aktualisiert; native Unitqualifikation12+6. Jobs bleiben deaktiviert, kein Binding/Ledger angelegt. | Tatsächlichen signierten Dienst-Sync, qualifizierte Uhr und vollständige Startgrenze nachweisen. Passive Migration und Unit-Fixturen ersetzen keinen Jobnachweis. | +| PowerShell | Begrenzter5.1-Executor implementiert; exakte Skriptbytes, atomarer Prozessbaum, Rohbytes und Unknown bei unklarer Wirkung. Server/UI unterstützen feste Plattformvarianten. Keine tatsächliche Ausführung, Richtlinie derzeit geerbt. | Ausstehende konkrete Richtlinienentscheidung beachten, Encoding/Prozessgrenzen unter LocalService tatsächlich qualifizieren; ausschließlich vollständiger Antrag und tatsächlicher WebUI-Klick. | +| Privilegierte Aktionen | Featureisolierte SYSTEM-Helper-/Named-Pipe-Quelle mit eigener Policy und unabhängigem Sync vorbereitet; keine Installation oder native Peer-/Wirkungsabnahme. | Gegenseitige tatsächliche SID/PID/Binary-/Dateibindung und unabhängigen Sync nativ prüfen; erst danach eng erlaubte Systemaktion. | | Pakete/Dienste/Logs | Noch keine native Windows-Aktionsabnahme. | Begrenzte geprüfte MSI-/EXE-Rezepte, Dienst-/Eventlogadapter und unabhängige Nachbedingungen. Keine allgemeinen Installershellstrings oder impliziten Reboots. | | Dauerhafte Jobs/Fehlerfälle | Linuxnachweise vorhanden; sie ersetzen keine nativen Windowsnachweise. | Redelivery/ACK-Verlust, Prozessabbruch, Offline/Ablauf/Entzug und Wiederanlauf am tatsächlichen Windows-Jobpfad prüfen. | | Mischplattform | Windows/Linux sind separat inventarisierbar; noch keine gemischte Skriptabnahme. | AT-15 mit festen Varianten/Zielen, passenden Interpretern und nachvollziehbaren Einzelresultaten. | diff --git a/tests/windows_clock_readiness.py b/tests/windows_clock_readiness.py new file mode 100644 index 0000000..930522e --- /dev/null +++ b/tests/windows_clock_readiness.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""Focused readback/error gates for the LocalService readiness bootstrap. No VM.""" +import hashlib +import pathlib +import sys +import tempfile +import unittest +from unittest.mock import patch +ROOT=pathlib.Path(__file__).resolve().parents[1] +sys.path.insert(0,str(ROOT/'deploy/windows')) +import clock_readiness as clock + + +class ReadinessGuards(unittest.TestCase): + def case(self,root): + ident='11111111-1111-4111-8111-111111111111' + folder=root/ident;folder.mkdir(mode=0o700) + clock.save(folder,'intent.json',dict(id=ident,binary='a'*64,source=hashlib.sha256(clock.SCRIPT.encode()).hexdigest(),no_jobs=True)) + return ident,folder + + def result(self,ident,trusted=False): + return dict(id=ident,native_report=dict(case_id=ident,token_sid='S-1-5-19',elevated=False,read_only=True, + samples=[dict(trusted=trusted,reason='CLOCK_PERMISSION_DENIED',rpc_code=5)]*2),service_removed=True,no_jobs=True) + + def test_lost_start_reply_only_readbacks_and_retains_untrusted_evidence(self): + with tempfile.TemporaryDirectory() as tmp: + root=pathlib.Path(tmp);ident,folder=self.case(root);calls=[] + def remote(script,payload,**kwargs): + self.assertEqual(script,clock.LAUNCH);calls.append(payload['action']);return self.result(ident) + with patch.object(clock,'STATE',root),patch.object(sys,'argv',['clock','readback','--id',ident]),patch.object(clock.cb,'powershell',side_effect=remote),patch('builtins.print'): + clock.main();clock.main() + self.assertEqual(calls,['readback','readback']) + report=clock.cb.contract.protected_json(folder/'result.json') + self.assertTrue(report['native_execution_verified']);self.assertFalse(report['clock_ready']) + self.assertFalse((folder/'start-intent.json').exists()) + + def test_good_raw_status_cannot_claim_production_clock_without_qualification(self): + with tempfile.TemporaryDirectory() as tmp: + root=pathlib.Path(tmp);ident,folder=self.case(root) + report=self.result(ident,trusted=True) + for sample in report['native_report']['samples']:sample['adapter_qualified']=False + with patch.object(clock,'STATE',root),patch.object(sys,'argv',['clock','readback','--id',ident]),patch.object(clock.cb,'powershell',return_value=report),patch('builtins.print'): + clock.main() + result=clock.cb.contract.protected_json(folder/'result.json') + self.assertTrue(result['diagnostic_status_ready']);self.assertFalse(result['adapter_qualified']);self.assertFalse(result['clock_ready']) + + def test_changed_source_cannot_resume_same_case(self): + with tempfile.TemporaryDirectory() as tmp: + root=pathlib.Path(tmp);ident,_=self.case(root) + with patch.object(clock,'STATE',root),patch.object(clock,'SCRIPT',clock.SCRIPT+'\n'),patch.object(sys,'argv',['clock','readback','--id',ident]),patch.object(clock.cb,'powershell',side_effect=AssertionError('no remote call')): + with self.assertRaisesRegex(RuntimeError,'QUALIFIED_SOURCE_CHANGED'):clock.main() + + def test_missing_native_report_cannot_claim_qualification(self): + with tempfile.TemporaryDirectory() as tmp: + root=pathlib.Path(tmp);ident,folder=self.case(root) + with patch.object(clock,'STATE',root),patch.object(sys,'argv',['clock','readback','--id',ident]),patch.object(clock.cb,'powershell',return_value=dict(native_report=None,service_removed=True)): + with self.assertRaisesRegex(RuntimeError,'INCOMPLETE'):clock.main() + self.assertFalse((folder/'result.json').exists()) + + +if __name__=='__main__':unittest.main()