This commit is contained in:
@@ -223,6 +223,8 @@ pub struct LocalUpdatePolicy {
|
||||
pub installed_record_path: String,
|
||||
pub keyring_path: String,
|
||||
pub health_pin_path: String,
|
||||
pub registry_path: String,
|
||||
pub reader_registry_sha256: String,
|
||||
pub services: Vec<LocalServicePin>,
|
||||
pub updater_service: LocalServicePin,
|
||||
pub updater_binary_sha256: String,
|
||||
@@ -254,6 +256,8 @@ impl LocalUpdatePolicy {
|
||||
&& self.installed_record_path == "/var/lib/rmm-agent-updater/installed-record.json"
|
||||
&& self.keyring_path == "/etc/rmm-agent-updater/keyring.json"
|
||||
&& self.health_pin_path == "/etc/rmm-agent-updater/health-key.json"
|
||||
&& self.registry_path == "/etc/rmm-agent-updater/reader-registry.json"
|
||||
&& digest(&self.reader_registry_sha256)
|
||||
&& (names == SERVICES
|
||||
|| names
|
||||
== [
|
||||
|
||||
@@ -0,0 +1,558 @@
|
||||
//! Complete current FD/maps observations plus exact known process generations.
|
||||
//! This is one half of admission, never a replacement for the independently
|
||||
//! qualified closed bootstrap/service registry or actual singleton/flock guard.
|
||||
use crate::{
|
||||
agent_startup::{BoundAgentLock, HeldAgentLock},
|
||||
census_process::{Proc, Stamp},
|
||||
reader_registry::QualifiedRegistry,
|
||||
retained::{RetainedSet, Retention},
|
||||
};
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use rmm_domain::jobs::hash;
|
||||
use rmm_updater_linux::{
|
||||
Budget,
|
||||
files::{Directory, Identity, LedgerGuard, LedgerIdentity},
|
||||
services::{HeldService, Service, ServiceProof, StoppedServices},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
fs::{File, OpenOptions},
|
||||
os::unix::fs::{MetadataExt, OpenOptionsExt},
|
||||
path::Path,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
const PATHS: [&str; 5] = [
|
||||
"/var/lib/rmm-agent-remote/journal.sqlite",
|
||||
"/var/lib/rmm-agent-remote/consumption.sqlite",
|
||||
"/var/lib/rmm-helper/consumption.sqlite",
|
||||
"/var/lib/rmm-helper/executor.lock",
|
||||
"/var/lib/rmm-agent-remote/agent.lock",
|
||||
];
|
||||
/// Raw metadata only. Authority requires equality with the separately protected
|
||||
/// compatible-bootstrap registry; own-namespace == PID1 alone is insufficient.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct HostContext {
|
||||
pub proc_device: u64,
|
||||
pub proc_inode: u64,
|
||||
pub user_namespace_device: u64,
|
||||
pub user_namespace_inode: u64,
|
||||
pub pid_namespace_device: u64,
|
||||
pub pid_namespace_inode: u64,
|
||||
pub cgroup_namespace_device: u64,
|
||||
pub cgroup_namespace_inode: u64,
|
||||
}
|
||||
pub fn current_host_context() -> Result<HostContext> {
|
||||
Proc::open()?.context()
|
||||
}
|
||||
struct Target {
|
||||
directory: Directory,
|
||||
file: File,
|
||||
identity: Identity,
|
||||
}
|
||||
/// Always the fixed three existing databases and two distinct existing locks.
|
||||
pub struct Targets {
|
||||
files: Vec<Target>,
|
||||
sha256: String,
|
||||
}
|
||||
impl Targets {
|
||||
pub fn bind(
|
||||
retained: &RetainedSet,
|
||||
ledger: &LedgerIdentity,
|
||||
agent: &BoundAgentLock,
|
||||
) -> Result<Self> {
|
||||
retained.verify()?;
|
||||
let specs = retained.specs();
|
||||
let mut files = Vec::new();
|
||||
for (index, path) in PATHS.iter().enumerate() {
|
||||
let expected = match index {
|
||||
3 => ledger.lock.clone(),
|
||||
4 => agent.identity().clone(),
|
||||
_ => {
|
||||
let spec = specs
|
||||
.iter()
|
||||
.find(|s| s.path == Path::new(path))
|
||||
.context("UPDATE_CENSUS_DATABASE_WITNESS_REQUIRED")?;
|
||||
ensure!(
|
||||
spec.retention == Retention::MutableDatabase,
|
||||
"UPDATE_CENSUS_DATABASE_WITNESS_REQUIRED"
|
||||
);
|
||||
if index == 2 {
|
||||
ensure!(
|
||||
spec.identity == ledger.ledger,
|
||||
"UPDATE_CENSUS_ROOT_LEDGER_CHANGED"
|
||||
);
|
||||
}
|
||||
spec.identity.clone()
|
||||
}
|
||||
};
|
||||
ensure!(
|
||||
expected.uid == if index < 2 || index == 4 { 993 } else { 0 }
|
||||
&& expected.mode & 0o022 == 0,
|
||||
"UPDATE_CENSUS_TARGET_PERMISSIONS"
|
||||
);
|
||||
let directory = Directory::open(
|
||||
Path::new(path)
|
||||
.parent()
|
||||
.context("UPDATE_CENSUS_TARGET_PARENT")?,
|
||||
expected.uid,
|
||||
true,
|
||||
)?;
|
||||
// O_PATH binds identity without reading any database/key contents.
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.custom_flags(libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC)
|
||||
.open(path)?;
|
||||
files.push(Target {
|
||||
directory,
|
||||
file,
|
||||
identity: expected,
|
||||
});
|
||||
}
|
||||
let sha256 = hash(&serde_json::to_vec(
|
||||
&files.iter().map(|t| &t.identity).collect::<Vec<_>>(),
|
||||
)?);
|
||||
let result = Self { files, sha256 };
|
||||
result.verify()?;
|
||||
Ok(result)
|
||||
}
|
||||
fn verify(&self) -> Result<()> {
|
||||
ensure!(self.files.len() == 5, "UPDATE_CENSUS_TARGET_SET");
|
||||
for (target, path) in self.files.iter().zip(PATHS) {
|
||||
target.directory.verify()?;
|
||||
let held = target.file.metadata()?;
|
||||
let named = std::fs::symlink_metadata(path)?;
|
||||
ensure!(
|
||||
held.is_file()
|
||||
&& named.is_file()
|
||||
&& !named.file_type().is_symlink()
|
||||
&& identity(&held) == target.identity
|
||||
&& identity(&named) == target.identity,
|
||||
"UPDATE_CENSUS_TARGET_REPLACED"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
struct Known {
|
||||
service: ServiceProof,
|
||||
stamp: Stamp,
|
||||
}
|
||||
/// Private observation, no Deserialize/Clone/caller completeness boolean.
|
||||
pub struct Admission {
|
||||
host: HostContext,
|
||||
targets_sha256: String,
|
||||
known: Vec<Known>,
|
||||
finished: Instant,
|
||||
summary: Summary,
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
struct Summary {
|
||||
schema_version: u32,
|
||||
phase: &'static str,
|
||||
targets_sha256: String,
|
||||
host_context_sha256: String,
|
||||
known_generations_sha256: String,
|
||||
pid_count: usize,
|
||||
fd_count: usize,
|
||||
map_count: usize,
|
||||
project_matches: Vec<Match>,
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
struct Match {
|
||||
pid: u32,
|
||||
birth: u64,
|
||||
target_indices: Vec<usize>,
|
||||
}
|
||||
pub struct Stopped {
|
||||
host: HostContext,
|
||||
targets_sha256: String,
|
||||
updater: ServiceProof,
|
||||
finished: Instant,
|
||||
summary: Summary,
|
||||
}
|
||||
pub struct ClosureInputs<'a, 'stopped> {
|
||||
pub targets: &'a Targets,
|
||||
pub root: &'a LedgerGuard<'stopped>,
|
||||
pub agent: &'a HeldAgentLock,
|
||||
pub stopped: &'a StoppedServices,
|
||||
pub updater: &'a HeldService,
|
||||
pub registry: &'a QualifiedRegistry,
|
||||
}
|
||||
/// The observed absence is retained only under continuously borrowed original
|
||||
/// singleton/flock guards. No freshness timestamp is renewed and no future
|
||||
/// noncooperating privileged process absence is claimed.
|
||||
pub struct ClosedReaders<'a, 'stopped> {
|
||||
proof: Stopped,
|
||||
input: ClosureInputs<'a, 'stopped>,
|
||||
}
|
||||
impl ClosedReaders<'_, '_> {
|
||||
pub fn verify(&self, budget: &Budget) -> Result<()> {
|
||||
self.input.registry.verify_protected()?;
|
||||
self.proof.verify_held(
|
||||
self.input.targets,
|
||||
self.input.root,
|
||||
self.input.agent,
|
||||
self.input.stopped,
|
||||
self.input.updater,
|
||||
budget,
|
||||
)
|
||||
}
|
||||
}
|
||||
impl Admission {
|
||||
pub fn sha256(&self) -> Result<String> {
|
||||
Ok(hash(&serde_json::to_vec(&self.summary)?))
|
||||
}
|
||||
/// Must be called again by the exact live original authorizer immediately
|
||||
/// before consumption; a passive persisted hash cannot stand in for it.
|
||||
pub fn verify_fresh(
|
||||
&self,
|
||||
targets: &Targets,
|
||||
known: &[&HeldService],
|
||||
budget: &Budget,
|
||||
) -> Result<()> {
|
||||
budget.check()?;
|
||||
ensure!(
|
||||
self.finished.elapsed() < Duration::from_secs(1)
|
||||
&& self.targets_sha256 == targets.sha256,
|
||||
"UPDATE_CENSUS_ADMISSION_STALE"
|
||||
);
|
||||
targets.verify()?;
|
||||
ensure!(
|
||||
known.len() == self.known.len(),
|
||||
"UPDATE_CENSUS_READER_SET_CHANGED"
|
||||
);
|
||||
let proc = Proc::open()?;
|
||||
ensure!(
|
||||
proc.context()? == self.host,
|
||||
"UPDATE_CENSUS_HOST_CONTEXT_CHANGED"
|
||||
);
|
||||
for (held, old) in known.iter().zip(&self.known) {
|
||||
held.verify(budget)?;
|
||||
ensure!(
|
||||
*held.proof() == old.service && proc.process(old.stamp.pid)?.stamp == old.stamp,
|
||||
"UPDATE_CENSUS_READER_GENERATION_CHANGED"
|
||||
);
|
||||
}
|
||||
targets.verify()?;
|
||||
budget.check()?;
|
||||
ensure!(
|
||||
self.finished.elapsed() < Duration::from_secs(1),
|
||||
"UPDATE_CENSUS_ADMISSION_STALE"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Stopped {
|
||||
pub fn bind<'a, 'stopped>(
|
||||
self,
|
||||
input: ClosureInputs<'a, 'stopped>,
|
||||
budget: &Budget,
|
||||
) -> Result<ClosedReaders<'a, 'stopped>> {
|
||||
input.registry.verify_protected()?;
|
||||
ensure!(
|
||||
*input.registry.host_context() == self.host,
|
||||
"UPDATE_CENSUS_REGISTRY_HOST_MISMATCH"
|
||||
);
|
||||
self.verify_fresh(
|
||||
input.targets,
|
||||
input.root,
|
||||
input.agent,
|
||||
input.stopped,
|
||||
input.updater,
|
||||
budget,
|
||||
)?;
|
||||
Ok(ClosedReaders { proof: self, input })
|
||||
}
|
||||
pub fn sha256(&self) -> Result<String> {
|
||||
Ok(hash(&serde_json::to_vec(&self.summary)?))
|
||||
}
|
||||
pub fn verify_fresh(
|
||||
&self,
|
||||
targets: &Targets,
|
||||
root: &LedgerGuard<'_>,
|
||||
agent: &HeldAgentLock,
|
||||
stopped: &StoppedServices,
|
||||
updater: &HeldService,
|
||||
budget: &Budget,
|
||||
) -> Result<()> {
|
||||
budget.check()?;
|
||||
ensure!(
|
||||
self.finished.elapsed() < Duration::from_secs(1)
|
||||
&& self.targets_sha256 == targets.sha256,
|
||||
"UPDATE_CENSUS_STOPPED_STALE"
|
||||
);
|
||||
self.verify_held(targets, root, agent, stopped, updater, budget)?;
|
||||
budget.check()?;
|
||||
ensure!(
|
||||
self.finished.elapsed() < Duration::from_secs(1),
|
||||
"UPDATE_CENSUS_STOPPED_STALE"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn verify_held(
|
||||
&self,
|
||||
targets: &Targets,
|
||||
root: &LedgerGuard<'_>,
|
||||
agent: &HeldAgentLock,
|
||||
stopped: &StoppedServices,
|
||||
updater: &HeldService,
|
||||
budget: &Budget,
|
||||
) -> Result<()> {
|
||||
targets.verify()?;
|
||||
root.verify_for_effect(budget)?;
|
||||
agent.verify()?;
|
||||
stopped.verify_still_stopped(budget)?;
|
||||
updater.verify(budget)?;
|
||||
ensure!(
|
||||
self.targets_sha256 == targets.sha256
|
||||
&& targets.files[2].identity == root.identity().ledger
|
||||
&& targets.files[3].identity == root.identity().lock
|
||||
&& targets.files[4].identity == *agent.identity()
|
||||
&& *updater.proof() == self.updater
|
||||
&& current_host_context()? == self.host,
|
||||
"UPDATE_CENSUS_HELD_CLOSURE_CHANGED"
|
||||
);
|
||||
targets.verify()?;
|
||||
budget.check()
|
||||
}
|
||||
}
|
||||
pub fn scan_admission(
|
||||
targets: &Targets,
|
||||
known: &[&HeldService],
|
||||
qualified_host: &HostContext,
|
||||
budget: &Budget,
|
||||
) -> Result<Admission> {
|
||||
ensure!(
|
||||
known.iter().map(|s| s.proof().service).eq([
|
||||
Service::Agent,
|
||||
Service::General,
|
||||
Service::Full,
|
||||
Service::Updater
|
||||
]),
|
||||
"UPDATE_CENSUS_KNOWN_READERS"
|
||||
);
|
||||
targets.verify()?;
|
||||
let proc = Proc::open()?;
|
||||
ensure!(
|
||||
proc.context()? == *qualified_host,
|
||||
"UPDATE_CENSUS_HOST_CONTEXT_UNQUALIFIED"
|
||||
);
|
||||
let mut saved = Vec::new();
|
||||
for held in known {
|
||||
held.verify(budget)?;
|
||||
let process = proc.process(held.proof().process.pid)?;
|
||||
proc.verify_known_namespace(&process.stamp)?;
|
||||
bind_process(&process.stamp, held.proof())?;
|
||||
saved.push(Known {
|
||||
service: held.proof().clone(),
|
||||
stamp: process.stamp,
|
||||
});
|
||||
}
|
||||
ensure!(
|
||||
saved
|
||||
.iter()
|
||||
.filter(|s| s.stamp.pid == std::process::id()
|
||||
&& matches!(s.service.service, Service::Full | Service::Updater))
|
||||
.count()
|
||||
== 1,
|
||||
"UPDATE_CENSUS_AUTHORIZER_PROCESS_REQUIRED"
|
||||
);
|
||||
let summary = scan(&proc, targets, &saved, &[], "admission", budget)?;
|
||||
let finished = Instant::now();
|
||||
for (held, old) in known.iter().zip(&saved) {
|
||||
held.verify(budget)?;
|
||||
ensure!(
|
||||
proc.process(old.stamp.pid)?.stamp == old.stamp,
|
||||
"UPDATE_CENSUS_READER_CHANGED"
|
||||
);
|
||||
}
|
||||
targets.verify()?;
|
||||
ensure!(
|
||||
finished.elapsed() < Duration::from_secs(1),
|
||||
"UPDATE_CENSUS_ADMISSION_STALE"
|
||||
);
|
||||
Ok(Admission {
|
||||
host: proc.context()?,
|
||||
targets_sha256: targets.sha256.clone(),
|
||||
known: saved,
|
||||
finished,
|
||||
summary,
|
||||
})
|
||||
}
|
||||
pub fn scan_stopped(
|
||||
targets: &Targets,
|
||||
admission: &Admission,
|
||||
root: &LedgerGuard<'_>,
|
||||
agent: &HeldAgentLock,
|
||||
stopped: &StoppedServices,
|
||||
updater: &HeldService,
|
||||
budget: &Budget,
|
||||
) -> Result<Stopped> {
|
||||
root.verify_for_effect(budget)?;
|
||||
agent.verify()?;
|
||||
stopped.verify_still_stopped(budget)?;
|
||||
updater.verify(budget)?;
|
||||
targets.verify()?;
|
||||
ensure!(
|
||||
admission.targets_sha256 == targets.sha256
|
||||
&& targets.files[2].identity == root.identity().ledger
|
||||
&& targets.files[3].identity == root.identity().lock
|
||||
&& targets.files[4].identity == *agent.identity()
|
||||
&& updater.proof().service == Service::Updater
|
||||
&& updater.proof().process.pid == std::process::id(),
|
||||
"UPDATE_CENSUS_STOPPED_LOCKS_OR_OWNER"
|
||||
);
|
||||
let old = stopped.proofs();
|
||||
ensure!(
|
||||
old.len() == 3
|
||||
&& old
|
||||
.iter()
|
||||
.zip(&admission.known)
|
||||
.all(|(s, k)| *s == k.service),
|
||||
"UPDATE_CENSUS_ORIGINAL_STOP_SET_CHANGED"
|
||||
);
|
||||
let original_updater = admission
|
||||
.known
|
||||
.last()
|
||||
.context("UPDATE_CENSUS_UPDATER_MISSING")?;
|
||||
ensure!(
|
||||
*updater.proof() == original_updater.service,
|
||||
"UPDATE_CENSUS_ORIGINAL_UPDATER_CHANGED"
|
||||
);
|
||||
let forbidden = admission.known[..3]
|
||||
.iter()
|
||||
.flat_map(|k| k.stamp.cgroup.iter().cloned())
|
||||
.collect::<Vec<_>>();
|
||||
let proc = Proc::open()?;
|
||||
ensure!(
|
||||
proc.context()? == admission.host,
|
||||
"UPDATE_CENSUS_HOST_CONTEXT_CHANGED"
|
||||
);
|
||||
proc.verify_known_namespace(&original_updater.stamp)?;
|
||||
let summary = scan(
|
||||
&proc,
|
||||
targets,
|
||||
std::slice::from_ref(original_updater),
|
||||
&forbidden,
|
||||
"stopped",
|
||||
budget,
|
||||
)?;
|
||||
let finished = Instant::now();
|
||||
root.verify_for_effect(budget)?;
|
||||
agent.verify()?;
|
||||
stopped.verify_still_stopped(budget)?;
|
||||
updater.verify(budget)?;
|
||||
targets.verify()?;
|
||||
ensure!(
|
||||
finished.elapsed() < Duration::from_secs(1),
|
||||
"UPDATE_CENSUS_STOPPED_STALE"
|
||||
);
|
||||
Ok(Stopped {
|
||||
host: admission.host.clone(),
|
||||
targets_sha256: targets.sha256.clone(),
|
||||
updater: updater.proof().clone(),
|
||||
finished,
|
||||
summary,
|
||||
})
|
||||
}
|
||||
fn scan(
|
||||
proc: &Proc,
|
||||
targets: &Targets,
|
||||
allowed: &[Known],
|
||||
forbidden_cgroups: &[String],
|
||||
phase: &'static str,
|
||||
budget: &Budget,
|
||||
) -> Result<Summary> {
|
||||
let began = Instant::now();
|
||||
let pids = proc.pids(budget)?;
|
||||
let ids = targets
|
||||
.files
|
||||
.iter()
|
||||
.map(|t| t.identity.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let mut summary = Summary {
|
||||
schema_version: 1,
|
||||
phase,
|
||||
targets_sha256: targets.sha256.clone(),
|
||||
host_context_sha256: hash(&serde_json::to_vec(&proc.context()?)?),
|
||||
known_generations_sha256: hash(&serde_json::to_vec(
|
||||
&allowed.iter().map(|k| &k.service).collect::<Vec<_>>(),
|
||||
)?),
|
||||
pid_count: pids.len(),
|
||||
fd_count: 0,
|
||||
map_count: 0,
|
||||
project_matches: Vec::new(),
|
||||
};
|
||||
for pid in &pids {
|
||||
budget.check()?;
|
||||
ensure!(
|
||||
began.elapsed() < Duration::from_secs(5),
|
||||
"UPDATE_CENSUS_TOTAL_DEADLINE"
|
||||
);
|
||||
let process = proc.process(*pid)?;
|
||||
let hits = process.inspect(&ids, budget)?;
|
||||
ensure!(
|
||||
!hits.task_cgroups.iter().any(|c| forbidden_cgroups
|
||||
.iter()
|
||||
.any(|old| c == old || c.starts_with(&(old.to_owned() + "/")))),
|
||||
"UPDATE_CENSUS_STOPPED_CGROUP_HAS_PROCESS"
|
||||
);
|
||||
summary.fd_count += hits.fd_count;
|
||||
summary.map_count += hits.map_count;
|
||||
let known = allowed.iter().find(|k| k.stamp.pid == *pid);
|
||||
if let Some(known) = known {
|
||||
ensure!(
|
||||
known.stamp == hits.stamp,
|
||||
"UPDATE_CENSUS_KNOWN_PROCESS_CHANGED"
|
||||
);
|
||||
}
|
||||
if !hits.descriptors.is_empty() || !hits.mappings.is_empty() {
|
||||
ensure!(known.is_some(), "UPDATE_CENSUS_UNKNOWN_READER");
|
||||
proc.verify_known_namespace(&hits.stamp)?;
|
||||
let mut indices = hits.descriptors;
|
||||
indices.extend(hits.mappings);
|
||||
indices.sort_unstable();
|
||||
indices.dedup();
|
||||
summary.project_matches.push(Match {
|
||||
pid: *pid,
|
||||
birth: hits.stamp.birth,
|
||||
target_indices: indices,
|
||||
});
|
||||
}
|
||||
}
|
||||
ensure!(
|
||||
proc.pids(budget)? == pids && began.elapsed() < Duration::from_secs(5),
|
||||
"UPDATE_CENSUS_INCOMPLETE_OR_CHANGED_PID_SET"
|
||||
);
|
||||
Ok(summary)
|
||||
}
|
||||
fn bind_process(stamp: &Stamp, service: &ServiceProof) -> Result<()> {
|
||||
ensure!(
|
||||
stamp.pid == service.process.pid
|
||||
&& stamp.birth == service.process.birth
|
||||
&& stamp.uid == service.process.uid
|
||||
&& stamp.gid == service.process.gid
|
||||
&& stamp.image.is_some(),
|
||||
"UPDATE_CENSUS_PINNED_PROCESS_CHANGED"
|
||||
);
|
||||
ensure!(
|
||||
stamp
|
||||
.cgroup
|
||||
.iter()
|
||||
.any(|p| p.rsplit('/').next() == Some(service.service.unit())),
|
||||
"UPDATE_CENSUS_SERVICE_CGROUP_UNBOUND"
|
||||
);
|
||||
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(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,697 @@
|
||||
//! Bounded kernel observations only. No command line/environment/key reads and
|
||||
//! no data from unrelated processes is returned. Not admission by itself.
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use rmm_updater_linux::{Budget, files::Identity};
|
||||
use std::{
|
||||
ffi::CString,
|
||||
fs::File,
|
||||
io::Read,
|
||||
os::{
|
||||
fd::{AsRawFd, FromRawFd},
|
||||
unix::fs::MetadataExt,
|
||||
},
|
||||
};
|
||||
|
||||
const MAX_PIDS: usize = 16384;
|
||||
const MAX_FDS: usize = 65536;
|
||||
const MAX_MAPS: usize = 8 * 1024 * 1024;
|
||||
const PROC_MAGIC: libc::c_long = 0x9fa0;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Namespace {
|
||||
pub device: u64,
|
||||
pub inode: u64,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Stamp {
|
||||
pub pid: u32,
|
||||
pub birth: u64,
|
||||
pub tgid: u32,
|
||||
pub uid: u32,
|
||||
pub gid: u32,
|
||||
pub image: Option<(u64, u64, i64, i64, i64, i64)>,
|
||||
pub cgroup: Vec<String>,
|
||||
pub user_ns: Namespace,
|
||||
pub pid_ns: Namespace,
|
||||
pub cgroup_ns: Namespace,
|
||||
}
|
||||
pub(crate) struct Process {
|
||||
pidfd: File,
|
||||
directory: File,
|
||||
pub stamp: Stamp,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Hits {
|
||||
pub stamp: Stamp,
|
||||
pub descriptors: Vec<usize>,
|
||||
pub mappings: Vec<usize>,
|
||||
pub fd_count: usize,
|
||||
pub task_cgroups: Vec<String>,
|
||||
pub map_count: usize,
|
||||
}
|
||||
|
||||
pub(crate) struct Proc {
|
||||
directory: File,
|
||||
user_ns: Namespace,
|
||||
pid_ns: Namespace,
|
||||
cgroup_ns: Namespace,
|
||||
}
|
||||
impl Proc {
|
||||
pub fn context(&self) -> Result<crate::census::HostContext> {
|
||||
let meta = self.directory.metadata()?;
|
||||
Ok(crate::census::HostContext {
|
||||
proc_device: meta.dev(),
|
||||
proc_inode: meta.ino(),
|
||||
user_namespace_device: self.user_ns.device,
|
||||
user_namespace_inode: self.user_ns.inode,
|
||||
pid_namespace_device: self.pid_ns.device,
|
||||
pid_namespace_inode: self.pid_ns.inode,
|
||||
cgroup_namespace_device: self.cgroup_ns.device,
|
||||
cgroup_namespace_inode: self.cgroup_ns.inode,
|
||||
})
|
||||
}
|
||||
pub fn open() -> Result<Self> {
|
||||
ensure!(
|
||||
unsafe { libc::geteuid() } == 0,
|
||||
"UPDATE_CENSUS_HOST_ROOT_REQUIRED"
|
||||
);
|
||||
let path = CString::new("/proc")?;
|
||||
let fd = unsafe {
|
||||
libc::open(
|
||||
path.as_ptr(),
|
||||
libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
|
||||
)
|
||||
};
|
||||
ensure!(fd >= 0, "UPDATE_CENSUS_PROC_OPEN");
|
||||
let directory = unsafe { File::from_raw_fd(fd) };
|
||||
let mut info = std::mem::MaybeUninit::<libc::statfs>::zeroed();
|
||||
ensure!(
|
||||
unsafe { libc::fstatfs(directory.as_raw_fd(), info.as_mut_ptr()) } == 0
|
||||
&& unsafe { info.assume_init() }.f_type == PROC_MAGIC,
|
||||
"UPDATE_CENSUS_PROC_FILESYSTEM"
|
||||
);
|
||||
ensure!(
|
||||
directory.metadata()?.uid() == 0 && directory.metadata()?.mode() & 0o022 == 0,
|
||||
"UPDATE_CENSUS_PROC_OWNER"
|
||||
);
|
||||
let group = open_dir(&directory, &std::process::id().to_string())?;
|
||||
let tasks = open_dir(&group, "task")?;
|
||||
let tid = unsafe { libc::syscall(libc::SYS_gettid) };
|
||||
ensure!(tid > 0, "UPDATE_CENSUS_CURRENT_TASK");
|
||||
let own = open_dir(&tasks, &tid.to_string())?;
|
||||
let own_stamp = stamp(&own, u32::try_from(tid)?)?;
|
||||
ensure!(
|
||||
own_stamp.tgid == std::process::id() && own_stamp.uid == 0,
|
||||
"UPDATE_CENSUS_CURRENT_TASK_NOT_HOST_ROOT"
|
||||
);
|
||||
let init = open_dir(&directory, "1")?;
|
||||
let user_ns = namespace(&own, "user")?;
|
||||
let pid_ns = namespace(&own, "pid")?;
|
||||
let cgroup_ns = namespace(&own, "cgroup")?;
|
||||
ensure!(
|
||||
namespace(&init, "user")? == user_ns && namespace(&init, "pid")? == pid_ns,
|
||||
"UPDATE_CENSUS_NAMESPACE_NOT_HOST_VIEW"
|
||||
);
|
||||
// A hidden/subset proc mount cannot prove a complete PID enumeration.
|
||||
// Paths are examined only in memory; no mountinfo content is exported.
|
||||
let raw = read(&own, "mountinfo", 256 * 1024)?;
|
||||
let text = std::str::from_utf8(&raw)?;
|
||||
let mut count = 0;
|
||||
for row in text.lines() {
|
||||
let (left, right) = row.split_once(" - ").context("UPDATE_CENSUS_MOUNTINFO")?;
|
||||
let left = left.split_ascii_whitespace().collect::<Vec<_>>();
|
||||
let right = right.split_ascii_whitespace().collect::<Vec<_>>();
|
||||
ensure!(
|
||||
left.len() >= 6 && right.len() >= 3,
|
||||
"UPDATE_CENSUS_MOUNTINFO"
|
||||
);
|
||||
if left[4] == "/proc" {
|
||||
count += 1;
|
||||
ensure!(
|
||||
left[3] == "/"
|
||||
&& right[0] == "proc"
|
||||
&& left[5]
|
||||
.split(',')
|
||||
.chain(right[2].split(','))
|
||||
.all(|v| matches!(
|
||||
v,
|
||||
"rw" | "ro"
|
||||
| "nosuid"
|
||||
| "nodev"
|
||||
| "noexec"
|
||||
| "relatime"
|
||||
| "strictatime"
|
||||
| "noatime"
|
||||
| "nodiratime"
|
||||
| "hidepid=0"
|
||||
| "hidepid=off"
|
||||
)),
|
||||
"UPDATE_CENSUS_HIDDEN_OR_UNKNOWN_PROC_OPTIONS"
|
||||
);
|
||||
}
|
||||
}
|
||||
ensure!(count == 1, "UPDATE_CENSUS_PROC_MOUNT_AMBIGUOUS");
|
||||
Ok(Self {
|
||||
directory,
|
||||
user_ns,
|
||||
pid_ns,
|
||||
cgroup_ns,
|
||||
})
|
||||
}
|
||||
pub fn pids(&self, budget: &Budget) -> Result<Vec<u32>> {
|
||||
let mut pids = Vec::new();
|
||||
for entry in std::fs::read_dir(format!(
|
||||
"/proc/thread-self/fd/{}",
|
||||
self.directory.as_raw_fd()
|
||||
))? {
|
||||
budget.check()?;
|
||||
let name = entry?.file_name();
|
||||
let Some(name) = name.to_str() else {
|
||||
anyhow::bail!("UPDATE_CENSUS_PROC_ENTRY")
|
||||
};
|
||||
if name.bytes().all(|v| v.is_ascii_digit()) {
|
||||
let pid: u32 = name.parse()?;
|
||||
ensure!(pid > 0 && pids.len() < MAX_PIDS, "UPDATE_CENSUS_PID_LIMIT");
|
||||
pids.push(pid);
|
||||
}
|
||||
}
|
||||
pids.sort_unstable();
|
||||
ensure!(
|
||||
!pids.is_empty() && !pids.windows(2).any(|w| w[0] == w[1]),
|
||||
"UPDATE_CENSUS_PID_SET"
|
||||
);
|
||||
Ok(pids)
|
||||
}
|
||||
pub fn process(&self, pid: u32) -> Result<Process> {
|
||||
ensure!(pid > 0, "UPDATE_CENSUS_PID");
|
||||
let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) };
|
||||
ensure!(fd >= 0, "UPDATE_CENSUS_PIDFD_UNAVAILABLE");
|
||||
let pidfd = unsafe { File::from_raw_fd(fd as i32) };
|
||||
let directory = open_dir(&self.directory, &pid.to_string())?;
|
||||
let stamp = stamp(&directory, pid)?;
|
||||
let result = Process {
|
||||
pidfd,
|
||||
directory,
|
||||
stamp,
|
||||
};
|
||||
result.verify()?;
|
||||
Ok(result)
|
||||
}
|
||||
pub fn verify_known_namespace(&self, stamp: &Stamp) -> Result<()> {
|
||||
ensure!(
|
||||
stamp.user_ns == self.user_ns
|
||||
&& stamp.pid_ns == self.pid_ns
|
||||
&& stamp.cgroup_ns == self.cgroup_ns,
|
||||
"UPDATE_CENSUS_READER_NAMESPACE_CHANGED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Process {
|
||||
pub 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
|
||||
&& stamp(&self.directory, self.stamp.pid)? == self.stamp,
|
||||
"UPDATE_CENSUS_PROCESS_CHANGED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
pub fn inspect(&self, targets: &[Identity], budget: &Budget) -> Result<Hits> {
|
||||
self.verify()?;
|
||||
let task_dir = open_dir(&self.directory, "task")?;
|
||||
let tids = task_ids(&task_dir, budget)?;
|
||||
let mut held_tasks = Vec::new();
|
||||
let mut descriptors = Vec::new();
|
||||
let mut fd_count = 0;
|
||||
let mut task_cgroups = Vec::new();
|
||||
for tid in &tids {
|
||||
self.verify()?;
|
||||
let directory = open_dir(&task_dir, &tid.to_string())?;
|
||||
let before = stamp(&directory, *tid)?;
|
||||
ensure!(
|
||||
before.tgid == self.stamp.pid,
|
||||
"UPDATE_CENSUS_TASK_GROUP_CHANGED"
|
||||
);
|
||||
let (hits, count) = inspect_fds(&directory, targets, budget)?;
|
||||
fd_count += count;
|
||||
ensure!(fd_count <= MAX_FDS, "UPDATE_CENSUS_TOTAL_FD_LIMIT");
|
||||
if !hits.is_empty() {
|
||||
ensure!(
|
||||
before.uid == self.stamp.uid
|
||||
&& before.gid == self.stamp.gid
|
||||
&& before.user_ns == self.stamp.user_ns
|
||||
&& before.pid_ns == self.stamp.pid_ns
|
||||
&& before.cgroup_ns == self.stamp.cgroup_ns,
|
||||
"UPDATE_CENSUS_READER_TASK_CONTEXT_CHANGED"
|
||||
);
|
||||
}
|
||||
descriptors.extend(hits);
|
||||
task_cgroups.extend(before.cgroup.iter().cloned());
|
||||
ensure!(
|
||||
stamp(&directory, *tid)? == before,
|
||||
"UPDATE_CENSUS_TASK_CHANGED"
|
||||
);
|
||||
// Retain each actual task directory until the complete probe ends;
|
||||
// a same-TID replacement cannot substitute a new task directory.
|
||||
held_tasks.push((directory, before));
|
||||
}
|
||||
let raw = read(&self.directory, "maps", MAX_MAPS)?;
|
||||
let text = std::str::from_utf8(&raw)?;
|
||||
let mut mappings = Vec::new();
|
||||
let mut map_count = 0;
|
||||
for row in text.lines() {
|
||||
budget.check()?;
|
||||
map_count += 1;
|
||||
ensure!(map_count <= 65536, "UPDATE_CENSUS_MAP_LIMIT");
|
||||
let mut fields = row.split_ascii_whitespace();
|
||||
for _ in 0..3 {
|
||||
fields.next().context("UPDATE_CENSUS_MAP_FIELDS")?;
|
||||
}
|
||||
let (major, minor) = fields
|
||||
.next()
|
||||
.context("UPDATE_CENSUS_MAP_DEVICE")?
|
||||
.split_once(':')
|
||||
.context("UPDATE_CENSUS_MAP_DEVICE")?;
|
||||
let device = libc::makedev(
|
||||
u32::from_str_radix(major, 16)?,
|
||||
u32::from_str_radix(minor, 16)?,
|
||||
);
|
||||
let inode: u64 = fields.next().context("UPDATE_CENSUS_MAP_INODE")?.parse()?;
|
||||
if inode != 0 {
|
||||
for (index, target) in targets.iter().enumerate() {
|
||||
if device == target.device && inode == target.inode {
|
||||
mappings.push(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
descriptors.sort_unstable();
|
||||
descriptors.dedup();
|
||||
mappings.sort_unstable();
|
||||
mappings.dedup();
|
||||
ensure!(
|
||||
task_ids(&task_dir, budget)? == tids,
|
||||
"UPDATE_CENSUS_TASK_SET_CHANGED"
|
||||
);
|
||||
for (directory, before) in held_tasks {
|
||||
ensure!(
|
||||
stamp(&directory, before.pid)? == before,
|
||||
"UPDATE_CENSUS_TASK_CHANGED"
|
||||
);
|
||||
}
|
||||
task_cgroups.sort();
|
||||
task_cgroups.dedup();
|
||||
self.verify()?;
|
||||
Ok(Hits {
|
||||
stamp: self.stamp.clone(),
|
||||
descriptors,
|
||||
mappings,
|
||||
fd_count,
|
||||
task_cgroups,
|
||||
map_count,
|
||||
})
|
||||
}
|
||||
}
|
||||
fn inspect_fds(
|
||||
directory: &File,
|
||||
targets: &[Identity],
|
||||
budget: &Budget,
|
||||
) -> Result<(Vec<usize>, usize)> {
|
||||
let fd_dir = open_dir(directory, "fd")?;
|
||||
let mut descriptors = Vec::new();
|
||||
let mut fd_count = 0;
|
||||
// Keep read_dir's descriptor alive while inspecting every magic link;
|
||||
// this also handles enumeration of our own descriptor without a gap.
|
||||
for entry in std::fs::read_dir(format!("/proc/thread-self/fd/{}", fd_dir.as_raw_fd()))? {
|
||||
budget.check()?;
|
||||
fd_count += 1;
|
||||
ensure!(fd_count <= MAX_FDS, "UPDATE_CENSUS_FD_LIMIT");
|
||||
let entry = entry?;
|
||||
let name = entry.file_name();
|
||||
let name = name.to_str().context("UPDATE_CENSUS_FD_NAME")?;
|
||||
ensure!(
|
||||
!name.is_empty() && name.bytes().all(|v| v.is_ascii_digit()),
|
||||
"UPDATE_CENSUS_FD_NAME"
|
||||
);
|
||||
let name = CString::new(name)?;
|
||||
let mut info = std::mem::MaybeUninit::<libc::stat>::zeroed();
|
||||
ensure!(
|
||||
unsafe { libc::fstatat(fd_dir.as_raw_fd(), name.as_ptr(), info.as_mut_ptr(), 0) } == 0,
|
||||
"UPDATE_CENSUS_INCOMPLETE_FD"
|
||||
);
|
||||
let info = unsafe { info.assume_init() };
|
||||
for (index, target) in targets.iter().enumerate() {
|
||||
if info.st_dev == target.device && info.st_ino == target.inode {
|
||||
descriptors.push(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((descriptors, fd_count))
|
||||
}
|
||||
fn task_ids(directory: &File, budget: &Budget) -> Result<Vec<u32>> {
|
||||
let mut ids = Vec::new();
|
||||
for entry in std::fs::read_dir(format!("/proc/thread-self/fd/{}", directory.as_raw_fd()))? {
|
||||
budget.check()?;
|
||||
let name = entry?.file_name();
|
||||
let text = name.to_str().context("UPDATE_CENSUS_TASK_NAME")?;
|
||||
ensure!(
|
||||
!text.is_empty() && text.bytes().all(|v| v.is_ascii_digit()) && ids.len() < 4096,
|
||||
"UPDATE_CENSUS_TASK_LIMIT"
|
||||
);
|
||||
ids.push(text.parse()?);
|
||||
}
|
||||
ids.sort_unstable();
|
||||
ensure!(
|
||||
!ids.is_empty() && !ids.windows(2).any(|w| w[0] == w[1]),
|
||||
"UPDATE_CENSUS_TASK_SET"
|
||||
);
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
fn open_dir(parent: &File, name: &str) -> Result<File> {
|
||||
let name = CString::new(name)?;
|
||||
let fd = unsafe {
|
||||
libc::openat(
|
||||
parent.as_raw_fd(),
|
||||
name.as_ptr(),
|
||||
libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
|
||||
)
|
||||
};
|
||||
ensure!(fd >= 0, "UPDATE_CENSUS_DIRECTORY_UNAVAILABLE");
|
||||
Ok(unsafe { File::from_raw_fd(fd) })
|
||||
}
|
||||
fn read(parent: &File, name: &str, max: usize) -> Result<Vec<u8>> {
|
||||
let name = CString::new(name)?;
|
||||
let fd = unsafe {
|
||||
libc::openat(
|
||||
parent.as_raw_fd(),
|
||||
name.as_ptr(),
|
||||
libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
|
||||
)
|
||||
};
|
||||
ensure!(fd >= 0, "UPDATE_CENSUS_PROC_DATA_UNAVAILABLE");
|
||||
let mut raw = Vec::new();
|
||||
unsafe { File::from_raw_fd(fd) }
|
||||
.take((max + 1) as u64)
|
||||
.read_to_end(&mut raw)?;
|
||||
ensure!(raw.len() <= max, "UPDATE_CENSUS_PROC_DATA_LIMIT");
|
||||
Ok(raw)
|
||||
}
|
||||
fn namespace(parent: &File, kind: &str) -> Result<Namespace> {
|
||||
let name = CString::new(format!("ns/{kind}"))?;
|
||||
let mut info = std::mem::MaybeUninit::<libc::stat>::zeroed();
|
||||
ensure!(
|
||||
unsafe { libc::fstatat(parent.as_raw_fd(), name.as_ptr(), info.as_mut_ptr(), 0) } == 0,
|
||||
"UPDATE_CENSUS_NAMESPACE_UNAVAILABLE"
|
||||
);
|
||||
let info = unsafe { info.assume_init() };
|
||||
Ok(Namespace {
|
||||
device: info.st_dev,
|
||||
inode: info.st_ino,
|
||||
})
|
||||
}
|
||||
fn stamp(parent: &File, pid: u32) -> Result<Stamp> {
|
||||
let raw = read(parent, "stat", 65536)?;
|
||||
let raw = std::str::from_utf8(&raw)?;
|
||||
let (_, fields) = raw.rsplit_once(") ").context("UPDATE_CENSUS_STAT")?;
|
||||
let fields = fields.split_ascii_whitespace().collect::<Vec<_>>();
|
||||
ensure!(fields.len() >= 20, "UPDATE_CENSUS_STAT");
|
||||
let birth = fields[19].parse()?;
|
||||
let flags: u64 = fields[6].parse()?;
|
||||
let raw = read(parent, "status", 65536)?;
|
||||
let text = std::str::from_utf8(&raw)?;
|
||||
let id = |label: &str| -> Result<u32> {
|
||||
let mut rows = text.lines().filter_map(|r| r.strip_prefix(label));
|
||||
let row = rows.next().context("UPDATE_CENSUS_CREDENTIALS")?;
|
||||
ensure!(rows.next().is_none(), "UPDATE_CENSUS_CREDENTIALS");
|
||||
let fields = row
|
||||
.split_ascii_whitespace()
|
||||
.map(str::parse)
|
||||
.collect::<std::result::Result<Vec<u32>, _>>()?;
|
||||
ensure!(
|
||||
fields.len() == 4 && fields.iter().all(|v| *v == fields[0]),
|
||||
"UPDATE_CENSUS_CHANGING_CREDENTIALS"
|
||||
);
|
||||
Ok(fields[0])
|
||||
};
|
||||
let uid = id("Uid:")?;
|
||||
let gid = id("Gid:")?;
|
||||
let mut tgids = text.lines().filter_map(|r| r.strip_prefix("Tgid:"));
|
||||
let tgid = tgids
|
||||
.next()
|
||||
.context("UPDATE_CENSUS_TASK_GROUP")?
|
||||
.trim()
|
||||
.parse()?;
|
||||
ensure!(tgids.next().is_none(), "UPDATE_CENSUS_TASK_GROUP");
|
||||
let name = CString::new("exe")?;
|
||||
let fd = unsafe {
|
||||
libc::openat(
|
||||
parent.as_raw_fd(),
|
||||
name.as_ptr(),
|
||||
libc::O_PATH | libc::O_CLOEXEC,
|
||||
)
|
||||
};
|
||||
let image = if fd >= 0 {
|
||||
let file = unsafe { File::from_raw_fd(fd) };
|
||||
let meta = file.metadata()?;
|
||||
ensure!(meta.is_file(), "UPDATE_CENSUS_PROCESS_IMAGE");
|
||||
Some((
|
||||
meta.dev(),
|
||||
meta.ino(),
|
||||
meta.mtime(),
|
||||
meta.mtime_nsec(),
|
||||
meta.ctime(),
|
||||
meta.ctime_nsec(),
|
||||
))
|
||||
} else {
|
||||
ensure!(
|
||||
std::io::Error::last_os_error().raw_os_error() == Some(libc::ENOENT)
|
||||
&& flags & 0x0020_0000 != 0,
|
||||
"UPDATE_CENSUS_PROCESS_IMAGE_UNAVAILABLE"
|
||||
);
|
||||
None
|
||||
};
|
||||
let raw = read(parent, "cgroup", 65536)?;
|
||||
let text = std::str::from_utf8(&raw)?;
|
||||
let mut cgroup = Vec::new();
|
||||
for line in text.lines() {
|
||||
let mut fields = line.splitn(3, ':');
|
||||
fields.next().context("UPDATE_CENSUS_CGROUP")?;
|
||||
fields.next().context("UPDATE_CENSUS_CGROUP")?;
|
||||
let path = fields.next().context("UPDATE_CENSUS_CGROUP")?;
|
||||
// Kernel cgroup paths are compared only as bounded opaque strings;
|
||||
// they are never used as filesystem paths. Host namespace authority
|
||||
// comes separately from the protected bootstrap registry.
|
||||
ensure!(
|
||||
path.starts_with('/') && path.len() <= 4096,
|
||||
"UPDATE_CENSUS_CGROUP"
|
||||
);
|
||||
cgroup.push(path.to_owned());
|
||||
}
|
||||
ensure!(
|
||||
!cgroup.is_empty() && cgroup.len() <= 64,
|
||||
"UPDATE_CENSUS_CGROUP"
|
||||
);
|
||||
Ok(Stamp {
|
||||
pid,
|
||||
birth,
|
||||
tgid,
|
||||
uid,
|
||||
gid,
|
||||
image,
|
||||
cgroup,
|
||||
user_ns: namespace(parent, "user")?,
|
||||
pid_ns: namespace(parent, "pid")?,
|
||||
cgroup_ns: namespace(parent, "cgroup")?,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::{
|
||||
fs::{self, OpenOptions},
|
||||
os::unix::fs::OpenOptionsExt,
|
||||
time::Duration,
|
||||
};
|
||||
#[test]
|
||||
fn private_thread_fd_table_cannot_hide_a_reader_from_the_group_probe() {
|
||||
assert_eq!(unsafe { libc::geteuid() }, 0);
|
||||
let path = std::path::Path::new("/run")
|
||||
.join(format!("rmm-census-thread-{}", uuid::Uuid::new_v4()));
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.mode(0o600)
|
||||
.open(&path)
|
||||
.unwrap();
|
||||
struct Cleanup(std::path::PathBuf);
|
||||
impl Drop for Cleanup {
|
||||
fn drop(&mut self) {
|
||||
fs::remove_file(&self.0).unwrap();
|
||||
}
|
||||
}
|
||||
let _cleanup = Cleanup(path.clone());
|
||||
let meta = file.metadata().unwrap();
|
||||
let target = Identity {
|
||||
device: meta.dev(),
|
||||
inode: meta.ino(),
|
||||
uid: meta.uid(),
|
||||
gid: meta.gid(),
|
||||
mode: meta.mode(),
|
||||
links: meta.nlink(),
|
||||
};
|
||||
let (ready, wait_ready) = std::sync::mpsc::channel();
|
||||
let (release, wait_release) = std::sync::mpsc::channel();
|
||||
let thread = std::thread::spawn(move || {
|
||||
// Only this owned fixture thread separates its descriptor table.
|
||||
// close_range(UNSHARE) is the same files-table operation without
|
||||
// Docker's unrelated unshare syscall gate. UINT_MAX cannot name
|
||||
// an open Linux fd, so no descriptor is closed. No namespace,
|
||||
// mount, machine policy, seccomp profile or service is changed.
|
||||
if unsafe {
|
||||
libc::syscall(
|
||||
libc::SYS_close_range,
|
||||
u32::MAX,
|
||||
u32::MAX,
|
||||
libc::CLOSE_RANGE_UNSHARE,
|
||||
)
|
||||
} != 0
|
||||
{
|
||||
ready
|
||||
.send(Err(std::io::Error::last_os_error().raw_os_error()))
|
||||
.unwrap();
|
||||
return;
|
||||
}
|
||||
let private = File::open(path).unwrap();
|
||||
ready.send(Ok(())).unwrap();
|
||||
let _ = wait_release.recv();
|
||||
drop(private);
|
||||
});
|
||||
struct Thread {
|
||||
release: Option<std::sync::mpsc::Sender<()>>,
|
||||
thread: Option<std::thread::JoinHandle<()>>,
|
||||
}
|
||||
impl Drop for Thread {
|
||||
fn drop(&mut self) {
|
||||
if let Some(tx) = self.release.take() {
|
||||
let _ = tx.send(());
|
||||
}
|
||||
if let Some(thread) = self.thread.take() {
|
||||
thread.join().unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
let thread = Thread {
|
||||
release: Some(release),
|
||||
thread: Some(thread),
|
||||
};
|
||||
assert_eq!(
|
||||
wait_ready.recv().unwrap(),
|
||||
Ok(()),
|
||||
"fixture requires close_range private-files-table support"
|
||||
);
|
||||
drop(file);
|
||||
let budget = Budget::new(
|
||||
fs::read_to_string("/proc/sys/kernel/random/boot_id")
|
||||
.unwrap()
|
||||
.trim()
|
||||
.parse()
|
||||
.unwrap(),
|
||||
Duration::from_secs(5),
|
||||
)
|
||||
.unwrap();
|
||||
let proc = Proc::open().unwrap();
|
||||
let process = proc.process(std::process::id()).unwrap();
|
||||
// Reproduces the incomplete TGID-only algorithm: no matching FD.
|
||||
assert!(
|
||||
inspect_fds(&process.directory, std::slice::from_ref(&target), &budget)
|
||||
.unwrap()
|
||||
.0
|
||||
.is_empty()
|
||||
);
|
||||
// The real complete probe must still find the reader's task table.
|
||||
let hits = process.inspect(&[target], &budget).unwrap();
|
||||
assert_eq!(hits.descriptors, [0]);
|
||||
assert!(hits.mappings.is_empty());
|
||||
drop(thread);
|
||||
}
|
||||
#[test]
|
||||
fn actual_proc_probe_detects_existing_descriptors_and_mapped_inode_without_exporting_paths() {
|
||||
// An isolated network-none container process, not a host-wide scan,
|
||||
// service/namespace qualification or admission-positive fixture.
|
||||
assert_eq!(unsafe { libc::geteuid() }, 0);
|
||||
let path =
|
||||
std::path::Path::new("/run").join(format!("rmm-census-probe-{}", uuid::Uuid::new_v4()));
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.mode(0o600)
|
||||
.open(&path)
|
||||
.unwrap();
|
||||
file.set_len(4096).unwrap();
|
||||
struct Cleanup(std::path::PathBuf);
|
||||
impl Drop for Cleanup {
|
||||
fn drop(&mut self) {
|
||||
fs::remove_file(&self.0).unwrap();
|
||||
}
|
||||
}
|
||||
let _cleanup = Cleanup(path);
|
||||
let meta = file.metadata().unwrap();
|
||||
let target = Identity {
|
||||
device: meta.dev(),
|
||||
inode: meta.ino(),
|
||||
uid: meta.uid(),
|
||||
gid: meta.gid(),
|
||||
mode: meta.mode(),
|
||||
links: meta.nlink(),
|
||||
};
|
||||
let budget = Budget::new(
|
||||
fs::read_to_string("/proc/sys/kernel/random/boot_id")
|
||||
.unwrap()
|
||||
.trim()
|
||||
.parse()
|
||||
.unwrap(),
|
||||
Duration::from_secs(5),
|
||||
)
|
||||
.unwrap();
|
||||
let proc = Proc::open().unwrap();
|
||||
let process = proc.process(std::process::id()).unwrap();
|
||||
let before = process
|
||||
.inspect(std::slice::from_ref(&target), &budget)
|
||||
.unwrap();
|
||||
assert_eq!(before.descriptors, [0]);
|
||||
assert!(before.mappings.is_empty());
|
||||
let pointer = unsafe {
|
||||
libc::mmap(
|
||||
std::ptr::null_mut(),
|
||||
4096,
|
||||
libc::PROT_READ,
|
||||
libc::MAP_PRIVATE,
|
||||
file.as_raw_fd(),
|
||||
0,
|
||||
)
|
||||
};
|
||||
assert_ne!(pointer, libc::MAP_FAILED);
|
||||
struct Mapping(*mut libc::c_void);
|
||||
impl Drop for Mapping {
|
||||
fn drop(&mut self) {
|
||||
assert_eq!(unsafe { libc::munmap(self.0, 4096) }, 0);
|
||||
}
|
||||
}
|
||||
let _mapping = Mapping(pointer);
|
||||
drop(file);
|
||||
let mapped = process.inspect(&[target], &budget).unwrap();
|
||||
assert!(mapped.descriptors.is_empty());
|
||||
assert_eq!(mapped.mappings, [0]);
|
||||
assert_eq!(before.stamp, mapped.stamp);
|
||||
}
|
||||
}
|
||||
@@ -4,12 +4,13 @@
|
||||
use crate::{
|
||||
agent_startup::BoundAgentLock,
|
||||
bridge::{BridgeContext, FullBridge, Generation},
|
||||
bundle,
|
||||
bundle, census,
|
||||
clock::NativeClock,
|
||||
fence::LedgerFence,
|
||||
ledger::{OwnedInputs, OwnedLedger},
|
||||
original::Original,
|
||||
participants::{StableParticipant, verify_original_helper},
|
||||
reader_registry::QualifiedRegistry,
|
||||
retained::RetainedSet,
|
||||
returned,
|
||||
trust::TrustState,
|
||||
@@ -21,7 +22,7 @@ use rmm_agent_core::{
|
||||
update_handoff::{NativeControlOperation, NativeEffect, NativeEffectClaim, NativeService},
|
||||
};
|
||||
use rmm_domain::{
|
||||
agent_update::{ParticipantIdentity, ParticipantRole, UpdateInflightProof},
|
||||
agent_update::{ParticipantIdentity, ParticipantRole},
|
||||
agent_update_provisioning::{HealthKeyPin, InstalledReleaseRecord, LocalUpdatePolicy},
|
||||
jobs::hash,
|
||||
};
|
||||
@@ -75,6 +76,7 @@ impl Protected {
|
||||
pub struct Runtime {
|
||||
binding: Binding,
|
||||
policy: LocalUpdatePolicy,
|
||||
registry: QualifiedRegistry,
|
||||
policy_sha256: String,
|
||||
installed: InstalledReleaseRecord,
|
||||
installed_sha256: String,
|
||||
@@ -91,12 +93,8 @@ pub struct Runtime {
|
||||
head: Option<String>,
|
||||
}
|
||||
struct Queued {
|
||||
agent_startup: BoundAgentLock,
|
||||
original: Original,
|
||||
witnesses: bundle::Loaded,
|
||||
trust: TrustState,
|
||||
header: bundle::Header,
|
||||
budget: Budget,
|
||||
proof: UpdateInflightProof,
|
||||
}
|
||||
impl Runtime {
|
||||
pub fn new(binding: Binding) -> Result<Self> {
|
||||
@@ -117,6 +115,7 @@ impl Runtime {
|
||||
let installed = InstalledReleaseRecord::from_bytes(&raw).map_err(anyhow::Error::msg)?;
|
||||
let installed_sha256 = hash(&raw);
|
||||
let old_policies = service_policies(&policy, &installed, None)?;
|
||||
let registry = QualifiedRegistry::load(&policy)?;
|
||||
let (health_file, raw) = Protected::read(&policy.health_pin_path, 4096)?;
|
||||
let health: HealthKeyPin = serde_json::from_slice(&raw)?;
|
||||
let health_key = health.public_key().map_err(anyhow::Error::msg)?;
|
||||
@@ -131,6 +130,7 @@ impl Runtime {
|
||||
Ok(Self {
|
||||
binding,
|
||||
policy,
|
||||
registry,
|
||||
policy_sha256,
|
||||
installed,
|
||||
installed_sha256,
|
||||
@@ -150,7 +150,7 @@ impl Runtime {
|
||||
/// A lost activation reply disables this live runtime before any stop.
|
||||
/// Drive is deliberately private: it cannot run inside Engine::handle.
|
||||
pub fn serve_one(&mut self, listener: &ipc::Listener) -> Result<()> {
|
||||
self.require_reader_registry_and_census()?;
|
||||
self.registry.verify_protected()?;
|
||||
ensure!(!self.failed && !self.terminal, "UPDATE_ENGINE_CLOSED");
|
||||
let services = Systemd::new(self.old_policies.clone())?;
|
||||
let budget = observation_budget()?;
|
||||
@@ -173,12 +173,6 @@ impl Runtime {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn require_reader_registry_and_census(&self) -> Result<()> {
|
||||
// This is an explicit source-checkpoint barrier, not a caller boolean
|
||||
// or a known-unit-list substitute. Replace only with the real protected
|
||||
// bootstrap registry + complete live FD/maps census and both locks.
|
||||
anyhow::bail!("UPDATE_READER_CENSUS_NOT_CONFIGURED")
|
||||
}
|
||||
fn enqueue(
|
||||
&mut self,
|
||||
peer: &ParticipantIdentity,
|
||||
@@ -216,17 +210,33 @@ impl Runtime {
|
||||
verify_original_helper(&services, &header.delegation, &budget)?;
|
||||
self.updater
|
||||
.verify_delegation(&header.delegation, &budget)?;
|
||||
let mut bridge = FullBridge::original(BridgeContext {
|
||||
handoff: &header.handoff,
|
||||
delegation: &header.delegation,
|
||||
services: &services,
|
||||
updater: &self.updater,
|
||||
clock: &self.clock,
|
||||
budget: &budget,
|
||||
health_public_key: self.health_key,
|
||||
generation: Generation::Original,
|
||||
})?;
|
||||
let reply = bridge.call(NativeControlOperation::ReadOriginal)?;
|
||||
// The original Full is still synchronously waiting for this reply.
|
||||
// Do not recursively query its socket or ledger in the Activate handler.
|
||||
self.queued = Some(Queued { header, budget });
|
||||
Ok(())
|
||||
}
|
||||
fn drive(&mut self, queued: Queued) -> Result<()> {
|
||||
let Queued { header, budget } = queued;
|
||||
for file in &self.protected {
|
||||
file.verify()?;
|
||||
}
|
||||
let services = Systemd::new(self.old_policies.clone())?;
|
||||
verify_original_helper(&services, &header.delegation, &budget)?;
|
||||
self.updater
|
||||
.verify_delegation(&header.delegation, &budget)?;
|
||||
let reply = {
|
||||
let mut bridge = FullBridge::original(BridgeContext {
|
||||
handoff: &header.handoff,
|
||||
delegation: &header.delegation,
|
||||
services: &services,
|
||||
updater: &self.updater,
|
||||
clock: &self.clock,
|
||||
budget: &budget,
|
||||
health_public_key: self.health_key,
|
||||
generation: Generation::Original,
|
||||
})?;
|
||||
bridge.call(NativeControlOperation::ReadOriginal)?
|
||||
};
|
||||
let proof = reply.proof.context("UPDATE_ENGINE_ORIGINAL_PROOF")?;
|
||||
let original = Original::verify(
|
||||
&self.binding,
|
||||
@@ -256,32 +266,19 @@ impl Runtime {
|
||||
witnesses.retained.verify()?;
|
||||
let agent_startup = BoundAgentLock::bind(&witnesses.retained)?;
|
||||
self.head = Some(proof.head_sha256.clone());
|
||||
self.queued = Some(Queued {
|
||||
agent_startup,
|
||||
original,
|
||||
witnesses,
|
||||
trust,
|
||||
budget,
|
||||
proof,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
fn drive(&mut self, queued: Queued) -> Result<()> {
|
||||
let Queued {
|
||||
agent_startup,
|
||||
original,
|
||||
witnesses,
|
||||
trust,
|
||||
budget,
|
||||
proof,
|
||||
} = queued;
|
||||
original.check_current(&self.binding, &self.clock, &budget)?;
|
||||
trust.recheck(&original, &self.clock)?;
|
||||
let services = Systemd::new(self.old_policies.clone())?;
|
||||
let old = [Service::Agent, Service::General, Service::Full]
|
||||
self.registry.verify_admission(&self.policy, &budget)?;
|
||||
let held = [Service::Agent, Service::General, Service::Full]
|
||||
.into_iter()
|
||||
.map(|s| services.observe(s, &budget).map(|h| h.proof().clone()))
|
||||
.map(|s| services.observe(s, &budget))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let known = vec![&held[0], &held[1], &held[2], self.updater.held_service()];
|
||||
let old = held.iter().map(|h| h.proof().clone()).collect::<Vec<_>>();
|
||||
let targets =
|
||||
census::Targets::bind(&witnesses.retained, &witnesses.ledger, &agent_startup)?;
|
||||
let admission =
|
||||
census::scan_admission(&targets, &known, self.registry.host_context(), &budget)?;
|
||||
let mut bridge = FullBridge::new(
|
||||
BridgeContext {
|
||||
handoff: original.handoff(),
|
||||
@@ -321,6 +318,10 @@ impl Runtime {
|
||||
updater: &self.updater,
|
||||
trust: &trust,
|
||||
retained: &witnesses.retained,
|
||||
registry: &self.registry,
|
||||
targets: &targets,
|
||||
admission: &admission,
|
||||
known: &known,
|
||||
claims,
|
||||
old,
|
||||
next: 0,
|
||||
@@ -331,8 +332,30 @@ impl Runtime {
|
||||
let claims = stop_fence.finish()?;
|
||||
let agent_startup = agent_startup.acquire(&stopped, &budget)?;
|
||||
let os = LedgerGuard::acquire(&stopped, &witnesses.ledger, &budget)?;
|
||||
self.registry.verify_stopped(&self.policy, &budget)?;
|
||||
let readers = census::scan_stopped(
|
||||
&targets,
|
||||
&admission,
|
||||
&os,
|
||||
&agent_startup,
|
||||
&stopped,
|
||||
self.updater.held_service(),
|
||||
&budget,
|
||||
)?;
|
||||
let readers = readers.bind(
|
||||
census::ClosureInputs {
|
||||
targets: &targets,
|
||||
root: &os,
|
||||
agent: &agent_startup,
|
||||
stopped: &stopped,
|
||||
updater: self.updater.held_service(),
|
||||
registry: &self.registry,
|
||||
},
|
||||
&budget,
|
||||
)?;
|
||||
let mut ledger = OwnedLedger::open(OwnedInputs {
|
||||
os: &os,
|
||||
readers: &readers,
|
||||
original: &original,
|
||||
binding: &self.binding,
|
||||
clock: &self.clock,
|
||||
@@ -391,6 +414,9 @@ impl Runtime {
|
||||
return Err(error);
|
||||
}
|
||||
let prepared = ledger.prepare_return_and_close()?;
|
||||
// The original DB is actually closed. End the continuous census/lock
|
||||
// borrow before the same concrete guard can be consumed by Return.
|
||||
drop(readers);
|
||||
let reservation = prepared.bind(returned::Inputs {
|
||||
original: &original,
|
||||
binding: &self.binding,
|
||||
@@ -490,6 +516,10 @@ struct StopFence<'a> {
|
||||
updater: &'a StableParticipant,
|
||||
trust: &'a TrustState,
|
||||
retained: &'a RetainedSet,
|
||||
registry: &'a QualifiedRegistry,
|
||||
targets: &'a census::Targets,
|
||||
admission: &'a census::Admission,
|
||||
known: &'a [&'a rmm_updater_linux::services::HeldService],
|
||||
claims: Vec<NativeEffectClaim>,
|
||||
old: Vec<ServiceProof>,
|
||||
next: usize,
|
||||
@@ -503,6 +533,7 @@ impl StopFence<'_> {
|
||||
self.updater
|
||||
.verify_delegation(self.original.delegation(), self.budget)?;
|
||||
self.trust.recheck(self.original, self.clock)?;
|
||||
self.registry.verify_protected()?;
|
||||
self.retained.verify()
|
||||
}
|
||||
fn finish(self) -> Result<Vec<NativeEffectClaim>> {
|
||||
@@ -522,6 +553,10 @@ impl DurableEffectFence for StopFence<'_> {
|
||||
);
|
||||
self.poisoned = true;
|
||||
self.current()?;
|
||||
if self.next == 0 {
|
||||
self.admission
|
||||
.verify_fresh(self.targets, self.known, self.budget)?;
|
||||
}
|
||||
let service = [Service::Agent, Service::General, Service::Full][self.next];
|
||||
let native = [
|
||||
NativeService::Agent,
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
//! OS guard confirms every reader stopped. This module performs no bootstrap,
|
||||
//! consumption, schema reset, outcome healing or readiness transition.
|
||||
use crate::{
|
||||
clock::NativeClock, files::FileWitnesses, original::Original, participants::StableParticipant,
|
||||
retained::RetainedSet, returned::PreparedReservation, trust::TrustState,
|
||||
census::ClosedReaders, clock::NativeClock, files::FileWitnesses, original::Original,
|
||||
participants::StableParticipant, retained::RetainedSet, returned::PreparedReservation,
|
||||
trust::TrustState,
|
||||
};
|
||||
use anyhow::{Result, ensure};
|
||||
use rmm_agent_core::{
|
||||
@@ -41,6 +42,7 @@ fn file_role(role: NativeFileRole) -> rmm_updater_handoff::FileRole {
|
||||
|
||||
pub struct OwnedGuard<'a, 'stopped> {
|
||||
os: &'a LedgerGuard<'stopped>,
|
||||
readers: &'a ClosedReaders<'a, 'stopped>,
|
||||
original: &'a Original,
|
||||
binding: &'a Binding,
|
||||
clock: &'a NativeClock,
|
||||
@@ -54,6 +56,7 @@ pub struct OwnedGuard<'a, 'stopped> {
|
||||
}
|
||||
pub struct OwnedInputs<'a, 'stopped> {
|
||||
pub os: &'a LedgerGuard<'stopped>,
|
||||
pub readers: &'a ClosedReaders<'a, 'stopped>,
|
||||
pub original: &'a Original,
|
||||
pub binding: &'a Binding,
|
||||
pub clock: &'a NativeClock,
|
||||
@@ -70,6 +73,7 @@ pub struct OwnedLedger<'a, 'stopped> {
|
||||
}
|
||||
impl<'a, 'stopped> OwnedLedger<'a, 'stopped> {
|
||||
pub fn open(input: OwnedInputs<'a, 'stopped>) -> Result<Self> {
|
||||
input.readers.verify(&observation_budget()?)?;
|
||||
input.os.verify_for_effect(&observation_budget()?)?;
|
||||
ensure!(
|
||||
input.os.identity().sha256()? == input.original.handoff().ledger_identity_sha256
|
||||
@@ -92,6 +96,7 @@ impl<'a, 'stopped> OwnedLedger<'a, 'stopped> {
|
||||
input.files.bind(input.original.handoff())?;
|
||||
let guard = OwnedGuard {
|
||||
os: input.os,
|
||||
readers: input.readers,
|
||||
original: input.original,
|
||||
binding: input.binding,
|
||||
clock: input.clock,
|
||||
@@ -290,6 +295,7 @@ impl<'a, 'stopped> OwnedLedger<'a, 'stopped> {
|
||||
impl ExecutorLedgerGuard for OwnedGuard<'_, '_> {
|
||||
fn check(&self, db: &Connection) -> Result<()> {
|
||||
let observation = observation_budget()?;
|
||||
self.readers.verify(&observation)?;
|
||||
self.os.verify_for_effect(&observation)?;
|
||||
ensure!(
|
||||
unsafe { db.handle() } as usize == self.sqlite_handle,
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
pub mod agent_startup;
|
||||
pub mod bridge;
|
||||
pub mod bundle;
|
||||
pub mod census;
|
||||
mod census_process;
|
||||
pub mod clock;
|
||||
pub mod engine;
|
||||
pub mod fence;
|
||||
@@ -13,6 +15,7 @@ pub mod history;
|
||||
pub mod ledger;
|
||||
pub mod original;
|
||||
pub mod participants;
|
||||
pub mod reader_registry;
|
||||
pub mod record;
|
||||
pub mod retained;
|
||||
pub mod returned;
|
||||
|
||||
@@ -43,6 +43,9 @@ impl StableParticipant {
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
pub fn held_service(&self) -> &HeldService {
|
||||
&self.held
|
||||
}
|
||||
pub fn identity(&self) -> &ParticipantIdentity {
|
||||
&self.identity
|
||||
}
|
||||
|
||||
@@ -0,0 +1,835 @@
|
||||
//! 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<Unit>,
|
||||
rollback_timers: Vec<Unit>,
|
||||
}
|
||||
#[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<String>,
|
||||
triggered_by: Vec<String>,
|
||||
}
|
||||
#[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<Self> {
|
||||
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<HeldFile>,
|
||||
path: PathBuf,
|
||||
proof: FileProof,
|
||||
stamp: Stamp,
|
||||
raw: Vec<u8>,
|
||||
}
|
||||
impl Protected {
|
||||
fn open(path: &Path) -> Result<Self> {
|
||||
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<Protected>,
|
||||
policy_sha256: String,
|
||||
}
|
||||
impl QualifiedRegistry {
|
||||
pub fn load(policy: &LocalUpdatePolicy) -> Result<Self> {
|
||||
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)
|
||||
}
|
||||
pub fn verify_stopped(&self, policy: &LocalUpdatePolicy, budget: &Budget) -> Result<()> {
|
||||
self.verify_phase(policy, budget, true)
|
||||
}
|
||||
fn verify_phase(
|
||||
&self,
|
||||
policy: &LocalUpdatePolicy,
|
||||
budget: &Budget,
|
||||
stopped: bool,
|
||||
) -> 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)?;
|
||||
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<String> {
|
||||
let mut names = SERVICES.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
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<String> = 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<String, String>,
|
||||
main_pid: Option<u32>,
|
||||
control_pid: Option<u32>,
|
||||
connections: Option<u32>,
|
||||
}
|
||||
const GENERIC: [&str; 11] = [
|
||||
"Id",
|
||||
"LoadState",
|
||||
"ActiveState",
|
||||
"SubState",
|
||||
"InvocationID",
|
||||
"UnitFileState",
|
||||
"FragmentPath",
|
||||
"DropInPaths",
|
||||
"Triggers",
|
||||
"TriggeredBy",
|
||||
"Job",
|
||||
];
|
||||
impl Status {
|
||||
fn parse(unit: &str, raw: &[u8]) -> Result<Self> {
|
||||
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<String, String> = 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<Option<u32>> {
|
||||
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(&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<Vec<String>> {
|
||||
let mut names = value
|
||||
.split_ascii_whitespace()
|
||||
.map(str::to_owned)
|
||||
.collect::<Vec<_>>();
|
||||
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<Status> {
|
||||
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<BTreeSet<String>> {
|
||||
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<u8>) -> 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<Vec<u8>> {
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn timer() -> Vec<u8> {
|
||||
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"));
|
||||
}
|
||||
}
|
||||
@@ -89,6 +89,12 @@ impl TrustState {
|
||||
"UPDATE_PROTECTED_POLICY_CHANGED"
|
||||
);
|
||||
protected.push(file);
|
||||
let (file, raw) = Protected::read(Path::new(&policy.registry_path), 65536)?;
|
||||
ensure!(
|
||||
hash(&raw) == policy.reader_registry_sha256,
|
||||
"UPDATE_PROTECTED_READER_REGISTRY_CHANGED"
|
||||
);
|
||||
protected.push(file);
|
||||
let (file, raw) = Protected::read(Path::new(&policy.keyring_path), 16384)?;
|
||||
let keys: UpdateKeyringFile = serde_json::from_slice(&raw)?;
|
||||
ensure!(
|
||||
|
||||
Reference in New Issue
Block a user