Compare commits

...
Author SHA1 Message Date
kevin_janssen c6c4037d07 Bind the tested Windows passive time candidate to its exact source revision
Rust development slice / linux (push) Failing after 7s
2026-11-15 15:49:14 +01:00
3 changed files with 158 additions and 19 deletions
+32 -2
View File
@@ -785,8 +785,38 @@ pub(crate) fn msi_test_job() -> JobPayload {
}
}
fn write_current_probe(state: &Path, value: &serde_json::Value) -> Result<()> {
write_report(state, PROBE_FILE, ".helper-probe.pending", value)
}
/// A historical observation by the agent. The helper lane calls this only after
/// the authenticated peer has acknowledged its own signature verification.
pub fn record_verified_time(
state: &Path,
request: &rmm_time_attestation::Request,
response_sha256: &str,
observed_at: chrono::DateTime<chrono::Utc>,
) -> Result<()> {
use sha2::{Digest, Sha256};
let (filename, pending) = match request.context.role {
rmm_time_attestation::Role::Agent => ("agent-time-sample.json", ".agent-time.pending"),
rmm_time_attestation::Role::SystemHelper => {
("helper-time-sample.json", ".helper-time.pending")
}
};
let value = json!({
"schema_version": 1, "agent_pid": std::process::id(), "observed_at": observed_at,
"role": request.context.role, "windows_boot_id": request.context.windows_boot_id,
"connection_generation": request.context.connection_generation,
"verifier_incarnation": request.context.verifier_incarnation,
"request_sha256": format!("{:x}", Sha256::digest(serde_json::to_vec(request)?)),
"response_sha256": response_sha256
});
write_report(state, filename, pending, &value)
}
fn write_report(state: &Path, name: &str, pending: &str, value: &serde_json::Value) -> Result<()> {
native::private_path(state, true)?;
let path = state.join(PROBE_FILE);
let path = state.join(name);
if path.try_exists()? {
native::private_path(&path, false)?;
}
@@ -794,7 +824,7 @@ fn write_current_probe(state: &Path, value: &serde_json::Value) -> Result<()> {
ensure!(bytes.len() <= 8192, "HELPER_PROBE_REPORT_LIMIT");
// One fixed create-only staging file bounds even interrupted-report state.
// A leftover from a killed process is refused; it is never overwritten.
let temporary = state.join(".helper-probe.pending");
let temporary = state.join(pending);
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
+79 -17
View File
@@ -176,6 +176,7 @@ struct TimeRefresh {
clock: rmm_agent_windows::signed_clock::RuntimeClock,
helper: Option<rmm_agent_windows::helper_runtime::Client>,
tasks: Vec<tokio::task::JoinHandle<()>>,
samples: Vec<Arc<std::sync::OnceLock<VerifiedTimeSample>>>,
}
#[cfg(feature = "system-helper")]
impl Drop for TimeRefresh {
@@ -188,6 +189,30 @@ impl Drop for TimeRefresh {
}
}
#[cfg(feature = "system-helper")]
struct VerifiedTimeSample {
request: rmm_time_attestation::Request,
response_hash: String,
observed_at: chrono::DateTime<Utc>,
}
#[cfg(feature = "system-helper")]
impl VerifiedTimeSample {
fn new(request: rmm_time_attestation::Request, response_hash: String) -> Self {
Self {
request,
response_hash,
observed_at: Utc::now(),
}
}
fn persist(&self, state: &Path) -> Result<()> {
rmm_agent_windows::helper_runtime::record_verified_time(
state,
&self.request,
&self.response_hash,
self.observed_at,
)
}
}
#[cfg(feature = "system-helper")]
async fn time_response(
client: &reqwest::Client,
address: std::net::SocketAddr,
@@ -455,9 +480,13 @@ impl Agent {
identity: &crate::certificate_rotation::DeviceIdentity,
) -> Result<()> {
ensure!(self.time_refresh.is_none(), "TIME_REFRESH_ALREADY_RUNNING");
if !self.config.enable_jobs {
use rmm_agent_windows::signed_clock::{CONFIG_PATH, SamplingMode};
// 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))?
else {
return Ok(());
}
};
let client = crate::https_channel::mtls_client(
self.config.connect_address,
&self.ca,
@@ -477,6 +506,17 @@ impl Agent {
let own_stop = stop.clone();
let own_http = client.clone();
let address = self.config.connect_address;
// Only the connection owner publishes observations. Dropping it also
// discards unfinished samples, so an old worker cannot overwrite a newer report.
let sample_slot =
|| (mode == SamplingMode::Passive).then(|| Arc::new(std::sync::OnceLock::new()));
let own_receipt = sample_slot();
let helper_receipt = helper.as_ref().and_then(|_| sample_slot());
let samples = own_receipt
.iter()
.chain(helper_receipt.iter())
.cloned()
.collect();
tasks.push(tokio::spawn(async move {
while !own_stop.load(Ordering::SeqCst) {
let result = async {
@@ -486,18 +526,18 @@ impl Agent {
let request = own_clock.begin(generation)?;
let bytes = time_response(&own_http, address, &request).await?;
ensure!(!own_stop.load(Ordering::SeqCst), "TIME_CONNECTION_CLOSED");
own_clock.complete(generation, &bytes)
own_clock.complete(generation, &bytes)?;
if let Some(slot) = own_receipt.as_ref().filter(|s| s.get().is_none()) {
let hash = format!("{:x}", Sha256::digest(&bytes));
let _ = slot.set(VerifiedTimeSample::new(request, hash));
}
Ok::<(), anyhow::Error>(())
}
.await;
if result.is_err() {
let _ = own_clock.close_generation(generation);
}
tokio::time::sleep(if result.is_ok() {
Duration::from_millis(20)
} else {
Duration::from_millis(500)
})
.await;
tokio::time::sleep(mode.interval(result.is_ok())).await;
}
let _ = own_clock.close_generation(generation);
}));
@@ -512,18 +552,20 @@ impl Agent {
!helper_stop.load(Ordering::SeqCst),
"TIME_CONNECTION_CLOSED"
);
time_helper.time_complete(generation, bytes).await
let pending = helper_receipt.as_ref().filter(|s| s.get().is_none());
let report =
pending.map(|slot| (slot, format!("{:x}", Sha256::digest(&bytes))));
time_helper.time_complete(generation, bytes).await?;
if let Some((slot, hash)) = report {
let _ = slot.set(VerifiedTimeSample::new(request, hash));
}
Ok::<(), anyhow::Error>(())
}
.await;
if result.is_err() {
let _ = time_helper.time_close(generation).await;
}
tokio::time::sleep(if result.is_ok() {
Duration::from_millis(20)
} else {
Duration::from_millis(500)
})
.await;
tokio::time::sleep(mode.interval(result.is_ok())).await;
}
let _ = time_helper.time_close(generation).await;
}));
@@ -534,6 +576,7 @@ impl Agent {
clock,
helper,
tasks,
samples,
});
Ok(())
}
@@ -1540,7 +1583,9 @@ impl Agent {
);
self.clock = self.clock.for_generation(generation);
#[cfg(feature = "system-helper")]
self.start_time_refresh(generation, &identity)?;
if self.config.enable_jobs {
self.start_time_refresh(generation, &identity)?;
}
self.queue_inventory(generation)?;
self.queue_update_observation(generation)?;
self.replay(&channel, generation).await?;
@@ -1643,6 +1688,15 @@ impl Agent {
continue;
}
if heartbeat.elapsed() >= heartbeat_after {
#[cfg(feature = "system-helper")]
if !self.config.enable_jobs
&& self.time_refresh.is_none()
&& self.start_time_refresh(generation, &identity).is_err()
{
// An absent or unreadable profile must never take passive
// inventory offline. Retry setup at the next heartbeat.
eprintln!("PASSIVE_SIGNED_TIME_UNAVAILABLE");
}
let payload = Payload::Heartbeat(Heartbeat {
instance_id: self.instance.clone(),
uptime_seconds: self.started.elapsed().as_secs(),
@@ -1659,6 +1713,14 @@ impl Agent {
)?;
channel.poll(poll).await?;
}
#[cfg(feature = "system-helper")]
if let Some(refresh) = &mut self.time_refresh {
let state = &self.config.state_directory;
refresh.samples.retain(|slot| {
slot.get()
.is_none_or(|sample| sample.persist(state).is_err())
});
}
heartbeat = Instant::now();
heartbeat_after = Duration::from_millis(rand::random_range(27000..33000));
}
+47
View File
@@ -10,6 +10,29 @@ use uuid::Uuid;
const SECOND_NS: u64 = 1_000_000_000;
const MAX_BASE_ERROR_NS: u64 = 10_000_000;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SamplingMode {
Passive,
Jobs,
}
impl SamplingMode {
pub fn configured(jobs: bool, profile: &std::path::Path) -> std::io::Result<Option<Self>> {
if jobs {
return Ok(Some(Self::Jobs));
}
Ok(profile.try_exists()?.then_some(Self::Passive))
}
pub fn interval(self, verified: bool) -> std::time::Duration {
use std::time::Duration;
match (self, verified) {
(Self::Passive, _) => Duration::from_secs(30),
(Self::Jobs, true) => Duration::from_millis(20),
(Self::Jobs, false) => Duration::from_millis(500),
}
}
}
fn independent_time_key(time_key_hex: &str, job_key_hex: &str) -> Result<[u8; 32]> {
fn decode(value: &str) -> Result<[u8; 32]> {
ensure!(
@@ -1137,6 +1160,30 @@ pub use installed::{BoundClock, CONFIG_PATH, Comparison, RuntimeClock, SignedClo
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn passive_sampling_requires_a_profile_and_uses_heartbeat_cadence() {
let dir = std::env::temp_dir().join(Uuid::new_v4().to_string());
std::fs::create_dir(&dir).unwrap();
let profile = dir.join("time-attestation.json");
assert_eq!(SamplingMode::configured(false, &profile).unwrap(), None);
assert_eq!(
SamplingMode::configured(true, &profile).unwrap(),
Some(SamplingMode::Jobs)
);
std::fs::write(&profile, b"{}").unwrap();
assert_eq!(
SamplingMode::configured(false, &profile).unwrap(),
Some(SamplingMode::Passive)
);
for verified in [false, true] {
assert_eq!(
SamplingMode::Passive.interval(verified),
std::time::Duration::from_secs(30)
);
}
std::fs::remove_dir_all(dir).unwrap();
}
fn sample(ns: u64) -> Sample {
Sample {
wall_utc_ns: 1_800_000_000_000_000_000 + ns as i64,