//! Capability-relative held files. No network-provided path or global JSON //! replacement. Existing bound hardlinks are retained; new stages have nlink1. use crate::{Budget, DurableEffectFence, Effect, digest, valid_digest}; use anyhow::{Context, Result, ensure}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::{ ffi::{CString, OsStr}, fs::{File, Metadata}, io::{Read, Seek, SeekFrom, Write}, os::{ fd::{AsRawFd, FromRawFd}, unix::{ffi::OsStrExt, fs::MetadataExt}, }, path::{Component, Path, PathBuf}, }; use uuid::Uuid; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Role { Agent, Helper, FullConfig, FullPin, } impl Role { pub fn handoff_role(self) -> rmm_updater_handoff::FileRole { match self { Self::Agent => rmm_updater_handoff::FileRole::AgentBinary, Self::Helper => rmm_updater_handoff::FileRole::HelperBinary, Self::FullConfig => rmm_updater_handoff::FileRole::LinuxFullConfig, Self::FullPin => rmm_updater_handoff::FileRole::LinuxFullPin, } } pub fn target(self) -> &'static str { match self { Self::Agent => "/usr/local/libexec/rmm-agent-remote", Self::Helper => "/usr/local/libexec/rmm-privileged-helper", Self::FullConfig => "/etc/rmm-remote/helper-full-maintenance.json", Self::FullPin => "/etc/rmm-remote/full-maintenance-helper-proof.json", } } fn label(self) -> &'static str { match self { Self::Agent => "agent", Self::Helper => "helper", Self::FullConfig => "full-config", Self::FullPin => "full-pin", } } } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Identity { pub device: u64, pub inode: u64, pub uid: u32, pub gid: u32, pub mode: u32, pub links: u64, } impl Identity { fn of(m: &Metadata) -> Self { Self { device: m.dev(), inode: m.ino(), uid: m.uid(), gid: m.gid(), mode: m.mode(), links: m.nlink(), } } } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct FileProof { pub identity: Identity, pub bytes: u64, pub sha256: String, } fn name(value: &OsStr) -> Result { let bytes = value.as_bytes(); ensure!( !bytes.is_empty() && bytes != b"." && bytes != b".." && !bytes.contains(&b'/'), "UPDATE_BASENAME" ); Ok(CString::new(bytes)?) } fn openat(parent: &File, value: &OsStr, flags: i32, mode: u32) -> Result { let value = name(value)?; // SAFETY: valid owned directory fd and NUL-terminated one-component name; // successful descriptor is immediately transferred into exactly one File. let fd = unsafe { libc::openat( parent.as_raw_fd(), value.as_ptr(), flags | libc::O_CLOEXEC | libc::O_NOFOLLOW, mode, ) }; ensure!( fd >= 0, "UPDATE_OPENAT: {}", std::io::Error::last_os_error() ); Ok(unsafe { File::from_raw_fd(fd) }) } pub struct Directory { fd: File, path: PathBuf, identity: Identity, } impl Directory { /// All ancestors are held while opening their child with O_NOFOLLOW. A /// writable ancestor (including /tmp) is deliberately not an install root. pub fn open(path: &Path, owner: u32, private: bool) -> Result { ensure!(path.is_absolute(), "UPDATE_ABSOLUTE_DIRECTORY"); let mut fd = File::open("/")?; let components: Vec<_> = path.components().collect(); for (i, component) in components.iter().enumerate().skip(1) { let Component::Normal(value) = component else { anyhow::bail!("UPDATE_DIRECTORY_COMPONENT") }; fd = openat(&fd, value, libc::O_RDONLY | libc::O_DIRECTORY, 0)?; let m = fd.metadata()?; ensure!( m.is_dir() && m.uid() == if i + 1 == components.len() { owner } else { 0 } && m.mode() & 0o022 == 0, "UPDATE_PROTECTED_DIRECTORY" ); } let m = fd.metadata()?; ensure!( m.uid() == owner && (!private || m.mode() & 0o077 == 0), "UPDATE_PRIVATE_DIRECTORY" ); Ok(Self { identity: Identity::of(&m), fd, path: path.to_path_buf(), }) } pub fn identity(&self) -> &Identity { &self.identity } pub fn verify(&self) -> Result<()> { let current = Self::open(&self.path, self.identity.uid, false)?; ensure!( current.identity == self.identity && Identity::of(&self.fd.metadata()?) == self.identity, "UPDATE_DIRECTORY_REPLACED" ); Ok(()) } pub fn file(&self, basename: &OsStr, expected: &FileProof, max: u64) -> Result { self.verify()?; let mut held = HeldFile { fd: openat(&self.fd, basename, libc::O_RDONLY | libc::O_NONBLOCK, 0)?, proof: expected.clone(), }; held.verify(max)?; self.named(basename, &held.proof.identity)?; Ok(held) } pub fn inspect(&self, basename: &OsStr, owner: u32, max: u64) -> Result { self.verify()?; let mut fd = openat(&self.fd, basename, libc::O_RDONLY | libc::O_NONBLOCK, 0)?; let m = fd.metadata()?; ensure!( m.is_file() && m.uid() == owner && m.mode() & 0o022 == 0 && m.nlink() > 0 && m.len() <= max, "UPDATE_PROTECTED_FILE" ); let hash = hash_file(&mut fd, max)?; let proof = FileProof { identity: Identity::of(&m), bytes: m.len(), sha256: hash, }; let mut result = HeldFile { fd, proof }; result.verify(max)?; self.named(basename, &result.proof.identity)?; Ok(result) } fn named(&self, basename: &OsStr, expected: &Identity) -> Result<()> { let file = openat(&self.fd, basename, libc::O_PATH, 0)?; ensure!( Identity::of(&file.metadata()?) == *expected, "UPDATE_NAMED_INODE_CHANGED" ); Ok(()) } fn absent(&self, basename: &OsStr) -> Result<()> { let value = name(basename)?; let mut m = std::mem::MaybeUninit::::uninit(); // SAFETY: live dirfd, valid basename, properly sized writable stat. let rc = unsafe { libc::fstatat( self.fd.as_raw_fd(), value.as_ptr(), m.as_mut_ptr(), libc::AT_SYMLINK_NOFOLLOW, ) }; ensure!( rc < 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ENOENT), "UPDATE_DESTINATION_EXISTS" ); Ok(()) } fn sync(&self) -> Result<()> { self.fd.sync_all()?; Ok(()) } fn rename_new(&self, from: &OsStr, to: &OsStr) -> Result<()> { let a = name(from)?; let b = name(to)?; // SAFETY: same held directory, valid component strings; NOREPLACE // forbids overwriting an unexpected target including a dangling link. let rc = unsafe { libc::renameat2( self.fd.as_raw_fd(), a.as_ptr(), self.fd.as_raw_fd(), b.as_ptr(), libc::RENAME_NOREPLACE, ) }; ensure!( rc == 0, "UPDATE_RENAME: {}", std::io::Error::last_os_error() ); self.sync() } } pub struct HeldFile { fd: File, proof: FileProof, } impl HeldFile { pub fn proof(&self) -> &FileProof { &self.proof } pub fn verify(&mut self, max: u64) -> Result<()> { let m = self.fd.metadata()?; ensure!( m.is_file() && Identity::of(&m) == self.proof.identity && m.len() == self.proof.bytes && self.proof.bytes <= max && valid_digest(&self.proof.sha256), "UPDATE_HELD_FILE_CHANGED" ); ensure!( hash_file(&mut self.fd, max)? == self.proof.sha256, "UPDATE_HELD_HASH_CHANGED" ); let after = self.fd.metadata()?; ensure!( Identity::of(&m) == Identity::of(&after) && m.len() == after.len() && m.mtime_nsec() == after.mtime_nsec() && m.mtime() == after.mtime() && m.ctime() == after.ctime() && m.ctime_nsec() == after.ctime_nsec(), "UPDATE_FILE_CHANGED_DURING_HASH" ); Ok(()) } pub fn bytes(&mut self, max: u64) -> Result> { self.verify(max)?; self.fd.seek(SeekFrom::Start(0))?; let mut bytes = Vec::with_capacity(self.proof.bytes as usize); Read::by_ref(&mut self.fd) .take(max + 1) .read_to_end(&mut bytes)?; ensure!( bytes.len() as u64 == self.proof.bytes && digest(&bytes) == self.proof.sha256, "UPDATE_READ_CHANGED" ); self.verify(max)?; Ok(bytes) } } fn hash_file(fd: &mut File, max: u64) -> Result { ensure!(max <= 256 * 1024 * 1024, "UPDATE_HASH_LIMIT"); fd.seek(SeekFrom::Start(0))?; let mut hash = Sha256::new(); let mut buffer = [0; 32768]; let mut total = 0u64; loop { let n = fd.read(&mut buffer)?; if n == 0 { break; } total = total.checked_add(n as u64).context("UPDATE_HASH_LIMIT")?; ensure!(total <= max, "UPDATE_HASH_LIMIT"); hash.update(&buffer[..n]); } Ok(hex::encode(hash.finalize())) } /// File creation is confined to the SAME held installation directory. The /// private fields bind successful EOF/hash/mode checking to subsequent swap. pub struct Staged { role: Role, nonce: Uuid, basename: String, file: HeldFile, target: String, original: FileProof, } /// All descriptors remain untrusted input until the exact protected predecessor /// and the approved target hashes have been independently checked by runtime. pub struct StageDescriptor<'a> { pub role: Role, pub nonce: Uuid, pub original: &'a FileProof, pub expected_sha: &'a str, pub length: u64, } /// Original immutable proof bytes from the protected consumed handoff bundle. /// Reopening them supplies held observations only, never dispatch/resume. pub struct BoundStage<'a> { pub role: Role, pub nonce: Uuid, pub original: &'a FileProof, pub staged: &'a FileProof, } impl Staged { pub fn reopen_bound(dir: &Directory, bound: BoundStage<'_>, budget: &Budget) -> Result { ensure!( Path::new(bound.role.target()).parent() == Some(dir.path.as_path()), "UPDATE_FIXED_ROLE_DIRECTORY" ); Self::reopen_held(dir, bound, budget) } fn reopen_held(dir: &Directory, bound: BoundStage<'_>, budget: &Budget) -> Result { budget.check()?; dir.verify()?; ensure!( !bound.nonce.is_nil() && valid_digest(&bound.original.sha256) && valid_digest(&bound.staged.sha256) && bound.original.bytes > 0 && bound.original.bytes <= 256 * 1024 * 1024 && bound.staged.bytes > 0 && bound.staged.bytes <= 256 * 1024 * 1024 && bound.original.identity.uid == 0 && bound.original.identity.mode & 0o022 == 0 && bound.staged.identity.uid == bound.original.identity.uid && bound.staged.identity.gid == bound.original.identity.gid && bound.staged.identity.mode == bound.original.identity.mode && bound.staged.identity.links == 1 && bound.staged.identity.device == bound.original.identity.device && bound.staged.identity.inode != bound.original.identity.inode, "UPDATE_REOPEN_PROOF_SHAPE" ); let target = Path::new(bound.role.target()) .file_name() .context("UPDATE_TARGET")? .to_str() .context("UPDATE_TARGET")? .to_owned(); let basename = format!(".rmm-update-{}-{}.stage", bound.nonce, bound.role.label()); dir.file(OsStr::new(&target), bound.original, 256 * 1024 * 1024)?; let file = dir.file(OsStr::new(&basename), bound.staged, 256 * 1024 * 1024)?; // A partially applied prior pass is never reconstructed as a stage. dir.absent(OsStr::new(&format!( ".rmm-update-{}-{}.previous", bound.nonce, bound.role.label() )))?; dir.absent(OsStr::new(&format!( ".rmm-update-{}-{}.rejected", bound.nonce, bound.role.label() )))?; budget.check()?; Ok(Self { role: bound.role, nonce: bound.nonce, basename, file, target, original: bound.original.clone(), }) } /// Stage only after the embedding agent has a real fixed approved job and /// authorized download. This function alone grants no stop/swap authority. pub fn write( dir: &Directory, descriptor: StageDescriptor<'_>, source: &mut impl Read, budget: &Budget, ) -> Result { let StageDescriptor { role, nonce, original, expected_sha, length, } = descriptor; ensure!( !nonce.is_nil() && valid_digest(expected_sha) && length > 0 && length <= 256 * 1024 * 1024, "UPDATE_STAGE_DESCRIPTOR" ); ensure!( original.identity.uid == 0 && original.identity.mode & 0o022 == 0, "UPDATE_ORIGINAL_METADATA" ); let target = Path::new(role.target()) .file_name() .context("UPDATE_TARGET")? .to_str() .context("UPDATE_TARGET")? .to_owned(); ensure!( Path::new(role.target()).parent() == Some(dir.path.as_path()), "UPDATE_FIXED_ROLE_DIRECTORY" ); dir.file(OsStr::new(&target), original, 256 * 1024 * 1024)?; let basename = format!(".rmm-update-{nonce}-{}.stage", role.label()); budget.check()?; let mut fd = openat( &dir.fd, OsStr::new(&basename), libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL, 0o600, )?; let mut remaining = length; let mut hash = Sha256::new(); let mut buffer = [0; 32768]; while remaining > 0 { budget.check()?; let take = remaining.min(buffer.len() as u64) as usize; let n = source.read(&mut buffer[..take])?; ensure!(n > 0, "UPDATE_STAGE_SHORT"); fd.write_all(&buffer[..n])?; hash.update(&buffer[..n]); remaining -= n as u64; } let mut tail = [0; 1]; ensure!( source.read(&mut tail)? == 0 && hex::encode(hash.finalize()) == expected_sha, "UPDATE_STAGE_HASH_OR_EXCESS" ); budget.check()?; // SAFETY: owned regular newly created file. Preserve old owner/group // and all mode bits; binaries/configs are not made more permissive. ensure!( unsafe { libc::fchown(fd.as_raw_fd(), original.identity.uid, original.identity.gid) } == 0, "UPDATE_STAGE_OWNER" ); ensure!( unsafe { libc::fchmod(fd.as_raw_fd(), original.identity.mode & 0o7777) } == 0, "UPDATE_STAGE_MODE" ); fd.sync_all()?; dir.sync()?; drop(fd); let file = dir.inspect(OsStr::new(&basename), 0, 256 * 1024 * 1024)?; ensure!( file.proof.identity.links == 1 && file.proof.sha256 == expected_sha && file.proof.bytes == length, "UPDATE_STAGE_VERIFIED" ); Ok(Self { role, nonce, basename, file, target, original: original.clone(), }) } pub fn proof(&self) -> &FileProof { self.file.proof() } /// Two separately fenced namespace changes; a crash in between leaves the /// original backup and stage intact. This method NEVER retries or resumes. pub fn install( mut self, dir: &Directory, guard: &LedgerGuard<'_>, budget: &Budget, fence: &mut impl DurableEffectFence, ) -> Result { guard.verify_for_effect(budget)?; dir.verify()?; self.file.verify(256 * 1024 * 1024)?; dir.file(OsStr::new(&self.target), &self.original, 256 * 1024 * 1024)?; let backup = format!(".rmm-update-{}-{}.previous", self.nonce, self.role.label()); dir.absent(OsStr::new(&backup))?; let save = Effect::SavePredecessor { role: self.role }; fence.before_effect(&save)?; guard.verify_for_effect(budget)?; dir.named(OsStr::new(&self.target), &self.original.identity)?; dir.named(OsStr::new(&self.basename), &self.file.proof.identity)?; dir.rename_new(OsStr::new(&self.target), OsStr::new(&backup))?; dir.file(OsStr::new(&backup), &self.original, 256 * 1024 * 1024)?; fence.after_effect(&save, &digest(&serde_json::to_vec(&self.original)?))?; let publish = Effect::PublishReplacement { role: self.role }; fence.before_effect(&publish)?; guard.verify_for_effect(budget)?; dir.named(OsStr::new(&self.basename), &self.file.proof.identity)?; dir.absent(OsStr::new(&self.target))?; dir.rename_new(OsStr::new(&self.basename), OsStr::new(&self.target))?; let current = dir.file( OsStr::new(&self.target), &self.file.proof, 256 * 1024 * 1024, )?; fence.after_effect(&publish, &digest(&serde_json::to_vec(current.proof())?))?; Ok(Installed { role: self.role, target: self.target, backup, old: self.original, new: current.proof, }) } } pub struct Installed { pub role: Role, target: String, backup: String, old: FileProof, new: FileProof, } impl Installed { pub fn old(&self) -> &FileProof { &self.old } pub fn new_file(&self) -> &FileProof { &self.new } /// A rollback is NOT inferred from a failed health check. Only a separately /// bound rollback fence may authorize it; unknown intermediate state denies. pub fn restore( self, dir: &Directory, guard: &LedgerGuard<'_>, budget: &Budget, fence: &mut impl DurableEffectFence, ) -> Result<()> { guard.verify_for_effect(budget)?; dir.file(OsStr::new(&self.target), &self.new, 256 * 1024 * 1024)?; dir.file(OsStr::new(&self.backup), &self.old, 256 * 1024 * 1024)?; let displaced = self.backup.replace(".previous", ".rejected"); dir.absent(OsStr::new(&displaced))?; let effect = Effect::RestorePredecessor { role: self.role }; fence.before_effect(&effect)?; guard.verify_for_effect(budget)?; dir.rename_new(OsStr::new(&self.target), OsStr::new(&displaced))?; // No existing target can be overwritten; both code generations remain. guard.verify_for_effect(budget)?; dir.rename_new(OsStr::new(&self.backup), OsStr::new(&self.target))?; dir.file(OsStr::new(&self.target), &self.old, 256 * 1024 * 1024)?; fence.after_effect(&effect, &digest(&serde_json::to_vec(&self.old)?)) } } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct LedgerIdentity { pub ledger: Identity, pub lock: Identity, } impl LedgerIdentity { pub fn sha256(&self) -> Result { Ok(digest(&serde_json::to_vec(self)?)) } } /// Existing lock only: no create, truncate or alternate database. Acquire only /// after the caller independently confirmed every installed reader stopped. pub struct LedgerGuard<'a> { ledger: File, lock: File, directory: Directory, identity: LedgerIdentity, stopped: &'a crate::services::StoppedServices, } impl<'a> LedgerGuard<'a> { pub fn acquire( stopped: &'a crate::services::StoppedServices, identity: &LedgerIdentity, budget: &Budget, ) -> Result { stopped.verify_still_stopped(budget)?; let directory = Directory::open(Path::new("/var/lib/rmm-helper"), 0, true)?; let ledger = openat( &directory.fd, OsStr::new("consumption.sqlite"), libc::O_RDONLY | libc::O_NONBLOCK, 0, )?; let lock = openat( &directory.fd, OsStr::new("executor.lock"), libc::O_RDWR | libc::O_NONBLOCK, 0, )?; let actual = LedgerIdentity { ledger: Identity::of(&ledger.metadata()?), lock: Identity::of(&lock.metadata()?), }; ensure!( actual == *identity && ledger.metadata()?.is_file() && lock.metadata()?.is_file() && actual.ledger.uid == 0 && actual.lock.uid == 0, "UPDATE_LEDGER_IDENTITY" ); ensure!( unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0, "UPDATE_LEDGER_BUSY" ); let result = Self { ledger, lock, directory, identity: actual, stopped, }; result.verify_for_effect(budget)?; Ok(result) } pub fn identity(&self) -> &LedgerIdentity { &self.identity } pub fn verify(&self) -> Result<()> { self.directory.verify()?; ensure!( Identity::of(&self.ledger.metadata()?) == self.identity.ledger && Identity::of(&self.lock.metadata()?) == self.identity.lock, "UPDATE_LEDGER_HELD_IDENTITY" ); self.directory .named(OsStr::new("consumption.sqlite"), &self.identity.ledger)?; self.directory .named(OsStr::new("executor.lock"), &self.identity.lock) } pub fn verify_for_effect(&self, budget: &Budget) -> Result<()> { self.verify()?; self.stopped.verify_still_stopped(budget) } /// Caller must first COMMIT the exact LedgerReturnIntent. This consumes the /// guard, so it cannot be retained accidentally across the helper start. pub fn release(self, budget: &Budget, fence: &mut impl DurableEffectFence) -> Result<()> { self.verify_for_effect(budget)?; fence.before_effect(&Effect::ReturnLedger)?; self.verify_for_effect(budget)?; drop(self); Ok(()) } } impl Drop for LedgerGuard<'_> { fn drop(&mut self) { unsafe { libc::flock(self.lock.as_raw_fd(), libc::LOCK_UN) }; } } #[cfg(test)] mod reopen_tests { use super::*; use std::{ fs, os::unix::fs::{OpenOptionsExt, PermissionsExt}, time::Duration, }; struct Fixture(PathBuf); impl Drop for Fixture { fn drop(&mut self) { fs::remove_dir_all(&self.0).unwrap(); } } #[test] fn bound_reopen_rejects_same_byte_name_substitution_and_added_stage_hardlink() { assert_eq!( unsafe { libc::geteuid() }, 0, "Use isolated Root unit fixture; never a host daemon" ); let path = PathBuf::from(format!("/run/rmm-stage-reopen-unit-{}", Uuid::new_v4())); fs::create_dir(&path).unwrap(); fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap(); let fixture = Fixture(path); let dir = Directory::open(&fixture.0, 0, true).unwrap(); let nonce = Uuid::new_v4(); let stage = format!(".rmm-update-{nonce}-agent.stage"); for (name, bytes) in [ ("rmm-agent-remote", b"old public fixture".as_slice()), (stage.as_str(), b"new public fixture".as_slice()), ] { let mut file = fs::OpenOptions::new() .create_new(true) .write(true) .mode(0o600) .open(fixture.0.join(name)) .unwrap(); file.write_all(bytes).unwrap(); file.sync_all().unwrap(); } let old = dir .inspect(OsStr::new("rmm-agent-remote"), 0, 1024) .unwrap() .proof() .clone(); let new = dir .inspect(OsStr::new(&stage), 0, 1024) .unwrap() .proof() .clone(); let bound = || BoundStage { role: Role::Agent, nonce, original: &old, staged: &new, }; let boot = fs::read_to_string("/proc/sys/kernel/random/boot_id") .unwrap() .trim() .parse() .unwrap(); let budget = Budget::new(boot, Duration::from_secs(10)).unwrap(); // Public API always enforces the real fixed parent. The shared private // FD-validation core is exercised only below this NEW /run fixture. assert!(Staged::reopen_bound(&dir, bound(), &budget).is_err()); let held = Staged::reopen_held(&dir, bound(), &budget).unwrap(); assert_eq!(held.proof(), &new); fs::rename( fixture.0.join(&stage), fixture.0.join("held-original-stage"), ) .unwrap(); let mut replacement = fs::OpenOptions::new() .create_new(true) .write(true) .mode(0o600) .open(fixture.0.join(&stage)) .unwrap(); replacement.write_all(b"new public fixture").unwrap(); replacement.sync_all().unwrap(); assert!(Staged::reopen_held(&dir, bound(), &budget).is_err()); assert_eq!(held.proof(), &new); drop(replacement); fs::remove_file(fixture.0.join(&stage)).unwrap(); fs::rename( fixture.0.join("held-original-stage"), fixture.0.join(&stage), ) .unwrap(); fs::hard_link( fixture.0.join(&stage), fixture.0.join("unexpected-stage-alias"), ) .unwrap(); assert!(Staged::reopen_held(&dir, bound(), &budget).is_err()); } }