//! 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 account AND service-bound ALPC, positive readiness, /// wrong-account/wrong-service denial and fail-closed qualification. pub const ADAPTER_QUALIFIED: bool = false; const SECOND: u64 = 10_000_000; const MAX_AGE: u64 = 3600 * SECOND; 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:W32Time:V5_descriptor: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() } /// Diagnostic-only ABI captured before the existing C layout guard. Presence /// flags are numeric0/1; no remote pointers, names or returned entries escape. #[derive(Clone, Copy, Debug, Default, Serialize)] #[repr(C)] pub struct StatusRpcTrace { pub stage: u32, pub native_rpc_return: u32, pub native_rpc_return_present: u32, pub rpc_exception: u32, pub status_present: u32, pub ul_size: u32, pub c_entries: u32, pub p_entries_present: u32, } #[derive(Debug, Serialize)] pub struct StatusRpcDiagnostic { pub rpc_code: u32, pub independent_call: bool, pub trace: Option, pub diagnostic_only: bool, pub adapter_qualified: bool, pub trusted: bool, } /// The fixed authenticated named-pipe call is observed separately. It never /// selects a production transport or supplies a trusted timestamp. One worker, /// one outstanding call and no replacement/retry after a local timeout. pub fn status_rpc_diagnostic() -> StatusRpcDiagnostic { #[cfg(windows)] let (rpc_code, trace) = { type Reply = std::sync::mpsc::SyncSender<(u32, StatusRpcTrace)>; type Requests = std::sync::mpsc::SyncSender; static WORKER: std::sync::OnceLock>> = std::sync::OnceLock::new(); let worker = WORKER.get_or_init(|| { let (sender, receiver) = std::sync::mpsc::sync_channel::(1); let created = std::thread::Builder::new() .name("rmm-clock-status-diag".into()) .spawn(move || { #[link(name = "rmm_clock_rpc", kind = "static")] #[link(name = "rpcrt4")] #[link(name = "advapi32")] unsafe extern "C" { fn rmm_clock_query_trace(trace: *mut StatusRpcTrace) -> u32; } while let Ok(reply) = receiver.recv() { let mut trace = StatusRpcTrace::default(); // SAFETY: fixed8*u32 C ABI; SEH stays contained inside C. let code = unsafe { rmm_clock_query_trace(&mut trace) }; let _ = reply.send((code, trace)); } }) .is_ok(); Mutex::new(created.then_some(sender)) }); if let Ok(mut worker) = worker.try_lock() { let (reply, receiver) = std::sync::mpsc::sync_channel(1); let sent = worker .as_ref() .is_some_and(|sender| sender.try_send(reply).is_ok()); if sent && let Ok((code, trace)) = receiver.recv_timeout(std::time::Duration::from_secs(2)) { (code, Some(trace)) } else { *worker = None; (1818, None) } } else { (170, None) } }; #[cfg(not(windows))] let (rpc_code, trace) = (50, None); StatusRpcDiagnostic { rpc_code, independent_call: true, trace, diagnostic_only: true, adapter_qualified: false, trusted: false, } } /// Read-only negative controls for the separate native readiness program. /// Neither control can produce clock authority, even if the OS accepts it. /// Rejection without a successful genuine status query is not identity proof. #[derive(Debug, Serialize)] pub struct IdentityControls { pub wrong_account_rpc_code: u32, pub wrong_service_rpc_code: u32, pub both_access_denied: bool, pub diagnostic_only: bool, } pub fn identity_controls() -> IdentityControls { #[cfg(windows)] let codes = { static WORKER: std::sync::OnceLock> = std::sync::OnceLock::new(); let worker = WORKER.get_or_init(|| Mutex::new(RpcWorker::new(raw_control))); match worker.try_lock() { Ok(mut worker) => ( worker.call(true, std::time::Duration::from_secs(1)).0, worker.call(false, std::time::Duration::from_secs(1)).0, ), Err(_) => (170, 170), } }; #[cfg(not(windows))] let codes = (50, 50); IdentityControls { wrong_account_rpc_code: codes.0, wrong_service_rpc_code: codes.1, both_access_denied: codes == (5, 5), diagnostic_only: true, } } impl rmm_agent_core::reconcile::SyncClock for NativeClock { fn now(&self) -> Result> { 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(windows)] fn raw_control(wrong_account: bool) -> (u32, Status) { #[link(name = "rmm_clock_rpc", kind = "static")] #[link(name = "rpcrt4")] #[link(name = "advapi32")] unsafe extern "C" { fn rmm_clock_wrong_account(status: *mut Status) -> u32; fn rmm_clock_wrong_service(status: *mut Status) -> u32; } let mut status = Status::default(); // SAFETY: fixed C ABI, fixed two local negative identities, contained SEH. let code = unsafe { if wrong_account { rmm_clock_wrong_account(&mut status) } else { rmm_clock_wrong_service(&mut status) } }; (code, status) } #[cfg(any(windows, test))] type RpcReply = std::sync::mpsc::SyncSender<(u32, Status)>; #[cfg(any(windows, test))] 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!(std::mem::size_of::(), 32); 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()); } }