//! Held state identities without reading/exporting private key contents. //! Paths must come from independently provisioned LOCAL policy, never IPC/jobs. use anyhow::{Context, Result, ensure}; use rmm_domain::jobs::hash; use rmm_updater_linux::files::{Directory, Identity}; use serde::{Deserialize, Serialize}; use std::{ fs::File, os::unix::fs::{MetadataExt, OpenOptionsExt}, path::{Path, PathBuf}, }; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Retention { /// Journal content is expected to advance, but the actual file stays held. MutableDatabase, /// Keys/configs remain byte-unread: additionally bind size/mtime/ctime. ImmutableMetadata, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct RetainedFileSpec { pub path: PathBuf, pub parent_uid: u32, pub identity: Identity, pub retention: Retention, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] struct Stamp { size: u64, mtime: i64, mtime_nsec: i64, ctime: i64, ctime_nsec: i64, } impl Stamp { fn of(meta: &std::fs::Metadata) -> Self { Self { size: meta.len(), mtime: meta.mtime(), mtime_nsec: meta.mtime_nsec(), ctime: meta.ctime(), ctime_nsec: meta.ctime_nsec(), } } } struct HeldState { spec: RetainedFileSpec, directory: Directory, file: File, stamp: Stamp, } pub struct RetainedSet { files: Vec, digest: String, } impl RetainedSet { pub fn capture(specs: Vec) -> Result { ensure!( !specs.is_empty() && specs.len() <= 64, "UPDATE_RETAINED_FILESET_LIMIT" ); let mut files = Vec::new(); for spec in specs { ensure!( spec.path.is_absolute() && spec.path.components().all(|c| matches!( c, std::path::Component::RootDir | std::path::Component::Normal(_) )) && !files.iter().any(|v: &HeldState| v.spec.path == spec.path), "UPDATE_RETAINED_PATH" ); // No state-reset/namespace substitution and no effect code files in // this preservation set. Historical bound hardlinks are allowed. ensure!( ![ rmm_updater_linux::files::Role::Agent, rmm_updater_linux::files::Role::Helper, rmm_updater_linux::files::Role::FullConfig, rmm_updater_linux::files::Role::FullPin ] .iter() .any(|role| Path::new(role.target()) == spec.path), "UPDATE_RETAINED_CODE_PATH" ); let parent = spec.path.parent().context("UPDATE_RETAINED_PARENT")?; let directory = Directory::open(parent, spec.parent_uid, false)?; let file = std::fs::OpenOptions::new() .read(true) .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC) .open(&spec.path)?; let stamp = Stamp::of(&file.metadata()?); let held = HeldState { spec, directory, file, stamp, }; held.verify()?; files.push(held); } let serial: Vec<_> = files .iter() .map(|f| { ( &f.spec, if f.spec.retention == Retention::ImmutableMetadata { Some(&f.stamp) } else { None }, ) }) .collect(); let digest = hash(&serde_json::to_vec(&serial)?); Ok(Self { files, digest }) } pub fn sha256(&self) -> &str { &self.digest } pub fn specs(&self) -> Vec<&RetainedFileSpec> { self.files.iter().map(|file| &file.spec).collect() } /// Exact ORIGINAL spec/stamp bytes. No current timestamp is substituted. pub fn bytes(&self) -> Result> { let serial: Vec<_> = self .files .iter() .map(|f| { ( &f.spec, if f.spec.retention == Retention::ImmutableMetadata { Some(&f.stamp) } else { None }, ) }) .collect(); let raw = serde_json::to_vec(&serial)?; ensure!( raw.len() <= 65536 && hash(&raw) == self.digest, "UPDATE_RETAINED_WITNESS_CHANGED" ); Ok(raw) } pub fn from_bound_bytes(raw: &[u8], handoff: &rmm_updater_handoff::Handoff) -> Result { Self::from_bound_digest(raw, &handoff.retained_state_sha256) } fn from_bound_digest(raw: &[u8], original_sha256: &str) -> Result { ensure!( !raw.is_empty() && raw.len() <= 65536 && hash(raw) == original_sha256, "UPDATE_RETAINED_WITNESS_HASH" ); let snapshot: Vec<(RetainedFileSpec, Option)> = serde_json::from_slice(raw)?; ensure!( !snapshot.is_empty() && snapshot.len() <= 64 && serde_json::to_vec(&snapshot)? == raw && snapshot.iter().all(|(spec, stamp)| (spec.retention == Retention::ImmutableMetadata) == stamp.is_some()), "UPDATE_RETAINED_WITNESS_CODEC" ); // Reopen current files but compare their actual stamps to the ORIGINAL // canonical bytes. Any changed immutable stamp fails; never refresh it. let current = Self::capture(snapshot.into_iter().map(|(spec, _)| spec).collect())?; ensure!( current.bytes()? == raw && current.digest == original_sha256, "UPDATE_RETAINED_ORIGINAL_STAMP_CHANGED" ); Ok(current) } pub fn verify(&self) -> Result<()> { for file in &self.files { file.verify()?; } Ok(()) } } 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(), } } impl HeldState { fn verify(&self) -> Result<()> { self.directory.verify()?; let held = self.file.metadata()?; let named = std::fs::symlink_metadata(&self.spec.path)?; ensure!( held.is_file() && named.is_file() && !named.file_type().is_symlink() && identity(&held) == self.spec.identity && identity(&named) == self.spec.identity && held.mode() & 0o022 == 0 && held.nlink() > 0, "UPDATE_RETAINED_IDENTITY_CHANGED" ); if self.spec.retention == Retention::ImmutableMetadata { ensure!( Stamp::of(&held) == self.stamp && Stamp::of(&named) == self.stamp, "UPDATE_RETAINED_METADATA_CHANGED" ); } self.directory.verify() } } #[cfg(test)] mod tests { use super::*; use std::{fs, io::Write, os::unix::fs::PermissionsExt}; struct Fixture(PathBuf); impl Drop for Fixture { fn drop(&mut self) { fs::remove_dir_all(&self.0).unwrap(); } } #[test] fn reopen_preserves_original_stamps_and_rejects_replaced_state_without_reading_keys() { assert_eq!( unsafe { libc::geteuid() }, 0, "Use isolated root-owned unit container, never a host daemon" ); let path = PathBuf::from(format!( "/run/rmm-worker-witness-unit-{}", uuid::Uuid::new_v4() )); fs::create_dir(&path).unwrap(); fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap(); let f = Fixture(path); let mut specs = Vec::new(); for (name, retention) in [ ("unit-db", Retention::MutableDatabase), ("public-fixture", Retention::ImmutableMetadata), ] { let path = f.0.join(name); let mut file = fs::OpenOptions::new() .create_new(true) .write(true) .mode(0o600) .open(&path) .unwrap(); file.write_all(b"public unit fixture").unwrap(); file.sync_all().unwrap(); specs.push(RetainedFileSpec { path, parent_uid: 0, identity: identity(&file.metadata().unwrap()), retention, }); } let captured = RetainedSet::capture(specs).unwrap(); let original = captured.bytes().unwrap(); let sha = captured.sha256().to_owned(); fs::OpenOptions::new() .append(true) .open(f.0.join("unit-db")) .unwrap() .write_all(b" advanced") .unwrap(); assert_eq!( RetainedSet::from_bound_digest(&original, &sha) .unwrap() .bytes() .unwrap(), original ); fs::rename(f.0.join("unit-db"), f.0.join("old-db")).unwrap(); let mut replacement = fs::OpenOptions::new() .create_new(true) .write(true) .mode(0o600) .open(f.0.join("unit-db")) .unwrap(); replacement .write_all(b"same name does not preserve identity") .unwrap(); assert!(RetainedSet::from_bound_digest(&original, &sha).is_err()); drop(replacement); fs::remove_file(f.0.join("unit-db")).unwrap(); fs::rename(f.0.join("old-db"), f.0.join("unit-db")).unwrap(); assert!(RetainedSet::from_bound_digest(&original, &sha).is_ok()); fs::OpenOptions::new() .append(true) .open(f.0.join("public-fixture")) .unwrap() .write_all(b" changed") .unwrap(); assert!(RetainedSet::from_bound_digest(&original, &sha).is_err()); assert!(captured.verify().is_err()); assert_eq!(captured.bytes().unwrap(), original); } }