895 lines
30 KiB
Rust
895 lines
30 KiB
Rust
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: libc::nlink_t,
|
|
}
|
|
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();
|
|
}
|
|
}
|
|
}
|
|
|
|
// Linux pathname DGRAM send requires socket write permission; read/execute
|
|
// bits grant no sending authority. Directory ancestry is separately held and
|
|
// verified. Neither group nor other may write this daemon-owned socket.
|
|
fn protected_server_socket(socket: Identity, uid: u32, gid: u32) -> bool {
|
|
socket.mode & libc::S_IFMT == libc::S_IFSOCK
|
|
&& socket.links == 1
|
|
&& socket.uid == uid
|
|
&& socket.gid == gid
|
|
&& socket.mode & 0o022 == 0
|
|
}
|
|
|
|
/// 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!(
|
|
protected_server_socket(
|
|
server_identity,
|
|
daemon.pin.daemon_uid,
|
|
daemon.pin.daemon_gid,
|
|
),
|
|
"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();
|
|
let server = Identity {
|
|
mode: libc::S_IFSOCK | 0o755,
|
|
..expected
|
|
};
|
|
assert!(protected_server_socket(server, server.uid, server.gid));
|
|
for mode in [0o775, 0o757] {
|
|
assert!(!protected_server_socket(
|
|
Identity {
|
|
mode: libc::S_IFSOCK | mode,
|
|
..server
|
|
},
|
|
server.uid,
|
|
server.gid,
|
|
));
|
|
}
|
|
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();
|
|
}
|
|
}
|