Align signed time audience and add bounded native Chrony source
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
@@ -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