Qualify enrolled Windows job clocks from the local time service
Rust development slice / linux (push) Failing after 15s

This commit is contained in:
2026-11-19 11:47:49 +01:00
parent 6aeb618170
commit b002202d62
9 changed files with 532 additions and 49 deletions
+167 -25
View File
@@ -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();
+19 -10
View File
@@ -899,9 +899,14 @@ impl SystemHelper {
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 = if settings.windows_update_only() || settings.managed_scripts() {
let role = rmm_time_attestation::Role::SystemHelper;
let clock = if settings.managed_scripts() {
RuntimeClock::local(role)
} else if settings.windows_update_only() {
RuntimeClock::enrolled_windows_update_helper(settings.binding.clone(), settings.helper.clone())
} else { RuntimeClock::new(rmm_time_attestation::Role::SystemHelper) }.for_generation(0);
} else {
RuntimeClock::new(role)
}.for_generation(0);
let boot = WindowsBoot::capture()?;
Ok(Self {
settings,
@@ -1806,14 +1811,18 @@ unsafe extern "system" fn service_main(_: u32, _: *mut *mut u16) {
let result = (|| -> Result<()> {
let mut helper = SystemHelper::open()?;
let server = ipc::Server::bind(helper.pin().clone())?;
let time_server = ipc::Server::bind_time(helper.pin().clone())?;
let update_server=crate::update_control::server_pin(&helper.settings.binding,&helper.pin.helper)?
.map(crate::update_control_ipc::Server::bind).transpose()?;
let time_pin = helper.pin().clone();
let time_clock = helper.clock.source();
let time_worker = std::thread::Builder::new()
.name("rmm-helper-time-control".into())
.spawn(move || time_control(time_server, time_pin, time_clock))?;
let time_worker = if time_clock.uses_local_clock() {
None
} else {
let time_pin = helper.pin().clone();
let time_server = ipc::Server::bind_time(time_pin.clone())?;
Some(std::thread::Builder::new()
.name("rmm-helper-time-control".into())
.spawn(move || time_control(time_server, time_pin, time_clock))?)
};
scm_status(SERVICE_RUNNING, 0);
let mut next_update_unknown=Instant::now();
while !STOP.load(Ordering::SeqCst) {
@@ -1890,9 +1899,9 @@ unsafe extern "system" fn service_main(_: u32, _: *mut *mut u16) {
}
// The time lane has no ledger/job operation and its receive wait is
// bounded. Shutdown closes its private evidence before service exit.
time_worker
.join()
.map_err(|_| anyhow::anyhow!("SYSTEM_TIME_WORKER_FAILED"))??;
if let Some(worker) = time_worker {
worker.join().map_err(|_| anyhow::anyhow!("SYSTEM_TIME_WORKER_FAILED"))??;
}
Ok(())
})();
scm_status(SERVICE_STOPPED, if result.is_ok() { 0 } else { 1066 });
@@ -53,6 +53,7 @@ pub fn clock_code(error: &anyhow::Error) -> &'static str {
"TIME_RUNTIME_NO_CONNECTION",
"TIME_LOCAL_WALL_OUTSIDE_BOUND",
"TIME_SOURCE_AGE_AT_CHECK",
"TIME_WINDOWS_LOCAL_CLOCK",
];
error
.chain()
+15 -5
View File
@@ -839,6 +839,10 @@ impl Agent {
) -> Result<()> {
ensure!(self.time_refresh.is_none(), "TIME_REFRESH_ALREADY_RUNNING");
use rmm_agent_windows::signed_clock::{CONFIG_PATH, SamplingMode};
let clock = self.clock.native.source();
if clock.uses_local_clock() {
return Ok(());
}
// Presence opts into sampling only. Each role opens and verifies the
// protected profile and signed response itself before accepting time.
let Some(mode) = SamplingMode::configured(self.config.enable_jobs, Path::new(CONFIG_PATH))?
@@ -860,7 +864,6 @@ impl Agent {
self.binding.as_ref(),
self.helper_lane.clone(),
)? };
let clock = self.clock.native.source();
let stop = Arc::new(AtomicBool::new(false));
let mut tasks = Vec::new();
let own_clock = clock.clone();
@@ -3072,10 +3075,17 @@ async fn run_service_binding(path: &Path, stop: &'static AtomicBool, release_gua
let clock=JobClock::new(config.enable_jobs);
#[cfg(feature = "system-helper")]
let clock = if let Some(policy) = &config.localservice_time_policy {
let binding = binding.clone().context("JOB_BINDING_REQUIRED")?;
JobClock { enabled: true, native: rmm_agent_windows::signed_clock::RuntimeClock::enrolled_local_service(
binding, policy.clone(), installed_tenant.context("INSTALLED_TENANT_REQUIRED")?
).for_generation(0) }
use rmm_agent_windows::signed_clock::RuntimeClock;
let source = if config.windows_update_helper {
RuntimeClock::enrolled_local_service(
binding.clone().context("JOB_BINDING_REQUIRED")?,
policy.clone(),
installed_tenant.context("INSTALLED_TENANT_REQUIRED")?,
)
} else {
RuntimeClock::local(rmm_time_attestation::Role::Agent)
};
JobClock { enabled: true, native: source.for_generation(0) }
} else { clock };
let mut config=config;
if config.enable_jobs {
+18
View File
@@ -1410,6 +1410,7 @@ mod installed {
#[derive(Clone)]
pub struct RuntimeClock {
role: Role,
native: Option<Arc<crate::clock::NativeClock>>,
enrolled_helper: Option<ipc::PeerPin>,
local_policy: Option<(rmm_agent_core::auth::Binding, std::path::PathBuf, Uuid)>,
state: Arc<Mutex<Option<(u64, SignedClock)>>>,
@@ -1423,11 +1424,20 @@ mod installed {
pub fn new(role: Role) -> Self {
Self {
role,
native: None,
enrolled_helper: None,
local_policy: None,
state: Arc::new(Mutex::new(None)),
}
}
pub fn local(role: Role) -> Self {
let mut clock = Self::new(role);
clock.native = Some(Arc::new(crate::clock::NativeClock::new()));
clock
}
pub fn uses_local_clock(&self) -> bool {
self.native.is_some()
}
pub fn enrolled_local_service(
binding: rmm_agent_core::auth::Binding,
policy: std::path::PathBuf,
@@ -1528,6 +1538,10 @@ mod installed {
}
fn bounds(&self) -> Result<(chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>)> {
ensure!(self.generation > 0, "TIME_RUNTIME_NO_CONNECTION");
if let Some(native) = &self.source.native {
return rmm_agent_core::reconcile::SyncClock::bounds(native.as_ref())
.context("TIME_WINDOWS_LOCAL_CLOCK");
}
let mut state = self
.source
.state
@@ -1544,6 +1558,10 @@ mod installed {
}
fn reading(&self) -> Result<rmm_agent_core::reconcile::ClockReading> {
ensure!(self.generation > 0, "TIME_RUNTIME_NO_CONNECTION");
if let Some(native) = &self.source.native {
return rmm_agent_core::reconcile::SyncClock::reading(native.as_ref())
.context("TIME_WINDOWS_LOCAL_CLOCK");
}
let mut state = self
.source
.state