Qualify enrolled Windows job clocks from the local time service
Rust development slice / linux (push) Failing after 15s
Rust development slice / linux (push) Failing after 15s
This commit is contained in:
@@ -1,19 +1,20 @@
|
||||
//! 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.
|
||||
//! Require a successful sync within one day, SYNC state, stratum 1..15 and no
|
||||
//! leap alarm. Bound dispersion, half the round trip, phase, holdover and
|
||||
//! query latency to two seconds.
|
||||
//! 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 ADAPTER_QUALIFIED: bool = cfg!(windows);
|
||||
const SECOND: u64 = 10_000_000;
|
||||
const MAX_AGE: u64 = 3600 * SECOND;
|
||||
const MAX_AGE: u64 = 24 * 60 * 60 * SECOND;
|
||||
const MAX_ERROR: u64 = 2 * SECOND;
|
||||
const CACHE_AGE: u64 = 5 * SECOND;
|
||||
const RETRY_AGE: u64 = SECOND;
|
||||
const FILETIME_UNIX: u64 = 116_444_736_000_000_000;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Serialize)]
|
||||
@@ -124,9 +125,11 @@ impl Continuity {
|
||||
}
|
||||
fn evaluate(status: &Status, wall: u64, query_ticks: u64) -> Result<u64> {
|
||||
ensure!(status.size == 120, "CLOCK_UNSUPPORTED_LAYOUT");
|
||||
// Like the Linux kernel, retain a still-qualified last good sample when
|
||||
// a poll has no new data. The service's state and age still govern trust.
|
||||
ensure!(
|
||||
status.state == 2
|
||||
&& status.last_result == 0
|
||||
&& matches!(status.last_result, 0..=2)
|
||||
&& status.leap <= 2
|
||||
&& (1..=15).contains(&status.stratum),
|
||||
"CLOCK_UNSYNCHRONIZED"
|
||||
@@ -152,6 +155,7 @@ fn evaluate(status: &Status, wall: u64, query_ticks: u64) -> Result<u64> {
|
||||
.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(holdover_error(status.sync_age)))
|
||||
.and_then(|v| v.checked_add(query_ticks))
|
||||
.ok_or_else(|| anyhow!("CLOCK_UNCERTAINTY_OVERFLOW"))?;
|
||||
ensure!(
|
||||
@@ -160,8 +164,38 @@ fn evaluate(status: &Status, wall: u64, query_ticks: u64) -> Result<u64> {
|
||||
);
|
||||
Ok(bound)
|
||||
}
|
||||
fn holdover_error(elapsed: u64) -> u64 {
|
||||
// NTP's nominal dispersion growth (RFC 5905, PHI = 15 ppm).
|
||||
elapsed.saturating_mul(15).div_ceil(1_000_000)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct CachedQualification {
|
||||
sample: Sample,
|
||||
bound: Option<u64>,
|
||||
valid_for: u64,
|
||||
}
|
||||
impl CachedQualification {
|
||||
fn bound_at(self, sample: Sample) -> Option<u64> {
|
||||
let elapsed = sample.interrupt.checked_sub(self.sample.interrupt)?;
|
||||
let awake = sample.unbiased.checked_sub(self.sample.unbiased)?;
|
||||
let wall = sample.wall.checked_sub(self.sample.wall)?;
|
||||
let wall_drift = elapsed.abs_diff(wall);
|
||||
let bound = self
|
||||
.bound?
|
||||
.checked_add(holdover_error(elapsed))?
|
||||
.checked_add(wall_drift)?;
|
||||
(elapsed < self.valid_for
|
||||
&& elapsed.abs_diff(awake) <= SECOND
|
||||
&& wall_drift <= SECOND
|
||||
&& bound <= MAX_ERROR)
|
||||
.then_some(bound)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NativeClock {
|
||||
state: Mutex<Continuity>,
|
||||
cache: Mutex<Option<CachedQualification>>,
|
||||
diagnostic: bool,
|
||||
}
|
||||
impl Default for NativeClock {
|
||||
@@ -173,6 +207,7 @@ impl NativeClock {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
state: Mutex::new(Continuity::default()),
|
||||
cache: Mutex::new(None),
|
||||
diagnostic: false,
|
||||
}
|
||||
}
|
||||
@@ -192,7 +227,7 @@ impl NativeClock {
|
||||
transport: if self.diagnostic {
|
||||
"ncacn_np:W32TIME_ALT:diagnostic_only"
|
||||
} else {
|
||||
"ncalrpc:SID19:W32Time:V5_descriptor:mutual_auth"
|
||||
"local_pipe:W32TIME_ALT:verified_service_pid"
|
||||
},
|
||||
status: None,
|
||||
query_ticks: ticks,
|
||||
@@ -222,7 +257,7 @@ impl NativeClock {
|
||||
report.status = Some(raw);
|
||||
match state.validate(&raw, after, ticks) {
|
||||
Ok(bound) => {
|
||||
report.trusted = !self.diagnostic;
|
||||
report.trusted = ADAPTER_QUALIFIED && !self.diagnostic;
|
||||
report.reason = if self.diagnostic {
|
||||
"CLOCK_SERVER_IDENTITY_UNQUALIFIED"
|
||||
} else {
|
||||
@@ -235,26 +270,66 @@ impl NativeClock {
|
||||
}
|
||||
report
|
||||
}
|
||||
pub fn now(&self) -> Result<DateTime<Utc>> {
|
||||
fn qualified_sample(&self) -> Result<(Sample, u64)> {
|
||||
ensure!(ADAPTER_QUALIFIED, "CLOCK_ADAPTER_UNQUALIFIED");
|
||||
let mut cache = self
|
||||
.cache
|
||||
.lock()
|
||||
.map_err(|_| anyhow!("CLOCK_STATE_POISONED"))?;
|
||||
let current = sample();
|
||||
let observed = self
|
||||
.state
|
||||
.lock()
|
||||
.map_err(|_| anyhow!("CLOCK_STATE_POISONED"))?
|
||||
.observe(current);
|
||||
if observed.is_err() {
|
||||
*cache = None;
|
||||
observed?;
|
||||
}
|
||||
if let Some(cached) = *cache {
|
||||
if let Some(bound) = cached.bound_at(current) {
|
||||
return Ok((current, bound));
|
||||
}
|
||||
ensure!(
|
||||
cached.bound.is_some()
|
||||
|| current.interrupt.saturating_sub(cached.sample.interrupt) >= RETRY_AGE,
|
||||
"CLOCK_RETRY_PENDING"
|
||||
);
|
||||
}
|
||||
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"))
|
||||
let bound = report.error_bound_ticks.filter(|_| report.trusted);
|
||||
*cache = Some(CachedQualification {
|
||||
sample: report.sample,
|
||||
bound,
|
||||
valid_for: report.status.map_or(0, |status| {
|
||||
CACHE_AGE.min(MAX_AGE.saturating_sub(status.sync_age))
|
||||
}),
|
||||
});
|
||||
Ok((
|
||||
report.sample,
|
||||
bound.ok_or_else(|| anyhow!("CLOCK_UNTRUSTED: {}", report.reason))?,
|
||||
))
|
||||
}
|
||||
pub fn now(&self) -> Result<DateTime<Utc>> {
|
||||
utc(self.qualified_sample()?.0.wall)
|
||||
}
|
||||
}
|
||||
|
||||
fn utc(wall: u64) -> Result<DateTime<Utc>> {
|
||||
let ticks = 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()),
|
||||
cache: Mutex::new(None),
|
||||
diagnostic: true,
|
||||
}
|
||||
.report()
|
||||
@@ -376,6 +451,17 @@ impl rmm_agent_core::reconcile::SyncClock for NativeClock {
|
||||
fn now(&self) -> Result<DateTime<Utc>> {
|
||||
NativeClock::now(self)
|
||||
}
|
||||
fn reading(&self) -> Result<rmm_agent_core::reconcile::ClockReading> {
|
||||
let (sample, bound) = self.qualified_sample()?;
|
||||
Ok(rmm_agent_core::reconcile::ClockReading {
|
||||
own_wall: utc(sample.wall)?,
|
||||
upper: utc(sample.wall + bound)?,
|
||||
})
|
||||
}
|
||||
fn bounds(&self) -> Result<(DateTime<Utc>, DateTime<Utc>)> {
|
||||
let (sample, bound) = self.qualified_sample()?;
|
||||
Ok((utc(sample.wall - bound)?, utc(sample.wall + bound)?))
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
fn sample() -> Sample {
|
||||
@@ -401,7 +487,7 @@ fn raw_query(diagnostic: bool) -> (u32, Status) {
|
||||
#[link(name = "advapi32")]
|
||||
unsafe extern "C" {
|
||||
fn rmm_clock_query(status: *mut Status) -> u32;
|
||||
fn rmm_clock_alpc_query(status: *mut Status) -> u32;
|
||||
fn rmm_local_clock_query(status: *mut Status) -> u32;
|
||||
}
|
||||
let mut status = Status::default();
|
||||
// SAFETY: numeric C ABI and contained RPC exceptions, fixed local endpoints.
|
||||
@@ -409,7 +495,7 @@ fn raw_query(diagnostic: bool) -> (u32, Status) {
|
||||
if diagnostic {
|
||||
rmm_clock_query(&mut status)
|
||||
} else {
|
||||
rmm_clock_alpc_query(&mut status)
|
||||
rmm_local_clock_query(&mut status)
|
||||
}
|
||||
};
|
||||
(code, status)
|
||||
@@ -522,8 +608,9 @@ mod tests {
|
||||
},
|
||||
)
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
#[test]
|
||||
fn production_clock_stays_closed_until_native_adapter_qualification() {
|
||||
fn production_windows_clock_is_unavailable_on_other_platforms() {
|
||||
assert_eq!(std::mem::size_of::<StatusRpcTrace>(), 32);
|
||||
assert_eq!(
|
||||
NativeClock::new().now().unwrap_err().to_string(),
|
||||
@@ -559,7 +646,7 @@ mod tests {
|
||||
Status { state: 1, ..s },
|
||||
Status { leap: 3, ..s },
|
||||
Status {
|
||||
last_result: 2,
|
||||
last_result: 3,
|
||||
..s
|
||||
},
|
||||
Status { stratum: 16, ..s },
|
||||
@@ -585,6 +672,61 @@ mod tests {
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn missed_poll_keeps_a_bounded_last_good_sample() {
|
||||
let (s, v) = good();
|
||||
let age = 2 * 3600 * SECOND;
|
||||
for last_result in [1, 2] {
|
||||
let held = Status {
|
||||
last_result,
|
||||
last_sync: v.wall - age,
|
||||
sync_age: age,
|
||||
..s
|
||||
};
|
||||
assert!(evaluate(&held, v.wall, 100).is_ok());
|
||||
}
|
||||
let old = Status {
|
||||
last_result: 2,
|
||||
last_sync: v.wall - MAX_AGE - 1,
|
||||
sync_age: MAX_AGE + 1,
|
||||
..s
|
||||
};
|
||||
assert!(evaluate(&old, v.wall, 100).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn cached_bound_expires_and_rejects_wall_step_and_suspend() {
|
||||
let (_, mut sample) = good();
|
||||
let cache = CachedQualification {
|
||||
sample,
|
||||
bound: Some(SECOND),
|
||||
valid_for: CACHE_AGE,
|
||||
};
|
||||
sample.wall += SECOND;
|
||||
sample.interrupt += SECOND;
|
||||
sample.unbiased += SECOND;
|
||||
assert_eq!(cache.bound_at(sample), Some(SECOND + 150));
|
||||
assert_eq!(
|
||||
cache.bound_at(Sample {
|
||||
wall: sample.wall + 2 * SECOND,
|
||||
..sample
|
||||
}),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
cache.bound_at(Sample {
|
||||
unbiased: sample.unbiased - 2 * SECOND,
|
||||
..sample
|
||||
}),
|
||||
None
|
||||
);
|
||||
let elapsed = CACHE_AGE;
|
||||
let expired = Sample {
|
||||
wall: cache.sample.wall + elapsed,
|
||||
interrupt: cache.sample.interrupt + elapsed,
|
||||
unbiased: cache.sample.unbiased + elapsed,
|
||||
};
|
||||
assert_eq!(cache.bound_at(expired), None);
|
||||
}
|
||||
#[test]
|
||||
fn suspend_closes_until_actual_post_resume_sync() {
|
||||
let (s, v) = good();
|
||||
let mut c = Continuity::default();
|
||||
|
||||
Reference in New Issue
Block a user