//! Protected compatible-reader registry plus read-only systemd closure. //! This does not replace complete current task/FD/maps census, both real locks, //! original authorization or live process/image proofs. No future-exec promise. use crate::census::{HostContext, current_host_context}; use anyhow::{Context, Result, ensure}; use rmm_domain::{ agent_update::digest, agent_update_provisioning::{ActivationEvidence, LocalUpdatePolicy}, jobs::hash, }; use rmm_updater_linux::{ Budget, files::{Directory, FileProof, HeldFile}, }; use serde::{Deserialize, Serialize}; use std::{ collections::{BTreeMap, BTreeSet}, fs::Metadata, io::Read, os::{ fd::{AsRawFd, FromRawFd}, unix::fs::MetadataExt, }, path::{Path, PathBuf}, process::{Child, Command, Stdio}, sync::Mutex, thread, time::{Duration, Instant}, }; pub const READER_CONTRACT: &[u8] = b"rmm.linux-shared-readers.v1\0root-helper:existing-executor.lock-before-sqlite-open-and-every-sql-or-effect-operation;agent:existing-agent.lock-before-both-agent-sqlite-opens-and-held-for-process-lifetime;all-allowed-readers:update-handoff-inflight-decoder-compatible;admission:protected-bootstrap-plus-current-complete-task-fd-maps-census-and-both-original-locks;scope:no-global-future-exec-absence-promise\n"; pub fn reader_contract_sha256() -> String { hash(READER_CONTRACT) } const REGISTRY: &str = "/etc/rmm-agent-updater/reader-registry.json"; const MAX_BYTES: u64 = 65536; const MAX_ROLLBACK: usize = 32; const MAX_FILES: usize = 128; const SERVICES: [&str; 7] = [ "rmm-agent-remote.service", "rmm-helper-cloud.service", "rmm-full-maintenance-helper.service", "rmm-agent-updater.service", "rmm-apt-helper.service", "rmm-agent.service", "rmm-helper-dev-test.service", ]; const ROLLBACK_PATTERN: &str = "rmm-general-startup-rollback-*.timer"; #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] struct Registry { schema_version: u32, profile: String, bootstrap_receipt_sha256: String, reader_contract_sha256: String, host_context: HostContext, units: Vec, rollback_timers: Vec, } #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] struct Unit { unit: String, unit_file_state: String, /// Exactly the Frozen OS unit_composition vector: fragment, then DropInPaths /// in their actual order. FileProof includes original device/inode metadata. composition: Vec<(String, FileProof)>, triggers: Vec, triggered_by: Vec, } #[derive(PartialEq, Eq)] struct Stamp { dev: u64, ino: u64, uid: u32, gid: u32, mode: u32, links: u64, bytes: u64, mtime: i64, mtime_ns: i64, ctime: i64, ctime_ns: i64, } impl Stamp { fn read(path: &Path) -> Result { let m = std::fs::symlink_metadata(path)?; ensure!( m.is_file() && !m.file_type().is_symlink(), "UPDATE_REGISTRY_REGULAR_FILE" ); Ok(Self::of(&m)) } fn of(m: &Metadata) -> Self { Self { dev: m.dev(), ino: m.ino(), uid: m.uid(), gid: m.gid(), mode: m.mode(), links: m.nlink(), bytes: m.len(), mtime: m.mtime(), mtime_ns: m.mtime_nsec(), ctime: m.ctime(), ctime_ns: m.ctime_nsec(), } } } struct Protected { directory: Directory, file: Mutex, path: PathBuf, proof: FileProof, stamp: Stamp, raw: Vec, } impl Protected { fn open(path: &Path) -> Result { let before = Stamp::read(path)?; let directory = Directory::open(path.parent().context("UPDATE_REGISTRY_PARENT")?, 0, false)?; let mut file = directory.inspect( path.file_name().context("UPDATE_REGISTRY_FILENAME")?, 0, MAX_BYTES, )?; let raw = file.bytes(MAX_BYTES)?; let proof = file.proof().clone(); ensure!( before == Stamp::read(path)? && before.uid == 0 && before.mode & 0o022 == 0 && before.bytes == raw.len() as u64, "UPDATE_REGISTRY_CHANGED_DURING_READ" ); let result = Self { directory, file: Mutex::new(file), path: path.into(), proof, stamp: before, raw, }; result.verify()?; Ok(result) } fn verify(&self) -> Result<()> { self.directory.verify()?; ensure!( Stamp::read(&self.path)? == self.stamp, "UPDATE_REGISTRY_METADATA_CHANGED" ); let mut held = self .file .try_lock() .map_err(|_| anyhow::anyhow!("UPDATE_REGISTRY_HELD_FILE_BUSY"))?; held.verify(MAX_BYTES)?; let mut named = self.directory.file( self.path.file_name().context("UPDATE_REGISTRY_FILENAME")?, &self.proof, MAX_BYTES, )?; ensure!( named.bytes(MAX_BYTES)? == self.raw && Stamp::read(&self.path)? == self.stamp, "UPDATE_REGISTRY_ORIGINAL_RAW_CHANGED" ); Ok(()) } } /// Non-cloneable independently loaded original registry. No caller completeness /// flag and no command/path selection is exposed by its public API. pub struct QualifiedRegistry { registry: Registry, protected: Vec, policy_sha256: String, } impl QualifiedRegistry { pub fn load(policy: &LocalUpdatePolicy) -> Result { ensure!( policy.validate() && policy.registry_path == REGISTRY, "UPDATE_READER_POLICY" ); let original = Protected::open(Path::new(REGISTRY))?; ensure!( original.proof.identity.links == 1 && hash(&original.raw) == policy.reader_registry_sha256, "UPDATE_READER_REGISTRY_PIN" ); let registry: Registry = serde_json::from_slice(&original.raw) .map_err(|_| anyhow::anyhow!("UPDATE_READER_REGISTRY_CODEC"))?; validate_registry(®istry, policy)?; let mut protected = vec![original]; let mut seen = BTreeMap::new(); for unit in registry.units.iter().chain(®istry.rollback_timers) { for (path, expected) in &unit.composition { if let Some(existing) = seen.get(path) { ensure!( existing == expected, "UPDATE_READER_SHARED_UNIT_PROOF_CONFLICT" ); continue; } ensure!(protected.len() <= MAX_FILES, "UPDATE_READER_FILE_LIMIT"); let held = Protected::open(Path::new(path))?; ensure!( held.proof == *expected, "UPDATE_READER_UNIT_ORIGINAL_CHANGED" ); seen.insert(path.clone(), expected.clone()); protected.push(held); } } let result = Self { registry, protected, policy_sha256: hash(&serde_json::to_vec(policy)?), }; result.verify_protected()?; Ok(result) } pub fn host_context(&self) -> &HostContext { &self.registry.host_context } pub fn verify_protected(&self) -> Result<()> { for file in &self.protected { file.verify()?; } Ok(()) } pub fn verify_admission(&self, policy: &LocalUpdatePolicy, budget: &Budget) -> Result<()> { self.verify_phase(policy, budget, false, None) } pub fn verify_stopped(&self, policy: &LocalUpdatePolicy, budget: &Budget) -> Result<()> { self.verify_phase(policy, budget, true, None) } pub fn verify_known_failure_stopped( &self, policy: &LocalUpdatePolicy, stopped: &rmm_updater_linux::services::StoppedServices, budget: &Budget, ) -> Result<()> { let source = stopped.early_full_failure(budget)?; self.verify_phase(policy, budget, true, Some(source.failure()))?; stopped.early_full_failure(budget)?; Ok(()) } fn verify_phase( &self, policy: &LocalUpdatePolicy, budget: &Budget, stopped: bool, failed: Option<&rmm_updater_linux::services::FailedStartProof>, ) -> Result<()> { budget.check()?; self.verify_protected()?; ensure!( hash(&serde_json::to_vec(policy)?) == self.policy_sha256, "UPDATE_READER_POLICY_CHANGED" ); ensure!( current_host_context()? == self.registry.host_context, "UPDATE_READER_HOST_CONTEXT_CHANGED" ); let first_names = rollback_names(budget)?; let allowed: BTreeSet<_> = self .registry .rollback_timers .iter() .map(|u| u.unit.as_str()) .collect(); ensure!( first_names .iter() .all(|name| allowed.contains(name.as_str())), "UPDATE_READER_UNKNOWN_ROLLBACK_TIMER" ); let mut first = BTreeMap::new(); for (index, unit) in self.registry.units.iter().enumerate() { let active = index < 4 && (!stopped || index == 3); let status = observe(unit, budget)?; if let Some(failure) = failed.filter(|f| f.service.unit() == unit.unit) { ensure!( stopped && index < 3 && !active, "UPDATE_FAILED_READER_SCOPE" ); status.verify_known_failed(unit, failure)?; } else { status.verify(unit, active, index < 4)?; } first.insert(unit.unit.clone(), status); } for unit in &self.registry.rollback_timers { let status = observe(unit, budget)?; status.verify(unit, false, false)?; first.insert(unit.unit.clone(), status); } // Structural trigger names are not an assertion that a source is live. // Every exact registered relevant source is independently closed below. for unit in self .registry .units .iter() .chain(&self.registry.rollback_timers) { if !unit.triggers.is_empty() { ensure!( first[&unit.unit].closed(), "UPDATE_READER_ACTIVATION_SOURCE_OPEN" ); } for name in &unit.triggered_by { ensure!( first.get(name).is_some_and(|source| source.closed()), "UPDATE_READER_ACTIVATION_PATH_OPEN" ); } } ensure!( rollback_names(budget)? == first_names, "UPDATE_READER_ROLLBACK_TIMER_SET_CHANGED" ); self.verify_protected()?; for unit in self .registry .units .iter() .chain(&self.registry.rollback_timers) { ensure!( observe(unit, budget)? == first[&unit.unit], "UPDATE_READER_STATUS_CHANGED" ); } ensure!( current_host_context()? == self.registry.host_context, "UPDATE_READER_HOST_CONTEXT_CHANGED" ); self.verify_protected()?; budget.check() } } fn fixed_units() -> Vec { let mut names = SERVICES.iter().map(|s| s.to_string()).collect::>(); for name in SERVICES { let base = name.strip_suffix(".service").expect("fixed service"); for suffix in ["socket", "timer"] { names.push(format!("{base}.{suffix}")); } } names } fn rollback(name: &str) -> bool { let Some(value) = name .strip_prefix("rmm-general-startup-rollback-") .and_then(|s| s.strip_suffix(".timer")) else { return false; }; uuid::Uuid::parse_str(value) .is_ok_and(|id| id.get_version_num() == 4 && id.to_string() == value) } fn validate_registry(registry: &Registry, policy: &LocalUpdatePolicy) -> Result<()> { ensure!( registry.schema_version == 1 && registry.profile == "linux_shared_readers_v1" && registry.reader_contract_sha256 == reader_contract_sha256(), "UPDATE_READER_REGISTRY_PROFILE" ); let baseline = policy .initial_baseline .decode() .map_err(anyhow::Error::msg)?; let ActivationEvidence::Bootstrap { qualification_receipt_sha256, } = baseline.record.activation_evidence else { anyhow::bail!("UPDATE_READER_INITIAL_BOOTSTRAP_REQUIRED"); }; ensure!( digest(®istry.bootstrap_receipt_sha256) && registry.bootstrap_receipt_sha256 == qualification_receipt_sha256, "UPDATE_READER_BOOTSTRAP_RECEIPT" ); let host = ®istry.host_context; ensure!( [ host.proc_inode, host.user_namespace_inode, host.pid_namespace_inode, host.cgroup_namespace_inode ] .iter() .all(|n| *n > 0), "UPDATE_READER_HOST_CONTEXT_SHAPE" ); ensure!( registry .units .iter() .map(|u| u.unit.clone()) .eq(fixed_units()) && registry.rollback_timers.len() <= MAX_ROLLBACK, "UPDATE_READER_CLOSED_UNIT_SET" ); let mut all: BTreeSet = fixed_units().into_iter().collect(); let mut previous = None; for unit in ®istry.rollback_timers { ensure!( rollback(&unit.unit) && previous .as_ref() .is_none_or(|old: &String| old < &unit.unit) && all.insert(unit.unit.clone()), "UPDATE_READER_ROLLBACK_NAMES" ); previous = Some(unit.unit.clone()); } let mut total = 0; for (index, unit) in registry .units .iter() .chain(®istry.rollback_timers) .enumerate() { let active = index < 4; ensure!( unit.composition.len() <= 17 && ((!unit.composition.is_empty() && if active { matches!(unit.unit_file_state.as_str(), "enabled" | "disabled") } else { unit.unit_file_state == "disabled" }) || (!active && unit.composition.is_empty() && unit.unit_file_state.is_empty())), "UPDATE_READER_UNIT_STATE_SHAPE" ); let mut paths = BTreeSet::new(); for (position, (path, proof)) in unit.composition.iter().enumerate() { let filename = Path::new(path).file_name().and_then(|name| name.to_str()); ensure!( if position == 0 { filename == Some(unit.unit.as_str()) } else { filename.is_some_and(|name| name.ends_with(".conf")) }, "UPDATE_READER_UNIT_LEAF_NAME" ); ensure!( unit_path(path) && paths.insert(path) && proof.identity.uid == 0 && proof.identity.inode > 0 && proof.identity.links > 0 && proof.identity.mode & libc::S_IFMT == libc::S_IFREG && proof.identity.mode & 0o022 == 0 && proof.bytes <= MAX_BYTES && digest(&proof.sha256), "UPDATE_READER_UNIT_PROOF_SHAPE" ); total += 1; } for names in [&unit.triggers, &unit.triggered_by] { ensure!( names.len() <= 32 && names.windows(2).all(|pair| pair[0] < pair[1]) && names.iter().all(|name| all.contains(name)), "UPDATE_READER_UNKNOWN_ACTIVATION_RELATION" ); } if unit.composition.is_empty() { ensure!( unit.triggers.is_empty() && unit.triggered_by.is_empty(), "UPDATE_READER_ABSENT_RELATIONS" ); } let pin = if index < 3 { Some(&policy.services[index]) } else if index == 3 { Some(&policy.updater_service) } else if index == 4 { policy.services.get(3) } else { None }; if let Some(pin) = pin { ensure!( pin.unit == unit.unit && !unit.composition.is_empty() && hash(&serde_json::to_vec(&unit.composition)?) == pin.unit_sha256, "UPDATE_READER_POLICY_UNIT_COMPOSITION" ); } if index == 4 && policy.services.len() == 3 { ensure!( unit.composition.is_empty(), "UPDATE_READER_APT_NOT_IN_POLICY" ); } } ensure!(total <= MAX_FILES, "UPDATE_READER_FILE_LIMIT"); Ok(()) } fn unit_path(value: &str) -> bool { value.len() <= 4096 && value.starts_with('/') && value .split('/') .skip(1) .all(|part| !part.is_empty() && part != "." && part != "..") && value.bytes().all(|b| b.is_ascii_graphic() && b != b'\\') && [ "/etc/systemd/system/", "/usr/lib/systemd/system/", "/lib/systemd/system/", "/run/systemd/system/", "/run/systemd/transient/", ] .iter() .any(|root| value.starts_with(root)) } #[derive(Clone, Debug, PartialEq, Eq)] struct Status { fields: BTreeMap, main_pid: Option, control_pid: Option, connections: Option, } const GENERIC: [&str; 11] = [ "Id", "LoadState", "ActiveState", "SubState", "InvocationID", "UnitFileState", "FragmentPath", "DropInPaths", "Triggers", "TriggeredBy", "Job", ]; impl Status { fn parse(unit: &str, raw: &[u8]) -> Result { ensure!( raw.len() <= 16384 && raw.is_ascii(), "UPDATE_READER_STATUS_LIMIT" ); let text = std::str::from_utf8(raw).map_err(|_| anyhow::anyhow!("UPDATE_READER_STATUS_CODEC"))?; let mut fields: BTreeMap = BTreeMap::new(); let mut permitted = GENERIC.to_vec(); if unit.ends_with(".service") { permitted.extend(["MainPID", "ControlPID"]); } else if unit.ends_with(".socket") { permitted.extend(["ControlPID", "NConnections"]); } for line in text.lines() { let (key, value) = line.split_once('=').context("UPDATE_READER_STATUS_CODEC")?; ensure!( permitted.contains(&key) && fields.insert(key.into(), value.into()).is_none(), "UPDATE_READER_STATUS_FIELDS" ); } ensure!( GENERIC.iter().all(|key| fields.contains_key(*key)) && fields["Id"] == unit, "UPDATE_READER_STATUS_INCOMPLETE" ); let loaded = fields["LoadState"] == "loaded"; let number = |key: &str, required: bool| -> Result> { match fields.get(key) { Some(value) => { ensure!( !value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()), "UPDATE_READER_PID_CODEC" ); Ok(Some( value .parse() .map_err(|_| anyhow::anyhow!("UPDATE_READER_PID_RANGE"))?, )) } None => { ensure!(!required, "UPDATE_READER_MISSING_PID_PROPERTY"); Ok(None) } } }; let main_pid = number("MainPID", loaded && unit.ends_with(".service"))?; let control_pid = number("ControlPID", loaded && !unit.ends_with(".timer"))?; let connections = number("NConnections", loaded && unit.ends_with(".socket"))?; Ok(Self { fields, main_pid, control_pid, connections, }) } fn closed(&self) -> bool { self.fields["ActiveState"] == "inactive" && self.fields["SubState"] == "dead" && self.main_pid.is_none_or(|n| n == 0) && self.control_pid.is_none_or(|n| n == 0) && self.connections.is_none_or(|n| n == 0) && self.fields["Job"].is_empty() } fn verify_known_failed( &self, unit: &Unit, failure: &rmm_updater_linux::services::FailedStartProof, ) -> Result<()> { let f = &self.fields; ensure!( !unit.composition.is_empty() && failure.service.unit() == unit.unit && f["ActiveState"] == "failed" && f["SubState"] == "failed" && self.main_pid == Some(0) && self.control_pid == Some(0) && f["Job"].is_empty() && f["LoadState"] == "loaded" && f["UnitFileState"] == unit.unit_file_state && relations(&f["Triggers"])? == unit.triggers && relations(&f["TriggeredBy"])? == unit.triggered_by, "UPDATE_FAILED_READER_NOT_CLOSED" ); let mut paths = vec![f["FragmentPath"].as_str()]; paths.extend(f["DropInPaths"].split_ascii_whitespace()); ensure!( paths .into_iter() .eq(unit.composition.iter().map(|(p, _)| p.as_str())), "UPDATE_FAILED_READER_UNIT_CHANGED" ); for (key, value) in &failure.status { if let Some(actual) = f.get(key) { ensure!(actual == value, "UPDATE_FAILED_READER_STATUS_CHANGED"); } } Ok(()) } fn verify(&self, unit: &Unit, active: bool, original_reader: bool) -> Result<()> { let fields = &self.fields; ensure!( fields["UnitFileState"] == unit.unit_file_state && relations(&fields["Triggers"])? == unit.triggers && relations(&fields["TriggeredBy"])? == unit.triggered_by, "UPDATE_READER_UNIT_RELATIONS_CHANGED" ); if unit.composition.is_empty() { ensure!( !active && fields["LoadState"] == "not-found" && fields["FragmentPath"].is_empty() && fields["DropInPaths"].is_empty() && self.closed(), "UPDATE_READER_ABSENT_UNIT_CHANGED" ); } else { ensure!( fields["LoadState"] == "loaded", "UPDATE_READER_UNIT_NOT_LOADED" ); let mut paths = vec![fields["FragmentPath"].as_str()]; paths.extend(fields["DropInPaths"].split_ascii_whitespace()); ensure!( paths .iter() .copied() .eq(unit.composition.iter().map(|(path, _)| path.as_str())), "UPDATE_READER_UNIT_COMPOSITION_CHANGED" ); if active { ensure!( fields["ActiveState"] == "active" && fields["SubState"] == "running" && self.main_pid.is_some_and(|pid| pid > 1) && self.control_pid == Some(0) && fields["Job"].is_empty() && fields["InvocationID"].len() == 32 && fields["InvocationID"] .bytes() .all(|b| b.is_ascii_hexdigit()) && fields["InvocationID"].bytes().any(|b| b != b'0'), "UPDATE_READER_ACTIVE_REQUIRED" ); } else { ensure!( (original_reader || unit.unit_file_state == "disabled") && self.closed(), "UPDATE_READER_UNIT_NOT_CLOSED" ); } } Ok(()) } } fn relations(value: &str) -> Result> { let mut names = value .split_ascii_whitespace() .map(str::to_owned) .collect::>(); ensure!(names.len() <= 32, "UPDATE_READER_RELATION_LIMIT"); names.sort(); ensure!( names.windows(2).all(|pair| pair[0] < pair[1]), "UPDATE_READER_DUPLICATE_RELATION" ); Ok(names) } fn observe(unit: &Unit, budget: &Budget) -> Result { let mut properties = GENERIC.to_vec(); if unit.unit.ends_with(".service") { properties.extend(["MainPID", "ControlPID"]); } else if unit.unit.ends_with(".socket") { properties.extend(["ControlPID", "NConnections"]); } let property = format!("--property={}", properties.join(",")); let raw = command(&["show", "--all", &property, "--", &unit.unit], budget)?; Status::parse(&unit.unit, &raw) } fn rollback_names(budget: &Budget) -> Result> { let mut names = BTreeSet::new(); for args in [ vec![ "list-units", "--all", "--plain", "--no-legend", "--type=timer", "--", ROLLBACK_PATTERN, ], vec!["list-unit-files", "--no-legend", "--", ROLLBACK_PATTERN], ] { let raw = command(&args, budget)?; ensure!(raw.is_ascii(), "UPDATE_READER_TIMER_LIST_CODEC"); for line in std::str::from_utf8(&raw) .map_err(|_| anyhow::anyhow!("UPDATE_READER_TIMER_LIST_CODEC"))? .lines() { let name = line .split_ascii_whitespace() .next() .context("UPDATE_READER_TIMER_LIST_CODEC")?; ensure!( rollback(name) && names.len() < MAX_ROLLBACK + 1, "UPDATE_READER_TIMER_LIST_LIMIT" ); names.insert(name.to_owned()); } } Ok(names) } struct OwnedCommand { child: Child, pidfd: std::fs::File, } impl Drop for OwnedCommand { fn drop(&mut self) { unsafe { libc::syscall( libc::SYS_pidfd_send_signal, self.pidfd.as_raw_fd(), libc::SIGKILL, 0usize, 0, ) }; let _ = self.child.wait(); } } fn drain(stream: &mut dyn Read, raw: &mut Vec) -> Result<()> { let mut chunk = [0; 1024]; loop { match stream.read(&mut chunk) { Ok(0) => break, Ok(count) => { ensure!( raw.len() + count <= 16384, "UPDATE_READER_COMMAND_OUTPUT_LIMIT" ); raw.extend_from_slice(&chunk[..count]); } Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => break, Err(_) => anyhow::bail!("UPDATE_READER_COMMAND_READ"), } } Ok(()) } fn command(args: &[&str], budget: &Budget) -> Result> { budget.check()?; let child = Command::new("/usr/bin/systemctl") .args(["--system", "--no-ask-password", "--no-pager", "--full"]) .args(args) .env_clear() .env("PATH", "/usr/bin:/bin") .env("LC_ALL", "C") .env("SYSTEMD_COLORS", "0") .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .map_err(|_| anyhow::anyhow!("UPDATE_READER_COMMAND_SPAWN"))?; let mut child = child; let pid = unsafe { libc::syscall(libc::SYS_pidfd_open, child.id(), 0) }; if pid < 0 { let _ = child.kill(); let _ = child.wait(); anyhow::bail!("UPDATE_READER_COMMAND_PIDFD"); } let mut owned = OwnedCommand { child, pidfd: unsafe { std::fs::File::from_raw_fd(pid as i32) }, }; let mut stdout = owned.child.stdout.take().context("UPDATE_READER_STDOUT")?; let mut stderr = owned.child.stderr.take().context("UPDATE_READER_STDERR")?; for fd in [stdout.as_raw_fd(), stderr.as_raw_fd()] { ensure!( unsafe { libc::fcntl(fd, libc::F_SETFL, libc::O_NONBLOCK) } >= 0, "UPDATE_READER_COMMAND_NONBLOCK" ); } let started = Instant::now(); let mut out = Vec::new(); let mut error = Vec::new(); loop { budget.check()?; ensure!( started.elapsed() < Duration::from_secs(10), "UPDATE_READER_COMMAND_TIMEOUT" ); drain(&mut stdout, &mut out)?; drain(&mut stderr, &mut error)?; if let Some(status) = owned .child .try_wait() .map_err(|_| anyhow::anyhow!("UPDATE_READER_COMMAND_WAIT"))? { drain(&mut stdout, &mut out)?; drain(&mut stderr, &mut error)?; ensure!( status.success() && error.is_empty(), "UPDATE_READER_SYSTEMD_FAILED" ); budget.check()?; return Ok(out); } thread::sleep(Duration::from_millis(2)); } } /// Public bootstrap metadata only. This does not publish policy, qualify a /// reader, start the updater or grant any update/job authority. The operator /// must bind the qualification receipt to actual freshly verified code/sync. #[derive(Serialize)] pub struct BootstrapMetadata { pub registry_bytes: Vec, pub reader_registry_sha256: String, pub services: Vec, pub updater_service: rmm_domain::agent_update_provisioning::LocalServicePin, } /// Read the actual fixed 21-unit closure AFTER compatible pair startup and /// installation of the still-stopped stable updater unit. Never invent file IDs /// or infer a registry from source unit text; retain each measured file until /// the second identical actual observation. No filesystem/SCM mutations. pub fn bootstrap_metadata( qualification_sha256: &str, budget: &Budget, ) -> Result { ensure!( digest(qualification_sha256) && unsafe { libc::geteuid() } == 0, "UPDATE_BOOTSTRAP_METADATA_SCOPE" ); let host_context = current_host_context()?; let first_rollback = rollback_names(budget)?; let names = fixed_units() .into_iter() .chain(first_rollback.iter().cloned()) .collect::>(); let mut retained = Vec::new(); let mut units = Vec::new(); let mut first = Vec::new(); for (index, name) in names.iter().enumerate() { let mut unit = Unit { unit: name.clone(), unit_file_state: String::new(), composition: Vec::new(), triggers: Vec::new(), triggered_by: Vec::new(), }; let status = observe(&unit, budget)?; let fields = &status.fields; unit.unit_file_state = fields["UnitFileState"].clone(); unit.triggers = relations(&fields["Triggers"])?; unit.triggered_by = relations(&fields["TriggeredBy"])?; ensure!( unit.triggers .iter() .chain(&unit.triggered_by) .all(|n| names.contains(n)), "UPDATE_BOOTSTRAP_UNKNOWN_ACTIVATION_RELATION" ); if fields["LoadState"] == "loaded" { let mut paths = vec![fields["FragmentPath"].as_str()]; paths.extend(fields["DropInPaths"].split_ascii_whitespace()); ensure!( !paths[0].is_empty() && paths.len() <= 17, "UPDATE_BOOTSTRAP_UNIT_PATHS" ); for (position, path) in paths.into_iter().enumerate() { let leaf = Path::new(path).file_name().and_then(|v| v.to_str()); ensure!( unit_path(path) && if position == 0 { leaf == Some(name.as_str()) } else { leaf.is_some_and(|v| v.ends_with(".conf")) }, "UPDATE_BOOTSTRAP_UNIT_PATH" ); let held = Protected::open(Path::new(path))?; unit.composition.push((path.into(), held.proof.clone())); retained.push(held); } } // The prospective updater is deliberately inactive until ALL protected // trust/baseline/retained material has been independently provisioned. status.verify(&unit, index < 3, index < 4)?; if index >= 4 && !unit.composition.is_empty() { ensure!( unit.unit_file_state == "disabled", "UPDATE_BOOTSTRAP_CLOSED_UNIT_AUTOSTART" ); } ensure!(retained.len() <= MAX_FILES, "UPDATE_BOOTSTRAP_FILE_LIMIT"); first.push(status); units.push(unit); } ensure!( units.len() == 21 + first_rollback.len() && !units[3].composition.is_empty(), "UPDATE_BOOTSTRAP_UPDATER_UNIT_REQUIRED" ); for (unit, status) in units.iter().zip(&first) { ensure!( observe(unit, budget)? == *status, "UPDATE_BOOTSTRAP_UNIT_CHANGED" ); } for held in &retained { held.verify()?; } ensure!( rollback_names(budget)? == first_rollback && current_host_context()? == host_context, "UPDATE_BOOTSTRAP_HOST_OR_TIMER_CHANGED" ); let pin = |unit: &Unit| -> Result { Ok(rmm_domain::agent_update_provisioning::LocalServicePin { unit: unit.unit.clone(), unit_sha256: hash(&serde_json::to_vec(&unit.composition)?), }) }; let mut services = units[..3].iter().map(pin).collect::>>()?; if !units[4].composition.is_empty() { services.push(pin(&units[4])?); } let updater_service = pin(&units[3])?; let rollback_timers = units.split_off(21); let registry = Registry { schema_version: 1, profile: "linux_shared_readers_v1".into(), bootstrap_receipt_sha256: qualification_sha256.into(), reader_contract_sha256: reader_contract_sha256(), host_context, units, rollback_timers, }; let registry_bytes = serde_json::to_vec(®istry)?; ensure!( registry_bytes.len() <= MAX_BYTES as usize, "UPDATE_BOOTSTRAP_REGISTRY_LIMIT" ); budget.check()?; Ok(BootstrapMetadata { reader_registry_sha256: hash(®istry_bytes), registry_bytes, services, updater_service, }) } #[cfg(test)] mod tests { use super::*; fn timer() -> Vec { b"Id=rmm-agent-remote.timer\nLoadState=loaded\nActiveState=inactive\nSubState=dead\nInvocationID=\nUnitFileState=disabled\nFragmentPath=/etc/systemd/system/rmm-agent-remote.timer\nDropInPaths=\nTriggers=rmm-agent-remote.service\nTriggeredBy=\nJob=\n".to_vec() } #[test] fn timer_without_process_interface_is_typed_but_missing_service_pid_or_pending_job_denies() { let raw = timer(); let status = Status::parse("rmm-agent-remote.timer", &raw).unwrap(); assert_eq!(status.main_pid, None); assert_eq!(status.control_pid, None); assert!(status.closed()); let pending = String::from_utf8(raw.clone()) .unwrap() .replace("Job=\n", "Job=123\n"); assert!( !Status::parse("rmm-agent-remote.timer", pending.as_bytes()) .unwrap() .closed() ); let service = String::from_utf8(raw.clone()) .unwrap() .replace("rmm-agent-remote.timer", "rmm-agent-remote.service"); assert!(Status::parse("rmm-agent-remote.service", service.as_bytes()).is_err()); let mut unknown = raw.clone(); unknown.extend_from_slice(b"MainPID=0\n"); assert!(Status::parse("rmm-agent-remote.timer", &unknown).is_err()); let mut duplicate = raw; duplicate.extend_from_slice(b"Job=\n"); assert!(Status::parse("rmm-agent-remote.timer", &duplicate).is_err()); assert!(rollback( "rmm-general-startup-rollback-11111111-1111-4111-8111-111111111111.timer" )); assert!(!rollback("rmm-general-startup-rollback-*.timer")); } }