//! Existing Agent singleton fence. No create, ACL change or Root-ledger alias. //! The agent holds this exact lock before opening BOTH of its SQLite files. use crate::retained::{RetainedSet, Retention}; use anyhow::{Context, Result, ensure}; use rmm_updater_linux::{ Budget, files::{Directory, Identity}, services::StoppedServices, }; use std::{ fs::{File, OpenOptions}, os::{ fd::AsRawFd, unix::fs::{MetadataExt, OpenOptionsExt}, }, path::Path, }; const PARENT: &str = "/var/lib/rmm-agent-remote"; const PATH: &str = "/var/lib/rmm-agent-remote/agent.lock"; pub struct BoundAgentLock { directory: Directory, file: File, expected: Identity, } impl BoundAgentLock { /// Open/bind before any stop, so a missing preservation witness cannot be /// discovered only after stopping the Agent. Reading never takes its lock. pub fn bind(retained: &RetainedSet) -> Result { retained.verify()?; let specs = retained.specs(); let spec = specs .iter() .find(|s| s.path == Path::new(PATH)) .context("UPDATE_AGENT_LOCK_WITNESS_REQUIRED")?; ensure!( spec.retention == Retention::ImmutableMetadata && spec.parent_uid == 993 && spec.identity.uid == 993 && spec.identity.gid == 984 && spec.identity.mode & 0o7777 == 0o600 && spec.identity.links == 1, "UPDATE_AGENT_LOCK_PROVISIONING" ); let directory = Directory::open(Path::new(PARENT), 993, true)?; let file = OpenOptions::new() .read(true) .write(true) .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC) .open(PATH)?; let result = Self { directory, file, expected: spec.identity.clone(), }; result.verify()?; Ok(result) } fn verify(&self) -> Result<()> { self.directory.verify()?; let held = self.file.metadata()?; let named = std::fs::symlink_metadata(PATH)?; ensure!( held.is_file() && held.len() == 0 && named.is_file() && !named.file_type().is_symlink() && identity(&held) == self.expected && identity(&named) == self.expected, "UPDATE_AGENT_LOCK_IDENTITY_CHANGED" ); Ok(()) } pub fn identity(&self) -> &Identity { &self.expected } /// Real, fresh stopped-service proof precedes the existing nonblocking /// singleton acquisition. A running/restarted Agent makes this fail closed. pub fn acquire(self, stopped: &StoppedServices, budget: &Budget) -> Result { stopped.verify_still_stopped(budget)?; let result = self.acquire_existing()?; stopped.verify_still_stopped(budget)?; Ok(result) } fn acquire_existing(self) -> Result { self.verify()?; ensure!( unsafe { libc::flock(self.file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0, "UPDATE_AGENT_STARTUP_BUSY" ); let result = HeldAgentLock { bound: self }; result.verify()?; Ok(result) } } pub struct HeldAgentLock { bound: BoundAgentLock, } impl HeldAgentLock { pub fn verify(&self) -> Result<()> { self.bound.verify() } pub fn identity(&self) -> &Identity { self.bound.identity() } /// Only the live Engine calls this after SQLite close and actual original /// Root flock return, before the explicit once-only service start sequence. pub(crate) fn return_after_root_release(self, budget: &Budget) -> Result<()> { budget.check()?; self.verify()?; ensure!( unsafe { libc::flock(self.bound.file.as_raw_fd(), libc::LOCK_UN) } == 0, "UPDATE_AGENT_STARTUP_RETURN_FAILED" ); Ok(()) } } impl Drop for HeldAgentLock { fn drop(&mut self) { unsafe { libc::flock(self.bound.file.as_raw_fd(), libc::LOCK_UN); } } } fn identity(meta: &std::fs::Metadata) -> Identity { Identity { device: meta.dev(), inode: meta.ino(), uid: meta.uid(), gid: meta.gid(), mode: meta.mode(), links: meta.nlink(), } } #[cfg(test)] mod tests { use super::*; use crate::retained::RetainedFileSpec; use std::os::unix::fs::PermissionsExt; struct Cleanup; impl Drop for Cleanup { fn drop(&mut self) { std::fs::remove_dir_all(PARENT).unwrap(); } } #[test] fn existing_agent_lock_blocks_aliases_and_rejects_samebyte_inode_substitution() { // Private network-none/root container fixture ONLY; no host path/test. assert_eq!(unsafe { libc::geteuid() }, 0); assert!(!Path::new(PARENT).exists()); std::fs::create_dir_all(PARENT).unwrap(); let _cleanup = Cleanup; std::fs::set_permissions(PARENT, std::fs::Permissions::from_mode(0o700)).unwrap(); let file = OpenOptions::new() .create_new(true) .read(true) .write(true) .mode(0o600) .open(PATH) .unwrap(); for path in [PARENT, PATH] { let path = std::ffi::CString::new(path).unwrap(); assert_eq!(unsafe { libc::chown(path.as_ptr(), 993, 984) }, 0); } let retained = RetainedSet::capture(vec![RetainedFileSpec { path: Path::new(PATH).to_owned(), parent_uid: 993, identity: identity(&file.metadata().unwrap()), retention: Retention::ImmutableMetadata, }]) .unwrap(); let bound = BoundAgentLock::bind(&retained).unwrap(); // The existing Agent's separately opened descriptor owns the lock. assert_eq!( unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, 0 ); assert!(bound.acquire_existing().is_err()); assert_eq!(unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_UN) }, 0); let held = BoundAgentLock::bind(&retained) .unwrap() .acquire_existing() .unwrap(); assert_ne!( unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, 0 ); held.verify().unwrap(); std::fs::rename(PATH, Path::new(PARENT).join("agent.lock.previous")).unwrap(); let replacement = OpenOptions::new() .create_new(true) .read(true) .write(true) .mode(0o600) .open(PATH) .unwrap(); let path = std::ffi::CString::new(PATH).unwrap(); assert_eq!(unsafe { libc::chown(path.as_ptr(), 993, 984) }, 0); assert_eq!(replacement.metadata().unwrap().len(), 0); assert!(held.verify().is_err()); assert!(BoundAgentLock::bind(&retained).is_err()); drop(held); assert_eq!( unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, 0 ); } }