Merge commit '74402ef' into codex/agent-updater
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
@@ -31,6 +31,7 @@ uuid.workspace = true
|
||||
rmm-domain = { path = "../domain" }
|
||||
rmm-agent-core = { path = "../agent-core" }
|
||||
rmm-protocol = { path = "../protocol" }
|
||||
rmm-time-attestation = { path = "../time-attestation" }
|
||||
rusqlite = { version = "0.32.1", features = ["bundled"] }
|
||||
fs2 = "0.4.3"
|
||||
rcgen = { version = "=0.14.10", default-features = false, features = ["crypto", "ring", "pem"] }
|
||||
|
||||
@@ -27,6 +27,7 @@ pub mod package;
|
||||
pub mod process;
|
||||
#[cfg(windows)]
|
||||
pub mod service;
|
||||
pub mod signed_clock;
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
mod system_script;
|
||||
|
||||
|
||||
@@ -0,0 +1,623 @@
|
||||
//! Independent signed time comparison for the Windows agent and SYSTEM helper.
|
||||
//! This module does not implement SyncClock, advertise a capability, start a job,
|
||||
//! change W32Time or replace the still-closed legacy NativeClock adapter.
|
||||
#![cfg(any(test, all(windows, feature = "system-helper")))]
|
||||
use anyhow::{Result, ensure};
|
||||
use rmm_time_attestation::Sample;
|
||||
use uuid::Uuid;
|
||||
|
||||
const SECOND_NS: u64 = 1_000_000_000;
|
||||
const MAX_BASE_ERROR_NS: u64 = 10_000_000;
|
||||
|
||||
fn independent_time_key(time_key_hex: &str, job_key_hex: &str) -> Result<[u8; 32]> {
|
||||
fn decode(value: &str) -> Result<[u8; 32]> {
|
||||
ensure!(
|
||||
value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit()),
|
||||
"TIME_NATIVE_PUBLIC_KEY"
|
||||
);
|
||||
let mut raw = [0u8; 32];
|
||||
for (index, byte) in raw.iter_mut().enumerate() {
|
||||
*byte = u8::from_str_radix(&value[index * 2..index * 2 + 2], 16)?;
|
||||
}
|
||||
Ok(raw)
|
||||
}
|
||||
let time = decode(time_key_hex)?;
|
||||
let job = decode(job_key_hex)?;
|
||||
ensure!(time != job, "TIME_NATIVE_KEY_ROLE_REUSE");
|
||||
Ok(time)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Continuity {
|
||||
boot_id: Option<Uuid>,
|
||||
previous: Option<Sample>,
|
||||
epoch: u64,
|
||||
exhausted: bool,
|
||||
active: Option<Uuid>,
|
||||
configuration: Option<(u64, String)>,
|
||||
connection_generation: Option<u64>,
|
||||
}
|
||||
impl Continuity {
|
||||
fn invalidate(&mut self) {
|
||||
self.active = None;
|
||||
match self.epoch.checked_add(1) {
|
||||
Some(epoch) if !self.exhausted => self.epoch = epoch,
|
||||
_ => self.exhausted = true,
|
||||
}
|
||||
}
|
||||
fn observe(&mut self, boot_id: Uuid, sample: Sample) -> Result<()> {
|
||||
let valid = !boot_id.is_nil()
|
||||
&& !self.exhausted
|
||||
&& self.boot_id.is_none_or(|old| old == boot_id)
|
||||
&& sample.wall_utc_ns > 0
|
||||
&& sample.capture_error_ns <= rmm_time_attestation::MAX_CAPTURE_ERROR_NS
|
||||
&& self.previous.is_none_or(|old| {
|
||||
match (
|
||||
sample.wall_utc_ns.checked_sub(old.wall_utc_ns),
|
||||
sample.interrupt_ns.checked_sub(old.interrupt_ns),
|
||||
sample.unbiased_ns.checked_sub(old.unbiased_ns),
|
||||
) {
|
||||
(Some(wall), Some(interrupt), Some(unbiased)) if wall >= 0 => {
|
||||
(wall as u64).abs_diff(interrupt) <= SECOND_NS
|
||||
&& interrupt.abs_diff(unbiased) <= SECOND_NS
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
});
|
||||
// Never adopt a different boot in a surviving process. A new adapter
|
||||
// object cannot erase this process-wide identity/continuity history.
|
||||
self.boot_id.get_or_insert(boot_id);
|
||||
self.previous = Some(sample);
|
||||
if !valid {
|
||||
self.invalidate();
|
||||
}
|
||||
ensure!(valid, "TIME_NATIVE_DISCONTINUITY_OR_BOOT");
|
||||
Ok(())
|
||||
}
|
||||
fn accept_configuration(&mut self, generation: u64, sha256: &str) -> Result<()> {
|
||||
ensure!(
|
||||
generation > 0 && !self.exhausted,
|
||||
"TIME_NATIVE_CONFIGURATION_GENERATION"
|
||||
);
|
||||
if let Some((current, hash)) = &self.configuration {
|
||||
ensure!(
|
||||
generation >= *current && (generation != *current || hash == sha256),
|
||||
"TIME_NATIVE_CONFIGURATION_ROLLBACK_OR_FORK"
|
||||
);
|
||||
if generation > *current {
|
||||
self.invalidate();
|
||||
}
|
||||
}
|
||||
self.configuration = Some((generation, sha256.into()));
|
||||
Ok(())
|
||||
}
|
||||
fn accept_connection(&mut self, generation: u64) -> Result<()> {
|
||||
ensure!(
|
||||
generation > 0
|
||||
&& !self.exhausted
|
||||
&& self
|
||||
.connection_generation
|
||||
.is_none_or(|old| generation >= old),
|
||||
"TIME_NATIVE_CONNECTION_ROLLBACK"
|
||||
);
|
||||
if self
|
||||
.connection_generation
|
||||
.is_some_and(|old| generation > old)
|
||||
{
|
||||
self.invalidate();
|
||||
}
|
||||
self.connection_generation = Some(generation);
|
||||
Ok(())
|
||||
}
|
||||
fn require_connection(&self, generation: u64) -> Result<()> {
|
||||
ensure!(
|
||||
!self.exhausted && self.connection_generation == Some(generation),
|
||||
"TIME_NATIVE_CONNECTION_CHANGED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn reserve(&mut self, owner: Uuid) -> Result<u64> {
|
||||
ensure!(
|
||||
!self.exhausted && !owner.is_nil() && self.active.is_none(),
|
||||
"TIME_NATIVE_CHALLENGE_BUSY"
|
||||
);
|
||||
self.active = Some(owner);
|
||||
Ok(self.epoch)
|
||||
}
|
||||
fn require_owner(&self, owner: Uuid, epoch: u64) -> Result<()> {
|
||||
ensure!(
|
||||
!self.exhausted && self.active == Some(owner) && self.epoch == epoch,
|
||||
"TIME_NATIVE_CHALLENGE_INVALIDATED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// All three native clocks are read in one bracket. The qualified base error
|
||||
/// is a protected installation input, never inferred from 100ns resolution.
|
||||
fn bracket_sample(
|
||||
wall_filetime: u64,
|
||||
interrupt_before: u64,
|
||||
interrupt_after: u64,
|
||||
unbiased_before: u64,
|
||||
unbiased_after: u64,
|
||||
base_error_ns: u64,
|
||||
) -> Result<Sample> {
|
||||
const FILETIME_UNIX: u64 = 116_444_736_000_000_000;
|
||||
ensure!(
|
||||
base_error_ns > 0 && base_error_ns <= MAX_BASE_ERROR_NS,
|
||||
"TIME_NATIVE_CALIBRATION_REQUIRED"
|
||||
);
|
||||
let width = interrupt_after
|
||||
.checked_sub(interrupt_before)
|
||||
.and_then(|value| value.checked_mul(100))
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_CAPTURE_COUNTER"))?;
|
||||
let unbiased_width = unbiased_after
|
||||
.checked_sub(unbiased_before)
|
||||
.and_then(|value| value.checked_mul(100))
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_CAPTURE_COUNTER"))?;
|
||||
ensure!(
|
||||
width.abs_diff(unbiased_width) <= SECOND_NS,
|
||||
"TIME_NATIVE_CAPTURE_SUSPEND"
|
||||
);
|
||||
let capture_error_ns = width
|
||||
.checked_add(base_error_ns)
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_CAPTURE_OVERFLOW"))?;
|
||||
ensure!(
|
||||
capture_error_ns <= rmm_time_attestation::MAX_CAPTURE_ERROR_NS,
|
||||
"TIME_NATIVE_CAPTURE_BUDGET"
|
||||
);
|
||||
let wall_utc_ns = wall_filetime
|
||||
.checked_sub(FILETIME_UNIX)
|
||||
.and_then(|value| value.checked_mul(100))
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_WALL_RANGE"))?
|
||||
.try_into()?;
|
||||
Ok(Sample {
|
||||
wall_utc_ns,
|
||||
interrupt_ns: interrupt_after
|
||||
.checked_mul(100)
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_COUNTER_RANGE"))?,
|
||||
unbiased_ns: unbiased_after
|
||||
.checked_mul(100)
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_COUNTER_RANGE"))?,
|
||||
capture_error_ns,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
mod installed {
|
||||
use super::*;
|
||||
use crate::helper_ipc::{self as ipc, PeerProof, PinnedFile};
|
||||
use anyhow::Context as _;
|
||||
use rmm_agent_core::auth::Binding;
|
||||
use rmm_domain::jobs::hash;
|
||||
use rmm_time_attestation::{
|
||||
Challenge, Context, Interval, Pins, Request, Role, SignedAttestation, Verifier,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
io::Read,
|
||||
path::Path,
|
||||
sync::{Mutex, OnceLock},
|
||||
};
|
||||
|
||||
pub const CONFIG_PATH: &str = r"C:\ProgramData\RustDiscoverySystem\time-attestation.json";
|
||||
const PUBLIC_ROOT: &str = r"C:\ProgramData\RustDiscoverySystem";
|
||||
const MAX_CONFIG_BYTES: usize = 16_384;
|
||||
const MAX_REPLY_BYTES: usize = 16_384;
|
||||
|
||||
/// Provision only after an independent qualification of these actual
|
||||
/// native APIs/platform/image. A file field is not a measured accuracy.
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Calibration {
|
||||
pub role: Role,
|
||||
pub binary_sha256: String,
|
||||
pub qualification_sha256: String,
|
||||
pub base_error_ns: u64,
|
||||
}
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Configuration {
|
||||
pub schema_version: u32,
|
||||
pub key_generation: u64,
|
||||
pub server_instance: Uuid,
|
||||
pub binding: Binding,
|
||||
pub public_keys_hex: BTreeMap<String, String>,
|
||||
pub calibrations: Vec<Calibration>,
|
||||
}
|
||||
fn digest(value: &str) -> bool {
|
||||
value.len() == 64
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
|
||||
}
|
||||
static PROCESS: OnceLock<Mutex<Continuity>> = OnceLock::new();
|
||||
static INCARNATION: OnceLock<Uuid> = OnceLock::new();
|
||||
fn process() -> &'static Mutex<Continuity> {
|
||||
PROCESS.get_or_init(|| Mutex::new(Continuity::default()))
|
||||
}
|
||||
fn capture(base_error_ns: u64) -> Result<Sample> {
|
||||
#[link(name = "kernel32")]
|
||||
unsafe extern "system" {
|
||||
fn GetSystemTimePreciseAsFileTime(value: *mut u64);
|
||||
fn QueryInterruptTimePrecise(value: *mut u64);
|
||||
fn QueryUnbiasedInterruptTimePrecise(value: *mut u64);
|
||||
}
|
||||
let (mut ib, mut ia, mut ub, mut ua, mut wall) = (0, 0, 0, 0, 0);
|
||||
// SAFETY: documented VOID kernel getters with valid aligned u64
|
||||
// outputs. Windows 10+ is required; no optional API fallback exists.
|
||||
unsafe {
|
||||
QueryInterruptTimePrecise(&mut ib);
|
||||
QueryUnbiasedInterruptTimePrecise(&mut ub);
|
||||
GetSystemTimePreciseAsFileTime(&mut wall);
|
||||
QueryUnbiasedInterruptTimePrecise(&mut ua);
|
||||
QueryInterruptTimePrecise(&mut ia);
|
||||
}
|
||||
bracket_sample(wall, ib, ia, ub, ua, base_error_ns)
|
||||
}
|
||||
fn observed(boot: Uuid, base_error_ns: u64) -> Result<(Sample, u64)> {
|
||||
let mut state = process()
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?;
|
||||
let value = match capture(base_error_ns) {
|
||||
Ok(value) => value,
|
||||
Err(error) => {
|
||||
state.invalidate();
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
state.observe(boot, value)?;
|
||||
Ok((value, state.epoch))
|
||||
}
|
||||
|
||||
struct Pending {
|
||||
owner: Uuid,
|
||||
epoch: u64,
|
||||
challenge: Challenge,
|
||||
}
|
||||
/// Own-process role proof, protected held configuration, private challenge
|
||||
/// and native timers. No constructor accepts agent-reported helper times.
|
||||
pub struct SignedClock {
|
||||
verifier: Verifier,
|
||||
own_process: PeerProof,
|
||||
files: Vec<PinnedFile>,
|
||||
config_sha256: String,
|
||||
boot_id: Uuid,
|
||||
connection_generation: u64,
|
||||
base_error_ns: u64,
|
||||
pending: Option<Pending>,
|
||||
}
|
||||
impl SignedClock {
|
||||
/// Connection generation is later confirmed by the independently
|
||||
/// signed server response. It is never itself a ready/sync flag.
|
||||
pub async fn open(role: Role, connection_generation: u64) -> Result<Self> {
|
||||
ensure!(connection_generation > 0, "TIME_NATIVE_CONNECTION");
|
||||
let (settings, mut files) = crate::helper_system::read_settings()?;
|
||||
let own_pin = match role {
|
||||
Role::Agent => &settings.agent,
|
||||
Role::SystemHelper => &settings.helper,
|
||||
};
|
||||
own_pin.validate(role == Role::SystemHelper)?;
|
||||
ipc::require_self(own_pin)?;
|
||||
let own_process = PeerProof::for_service(
|
||||
own_pin,
|
||||
// SAFETY: this getter takes no arguments and returns own PID.
|
||||
unsafe { windows_sys::Win32::System::Threading::GetCurrentProcessId() },
|
||||
)?;
|
||||
let readers = vec![
|
||||
settings.agent.service_sid.clone(),
|
||||
settings.helper.service_sid.clone(),
|
||||
];
|
||||
files.push(PinnedFile::open(
|
||||
Path::new(PUBLIC_ROOT),
|
||||
true,
|
||||
&readers,
|
||||
&[],
|
||||
false,
|
||||
)?);
|
||||
let mut config_file =
|
||||
PinnedFile::open(Path::new(CONFIG_PATH), false, &readers, &[], false)?;
|
||||
ensure!(
|
||||
config_file.file.metadata()?.len() <= MAX_CONFIG_BYTES as u64,
|
||||
"TIME_NATIVE_CONFIG_SIZE"
|
||||
);
|
||||
let mut raw = Vec::new();
|
||||
(&mut config_file.file)
|
||||
.take(MAX_CONFIG_BYTES as u64 + 1)
|
||||
.read_to_end(&mut raw)?;
|
||||
ensure!(raw.len() <= MAX_CONFIG_BYTES, "TIME_NATIVE_CONFIG_SIZE");
|
||||
let config: Configuration = serde_json::from_slice(&raw)?;
|
||||
ensure!(
|
||||
config.schema_version == 1
|
||||
&& config.key_generation > 0
|
||||
&& config.calibrations.len() == 2,
|
||||
"TIME_NATIVE_CONFIG_PROFILE"
|
||||
);
|
||||
ensure!(
|
||||
hash(&serde_json::to_vec(&config.binding)?)
|
||||
== hash(&serde_json::to_vec(&settings.binding)?),
|
||||
"TIME_NATIVE_DEVICE_BINDING"
|
||||
);
|
||||
for expected in [Role::Agent, Role::SystemHelper] {
|
||||
let mut values = config
|
||||
.calibrations
|
||||
.iter()
|
||||
.filter(|value| value.role == expected);
|
||||
let value = values.next().context("TIME_NATIVE_CALIBRATION_MISSING")?;
|
||||
ensure!(
|
||||
values.next().is_none()
|
||||
&& digest(&value.binary_sha256)
|
||||
&& digest(&value.qualification_sha256)
|
||||
&& value.base_error_ns > 0
|
||||
&& value.base_error_ns <= MAX_BASE_ERROR_NS,
|
||||
"TIME_NATIVE_CALIBRATION_PROFILE"
|
||||
);
|
||||
let pin = if expected == Role::Agent {
|
||||
&settings.agent
|
||||
} else {
|
||||
&settings.helper
|
||||
};
|
||||
ensure!(
|
||||
value.binary_sha256 == pin.binary_sha256,
|
||||
"TIME_NATIVE_CALIBRATION_IMAGE"
|
||||
);
|
||||
}
|
||||
let base_error_ns = config
|
||||
.calibrations
|
||||
.iter()
|
||||
.find(|value| value.role == role)
|
||||
.context("TIME_NATIVE_CALIBRATION_MISSING")?
|
||||
.base_error_ns;
|
||||
let keys = config
|
||||
.public_keys_hex
|
||||
.iter()
|
||||
.map(|(id, key)| {
|
||||
ensure!(digest(key), "TIME_NATIVE_PUBLIC_KEY");
|
||||
let raw = independent_time_key(key, &settings.binding.public_key_hex)?;
|
||||
Ok((id.clone(), raw))
|
||||
})
|
||||
.collect::<Result<BTreeMap<_, _>>>()?;
|
||||
let pins = Pins::new(config.key_generation, config.server_instance, keys)?;
|
||||
process()
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?
|
||||
.accept_configuration(config.key_generation, &hash(&raw))?;
|
||||
|
||||
// The existing fixed read-only native getter is independent in
|
||||
// each process. It finishes BEFORE challenge/RTT timing begins.
|
||||
let boot_id = Uuid::parse_str(&crate::native::boot_id().await?)?;
|
||||
let context = Context {
|
||||
tenant_id: settings.binding.tenant_id,
|
||||
asset_id: settings.binding.asset_id,
|
||||
agent_id: settings.binding.agent_id,
|
||||
enrollment_generation: settings.binding.enrollment_generation,
|
||||
assignment_generation: settings.binding.assignment_version,
|
||||
connection_generation,
|
||||
windows_boot_id: boot_id,
|
||||
verifier_incarnation: *INCARNATION.get_or_init(Uuid::new_v4),
|
||||
role,
|
||||
helper_image_sha256: (role == Role::SystemHelper)
|
||||
.then(|| own_pin.binary_sha256.clone()),
|
||||
binding_schema: 1,
|
||||
};
|
||||
files.push(config_file);
|
||||
let mut value = Self {
|
||||
verifier: Verifier::new(context, pins)?,
|
||||
own_process,
|
||||
files,
|
||||
config_sha256: hash(&raw),
|
||||
boot_id,
|
||||
connection_generation,
|
||||
base_error_ns,
|
||||
pending: None,
|
||||
};
|
||||
value.recheck()?;
|
||||
process()
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?
|
||||
.accept_connection(connection_generation)?;
|
||||
observed(boot_id, base_error_ns)?;
|
||||
Ok(value)
|
||||
}
|
||||
fn recheck(&mut self) -> Result<()> {
|
||||
self.own_process.check()?;
|
||||
for file in &mut self.files {
|
||||
file.check()?;
|
||||
}
|
||||
let config = self.files.last_mut().context("TIME_NATIVE_CONFIG_HELD")?;
|
||||
ensure!(
|
||||
config.sha256()? == self.config_sha256,
|
||||
"TIME_NATIVE_CONFIG_CHANGED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
pub fn begin(&mut self, connection_generation: u64) -> Result<Request> {
|
||||
if connection_generation != self.connection_generation {
|
||||
self.close();
|
||||
anyhow::bail!("TIME_NATIVE_CONNECTION_CHANGED");
|
||||
}
|
||||
ensure!(self.pending.is_none(), "TIME_NATIVE_PENDING");
|
||||
self.recheck()?;
|
||||
let mut state = process()
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?;
|
||||
state.require_connection(connection_generation)?;
|
||||
let sample = match capture(self.base_error_ns) {
|
||||
Ok(value) => value,
|
||||
Err(error) => {
|
||||
state.invalidate();
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
state.observe(self.boot_id, sample)?;
|
||||
let owner = Uuid::new_v4();
|
||||
let epoch = state.reserve(owner)?;
|
||||
let challenge = match self.verifier.begin(sample) {
|
||||
Ok(value) => value,
|
||||
Err(error) => {
|
||||
state.invalidate();
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
let request = challenge.request().clone();
|
||||
self.pending = Some(Pending {
|
||||
owner,
|
||||
epoch,
|
||||
challenge,
|
||||
});
|
||||
Ok(request)
|
||||
}
|
||||
/// Call immediately after this verifier receives the complete bounded
|
||||
/// response. The helper's caller supplies bytes only, never timestamps.
|
||||
/// All failures consume the original request; no transparent retry.
|
||||
pub fn complete<T>(
|
||||
&mut self,
|
||||
bytes: &[u8],
|
||||
consume: impl FnOnce(&Comparison) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
let pending = self.pending.take().context("TIME_NATIVE_NO_CHALLENGE")?;
|
||||
let result = (|| {
|
||||
let (received, epoch) = observed(self.boot_id, self.base_error_ns)?;
|
||||
ensure!(epoch == pending.epoch, "TIME_NATIVE_CHALLENGE_INVALIDATED");
|
||||
ensure!(bytes.len() <= MAX_REPLY_BYTES, "TIME_NATIVE_REPLY_SIZE");
|
||||
let signed: SignedAttestation = serde_json::from_slice(bytes)?;
|
||||
self.recheck()?;
|
||||
let mut checked = None;
|
||||
let interval =
|
||||
self.verifier
|
||||
.finish(pending.challenge, &signed, received, || {
|
||||
let (sample, epoch) = observed(self.boot_id, self.base_error_ns)?;
|
||||
ensure!(epoch == pending.epoch, "TIME_NATIVE_CHALLENGE_INVALIDATED");
|
||||
checked = Some(sample);
|
||||
Ok(sample)
|
||||
})?;
|
||||
let mut state = process()
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?;
|
||||
state.require_owner(pending.owner, pending.epoch)?;
|
||||
state.active = None;
|
||||
let comparison = Comparison {
|
||||
interval,
|
||||
wall_utc_ns: checked.context("TIME_NATIVE_FINAL_SAMPLE")?.wall_utc_ns,
|
||||
};
|
||||
drop(state);
|
||||
consume(&comparison)
|
||||
})();
|
||||
if result.is_err() {
|
||||
self.verifier.invalidate();
|
||||
if let Ok(mut state) = process().lock()
|
||||
&& state.active == Some(pending.owner)
|
||||
{
|
||||
state.invalidate();
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
pub fn close(&mut self) {
|
||||
self.verifier.invalidate();
|
||||
if let Some(pending) = self.pending.take()
|
||||
&& let Ok(mut state) = process().lock()
|
||||
&& state.active == Some(pending.owner)
|
||||
{
|
||||
state.invalidate();
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for SignedClock {
|
||||
fn drop(&mut self) {
|
||||
self.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// Borrowed only inside the completion callback, never returned as a
|
||||
/// storable clock/lease/permit. Runtime callers must retain all job gates.
|
||||
pub struct Comparison {
|
||||
interval: Interval,
|
||||
wall_utc_ns: i64,
|
||||
}
|
||||
impl Comparison {
|
||||
pub fn interval(&self) -> &Interval {
|
||||
&self.interval
|
||||
}
|
||||
pub fn wall_utc_ns(&self) -> i64 {
|
||||
self.wall_utc_ns
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
pub use installed::{CONFIG_PATH, Calibration, Comparison, Configuration, SignedClock};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn sample(ns: u64) -> Sample {
|
||||
Sample {
|
||||
wall_utc_ns: 1_800_000_000_000_000_000 + ns as i64,
|
||||
interrupt_ns: 10_000_000_000 + ns,
|
||||
unbiased_ns: 9_000_000_000 + ns,
|
||||
capture_error_ns: 1_000_000,
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn job_key_cannot_be_reintroduced_as_a_time_key_with_different_hex_case() {
|
||||
assert_eq!(
|
||||
independent_time_key(&"ab".repeat(32), &"AB".repeat(32))
|
||||
.unwrap_err()
|
||||
.to_string(),
|
||||
"TIME_NATIVE_KEY_ROLE_REUSE"
|
||||
);
|
||||
assert!(independent_time_key(&"ab".repeat(32), &"cd".repeat(32)).is_ok());
|
||||
assert!(independent_time_key(&"ab".repeat(32), "not-a-provisioned-job-key").is_err());
|
||||
}
|
||||
#[test]
|
||||
fn bracket_uses_actual_capture_width_and_refuses_unqualified_or_backward_counters() {
|
||||
let wall = 116_444_736_000_000_000 + 18_000_000_000_000_000;
|
||||
let result = bracket_sample(wall, 100, 120, 90, 110, 1_000_000).unwrap();
|
||||
assert_eq!(result.wall_utc_ns, 1_800_000_000_000_000_000);
|
||||
assert_eq!(result.capture_error_ns, 1_002_000);
|
||||
assert!(bracket_sample(wall, 100, 99, 90, 110, 1_000_000).is_err());
|
||||
assert!(bracket_sample(wall, 100, 120, 90, 89, 1_000_000).is_err());
|
||||
assert!(bracket_sample(wall, 100, 120, 90, 110, 0).is_err());
|
||||
assert!(bracket_sample(wall, 0, 500_000, 0, 500_000, 1_000_000).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn retained_process_fence_rejects_old_challenge_and_boot_substitution() {
|
||||
let boot = Uuid::new_v4();
|
||||
let owner = Uuid::new_v4();
|
||||
let mut state = Continuity::default();
|
||||
state.accept_configuration(4, "one-config").unwrap();
|
||||
state.accept_connection(3).unwrap();
|
||||
assert!(state.accept_configuration(3, "old-config").is_err());
|
||||
assert!(state.accept_configuration(4, "different-config").is_err());
|
||||
state.accept_configuration(4, "one-config").unwrap();
|
||||
|
||||
state.observe(boot, sample(0)).unwrap();
|
||||
let original_epoch = state.reserve(owner).unwrap();
|
||||
assert!(state.reserve(Uuid::new_v4()).is_err());
|
||||
let mut resumed = sample(2_000_000_000);
|
||||
resumed.unbiased_ns = 9_000_000_000;
|
||||
assert!(state.observe(boot, resumed).is_err());
|
||||
assert!(state.require_owner(owner, original_epoch).is_err());
|
||||
// A caller reconstructing its verifier still sees this retained state.
|
||||
state.observe(boot, resumed).unwrap();
|
||||
let next = Uuid::new_v4();
|
||||
let epoch = state.reserve(next).unwrap();
|
||||
assert!(epoch > original_epoch);
|
||||
state.require_owner(next, epoch).unwrap();
|
||||
state.accept_connection(4).unwrap();
|
||||
assert!(state.require_owner(next, epoch).is_err());
|
||||
assert!(state.require_connection(3).is_err());
|
||||
assert!(state.accept_connection(3).is_err());
|
||||
state.require_connection(4).unwrap();
|
||||
assert!(state.observe(Uuid::new_v4(), resumed).is_err());
|
||||
assert!(state.require_owner(next, epoch).is_err());
|
||||
state.epoch = u64::MAX;
|
||||
state.invalidate();
|
||||
assert!(state.exhausted);
|
||||
state.invalidate();
|
||||
assert!(state.exhausted);
|
||||
assert!(state.reserve(Uuid::new_v4()).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "rmm-time-attestation"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
ed25519-dalek = "=2.2.0"
|
||||
hex.workspace = true
|
||||
rand.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
sha2.workspace = true
|
||||
uuid.workspace = true
|
||||
@@ -0,0 +1,555 @@
|
||||
//! Independent online time comparison, never a sync lease or execution permit.
|
||||
//! Nanoseconds are signed UTC Unix ns, intervals are unsigned ns. Callers must
|
||||
//! hold their own native clock observations and protected context/pins.
|
||||
use anyhow::{Result, ensure};
|
||||
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::BTreeMap;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub const ENDPOINT: &str = "https://discovery.ease-technologies.de/agent/v1/time-attestation";
|
||||
pub const MAX_RTT_NS: u64 = 1_000_000_000;
|
||||
pub const MAX_RECEIVED_AGE_NS: u64 = 100_000_000;
|
||||
pub const MAX_CAPTURE_ERROR_NS: u64 = 50_000_000;
|
||||
pub const MAX_SERVER_ERROR_NS: u64 = 500_000_000;
|
||||
pub const MAX_SYNC_AGE_NS: u64 = 3_600_000_000_000;
|
||||
const DOMAIN: &[u8] = b"RMM-TIME-ATTESTATION/v1\0";
|
||||
const MAX_BYTES: usize = 8192;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Role {
|
||||
Agent,
|
||||
SystemHelper,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Context {
|
||||
pub tenant_id: Uuid,
|
||||
pub asset_id: Uuid,
|
||||
pub agent_id: Uuid,
|
||||
pub enrollment_generation: u64,
|
||||
pub assignment_generation: u64,
|
||||
pub connection_generation: u64,
|
||||
pub windows_boot_id: Uuid,
|
||||
pub verifier_incarnation: Uuid,
|
||||
pub role: Role,
|
||||
pub helper_image_sha256: Option<String>,
|
||||
pub binding_schema: u32,
|
||||
}
|
||||
impl Context {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
ensure!(
|
||||
[
|
||||
self.tenant_id,
|
||||
self.asset_id,
|
||||
self.agent_id,
|
||||
self.windows_boot_id,
|
||||
self.verifier_incarnation
|
||||
]
|
||||
.iter()
|
||||
.all(|v| !v.is_nil()),
|
||||
"TIME_CONTEXT_ID"
|
||||
);
|
||||
ensure!(
|
||||
self.enrollment_generation > 0
|
||||
&& self.assignment_generation > 0
|
||||
&& self.connection_generation > 0
|
||||
&& self.binding_schema == 1,
|
||||
"TIME_CONTEXT_GENERATION"
|
||||
);
|
||||
match self.role {
|
||||
Role::Agent => ensure!(
|
||||
self.helper_image_sha256.is_none(),
|
||||
"TIME_AGENT_HELPER_IMAGE"
|
||||
),
|
||||
Role::SystemHelper => {
|
||||
exact_hex(self.helper_image_sha256.as_deref().unwrap_or(""), 32)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Request {
|
||||
pub version: u32,
|
||||
pub endpoint: String,
|
||||
pub nonce: String,
|
||||
pub context: Context,
|
||||
}
|
||||
impl Request {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
ensure!(
|
||||
self.version == 1 && self.endpoint == ENDPOINT,
|
||||
"TIME_REQUEST_PROFILE"
|
||||
);
|
||||
exact_hex(&self.nonce, 32)?;
|
||||
self.context.validate()
|
||||
}
|
||||
pub fn sha256(&self) -> Result<String> {
|
||||
self.validate()?;
|
||||
Ok(hex::encode(Sha256::digest(serde_json::to_vec(self)?)))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Payload {
|
||||
pub version: u32,
|
||||
pub request_sha256: String,
|
||||
pub server_instance: Uuid,
|
||||
pub server_boot_id: Uuid,
|
||||
pub key_id: String,
|
||||
pub key_generation: u64,
|
||||
pub captured_utc_ns: i64,
|
||||
pub server_error_ns: u64,
|
||||
pub source_sync_age_ns: u64,
|
||||
}
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct SignedAttestation {
|
||||
/// Exact canonical JSON bytes (UTF-8); verification never normalizes input.
|
||||
pub payload: String,
|
||||
pub signature_hex: String,
|
||||
}
|
||||
fn exact_hex(value: &str, bytes: usize) -> Result<()> {
|
||||
ensure!(
|
||||
value.len() == bytes * 2
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
|
||||
"TIME_HEX_FORMAT"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn validate_payload(p: &Payload) -> Result<()> {
|
||||
ensure!(
|
||||
p.version == 1 && !p.server_instance.is_nil() && !p.server_boot_id.is_nil(),
|
||||
"TIME_SERVER_CONTEXT"
|
||||
);
|
||||
ensure!(
|
||||
!p.key_id.is_empty()
|
||||
&& p.key_id.len() <= 64
|
||||
&& p.key_id
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||
&& p.key_generation > 0,
|
||||
"TIME_KEY_CONTEXT"
|
||||
);
|
||||
exact_hex(&p.request_sha256, 32)?;
|
||||
ensure!(
|
||||
p.captured_utc_ns > 0
|
||||
&& p.server_error_ns <= MAX_SERVER_ERROR_NS
|
||||
&& p.source_sync_age_ns <= MAX_SYNC_AGE_NS,
|
||||
"TIME_SERVER_QUALITY"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
/// Only server code which has independently qualified the native source may
|
||||
/// construct/sign this payload. This codec is not a provider qualification.
|
||||
pub fn sign(payload: &Payload, key: &SigningKey) -> Result<SignedAttestation> {
|
||||
validate_payload(payload)?;
|
||||
let raw = serde_json::to_string(payload)?;
|
||||
let mut message = DOMAIN.to_vec();
|
||||
message.extend_from_slice(raw.as_bytes());
|
||||
Ok(SignedAttestation {
|
||||
payload: raw,
|
||||
signature_hex: hex::encode(key.sign(&message).to_bytes()),
|
||||
})
|
||||
}
|
||||
/// Loaded through the verifier's protected configuration, never an HTTP reply.
|
||||
pub struct Pins {
|
||||
generation: u64,
|
||||
server_instance: Uuid,
|
||||
keys: BTreeMap<String, VerifyingKey>,
|
||||
}
|
||||
impl Pins {
|
||||
pub fn new(
|
||||
generation: u64,
|
||||
server_instance: Uuid,
|
||||
keys: BTreeMap<String, [u8; 32]>,
|
||||
) -> Result<Self> {
|
||||
ensure!(
|
||||
generation > 0 && !server_instance.is_nil() && !keys.is_empty() && keys.len() <= 8,
|
||||
"TIME_PINS"
|
||||
);
|
||||
let keys = keys
|
||||
.into_iter()
|
||||
.map(|(id, raw)| Ok((id, VerifyingKey::from_bytes(&raw)?)))
|
||||
.collect::<Result<_>>()?;
|
||||
Ok(Self {
|
||||
generation,
|
||||
server_instance,
|
||||
keys,
|
||||
})
|
||||
}
|
||||
}
|
||||
/// A native, locally captured observation; ns counters share one process's OS
|
||||
/// clock domains. capture_error_ns must come from platform qualification.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Sample {
|
||||
pub wall_utc_ns: i64,
|
||||
pub interrupt_ns: u64,
|
||||
pub unbiased_ns: u64,
|
||||
pub capture_error_ns: u64,
|
||||
}
|
||||
impl Sample {
|
||||
fn validate(self) -> Result<()> {
|
||||
ensure!(
|
||||
self.wall_utc_ns > 0 && self.capture_error_ns <= MAX_CAPTURE_ERROR_NS,
|
||||
"TIME_LOCAL_SAMPLE"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
/// Opaque, noncloneable request authority: one attempt consumes it even when
|
||||
/// signature/quality checks fail. A transported Request alone is no authority.
|
||||
pub struct Challenge {
|
||||
request: Request,
|
||||
begin: Sample,
|
||||
epoch: u64,
|
||||
verifier_id: Uuid,
|
||||
}
|
||||
impl Challenge {
|
||||
pub fn request(&self) -> &Request {
|
||||
&self.request
|
||||
}
|
||||
}
|
||||
/// Lives with the verifier process; callers must not reconstruct it to clear a
|
||||
/// discontinuity. Native adapters additionally preserve the process-wide fence.
|
||||
pub struct Verifier {
|
||||
context: Context,
|
||||
pins: Pins,
|
||||
previous: Option<Sample>,
|
||||
epoch: u64,
|
||||
pending_nonce: Option<String>,
|
||||
verifier_id: Uuid,
|
||||
}
|
||||
impl Verifier {
|
||||
pub fn new(context: Context, pins: Pins) -> Result<Self> {
|
||||
context.validate()?;
|
||||
Ok(Self {
|
||||
context,
|
||||
pins,
|
||||
previous: None,
|
||||
epoch: 1,
|
||||
pending_nonce: None,
|
||||
verifier_id: Uuid::new_v4(),
|
||||
})
|
||||
}
|
||||
pub fn invalidate(&mut self) {
|
||||
self.pending_nonce = None;
|
||||
self.epoch = if self.epoch == 0 {
|
||||
0
|
||||
} else {
|
||||
self.epoch.checked_add(1).unwrap_or(0)
|
||||
};
|
||||
}
|
||||
pub fn observe(&mut self, sample: Sample) -> Result<()> {
|
||||
if let Err(error) = sample.validate() {
|
||||
self.invalidate();
|
||||
return Err(error);
|
||||
}
|
||||
let continuous = self.previous.is_none_or(|p| {
|
||||
match (
|
||||
sample.wall_utc_ns.checked_sub(p.wall_utc_ns),
|
||||
sample.interrupt_ns.checked_sub(p.interrupt_ns),
|
||||
sample.unbiased_ns.checked_sub(p.unbiased_ns),
|
||||
) {
|
||||
(Some(w), Some(i), Some(u)) if w >= 0 => {
|
||||
(w as u64).abs_diff(i) <= MAX_RTT_NS && i.abs_diff(u) <= MAX_RTT_NS
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
});
|
||||
self.previous = Some(sample);
|
||||
if !continuous {
|
||||
self.invalidate();
|
||||
}
|
||||
ensure!(continuous, "TIME_DISCONTINUITY");
|
||||
Ok(())
|
||||
}
|
||||
pub fn begin(&mut self, sample: Sample) -> Result<Challenge> {
|
||||
self.observe(sample)?;
|
||||
ensure!(
|
||||
self.epoch > 0 && self.pending_nonce.is_none(),
|
||||
"TIME_CHALLENGE_OUTSTANDING_OR_EXHAUSTED"
|
||||
);
|
||||
let nonce: [u8; 32] = rand::random();
|
||||
let request = Request {
|
||||
version: 1,
|
||||
endpoint: ENDPOINT.into(),
|
||||
nonce: hex::encode(nonce),
|
||||
context: self.context.clone(),
|
||||
};
|
||||
request.validate()?;
|
||||
self.pending_nonce = Some(request.nonce.clone());
|
||||
Ok(Challenge {
|
||||
request,
|
||||
begin: sample,
|
||||
epoch: self.epoch,
|
||||
verifier_id: self.verifier_id,
|
||||
})
|
||||
}
|
||||
pub fn finish(
|
||||
&mut self,
|
||||
challenge: Challenge,
|
||||
signed: &SignedAttestation,
|
||||
received: Sample,
|
||||
capture_checked: impl FnOnce() -> Result<Sample>,
|
||||
) -> Result<Interval> {
|
||||
let owned = challenge.verifier_id == self.verifier_id
|
||||
&& self.pending_nonce.as_deref() == Some(challenge.request.nonce.as_str())
|
||||
&& challenge.epoch == self.epoch
|
||||
&& challenge.request.context == self.context;
|
||||
self.pending_nonce = None;
|
||||
ensure!(owned, "TIME_CHALLENGE_NOT_OWNED");
|
||||
self.observe(received)?;
|
||||
ensure!(signed.payload.len() <= MAX_BYTES, "TIME_PAYLOAD_LIMIT");
|
||||
let p: Payload = serde_json::from_str(&signed.payload)?;
|
||||
ensure!(
|
||||
serde_json::to_string(&p)? == signed.payload,
|
||||
"TIME_NONCANONICAL_PAYLOAD"
|
||||
);
|
||||
validate_payload(&p)?;
|
||||
ensure!(
|
||||
p.request_sha256 == challenge.request.sha256()?
|
||||
&& p.server_instance == self.pins.server_instance
|
||||
&& p.key_generation == self.pins.generation,
|
||||
"TIME_BINDING"
|
||||
);
|
||||
let key = self
|
||||
.pins
|
||||
.keys
|
||||
.get(&p.key_id)
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_KEY_NOT_PINNED"))?;
|
||||
exact_hex(&signed.signature_hex, 64)?;
|
||||
let signature = Signature::from_slice(&hex::decode(&signed.signature_hex)?)?;
|
||||
let mut message = DOMAIN.to_vec();
|
||||
message.extend_from_slice(signed.payload.as_bytes());
|
||||
key.verify_strict(&message, &signature)?;
|
||||
let checked = capture_checked()?;
|
||||
self.observe(checked)?;
|
||||
let elapsed = checked
|
||||
.interrupt_ns
|
||||
.checked_sub(challenge.begin.interrupt_ns)
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_COUNTER"))?;
|
||||
let age = checked
|
||||
.interrupt_ns
|
||||
.checked_sub(received.interrupt_ns)
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_COUNTER"))?;
|
||||
ensure!(
|
||||
elapsed <= MAX_RTT_NS && age <= MAX_RECEIVED_AGE_NS,
|
||||
"TIME_STALE_RESPONSE"
|
||||
);
|
||||
// Include every local capture budget conservatively, never RTT/2.
|
||||
let delta = challenge
|
||||
.begin
|
||||
.capture_error_ns
|
||||
.checked_add(received.capture_error_ns)
|
||||
.and_then(|d| d.checked_add(checked.capture_error_ns))
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_ERROR_OVERFLOW"))?;
|
||||
ensure!(delta <= MAX_CAPTURE_ERROR_NS, "TIME_CAPTURE_BUDGET");
|
||||
ensure!(
|
||||
p.source_sync_age_ns
|
||||
.checked_add(elapsed)
|
||||
.and_then(|v| v.checked_add(delta))
|
||||
.is_some_and(|v| v <= MAX_SYNC_AGE_NS),
|
||||
"TIME_SOURCE_AGE_AT_CHECK"
|
||||
);
|
||||
let lower = i128::from(p.captured_utc_ns) - i128::from(p.server_error_ns);
|
||||
let upper = i128::from(p.captured_utc_ns)
|
||||
+ i128::from(p.server_error_ns)
|
||||
+ i128::from(elapsed)
|
||||
+ i128::from(delta);
|
||||
let wall = i128::from(checked.wall_utc_ns);
|
||||
ensure!(
|
||||
(wall - lower).abs().max((wall - upper).abs()) <= 2_000_000_000,
|
||||
"TIME_LOCAL_WALL_OUTSIDE_BOUND"
|
||||
);
|
||||
Ok(Interval {
|
||||
lower_utc_ns: lower.try_into()?,
|
||||
upper_utc_ns: upper.try_into()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
/// Fresh result only. Adapters must recapture/reverify for later use; this type
|
||||
/// carries no lease, serialization or execution authorization.
|
||||
#[derive(Debug)]
|
||||
pub struct Interval {
|
||||
lower_utc_ns: i64,
|
||||
upper_utc_ns: i64,
|
||||
}
|
||||
impl Interval {
|
||||
pub fn lower_utc_ns(&self) -> i64 {
|
||||
self.lower_utc_ns
|
||||
}
|
||||
pub fn upper_utc_ns(&self) -> i64 {
|
||||
self.upper_utc_ns
|
||||
}
|
||||
pub fn allows_start(&self, not_before_ns: i64, start_before_ns: i64) -> bool {
|
||||
self.lower_utc_ns >= not_before_ns && self.upper_utc_ns < start_before_ns
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
const T: i64 = 1_800_000_000_000_000_000;
|
||||
fn sample(elapsed: u64) -> Sample {
|
||||
Sample {
|
||||
wall_utc_ns: T + elapsed as i64,
|
||||
interrupt_ns: 10_000_000_000 + elapsed,
|
||||
unbiased_ns: 9_000_000_000 + elapsed,
|
||||
capture_error_ns: 1_000_000,
|
||||
}
|
||||
}
|
||||
fn context(role: Role) -> Context {
|
||||
Context {
|
||||
tenant_id: Uuid::new_v4(),
|
||||
asset_id: Uuid::new_v4(),
|
||||
agent_id: Uuid::new_v4(),
|
||||
enrollment_generation: 1,
|
||||
assignment_generation: 1,
|
||||
connection_generation: 2,
|
||||
windows_boot_id: Uuid::new_v4(),
|
||||
verifier_incarnation: Uuid::new_v4(),
|
||||
role,
|
||||
helper_image_sha256: (role == Role::SystemHelper).then(|| "ab".repeat(32)),
|
||||
binding_schema: 1,
|
||||
}
|
||||
}
|
||||
fn fixture(context: Context) -> (Verifier, SigningKey, Uuid) {
|
||||
let key = SigningKey::from_bytes(&rand::random());
|
||||
let server = Uuid::new_v4();
|
||||
let pins = Pins::new(
|
||||
4,
|
||||
server,
|
||||
BTreeMap::from([("time1".into(), key.verifying_key().to_bytes())]),
|
||||
)
|
||||
.unwrap();
|
||||
(Verifier::new(context, pins).unwrap(), key, server)
|
||||
}
|
||||
fn reply(c: &Challenge, key: &SigningKey, server: Uuid) -> SignedAttestation {
|
||||
sign(
|
||||
&Payload {
|
||||
version: 1,
|
||||
request_sha256: c.request().sha256().unwrap(),
|
||||
server_instance: server,
|
||||
server_boot_id: Uuid::new_v4(),
|
||||
key_id: "time1".into(),
|
||||
key_generation: 4,
|
||||
captured_utc_ns: T + 20_000_000,
|
||||
server_error_ns: 10_000_000,
|
||||
source_sync_age_ns: 100_000_000_000,
|
||||
},
|
||||
key,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
#[test]
|
||||
fn signed_roundtrip_uses_entire_rtt_and_strict_deadline_interval() {
|
||||
let (mut v, key, server) = fixture(context(Role::SystemHelper));
|
||||
let c = v.begin(sample(0)).unwrap();
|
||||
let signed = reply(&c, &key, server);
|
||||
let result = v
|
||||
.finish(c, &signed, sample(70_000_000), || Ok(sample(80_000_000)))
|
||||
.unwrap();
|
||||
assert_eq!(result.lower_utc_ns(), T + 10_000_000);
|
||||
assert_eq!(result.upper_utc_ns(), T + 113_000_000);
|
||||
assert!(result.allows_start(T, T + 114_000_000));
|
||||
assert!(!result.allows_start(T, T + 113_000_000));
|
||||
assert!(!result.allows_start(T + 11_000_000, T + 114_000_000));
|
||||
}
|
||||
#[test]
|
||||
fn tampering_wrong_role_nonce_key_and_delays_never_open() {
|
||||
for mutation in 0..7 {
|
||||
let (mut v, key, server) = fixture(context(Role::Agent));
|
||||
let c = v.begin(sample(0)).unwrap();
|
||||
let mut signed = reply(&c, &key, server);
|
||||
let mut received = sample(70_000_000);
|
||||
let mut checked = sample(80_000_000);
|
||||
match mutation {
|
||||
0 => {
|
||||
let mut bytes = hex::decode(&signed.signature_hex).unwrap();
|
||||
bytes[0] ^= 1;
|
||||
signed.signature_hex = hex::encode(bytes);
|
||||
}
|
||||
1 => {
|
||||
let mut p: Payload = serde_json::from_str(&signed.payload).unwrap();
|
||||
p.request_sha256 = "cd".repeat(32);
|
||||
signed = sign(&p, &key).unwrap();
|
||||
}
|
||||
2 => {
|
||||
let other = SigningKey::from_bytes(&rand::random());
|
||||
signed = reply(&c, &other, server);
|
||||
}
|
||||
3 => checked = sample(MAX_RTT_NS + 1),
|
||||
4 => {
|
||||
received = sample(10_000_000);
|
||||
checked = sample(110_000_001);
|
||||
}
|
||||
5 => {
|
||||
let mut p: Payload = serde_json::from_str(&signed.payload).unwrap();
|
||||
p.key_generation = 3;
|
||||
signed = sign(&p, &key).unwrap();
|
||||
}
|
||||
_ => signed.payload.push(' '),
|
||||
}
|
||||
assert!(
|
||||
v.finish(c, &signed, received, || Ok(checked)).is_err(),
|
||||
"mutation {mutation}"
|
||||
);
|
||||
assert!(v.pending_nonce.is_none());
|
||||
}
|
||||
let ctx = context(Role::Agent);
|
||||
let (mut a, key, server) = fixture(ctx.clone());
|
||||
let (mut b, _, _) = fixture(ctx);
|
||||
let ca = a.begin(sample(0)).unwrap();
|
||||
let signed = reply(&ca, &key, server);
|
||||
let _cb = b.begin(sample(0)).unwrap();
|
||||
assert!(
|
||||
b.finish(ca, &signed, sample(20_000_000), || Ok(sample(30_000_000)))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn foreign_reply_cannot_reenable_an_older_own_challenge() {
|
||||
let (mut a, key_a, server_a) = fixture(context(Role::Agent));
|
||||
let (mut b, key_b, server_b) = fixture(context(Role::Agent));
|
||||
let ca = a.begin(sample(0)).unwrap();
|
||||
let reply_a = reply(&ca, &key_a, server_a);
|
||||
let old_b = b.begin(sample(0)).unwrap();
|
||||
let old_reply_b = reply(&old_b, &key_b, server_b);
|
||||
assert!(
|
||||
b.finish(ca, &reply_a, sample(10_000_000), || Ok(sample(20_000_000)))
|
||||
.is_err()
|
||||
);
|
||||
let _current_b = b.begin(sample(30_000_000)).unwrap();
|
||||
assert!(
|
||||
b.finish(old_b, &old_reply_b, sample(40_000_000), || Ok(sample(
|
||||
50_000_000
|
||||
)))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn discontinuity_invalidates_outstanding_and_requires_new_challenge() {
|
||||
let (mut v, key, server) = fixture(context(Role::SystemHelper));
|
||||
let c = v.begin(sample(0)).unwrap();
|
||||
let signed = reply(&c, &key, server);
|
||||
let mut resumed = sample(2_000_000_000);
|
||||
resumed.unbiased_ns = 9_000_000_000;
|
||||
assert!(v.observe(resumed).is_err());
|
||||
assert!(v.finish(c, &signed, resumed, || Ok(resumed)).is_err());
|
||||
// A new post-discontinuity challenge is permitted, no old nonce reuse.
|
||||
let c = v.begin(resumed).unwrap();
|
||||
let mut p: Payload = serde_json::from_str(&reply(&c, &key, server).payload).unwrap();
|
||||
p.captured_utc_ns = resumed.wall_utc_ns;
|
||||
let signed = sign(&p, &key).unwrap();
|
||||
assert!(v.finish(c, &signed, resumed, || Ok(resumed)).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "rmm-time-source-linux"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
libc = "0.2"
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
sha2.workspace = true
|
||||
hex.workspace = true
|
||||
uuid.workspace = true
|
||||
@@ -0,0 +1,58 @@
|
||||
//! Native, read-only Chrony + Linux kernel quality observation.
|
||||
//! This is a source sample, never a job grant or a clock-setting interface.
|
||||
#[cfg(target_os = "linux")]
|
||||
mod native;
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
mod tracking;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub use native::NativeTimeSource;
|
||||
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Constructible only by the native authenticated observation. Consumers must
|
||||
/// account for all further elapsed time before signing a response; no holdover.
|
||||
#[derive(Debug)]
|
||||
pub struct QualifiedSample {
|
||||
captured_utc_ns: i64,
|
||||
server_error_ns: u64,
|
||||
source_sync_age_ns: u64,
|
||||
server_boot_id: Uuid,
|
||||
captured_monotonic_ns: u64,
|
||||
sampled_boottime_ns: u64,
|
||||
kernel_state: i32,
|
||||
}
|
||||
impl QualifiedSample {
|
||||
pub fn captured_utc_ns(&self) -> i64 {
|
||||
self.captured_utc_ns
|
||||
}
|
||||
pub fn server_error_ns(&self) -> u64 {
|
||||
self.server_error_ns
|
||||
}
|
||||
pub fn source_sync_age_ns(&self) -> u64 {
|
||||
self.source_sync_age_ns
|
||||
}
|
||||
pub fn server_boot_id(&self) -> Uuid {
|
||||
self.server_boot_id
|
||||
}
|
||||
pub fn captured_monotonic_ns(&self) -> u64 {
|
||||
self.captured_monotonic_ns
|
||||
}
|
||||
pub fn sampled_boottime_ns(&self) -> u64 {
|
||||
self.sampled_boottime_ns
|
||||
}
|
||||
pub fn kernel_state(&self) -> i32 {
|
||||
self.kernel_state
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub struct NativeTimeSource;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
impl NativeTimeSource {
|
||||
pub fn open() -> anyhow::Result<Self> {
|
||||
anyhow::bail!("TIME_SOURCE_LINUX_REQUIRED")
|
||||
}
|
||||
pub fn sample(&mut self) -> anyhow::Result<QualifiedSample> {
|
||||
anyhow::bail!("TIME_SOURCE_LINUX_REQUIRED")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,868 @@
|
||||
use crate::{QualifiedSample, tracking};
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use serde::Deserialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::ffi::CString;
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::mem::{self, size_of, size_of_val};
|
||||
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
use uuid::Uuid;
|
||||
|
||||
const PIN: &str = "/etc/rmm-time-source/chrony-pin.json";
|
||||
const DAEMON: &str = "/usr/sbin/chronyd";
|
||||
const SERVER_DIR: &str = "/run/chrony";
|
||||
const SERVER: &str = "/run/chrony/chronyd.sock";
|
||||
const CLIENT_DIR: &str = "/run/rmm-time-source/clients";
|
||||
const QUERY_NS: u64 = 100_000_000;
|
||||
const CAPTURE_NS: u64 = 10_000_000;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Pin {
|
||||
schema_version: u32,
|
||||
daemon_pid: i32,
|
||||
daemon_birth_ticks: u64,
|
||||
daemon_uid: u32,
|
||||
daemon_gid: u32,
|
||||
daemon_image_sha256: String,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct Identity {
|
||||
dev: u64,
|
||||
ino: u64,
|
||||
uid: u32,
|
||||
gid: u32,
|
||||
mode: u32,
|
||||
links: u64,
|
||||
}
|
||||
fn identity(fd: RawFd) -> Result<Identity> {
|
||||
let mut st = mem::MaybeUninit::<libc::stat>::uninit();
|
||||
// SAFETY: fstat initializes the supplied stat on success.
|
||||
ensure!(
|
||||
unsafe { libc::fstat(fd, st.as_mut_ptr()) } == 0,
|
||||
"TIME_FSTAT"
|
||||
);
|
||||
let st = unsafe { st.assume_init() };
|
||||
Ok(Identity {
|
||||
dev: st.st_dev,
|
||||
ino: st.st_ino,
|
||||
uid: st.st_uid,
|
||||
gid: st.st_gid,
|
||||
mode: st.st_mode,
|
||||
links: st.st_nlink,
|
||||
})
|
||||
}
|
||||
fn cstr(value: &str) -> Result<CString> {
|
||||
Ok(CString::new(value)?)
|
||||
}
|
||||
fn fd_result(value: i32) -> Result<OwnedFd> {
|
||||
if value < 0 {
|
||||
return Err(std::io::Error::last_os_error().into());
|
||||
}
|
||||
// SAFETY: every caller passes a newly allocated descriptor.
|
||||
Ok(unsafe { OwnedFd::from_raw_fd(value) })
|
||||
}
|
||||
fn openat(dir: RawFd, name: &str, flags: i32) -> Result<OwnedFd> {
|
||||
let name = cstr(name)?;
|
||||
// SAFETY: name is NUL terminated, dir remains held by the caller.
|
||||
fd_result(unsafe {
|
||||
libc::openat(
|
||||
dir,
|
||||
name.as_ptr(),
|
||||
flags | libc::O_CLOEXEC | libc::O_NOFOLLOW,
|
||||
)
|
||||
})
|
||||
}
|
||||
fn open_dir(path: &str, chrony: Option<(u32, u32)>) -> Result<OwnedFd> {
|
||||
ensure!(
|
||||
path.starts_with('/') && !path.contains(".."),
|
||||
"TIME_FIXED_DIRECTORY"
|
||||
);
|
||||
let slash = cstr("/")?;
|
||||
let mut fd = fd_result(unsafe {
|
||||
libc::open(
|
||||
slash.as_ptr(),
|
||||
libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC | libc::O_NOFOLLOW,
|
||||
)
|
||||
})?;
|
||||
let root = identity(fd.as_raw_fd())?;
|
||||
ensure!(
|
||||
root.uid == 0 && root.mode & libc::S_IFMT == libc::S_IFDIR && root.mode & 0o022 == 0,
|
||||
"TIME_ROOT_DIRECTORY"
|
||||
);
|
||||
let parts: Vec<_> = path.split('/').filter(|v| !v.is_empty()).collect();
|
||||
for (index, part) in parts.iter().enumerate() {
|
||||
fd = openat(fd.as_raw_fd(), part, libc::O_RDONLY | libc::O_DIRECTORY)?;
|
||||
let m = identity(fd.as_raw_fd())?;
|
||||
// The daemon-owned /run/chrony leaf is the sole permitted non-root owner.
|
||||
let daemon_leaf = path == SERVER_DIR
|
||||
&& index + 1 == parts.len()
|
||||
&& chrony.is_some_and(|(uid, gid)| m.uid == uid && m.gid == gid);
|
||||
ensure!(
|
||||
m.mode & libc::S_IFMT == libc::S_IFDIR
|
||||
&& (m.uid == 0 || daemon_leaf)
|
||||
&& m.mode & 0o022 == 0,
|
||||
"TIME_PROTECTED_DIRECTORY"
|
||||
);
|
||||
}
|
||||
Ok(fd)
|
||||
}
|
||||
fn bound_dir(path: &str, held: &OwnedFd, chrony: Option<(u32, u32)>) -> Result<()> {
|
||||
let current = open_dir(path, chrony)?;
|
||||
ensure!(
|
||||
identity(current.as_raw_fd())? == identity(held.as_raw_fd())?,
|
||||
"TIME_DIRECTORY_REPLACED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn read_bounded(fd: OwnedFd, limit: usize) -> Result<Vec<u8>> {
|
||||
let mut raw = Vec::new();
|
||||
File::from(fd)
|
||||
.take((limit + 1) as u64)
|
||||
.read_to_end(&mut raw)?;
|
||||
ensure!(raw.len() <= limit, "TIME_READ_BOUND");
|
||||
Ok(raw)
|
||||
}
|
||||
fn pin() -> Result<Pin> {
|
||||
let dir = open_dir("/etc/rmm-time-source", None)?;
|
||||
let fd = openat(dir.as_raw_fd(), "chrony-pin.json", libc::O_RDONLY)?;
|
||||
let m = identity(fd.as_raw_fd())?;
|
||||
ensure!(
|
||||
m.uid == 0
|
||||
&& m.mode & libc::S_IFMT == libc::S_IFREG
|
||||
&& m.mode & 0o7777 == 0o600
|
||||
&& m.links == 1,
|
||||
"TIME_PIN_PROTECTION"
|
||||
);
|
||||
let before = File::from(fd.try_clone()?).metadata()?;
|
||||
let raw = read_bounded(fd.try_clone()?, 4096)?;
|
||||
let after = File::from(fd.try_clone()?).metadata()?;
|
||||
ensure!(
|
||||
before.dev() == after.dev()
|
||||
&& before.ino() == after.ino()
|
||||
&& before.len() == after.len()
|
||||
&& before.mtime_nsec() == after.mtime_nsec()
|
||||
&& before.mtime() == after.mtime()
|
||||
&& before.ctime_nsec() == after.ctime_nsec()
|
||||
&& before.ctime() == after.ctime(),
|
||||
"TIME_PIN_CHANGED"
|
||||
);
|
||||
let p: Pin = serde_json::from_slice(&raw)?;
|
||||
ensure!(
|
||||
p.schema_version == 1
|
||||
&& p.daemon_pid > 1
|
||||
&& p.daemon_birth_ticks > 0
|
||||
&& p.daemon_image_sha256.len() == 64
|
||||
&& p.daemon_image_sha256
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
|
||||
"TIME_PIN_SCHEMA"
|
||||
);
|
||||
bound_dir("/etc/rmm-time-source", &dir, None)?;
|
||||
let current = openat(dir.as_raw_fd(), "chrony-pin.json", libc::O_RDONLY)?;
|
||||
ensure!(
|
||||
identity(fd.as_raw_fd())? == identity(current.as_raw_fd())?,
|
||||
"TIME_PIN_REPLACED"
|
||||
);
|
||||
Ok(p)
|
||||
}
|
||||
fn digest(fd: &OwnedFd) -> Result<String> {
|
||||
let before = File::from(fd.try_clone()?).metadata()?;
|
||||
ensure!(
|
||||
before.is_file()
|
||||
&& before.uid() == 0
|
||||
&& before.mode() & 0o022 == 0
|
||||
&& before.nlink() == 1
|
||||
&& before.len() <= 16 * 1024 * 1024,
|
||||
"TIME_DAEMON_IMAGE_PROTECTED"
|
||||
);
|
||||
let mut hasher = Sha256::new();
|
||||
let mut total = 0;
|
||||
let mut buf = [0u8; 16384];
|
||||
// pread avoids shared seek offsets in retained descriptors.
|
||||
loop {
|
||||
let got = unsafe { libc::pread(fd.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len(), total) };
|
||||
ensure!(got >= 0, "TIME_IMAGE_READ");
|
||||
if got == 0 {
|
||||
break;
|
||||
}
|
||||
total += i64::try_from(got)?;
|
||||
ensure!(total <= 16 * 1024 * 1024, "TIME_IMAGE_BOUND");
|
||||
hasher.update(&buf[..got as usize]);
|
||||
}
|
||||
let after = File::from(fd.try_clone()?).metadata()?;
|
||||
ensure!(
|
||||
before.len() == total as u64
|
||||
&& before.len() == after.len()
|
||||
&& before.dev() == after.dev()
|
||||
&& before.ino() == after.ino()
|
||||
&& before.mtime() == after.mtime()
|
||||
&& before.mtime_nsec() == after.mtime_nsec()
|
||||
&& before.ctime() == after.ctime()
|
||||
&& before.ctime_nsec() == after.ctime_nsec(),
|
||||
"TIME_IMAGE_CHANGED"
|
||||
);
|
||||
Ok(hex::encode(hasher.finalize()))
|
||||
}
|
||||
struct Daemon {
|
||||
pin: Pin,
|
||||
proc: OwnedFd,
|
||||
image: OwnedFd,
|
||||
pidfd: OwnedFd,
|
||||
image_id: Identity,
|
||||
}
|
||||
impl Daemon {
|
||||
fn open(pin: Pin) -> Result<Self> {
|
||||
let proc = openat(
|
||||
libc::AT_FDCWD,
|
||||
&format!("/proc/{}", pin.daemon_pid),
|
||||
libc::O_RDONLY | libc::O_DIRECTORY,
|
||||
)?;
|
||||
let pidfd =
|
||||
fd_result(unsafe { libc::syscall(libc::SYS_pidfd_open, pin.daemon_pid, 0) } as i32)?;
|
||||
let dir = open_dir("/usr/sbin", None)?;
|
||||
let image = openat(dir.as_raw_fd(), "chronyd", libc::O_RDONLY)?;
|
||||
let image_id = identity(image.as_raw_fd())?;
|
||||
let value = Self {
|
||||
pin,
|
||||
proc,
|
||||
image,
|
||||
pidfd,
|
||||
image_id,
|
||||
};
|
||||
value.verify()?;
|
||||
Ok(value)
|
||||
}
|
||||
fn exe(&self) -> Result<OwnedFd> {
|
||||
let name = cstr("exe")?;
|
||||
// /proc/PID/exe is intentionally a kernel symlink; procdir is retained.
|
||||
fd_result(unsafe {
|
||||
libc::openat(
|
||||
self.proc.as_raw_fd(),
|
||||
name.as_ptr(),
|
||||
libc::O_RDONLY | libc::O_CLOEXEC,
|
||||
)
|
||||
})
|
||||
}
|
||||
fn verify(&self) -> Result<()> {
|
||||
let mut poll = libc::pollfd {
|
||||
fd: self.pidfd.as_raw_fd(),
|
||||
events: libc::POLLIN,
|
||||
revents: 0,
|
||||
};
|
||||
ensure!(
|
||||
unsafe { libc::poll(&mut poll, 1, 0) } == 0 && poll.revents == 0,
|
||||
"TIME_DAEMON_EXITED"
|
||||
);
|
||||
let first = self.exe()?;
|
||||
ensure!(
|
||||
identity(first.as_raw_fd())? == self.image_id,
|
||||
"TIME_DAEMON_EXEC_CHANGED"
|
||||
);
|
||||
let stat = String::from_utf8(read_bounded(
|
||||
openat(self.proc.as_raw_fd(), "stat", libc::O_RDONLY)?,
|
||||
8192,
|
||||
)?)?;
|
||||
let rest = stat.rsplit_once(") ").context("TIME_PROC_STAT")?.1;
|
||||
ensure!(
|
||||
rest.split_whitespace()
|
||||
.nth(19)
|
||||
.context("TIME_PROC_BIRTH")?
|
||||
.parse::<u64>()?
|
||||
== self.pin.daemon_birth_ticks,
|
||||
"TIME_DAEMON_BIRTH"
|
||||
);
|
||||
let status = String::from_utf8(read_bounded(
|
||||
openat(self.proc.as_raw_fd(), "status", libc::O_RDONLY)?,
|
||||
16384,
|
||||
)?)?;
|
||||
for (label, expected) in [("Uid:", self.pin.daemon_uid), ("Gid:", self.pin.daemon_gid)] {
|
||||
let line = status
|
||||
.lines()
|
||||
.find(|v| v.starts_with(label))
|
||||
.context("TIME_PROC_CREDENTIALS")?;
|
||||
let ids: Vec<u32> = line
|
||||
.split_whitespace()
|
||||
.skip(1)
|
||||
.map(str::parse)
|
||||
.collect::<std::result::Result<_, _>>()?;
|
||||
ensure!(ids == [expected; 4], "TIME_DAEMON_ACCOUNT");
|
||||
}
|
||||
ensure!(
|
||||
digest(&self.image)? == self.pin.daemon_image_sha256
|
||||
&& digest(&first)? == self.pin.daemon_image_sha256,
|
||||
"TIME_DAEMON_IMAGE"
|
||||
);
|
||||
let fixed = openat(libc::AT_FDCWD, DAEMON, libc::O_RDONLY)?;
|
||||
ensure!(
|
||||
identity(fixed.as_raw_fd())? == self.image_id
|
||||
&& identity(self.exe()?.as_raw_fd())? == self.image_id,
|
||||
"TIME_DAEMON_IMAGE_REPLACED"
|
||||
);
|
||||
ensure!(
|
||||
unsafe { libc::poll(&mut poll, 1, 0) } == 0 && poll.revents == 0,
|
||||
"TIME_DAEMON_EXITED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Capture {
|
||||
mono: u64,
|
||||
end: u64,
|
||||
boot: u64,
|
||||
utc: i64,
|
||||
}
|
||||
fn clock(id: libc::clockid_t) -> Result<i128> {
|
||||
let mut ts = mem::MaybeUninit::<libc::timespec>::uninit();
|
||||
ensure!(
|
||||
unsafe { libc::clock_gettime(id, ts.as_mut_ptr()) } == 0,
|
||||
"TIME_CLOCK_GETTIME"
|
||||
);
|
||||
let ts = unsafe { ts.assume_init() };
|
||||
ensure!(
|
||||
ts.tv_sec >= 0 && (0..1_000_000_000).contains(&ts.tv_nsec),
|
||||
"TIME_CLOCK_RANGE"
|
||||
);
|
||||
Ok(i128::from(ts.tv_sec) * 1_000_000_000 + i128::from(ts.tv_nsec))
|
||||
}
|
||||
fn capture() -> Result<Capture> {
|
||||
let mono = u64::try_from(clock(libc::CLOCK_MONOTONIC)?)?;
|
||||
let boot = u64::try_from(clock(libc::CLOCK_BOOTTIME)?)?;
|
||||
let utc = i64::try_from(clock(libc::CLOCK_REALTIME)?)?;
|
||||
let end = u64::try_from(clock(libc::CLOCK_MONOTONIC)?)?;
|
||||
ensure!(
|
||||
end >= mono && end - mono <= CAPTURE_NS && utc > 0,
|
||||
"TIME_CAPTURE_BOUND"
|
||||
);
|
||||
Ok(Capture {
|
||||
mono,
|
||||
end,
|
||||
boot,
|
||||
utc,
|
||||
})
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
struct Kernel {
|
||||
state: i32,
|
||||
maxerror_ns: u64,
|
||||
}
|
||||
fn kernel() -> Result<Kernel> {
|
||||
let mut tx: libc::timex = unsafe { mem::zeroed() }; // modes=0: query only, never set time.
|
||||
let state = unsafe { libc::adjtimex(&mut tx) };
|
||||
ensure!(
|
||||
(0..=4).contains(&state)
|
||||
&& tx.status & (libc::STA_UNSYNC | libc::STA_CLOCKERR) == 0
|
||||
&& (0..=500_000).contains(&tx.maxerror),
|
||||
"TIME_KERNEL_UNQUALIFIED"
|
||||
);
|
||||
Ok(Kernel {
|
||||
state,
|
||||
maxerror_ns: u64::try_from(tx.maxerror)?
|
||||
.checked_mul(1000)
|
||||
.context("TIME_KERNEL_OVERFLOW")?,
|
||||
})
|
||||
}
|
||||
fn elapsed(before: Capture, after: Capture) -> Result<u64> {
|
||||
ensure!(
|
||||
after.mono >= before.end && after.boot >= before.boot && after.utc >= before.utc,
|
||||
"TIME_CLOCK_BACKWARD"
|
||||
);
|
||||
let span = after
|
||||
.end
|
||||
.checked_sub(before.mono)
|
||||
.context("TIME_MONOTONIC_OVERFLOW")?;
|
||||
ensure!(span <= QUERY_NS, "TIME_SOURCE_TOTAL_TIMEOUT");
|
||||
let mono = after.mono - before.mono;
|
||||
let boot = after.boot - before.boot;
|
||||
let wall = u64::try_from(after.utc - before.utc)?;
|
||||
let tolerance = (before.end - before.mono) + (after.end - after.mono);
|
||||
ensure!(
|
||||
mono.abs_diff(boot) <= tolerance && mono.abs_diff(wall) <= tolerance,
|
||||
"TIME_SOURCE_DISCONTINUITY"
|
||||
);
|
||||
Ok(span)
|
||||
}
|
||||
fn boot_id() -> Result<Uuid> {
|
||||
let raw = std::fs::read_to_string("/proc/sys/kernel/random/boot_id")?;
|
||||
let id = Uuid::parse_str(raw.trim())?;
|
||||
ensure!(!id.is_nil(), "TIME_BOOT_ID");
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
fn socket_identity(dir: RawFd, name: &str) -> Result<Identity> {
|
||||
let name = cstr(name)?;
|
||||
let mut st = mem::MaybeUninit::<libc::stat>::uninit();
|
||||
ensure!(
|
||||
unsafe {
|
||||
libc::fstatat(
|
||||
dir,
|
||||
name.as_ptr(),
|
||||
st.as_mut_ptr(),
|
||||
libc::AT_SYMLINK_NOFOLLOW,
|
||||
)
|
||||
} == 0,
|
||||
"TIME_SOCKET_STAT"
|
||||
);
|
||||
let st = unsafe { st.assume_init() };
|
||||
Ok(Identity {
|
||||
dev: st.st_dev,
|
||||
ino: st.st_ino,
|
||||
uid: st.st_uid,
|
||||
gid: st.st_gid,
|
||||
mode: st.st_mode,
|
||||
links: st.st_nlink,
|
||||
})
|
||||
}
|
||||
fn address(path: &str) -> Result<(libc::sockaddr_un, libc::socklen_t)> {
|
||||
let mut addr: libc::sockaddr_un = unsafe { mem::zeroed() };
|
||||
addr.sun_family = libc::AF_UNIX as _;
|
||||
ensure!(path.len() < addr.sun_path.len(), "TIME_SOCKET_PATH_BOUND");
|
||||
for (dst, src) in addr.sun_path.iter_mut().zip(path.bytes()) {
|
||||
*dst = src as _;
|
||||
}
|
||||
Ok((
|
||||
addr,
|
||||
(mem::offset_of!(libc::sockaddr_un, sun_path) + path.len() + 1) as _,
|
||||
))
|
||||
}
|
||||
struct Client {
|
||||
fd: OwnedFd,
|
||||
dir: OwnedFd,
|
||||
name: String,
|
||||
own: Option<Identity>,
|
||||
}
|
||||
impl Client {
|
||||
fn open(gid: u32) -> Result<Self> {
|
||||
let dir = open_dir(CLIENT_DIR, None)?;
|
||||
let d = identity(dir.as_raw_fd())?;
|
||||
ensure!(
|
||||
d.uid == 0 && d.gid == gid && d.mode & 0o7777 == 0o710,
|
||||
"TIME_CLIENT_DIRECTORY_PROFILE"
|
||||
);
|
||||
ensure!(
|
||||
unsafe { libc::flock(dir.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0,
|
||||
"TIME_CLIENT_SINGLE_OWNER"
|
||||
);
|
||||
// A leftover from an unknown cleanup blocks all future instances. Only
|
||||
// an operator may investigate it; no automatic deletion or new UUID loop.
|
||||
let mut entries = std::fs::read_dir(format!("/proc/self/fd/{}", dir.as_raw_fd()))?;
|
||||
ensure!(entries.next().is_none(), "TIME_CLIENT_DIRECTORY_NOT_EMPTY");
|
||||
let fd = fd_result(unsafe {
|
||||
libc::socket(
|
||||
libc::AF_UNIX,
|
||||
libc::SOCK_DGRAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK,
|
||||
0,
|
||||
)
|
||||
})?;
|
||||
let name = format!("tracking-{}.sock", Uuid::new_v4().simple());
|
||||
let mut value = Self {
|
||||
fd,
|
||||
dir,
|
||||
name,
|
||||
own: None,
|
||||
};
|
||||
let (addr, len) = address(&format!("{CLIENT_DIR}/{}", value.name))?;
|
||||
bound_dir(CLIENT_DIR, &value.dir, None)?;
|
||||
ensure!(
|
||||
unsafe {
|
||||
libc::bind(
|
||||
value.fd.as_raw_fd(),
|
||||
(&addr as *const libc::sockaddr_un).cast(),
|
||||
len,
|
||||
)
|
||||
} == 0,
|
||||
"TIME_CLIENT_BIND_ONCE"
|
||||
);
|
||||
let mut own = socket_identity(value.dir.as_raw_fd(), &value.name)?;
|
||||
ensure!(
|
||||
own.uid == 0 && own.mode & libc::S_IFMT == libc::S_IFSOCK && own.links == 1,
|
||||
"TIME_CLIENT_INITIAL_IDENTITY"
|
||||
);
|
||||
value.own = Some(own);
|
||||
let name = cstr(&value.name)?;
|
||||
ensure!(
|
||||
unsafe {
|
||||
libc::fchownat(
|
||||
value.dir.as_raw_fd(),
|
||||
name.as_ptr(),
|
||||
0,
|
||||
gid,
|
||||
libc::AT_SYMLINK_NOFOLLOW,
|
||||
)
|
||||
} == 0,
|
||||
"TIME_CLIENT_GROUP"
|
||||
);
|
||||
// Parent is root-write-only: no daemon or unprivileged process can swap
|
||||
// the leaf between this identity capture and chmod.
|
||||
ensure!(
|
||||
unsafe { libc::fchmodat(value.dir.as_raw_fd(), name.as_ptr(), 0o660, 0) } == 0,
|
||||
"TIME_CLIENT_MODE"
|
||||
);
|
||||
let next = socket_identity(value.dir.as_raw_fd(), &value.name)?;
|
||||
ensure!(
|
||||
next.dev == own.dev
|
||||
&& next.ino == own.ino
|
||||
&& next.uid == 0
|
||||
&& next.gid == gid
|
||||
&& next.mode & 0o7777 == 0o660
|
||||
&& next.links == 1,
|
||||
"TIME_CLIENT_READY_IDENTITY"
|
||||
);
|
||||
own = next;
|
||||
value.own = Some(own);
|
||||
value.verify()?;
|
||||
let yes: libc::c_int = 1;
|
||||
ensure!(
|
||||
unsafe {
|
||||
libc::setsockopt(
|
||||
value.fd.as_raw_fd(),
|
||||
libc::SOL_SOCKET,
|
||||
libc::SO_PASSCRED,
|
||||
(&yes as *const libc::c_int).cast(),
|
||||
size_of::<libc::c_int>() as _,
|
||||
)
|
||||
} == 0,
|
||||
"TIME_PASSCRED_REQUIRED"
|
||||
);
|
||||
let (server, len) = address(SERVER)?;
|
||||
ensure!(
|
||||
unsafe {
|
||||
libc::connect(
|
||||
value.fd.as_raw_fd(),
|
||||
(&server as *const libc::sockaddr_un).cast(),
|
||||
len,
|
||||
)
|
||||
} == 0,
|
||||
"TIME_CHRONY_CONNECT"
|
||||
);
|
||||
Ok(value)
|
||||
}
|
||||
fn verify(&self) -> Result<()> {
|
||||
bound_dir(CLIENT_DIR, &self.dir, None)?;
|
||||
ensure!(
|
||||
Some(socket_identity(self.dir.as_raw_fd(), &self.name)?) == self.own,
|
||||
"TIME_CLIENT_REPLACED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn cleanup(&mut self) -> Result<()> {
|
||||
// Consume cleanup authority before any fallible work. Unknown cleanup
|
||||
// never retries from Drop and never adopts a newly observed leaf.
|
||||
let expected = self
|
||||
.own
|
||||
.take()
|
||||
.context("TIME_CLIENT_CLEANUP_ALREADY_ATTEMPTED")?;
|
||||
bound_dir(CLIENT_DIR, &self.dir, None)?;
|
||||
unlink_owned(self.dir.as_raw_fd(), &self.name, expected)
|
||||
}
|
||||
fn exchange(&self, sequence: u32, daemon: &Pin, start: Capture) -> Result<tracking::Tracking> {
|
||||
let request = tracking::request(sequence);
|
||||
ensure!(
|
||||
unsafe {
|
||||
libc::send(
|
||||
self.fd.as_raw_fd(),
|
||||
request.as_ptr().cast(),
|
||||
request.len(),
|
||||
libc::MSG_DONTWAIT | libc::MSG_NOSIGNAL,
|
||||
)
|
||||
} == request.len() as isize,
|
||||
"TIME_CHRONY_SEND_ONCE"
|
||||
);
|
||||
let now = u64::try_from(clock(libc::CLOCK_MONOTONIC)?)?;
|
||||
let left = QUERY_NS
|
||||
.checked_sub(now.checked_sub(start.mono).context("TIME_QUERY_CLOCK")?)
|
||||
.context("TIME_QUERY_TIMEOUT")?;
|
||||
let timeout = libc::timespec {
|
||||
tv_sec: 0,
|
||||
tv_nsec: left as _,
|
||||
};
|
||||
let mut poll = libc::pollfd {
|
||||
fd: self.fd.as_raw_fd(),
|
||||
events: libc::POLLIN,
|
||||
revents: 0,
|
||||
};
|
||||
ensure!(
|
||||
unsafe { libc::ppoll(&mut poll, 1, &timeout, std::ptr::null()) } == 1
|
||||
&& poll.revents == libc::POLLIN,
|
||||
"TIME_CHRONY_TIMEOUT"
|
||||
);
|
||||
let mut packet = [0u8; tracking::PACKET_BYTES];
|
||||
let mut iov = libc::iovec {
|
||||
iov_base: packet.as_mut_ptr().cast(),
|
||||
iov_len: packet.len(),
|
||||
};
|
||||
let mut control = [0usize; 16];
|
||||
let mut msg: libc::msghdr = unsafe { mem::zeroed() };
|
||||
msg.msg_iov = &mut iov;
|
||||
msg.msg_iovlen = 1;
|
||||
msg.msg_control = control.as_mut_ptr().cast();
|
||||
msg.msg_controllen = size_of_val(&control);
|
||||
let got = unsafe { libc::recvmsg(self.fd.as_raw_fd(), &mut msg, libc::MSG_DONTWAIT) };
|
||||
ensure!(
|
||||
got == tracking::PACKET_BYTES as isize
|
||||
&& msg.msg_flags & (libc::MSG_TRUNC | libc::MSG_CTRUNC) == 0,
|
||||
"TIME_CHRONY_TRUNCATED"
|
||||
);
|
||||
ensure!(
|
||||
msg.msg_controllen <= size_of_val(&control),
|
||||
"TIME_CREDENTIALS_CONTROL_BOUND"
|
||||
);
|
||||
let control_start = msg.msg_control as usize;
|
||||
let control_end = control_start
|
||||
.checked_add(msg.msg_controllen)
|
||||
.context("TIME_CREDENTIALS_CONTROL_OVERFLOW")?;
|
||||
let mut count = 0;
|
||||
let mut header = unsafe { libc::CMSG_FIRSTHDR(&msg) };
|
||||
while !header.is_null() {
|
||||
let position = header as usize;
|
||||
ensure!(
|
||||
position >= control_start
|
||||
&& position
|
||||
.checked_add(size_of::<libc::cmsghdr>())
|
||||
.is_some_and(|n| n <= control_end),
|
||||
"TIME_CREDENTIALS_HEADER_BOUND"
|
||||
);
|
||||
let h = unsafe { &*header };
|
||||
ensure!(
|
||||
h.cmsg_len >= unsafe { libc::CMSG_LEN(0) } as usize
|
||||
&& h.cmsg_len <= control_end - position,
|
||||
"TIME_CREDENTIALS_LENGTH_BOUND"
|
||||
);
|
||||
ensure!(
|
||||
h.cmsg_level == libc::SOL_SOCKET
|
||||
&& h.cmsg_type == libc::SCM_CREDENTIALS
|
||||
&& h.cmsg_len
|
||||
== unsafe { libc::CMSG_LEN(size_of::<libc::ucred>() as _) } as usize,
|
||||
"TIME_CREDENTIALS_FORMAT"
|
||||
);
|
||||
let credentials =
|
||||
unsafe { std::ptr::read_unaligned(libc::CMSG_DATA(header).cast::<libc::ucred>()) };
|
||||
ensure!(
|
||||
credentials.pid == daemon.daemon_pid
|
||||
&& credentials.uid == daemon.daemon_uid
|
||||
&& credentials.gid == daemon.daemon_gid,
|
||||
"TIME_CREDENTIALS_MISMATCH"
|
||||
);
|
||||
count += 1;
|
||||
header = unsafe { libc::CMSG_NXTHDR(&msg, header) };
|
||||
}
|
||||
ensure!(count == 1, "TIME_CREDENTIALS_REQUIRED");
|
||||
tracking::reply(&packet, sequence)
|
||||
}
|
||||
}
|
||||
fn unlink_owned(dir: RawFd, name: &str, expected: Identity) -> Result<()> {
|
||||
ensure!(
|
||||
socket_identity(dir, name)? == expected,
|
||||
"TIME_CLIENT_CLEANUP_IDENTITY"
|
||||
);
|
||||
let name = cstr(name)?;
|
||||
ensure!(
|
||||
unsafe { libc::unlinkat(dir, name.as_ptr(), 0) } == 0,
|
||||
"TIME_CLIENT_UNLINK"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
impl Drop for Client {
|
||||
fn drop(&mut self) {
|
||||
// Lost identity is intentionally retained, never recursively removed.
|
||||
if self.own.is_some() {
|
||||
let _ = self.cleanup();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Root-only source broker primitive. No daemon discovery, adoption, commands,
|
||||
/// configurable endpoint, retry, IP transport or time-setting entrypoint.
|
||||
pub struct NativeTimeSource {
|
||||
daemon: Daemon,
|
||||
server_dir: OwnedFd,
|
||||
server_identity: Identity,
|
||||
boot: Uuid,
|
||||
poisoned: bool,
|
||||
}
|
||||
impl NativeTimeSource {
|
||||
pub fn open() -> Result<Self> {
|
||||
ensure!(
|
||||
unsafe { libc::geteuid() } == 0,
|
||||
"TIME_SOURCE_ROOT_BROKER_REQUIRED"
|
||||
);
|
||||
let pin = pin().with_context(|| format!("TIME_PROTECTED_PIN {PIN}"))?;
|
||||
let daemon = Daemon::open(pin)?;
|
||||
let server_dir = open_dir(
|
||||
SERVER_DIR,
|
||||
Some((daemon.pin.daemon_uid, daemon.pin.daemon_gid)),
|
||||
)?;
|
||||
let server_identity = socket_identity(server_dir.as_raw_fd(), "chronyd.sock")?;
|
||||
ensure!(
|
||||
server_identity.mode & libc::S_IFMT == libc::S_IFSOCK
|
||||
&& server_identity.links == 1
|
||||
&& server_identity.uid == daemon.pin.daemon_uid
|
||||
&& server_identity.gid == daemon.pin.daemon_gid
|
||||
&& server_identity.mode & 0o007 == 0,
|
||||
"TIME_CHRONY_SOCKET_PROTECTION"
|
||||
);
|
||||
Ok(Self {
|
||||
daemon,
|
||||
server_dir,
|
||||
server_identity,
|
||||
boot: boot_id()?,
|
||||
poisoned: false,
|
||||
})
|
||||
}
|
||||
fn verify(&self) -> Result<()> {
|
||||
self.daemon.verify()?;
|
||||
bound_dir(
|
||||
SERVER_DIR,
|
||||
&self.server_dir,
|
||||
Some((self.daemon.pin.daemon_uid, self.daemon.pin.daemon_gid)),
|
||||
)?;
|
||||
ensure!(
|
||||
socket_identity(self.server_dir.as_raw_fd(), "chronyd.sock")? == self.server_identity
|
||||
&& boot_id()? == self.boot,
|
||||
"TIME_SOURCE_GENERATION_CHANGED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
pub fn sample(&mut self) -> Result<QualifiedSample> {
|
||||
ensure!(!self.poisoned, "TIME_SOURCE_CLEANUP_UNCERTAIN");
|
||||
let before = capture()?;
|
||||
let first = kernel()?;
|
||||
self.verify()?;
|
||||
self.poisoned = true;
|
||||
let mut client = Client::open(self.daemon.pin.daemon_gid)?;
|
||||
let random = Uuid::new_v4();
|
||||
let sequence = u32::from_ne_bytes(random.as_bytes()[..4].try_into()?);
|
||||
let report = client.exchange(sequence, &self.daemon.pin, before)?;
|
||||
client.verify()?;
|
||||
self.verify()?;
|
||||
let last = kernel()?;
|
||||
let after = capture()?;
|
||||
let span = elapsed(before, after)?;
|
||||
let error = report
|
||||
.error_ns
|
||||
.checked_add(first.maxerror_ns.max(last.maxerror_ns))
|
||||
.and_then(|v| v.checked_add(span))
|
||||
.context("TIME_SOURCE_ERROR_OVERFLOW")?;
|
||||
ensure!(error <= tracking::MAX_ERROR_NS, "TIME_SOURCE_ERROR_LIMIT");
|
||||
ensure!(
|
||||
report.reference_utc_ns <= after.utc,
|
||||
"TIME_SOURCE_FUTURE_REFERENCE"
|
||||
);
|
||||
let age = u64::try_from(after.utc - report.reference_utc_ns)?
|
||||
.checked_add(error)
|
||||
.context("TIME_SOURCE_AGE_OVERFLOW")?;
|
||||
ensure!(age <= tracking::MAX_AGE_NS, "TIME_SOURCE_STALE_REFERENCE");
|
||||
// Cleanup is explicit and part of successful observation, not an ignored
|
||||
// Drop error. The returned sample is already aged by this final work.
|
||||
client.cleanup()?;
|
||||
self.poisoned = false;
|
||||
let final_capture = capture()?;
|
||||
let total = elapsed(before, final_capture)?;
|
||||
let post = total.checked_sub(span).context("TIME_SOURCE_FINAL_CLOCK")?;
|
||||
let error = error.checked_add(post).context("TIME_SOURCE_FINAL_ERROR")?;
|
||||
let age = age.checked_add(post).context("TIME_SOURCE_FINAL_AGE")?;
|
||||
ensure!(
|
||||
error <= tracking::MAX_ERROR_NS && age <= tracking::MAX_AGE_NS,
|
||||
"TIME_SOURCE_FINAL_QUALITY"
|
||||
);
|
||||
Ok(QualifiedSample {
|
||||
captured_utc_ns: after.utc,
|
||||
server_error_ns: error,
|
||||
source_sync_age_ns: age,
|
||||
server_boot_id: self.boot,
|
||||
captured_monotonic_ns: after.mono,
|
||||
sampled_boottime_ns: after.boot,
|
||||
kernel_state: last.state,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn clock_brackets_reject_suspend_step_backwards_and_total_timeout() {
|
||||
let a = Capture {
|
||||
mono: 1_000_000,
|
||||
end: 1_000_100,
|
||||
boot: 2_000_000,
|
||||
utc: 1_800_000_000_000_000_000,
|
||||
};
|
||||
let b = Capture {
|
||||
mono: 2_000_000,
|
||||
end: 2_000_100,
|
||||
boot: 3_000_000,
|
||||
utc: a.utc + 1_000_000,
|
||||
};
|
||||
assert!(elapsed(a, b).is_ok());
|
||||
assert!(
|
||||
elapsed(
|
||||
a,
|
||||
Capture {
|
||||
boot: b.boot + 1_000_000,
|
||||
..b
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
elapsed(
|
||||
a,
|
||||
Capture {
|
||||
utc: b.utc + 1_000_000,
|
||||
..b
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
elapsed(
|
||||
a,
|
||||
Capture {
|
||||
utc: a.utc - 1,
|
||||
..b
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
elapsed(
|
||||
a,
|
||||
Capture {
|
||||
end: a.mono + QUERY_NS + 1,
|
||||
..b
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn socket_cleanup_preserves_replaced_name_and_removes_only_exact_own_inode() {
|
||||
use std::os::unix::{fs::PermissionsExt, net::UnixDatagram};
|
||||
let path = std::env::temp_dir().join(format!("rmm-time-source-unit-{}", Uuid::new_v4()));
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let dir = openat(
|
||||
libc::AT_FDCWD,
|
||||
path.to_str().unwrap(),
|
||||
libc::O_RDONLY | libc::O_DIRECTORY,
|
||||
)
|
||||
.unwrap();
|
||||
let old = UnixDatagram::bind(path.join("own.sock")).unwrap();
|
||||
let expected = socket_identity(dir.as_raw_fd(), "own.sock").unwrap();
|
||||
std::fs::rename(path.join("own.sock"), path.join("held.sock")).unwrap();
|
||||
let new = UnixDatagram::bind(path.join("own.sock")).unwrap();
|
||||
assert!(unlink_owned(dir.as_raw_fd(), "own.sock", expected).is_err());
|
||||
assert!(path.join("own.sock").exists());
|
||||
let current = socket_identity(dir.as_raw_fd(), "own.sock").unwrap();
|
||||
unlink_owned(dir.as_raw_fd(), "own.sock", current).unwrap();
|
||||
assert!(!path.join("own.sock").exists());
|
||||
unlink_owned(dir.as_raw_fd(), "held.sock", expected).unwrap();
|
||||
drop((old, new));
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
use anyhow::{Result, ensure};
|
||||
pub(crate) const PACKET_BYTES: usize = 104;
|
||||
pub(crate) const MAX_ERROR_NS: u64 = 500_000_000;
|
||||
pub(crate) const MAX_AGE_NS: u64 = 3_600_000_000_000;
|
||||
|
||||
pub(crate) fn request(sequence: u32) -> [u8; PACKET_BYTES] {
|
||||
let mut out = [0; PACKET_BYTES];
|
||||
out[0] = 6;
|
||||
out[1] = 1;
|
||||
out[4..6].copy_from_slice(&33u16.to_be_bytes());
|
||||
out[8..12].copy_from_slice(&sequence.to_be_bytes());
|
||||
out
|
||||
}
|
||||
fn u16_at(raw: &[u8], n: usize) -> u16 {
|
||||
u16::from_be_bytes(raw[n..n + 2].try_into().expect("checked packet size"))
|
||||
}
|
||||
fn u32_at(raw: &[u8], n: usize) -> u32 {
|
||||
u32::from_be_bytes(raw[n..n + 4].try_into().expect("checked packet size"))
|
||||
}
|
||||
|
||||
/// Chrony's wire Float is signed7 exponent + signed25 coefficient, value
|
||||
/// coefficient * 2^(exponent-25). Convert its magnitude to ns, rounding upward
|
||||
/// using integer arithmetic; no IEEE conversion or underflow-to-zero.
|
||||
fn float_ns(raw: u32, allow_negative: bool) -> Result<u64> {
|
||||
let mut exponent = (raw >> 25) as i32;
|
||||
if exponent >= 64 {
|
||||
exponent -= 128;
|
||||
}
|
||||
let mut coefficient = (raw & 0x01ff_ffff) as i32;
|
||||
if coefficient >= 0x0100_0000 {
|
||||
coefficient -= 0x0200_0000;
|
||||
}
|
||||
ensure!(allow_negative || coefficient >= 0, "CHRONY_NEGATIVE_ERROR");
|
||||
let numerator = u128::from(coefficient.unsigned_abs()) * 1_000_000_000;
|
||||
let shift = exponent - 25;
|
||||
let rounded = if shift >= 0 {
|
||||
numerator
|
||||
.checked_shl(shift as u32)
|
||||
.ok_or_else(|| anyhow::anyhow!("CHRONY_FLOAT_OVERFLOW"))?
|
||||
} else {
|
||||
let denominator = 1u128
|
||||
.checked_shl((-shift) as u32)
|
||||
.ok_or_else(|| anyhow::anyhow!("CHRONY_FLOAT_OVERFLOW"))?;
|
||||
numerator.div_ceil(denominator)
|
||||
};
|
||||
u64::try_from(rounded).map_err(Into::into)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Tracking {
|
||||
pub reference_utc_ns: i64,
|
||||
pub error_ns: u64,
|
||||
}
|
||||
pub(crate) fn reply(raw: &[u8], sequence: u32) -> Result<Tracking> {
|
||||
ensure!(raw.len() == PACKET_BYTES, "CHRONY_PACKET_LENGTH");
|
||||
ensure!(
|
||||
raw[0] == 6
|
||||
&& raw[1] == 2
|
||||
&& raw[2..4] == [0, 0]
|
||||
&& u16_at(raw, 4) == 33
|
||||
&& u16_at(raw, 6) == 5
|
||||
&& u16_at(raw, 8) == 0
|
||||
&& raw[10..16] == [0; 6]
|
||||
&& raw[20..28] == [0; 8]
|
||||
&& u32_at(raw, 16) == sequence,
|
||||
"CHRONY_REPLY_BINDING"
|
||||
);
|
||||
let reference = u32_at(raw, 28);
|
||||
let family = u16_at(raw, 48);
|
||||
// Network peers only. Local/reference-clock fallback is deliberately outside
|
||||
// this profile; family UNSPEC/ID and loopback identities cannot qualify.
|
||||
ensure!(
|
||||
reference != 0
|
||||
&& reference != 0x4c4f_434c
|
||||
&& reference >> 24 != 127
|
||||
&& (family == 1 || family == 2)
|
||||
&& raw[50..52] == [0, 0],
|
||||
"CHRONY_REFERENCE_SOURCE"
|
||||
);
|
||||
if family == 1 {
|
||||
ensure!(
|
||||
raw[32] != 127 && raw[32..36] != [0; 4] && raw[36..48] == [0; 12],
|
||||
"CHRONY_LOCAL_IPV4"
|
||||
);
|
||||
} else {
|
||||
let address = &raw[32..48];
|
||||
let mapped = address[..10] == [0; 10] && address[10..12] == [0xff, 0xff];
|
||||
let compatible = address[..12] == [0; 12];
|
||||
ensure!(
|
||||
!((mapped || compatible) && (address[12] == 127 || address[12..16] == [0; 4])),
|
||||
"CHRONY_LOCAL_EMBEDDED_IPV4"
|
||||
);
|
||||
ensure!(
|
||||
raw[32..48] != [0; 16]
|
||||
&& raw[32..48] != [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
|
||||
"CHRONY_LOCAL_IPV6"
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
(1..=15).contains(&u16_at(raw, 52)) && u16_at(raw, 54) <= 2,
|
||||
"CHRONY_UNSYNCHRONIZED"
|
||||
);
|
||||
let high = u32_at(raw, 56);
|
||||
let seconds = if high == 0x7fff_ffff {
|
||||
u64::from(u32_at(raw, 60))
|
||||
} else {
|
||||
(u64::from(high) << 32) | u64::from(u32_at(raw, 60))
|
||||
};
|
||||
let nanos = u32_at(raw, 64);
|
||||
ensure!(
|
||||
seconds > 0 && nanos < 1_000_000_000,
|
||||
"CHRONY_REFERENCE_TIME"
|
||||
);
|
||||
let reference_utc_ns = i64::try_from(u128::from(seconds) * 1_000_000_000 + u128::from(nanos))?;
|
||||
let correction = float_ns(u32_at(raw, 68), true)?;
|
||||
let delay = float_ns(u32_at(raw, 92), false)?;
|
||||
let dispersion = float_ns(u32_at(raw, 96), false)?;
|
||||
let error_ns = correction
|
||||
.checked_add(delay.div_ceil(2))
|
||||
.and_then(|v| v.checked_add(dispersion))
|
||||
.ok_or_else(|| anyhow::anyhow!("CHRONY_ERROR_OVERFLOW"))?;
|
||||
ensure!(error_ns <= MAX_ERROR_NS, "CHRONY_ERROR_LIMIT");
|
||||
Ok(Tracking {
|
||||
reference_utc_ns,
|
||||
error_ns,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn good() -> [u8; PACKET_BYTES] {
|
||||
let mut b = [0; PACKET_BYTES];
|
||||
b[0] = 6;
|
||||
b[1] = 2;
|
||||
b[4..6].copy_from_slice(&33u16.to_be_bytes());
|
||||
b[6..8].copy_from_slice(&5u16.to_be_bytes());
|
||||
b[16..20].copy_from_slice(&7u32.to_be_bytes());
|
||||
b[28..32].copy_from_slice(&0xc0000201u32.to_be_bytes());
|
||||
b[32..36].copy_from_slice(&[192, 0, 2, 1]);
|
||||
b[48..50].copy_from_slice(&1u16.to_be_bytes());
|
||||
b[52..54].copy_from_slice(&2u16.to_be_bytes());
|
||||
b[60..64].copy_from_slice(&1_800_000_000u32.to_be_bytes());
|
||||
b
|
||||
}
|
||||
#[test]
|
||||
fn exact_packet_sequence_and_network_source() {
|
||||
let b = good();
|
||||
let t = reply(&b, 7).unwrap();
|
||||
assert_eq!(t.reference_utc_ns, 1_800_000_000_000_000_000);
|
||||
assert_eq!(t.error_ns, 0);
|
||||
assert!(reply(&b, 8).is_err());
|
||||
assert!(reply(&b[..103], 7).is_err());
|
||||
for offset in [0, 1, 4, 6, 8, 10, 20, 48, 54] {
|
||||
let mut bad = b;
|
||||
bad[offset] ^= 0x40;
|
||||
assert!(reply(&bad, 7).is_err(), "offset {offset}");
|
||||
}
|
||||
let mut bad = b;
|
||||
bad[48..50].fill(0);
|
||||
assert!(reply(&bad, 7).is_err());
|
||||
// IPv4 loopback/unspecified cannot hide inside mapped or compatible
|
||||
// IPv6. Ordinary IPv6 and mapped network peers remain accepted.
|
||||
for (mapped, ipv4) in [
|
||||
(true, [127, 0, 0, 1]),
|
||||
(true, [0, 0, 0, 0]),
|
||||
(false, [127, 0, 0, 1]),
|
||||
(false, [0, 0, 0, 0]),
|
||||
] {
|
||||
let mut bad = b;
|
||||
bad[48..50].copy_from_slice(&2u16.to_be_bytes());
|
||||
bad[32..48].fill(0);
|
||||
if mapped {
|
||||
bad[42..44].fill(0xff);
|
||||
}
|
||||
bad[44..48].copy_from_slice(&ipv4);
|
||||
assert!(reply(&bad, 7).is_err());
|
||||
}
|
||||
let mut ipv6 = b;
|
||||
ipv6[48..50].copy_from_slice(&2u16.to_be_bytes());
|
||||
ipv6[32..48].fill(0);
|
||||
ipv6[32..36].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb8]);
|
||||
ipv6[47] = 1;
|
||||
assert!(reply(&ipv6, 7).is_ok());
|
||||
ipv6[32..48].fill(0);
|
||||
ipv6[42..44].fill(0xff);
|
||||
ipv6[44..48].copy_from_slice(&[192, 0, 2, 1]);
|
||||
assert!(reply(&ipv6, 7).is_ok());
|
||||
assert_eq!(request(7).len(), 104);
|
||||
assert_eq!(&request(7)[8..12], &7u32.to_be_bytes());
|
||||
}
|
||||
#[test]
|
||||
fn signed_float_ceil_and_overflow_are_conservative() {
|
||||
// exp=-6, coeff=2^24 -> 1/128 sec, exactly 7_812_500ns.
|
||||
let positive = (122u32 << 25) | 0x0100_0000; // coeff -2^24
|
||||
assert_eq!(float_ns(positive, true).unwrap(), 7_812_500);
|
||||
assert!(float_ns(positive, false).is_err());
|
||||
assert_eq!(float_ns(64u32 << 25 | 1, true).unwrap(), 1);
|
||||
assert!(float_ns(63u32 << 25 | 0x00ff_ffff, true).is_err());
|
||||
let mut b = good();
|
||||
b[96..100].copy_from_slice(&(63u32 << 25 | 0x00ff_ffff).to_be_bytes());
|
||||
assert!(reply(&b, 7).is_err());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user