Bind updater reader registry and prove process census fixtures on cloud Linux
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
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!(
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Frozen ten-worker list, executing exactly two process-census guards only; no Apply.
|
||||
|
||||
Prepare copies the independently reviewed snapshot locally. Execute is one
|
||||
root-only Cloud-VM fixture run. After any lost reply read the original case;
|
||||
never execute it again or substitute another binary/source generation.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import uuid
|
||||
|
||||
import windows_msi_runtime_acceptance as support
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ACCESS_ROOT = ROOT.parent / 'rust-discovery'
|
||||
QUALIFICATION = ROOT / 'devstate/agent-updater-worker/reader-census-final-da31051b-269f-4fb5-947d-94c8ad162c2a'
|
||||
STATE = ROOT / 'devstate/updater-reader-census-linux'
|
||||
PROFILE = 'rmm.updater.two-process-census-guards.v1'
|
||||
RECEIPT_SHA = '9020992e888d0b22e71db88cab78f255e273be2a4a7856d43616b387c36c74ae'
|
||||
INPUTS_SHA = '382714b09349e448441345abbac6d99c0d523e98bdabaa78290b400768bac8f7'
|
||||
BINARY_SHA = 'e83fd334b005d81ac917389de2a1c7486bea3f62ae45d77bccbd331e131e4304'
|
||||
BINARY_BYTES = 7888096
|
||||
CENSUS_SOURCES = {'crates/updater-worker/src/census.rs': {'bytes': 17766, 'sha256': '5bee7f835c3b3c1f7e3a6afeeb1dc1fde780f1a6ca0d09a1bc85d897249e053c'}, 'crates/updater-worker/src/census_process.rs': {'bytes': 25024, 'sha256': 'f94b3032cee983fb01bfeb97a1cfc497fddcfd1e6f00e055d87269cc3f5dad5e'}, 'crates/updater-worker/src/reader_registry.rs': {'bytes': 29064, 'sha256': 'fc013cde406f4dac96a35df3852738b0ff84d912c4eeba401609b0d2b239d1b1'}}
|
||||
ALL_TESTS = ['agent_startup::tests::existing_agent_lock_blocks_aliases_and_rejects_samebyte_inode_substitution', 'census_process::tests::actual_proc_probe_detects_existing_descriptors_and_mapped_inode_without_exporting_paths', 'census_process::tests::private_thread_fd_table_cannot_hide_a_reader_from_the_group_probe', 'history::tests::completed_history_rejects_file_only_rollback_forks_and_tampered_activation_without_writes', 'history::tests::public_record_builder_binds_actual_original_key_and_exact_health_head', 'reader_registry::tests::timer_without_process_interface_is_typed_but_missing_service_pid_or_pending_job_denies', 'record::tests::same_byte_inode_substitution_and_foreign_current_block_without_resume', 'record::tests::separate_record_renames_preserve_original_inode_and_both_raw_archives', 'retained::tests::reopen_preserves_original_stamps_and_rejects_replaced_state_without_reading_keys', 'trust::tests::separately_signed_baseline_at_floor_is_historical_only_and_candidate_stays_strict']
|
||||
TESTS = ['census_process::tests::actual_proc_probe_detects_existing_descriptors_and_mapped_inode_without_exporting_paths', 'census_process::tests::private_thread_fd_table_cannot_hide_a_reader_from_the_group_probe']
|
||||
TEST_FILTER = 'census_process::tests::'
|
||||
AGENT_SHA = '0a7ad6eefaefda79ee80b6a41b2df904e9e7f50ae6ebeed01b98c25b6ce5c06f'
|
||||
HELPER_SHA = '79442727c3ba31cda02a8bc0e67481f14db9f39fc07520a880a90b64f10f1eaf'
|
||||
|
||||
|
||||
def sha(raw):
|
||||
return hashlib.sha256(raw).hexdigest()
|
||||
|
||||
|
||||
def save_local(path, value):
|
||||
support.save(path, value)
|
||||
fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def copy_exact(source, destination, digest, size):
|
||||
metadata = source.lstat()
|
||||
support.require(stat.S_ISREG(metadata.st_mode) and metadata.st_nlink == 1
|
||||
and metadata.st_uid in (0, os.getuid()) and not metadata.st_mode & 0o002
|
||||
and metadata.st_size == size and size <= 8 * 1024 * 1024, 'bounded regular frozen input')
|
||||
raw = source.read_bytes()
|
||||
support.require(sha(raw) == digest, 'frozen snapshot input hash')
|
||||
destination.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
support.private(destination.parent, True)
|
||||
fd = os.open(destination, os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 0o600)
|
||||
with os.fdopen(fd, 'wb') as stream:
|
||||
stream.write(raw); stream.flush(); os.fsync(stream.fileno())
|
||||
fd = os.open(destination.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def verify_case(folder):
|
||||
value = support.load(folder / 'manifest.json')
|
||||
support.require(value['profile'] == PROFILE and value['tests'] == TESTS and value['all_tests'] == ALL_TESTS
|
||||
and value['test_filter'] == TEST_FILTER
|
||||
and value['runner_sha256'] == sha(Path(__file__).read_bytes())
|
||||
and value['receipt_sha256'] == RECEIPT_SHA and value['binary_sha256'] == BINARY_SHA
|
||||
and value['binary_bytes'] == BINARY_BYTES, 'same original reviewed manifest')
|
||||
support.require(sha((folder / 'receipt.json').read_bytes()) == RECEIPT_SHA
|
||||
and sha((folder / 'inputs.json').read_bytes()) == INPUTS_SHA, 'original qualification provenance')
|
||||
source = support.load(folder / 'inputs.json')
|
||||
support.require(len(source) == 71 and source == value['source_files'], 'exact frozen 71 qualification inputs')
|
||||
for item in source:
|
||||
path = Path(item['path'])
|
||||
support.require(not path.is_absolute() and '..' not in path.parts, 'fixed snapshot relative path')
|
||||
file = folder / 'source' / path
|
||||
support.private(file)
|
||||
support.require(file.stat().st_size == item['bytes'] and sha(file.read_bytes()) == item['sha256'], 'retained source freeze')
|
||||
support.require({item['path']: dict(bytes=item['bytes'], sha256=item['sha256']) for item in source
|
||||
if item['path'] in CENSUS_SOURCES} == CENSUS_SOURCES, 'exact census and registry source snapshot')
|
||||
binary = folder / 'worker-census-tests'; support.private(binary)
|
||||
support.require(binary.stat().st_size == BINARY_BYTES and sha(binary.read_bytes()) == BINARY_SHA, 'original qualified test bytes')
|
||||
for path, digest in value['transport_sources'].items():
|
||||
support.require(sha((ROOT / path).read_bytes()) == digest, 'original strict transport source')
|
||||
return value
|
||||
|
||||
|
||||
def remote(p):
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import selectors
|
||||
import signal
|
||||
import stat
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
|
||||
def require(ok, message):
|
||||
if not ok:
|
||||
raise RuntimeError(message)
|
||||
|
||||
def enc(value):
|
||||
return json.dumps(value, sort_keys=True, separators=(',', ':')).encode()
|
||||
|
||||
def create(path, raw, mode=0o600):
|
||||
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode)
|
||||
with os.fdopen(fd, 'wb') as stream:
|
||||
stream.write(raw); stream.flush(); os.fsync(stream.fileno())
|
||||
fd = os.open(path.parent, os.O_DIRECTORY | os.O_RDONLY | os.O_NOFOLLOW)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
def run(args, timeout=20):
|
||||
# Keep the owned group leader unreaped until its entire group has been
|
||||
# cleaned up. Its PID therefore cannot be recycled before killpg.
|
||||
child = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, start_new_session=True,
|
||||
env={'PATH': '/usr/bin:/bin', 'LC_ALL': 'C', 'HOME': '/nonexistent'})
|
||||
selector = selectors.DefaultSelector()
|
||||
buffers = {'stdout': bytearray(), 'stderr': bytearray()}
|
||||
deadline = time.monotonic() + timeout
|
||||
try:
|
||||
for stream, name in ((child.stdout, 'stdout'), (child.stderr, 'stderr')):
|
||||
os.set_blocking(stream.fileno(), False); selector.register(stream, selectors.EVENT_READ, name)
|
||||
while True:
|
||||
require(time.monotonic() < deadline, 'owned native command timeout; read original case only')
|
||||
for key, _ in selector.select(0.02):
|
||||
raw = os.read(key.fileobj.fileno(), 4096)
|
||||
if raw:
|
||||
buffers[key.data].extend(raw)
|
||||
require(len(buffers[key.data]) <= 65536, 'bounded native output')
|
||||
else:
|
||||
selector.unregister(key.fileobj)
|
||||
ended = os.waitid(os.P_PID, child.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT)
|
||||
if ended is not None:
|
||||
# Child remains a zombie until finally: no PID/group reuse.
|
||||
os.killpg(child.pid, signal.SIGKILL)
|
||||
for key in list(selector.get_map().values()):
|
||||
while True:
|
||||
try:
|
||||
raw = os.read(key.fileobj.fileno(), 4096)
|
||||
except BlockingIOError:
|
||||
break
|
||||
if not raw:
|
||||
break
|
||||
buffers[key.data].extend(raw)
|
||||
require(len(buffers[key.data]) <= 65536, 'bounded native output')
|
||||
code = ended.si_status if ended.si_code == os.CLD_EXITED else -ended.si_status
|
||||
return code, bytes(buffers['stdout']), bytes(buffers['stderr'])
|
||||
finally:
|
||||
os.killpg(child.pid, signal.SIGKILL)
|
||||
child.wait()
|
||||
selector.close(); child.stdout.close(); child.stderr.close()
|
||||
|
||||
def metadata_identity(value):
|
||||
return (value.st_dev, value.st_ino, value.st_uid, value.st_gid, value.st_mode,
|
||||
value.st_nlink, value.st_size, value.st_mtime_ns, value.st_ctime_ns)
|
||||
|
||||
def hashed(path, maximum, process_image=False):
|
||||
fd = os.open(path, os.O_RDONLY | os.O_CLOEXEC | (0 if process_image else os.O_NOFOLLOW))
|
||||
with os.fdopen(fd, 'rb') as stream:
|
||||
before = os.fstat(stream.fileno()); require(stat.S_ISREG(before.st_mode) and before.st_size <= maximum, 'bounded witness file')
|
||||
digest = hashlib.sha256(); total = 0
|
||||
while True:
|
||||
raw = stream.read(32768)
|
||||
if not raw:
|
||||
break
|
||||
total += len(raw); require(total <= maximum, 'bounded witness hash'); digest.update(raw)
|
||||
after = os.fstat(stream.fileno())
|
||||
require(metadata_identity(before) == metadata_identity(after) and total == before.st_size, 'stable witness hash')
|
||||
return before, digest.hexdigest()
|
||||
|
||||
def witness():
|
||||
out = {'boot_id': Path('/proc/sys/kernel/random/boot_id').read_text().strip(), 'services': {}, 'files': {}}
|
||||
release = dict(line.split('=', 1) for line in Path('/etc/os-release').read_text().splitlines() if '=' in line)
|
||||
require(release.get('ID', '').strip('"') == 'ubuntu' and release.get('VERSION_ID', '').strip('"') == '24.04', 'fixed native Ubuntu24.04')
|
||||
out['os'] = {'id': 'ubuntu', 'version': '24.04', 'machine': os.uname().machine, 'kernel': os.uname().release}
|
||||
for name, uid, binary in (
|
||||
('rmm-agent-remote.service', 993, p['agent_sha256']),
|
||||
('rmm-helper-cloud.service', 0, p['helper_sha256']),
|
||||
('rmm-full-maintenance-helper.service', 0, p['helper_sha256'])):
|
||||
code, stdout, _ = run(['/usr/bin/systemctl', 'show', name, '-p', 'ActiveState', '-p', 'MainPID', '-p', 'UnitFileState', '-p', 'InvocationID'])
|
||||
require(code == 0, 'existing service read')
|
||||
service = dict(line.split('=', 1) for line in stdout.decode().splitlines())
|
||||
pid = int(service['MainPID']); require(service['ActiveState'] == 'active' and pid > 1, 'three existing services active')
|
||||
proc = Path('/proc', str(pid)); birth = (proc / 'stat').read_text().rsplit(') ', 1)[1].split()[19]
|
||||
ids = {line.split(':')[0]: line.split()[1:] for line in (proc / 'status').read_text().splitlines() if line.startswith(('Uid:', 'Gid:'))}
|
||||
metadata, image = hashed(proc / 'exe', 256 * 1024 * 1024, process_image=True)
|
||||
current = (proc / 'exe').stat()
|
||||
require(ids['Uid'] == [str(uid)] * 4 and ids['Gid'] == ['984'] * 4 and image == binary
|
||||
and (metadata.st_dev, metadata.st_ino) == (current.st_dev, current.st_ino)
|
||||
and (proc / 'stat').read_text().rsplit(') ', 1)[1].split()[19] == birth, 'current generation/account/image')
|
||||
out['services'][name] = dict(service, birth=birth, image=image, ids=ids)
|
||||
code, stdout, _ = run(['/usr/bin/systemctl', 'show', 'rmm-apt-helper.service', '-p', 'ActiveState', '-p', 'UnitFileState'])
|
||||
apt = dict(line.split('=', 1) for line in stdout.decode().splitlines())
|
||||
require(code == 0 and apt == {'ActiveState': 'inactive', 'UnitFileState': 'disabled'}, 'APT remains closed')
|
||||
out['apt'] = apt
|
||||
for name in ('/etc/rmm-remote/helper-general.json', '/etc/rmm-remote/helper-full-maintenance.json',
|
||||
'/etc/rmm-remote/full-maintenance-helper-proof.json', '/etc/systemd/system/rmm-full-maintenance-helper.service'):
|
||||
path = Path(name); metadata = path.lstat()
|
||||
require(not path.is_symlink() and stat.S_ISREG(metadata.st_mode) and metadata.st_uid == 0
|
||||
and not metadata.st_mode & 0o022 and metadata.st_nlink == 1, 'protected known control')
|
||||
current, digest = hashed(path, 65536)
|
||||
require(metadata_identity(current) == metadata_identity(metadata), 'same known control file')
|
||||
out['files'][name] = [metadata.st_dev, metadata.st_ino, metadata.st_uid, metadata.st_gid, metadata.st_mode,
|
||||
metadata.st_size, metadata.st_mtime_ns, metadata.st_ctime_ns, digest]
|
||||
for name in ('/var/lib/rmm-helper/consumption.sqlite', '/var/lib/rmm-helper/executor.lock',
|
||||
'/var/lib/rmm-agent-remote/journal.sqlite', '/var/lib/rmm-agent-remote/consumption.sqlite',
|
||||
'/var/lib/rmm-agent-remote/agent.lock'):
|
||||
path = Path(name); metadata = path.lstat()
|
||||
require(not path.is_symlink() and stat.S_ISREG(metadata.st_mode) and metadata.st_nlink == 1, 'existing state identity')
|
||||
out['files'][name] = [metadata.st_dev, metadata.st_ino, metadata.st_uid, metadata.st_gid, metadata.st_mode]
|
||||
return out
|
||||
|
||||
require(os.geteuid() == 0 and os.uname().machine == 'x86_64', 'fixed Cloud Linux root process-census fixtures')
|
||||
require(p['profile'] == 'rmm.updater.two-process-census-guards.v1'
|
||||
and p['binary_sha256'] == 'e83fd334b005d81ac917389de2a1c7486bea3f62ae45d77bccbd331e131e4304'
|
||||
and p['test_filter'] == 'census_process::tests::'
|
||||
and len(p['all_tests']) == 10 and len(p['tests']) == 2
|
||||
and [name for name in p['all_tests'] if name.startswith(p['test_filter'])] == p['tests'],
|
||||
'closed two-test census scope before remote case creation')
|
||||
ident = str(uuid.UUID(p['id'])); require(ident == p['id'], 'canonical original case')
|
||||
folder = Path('/var/tmp') / ('rmm-updater-reader-census-linux-' + ident)
|
||||
if p['action'] == 'read':
|
||||
metadata = folder.lstat()
|
||||
require(stat.S_ISDIR(metadata.st_mode) and not folder.is_symlink() and metadata.st_uid == 0
|
||||
and stat.S_IMODE(metadata.st_mode) == 0o700, 'own original case only')
|
||||
intent = json.loads((folder / 'intent.json').read_bytes())
|
||||
require(all(intent.get(key) == value for key,value in p.items() if key != 'action'), 'same original read binding')
|
||||
result = folder / 'result.json'
|
||||
return {'read_only': True, 'id': ident, 'entered': (folder / 'entered.json').exists(),
|
||||
'result': json.loads(result.read_bytes()) if result.exists() else None, 'current_witness': witness()}
|
||||
require(p['action'] == 'execute', 'one fixed process-census unit action')
|
||||
os.umask(0o077); folder.mkdir(mode=0o700)
|
||||
create(folder / 'intent.json', enc({key: value for key, value in p.items() if key != 'binary_b64'}))
|
||||
require(len(p['binary_b64']) == 10517464, 'bounded binary transfer')
|
||||
raw = base64.b64decode(p['binary_b64'], validate=True)
|
||||
require(len(raw) == 7888096 and hashlib.sha256(raw).hexdigest() == p['binary_sha256'], 'fixed worker test binary; only the closed census filter may run')
|
||||
binary = folder / 'worker-census-tests'; create(binary, raw, 0o700)
|
||||
before = witness(); create(folder / 'before.json', enc(before))
|
||||
command = ['/usr/bin/setpriv', '--reuid=0', '--regid=0', '--clear-groups', '--no-new-privs', str(binary)]
|
||||
code, stdout, stderr = run(command + ['--list', '--format', 'terse'])
|
||||
create(folder / 'list.stdout', stdout); create(folder / 'list.stderr', stderr)
|
||||
require(code == 0 and stderr == b'', 'native list succeeded')
|
||||
lines = stdout.decode().splitlines()
|
||||
require(len(lines) == 10 and all(line.endswith(': test') for line in lines) and sorted(line[:-6] for line in lines if line.endswith(': test')) == p['all_tests'], 'exact ten names before selecting only two census tests')
|
||||
create(folder / 'entered.json', enc({'id': ident, 'run_once': True, 'time_ns': time.time_ns()}))
|
||||
code, stdout, stderr = run(command + [p['test_filter'], '--test-threads=1', '--nocapture'])
|
||||
create(folder / 'run.stdout', stdout); create(folder / 'run.stderr', stderr)
|
||||
after = witness(); create(folder / 'after.json', enc(after))
|
||||
require(before == after and code == 0 and stderr == b''
|
||||
and b'2 passed; 0 failed; 0 ignored; 0 measured; 8 filtered out' in stdout
|
||||
and all((b'test ' + name.encode() + b' ... ok') in stdout for name in p['tests']), 'two selected native census guards, eight filtered and retained target state')
|
||||
receipt = dict(id=ident, profile=p['profile'], passed=2, ignored=0, filtered=8, listed=10, execution_uid=0, tests=p['tests'],
|
||||
all_tests=p['all_tests'], test_filter=p['test_filter'],
|
||||
before=before, after=after, binary_sha256=p['binary_sha256'], source_receipt_sha256=p['receipt_sha256'],
|
||||
source_manifest_sha256=p['manifest_sha256'], stdout_sha256=hashlib.sha256(stdout).hexdigest(),
|
||||
no_rmm_jobs=True, no_apply=True, no_service_control=True)
|
||||
create(folder / 'result.json', enc(receipt)); return receipt
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=('prepare', 'execute', 'read')); parser.add_argument('--case')
|
||||
args = parser.parse_args(); os.umask(0o077)
|
||||
STATE.mkdir(mode=0o700, parents=True, exist_ok=True); support.private(STATE, True)
|
||||
if args.action == 'prepare':
|
||||
support.require(args.case is None, 'prepare one new local case')
|
||||
receipt_path = QUALIFICATION / 'receipt.json'; support.private(receipt_path)
|
||||
support.require(sha(receipt_path.read_bytes()) == RECEIPT_SHA, 'independently reviewed source receipt')
|
||||
receipt = support.load(receipt_path); original = support.load(QUALIFICATION / 'inputs.json')
|
||||
support.require(sha((QUALIFICATION / 'inputs.json').read_bytes()) == INPUTS_SHA
|
||||
and receipt['inputs_sha256'] == INPUTS_SHA and len(original) == 71
|
||||
and receipt['input_count'] == 71 and receipt['tests'] == dict(passed=10,failed=0,ignored=0,filtered=0,complete_names=ALL_TESTS)
|
||||
and receipt['checks'] == dict(fmt=0,check=0,clippy=0,build=0,list=0,unit=0)
|
||||
and receipt['native_apply_run'] is False and receipt['target_calls'] is False,
|
||||
'reviewed ten-worker qualification, only two census tests selected')
|
||||
ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700)
|
||||
copy_exact(receipt_path, folder / 'receipt.json', RECEIPT_SHA, receipt_path.stat().st_size)
|
||||
copy_exact(QUALIFICATION / 'inputs.json', folder / 'inputs.json', INPUTS_SHA, (QUALIFICATION / 'inputs.json').stat().st_size)
|
||||
paths = set()
|
||||
for item in original:
|
||||
path = Path(item['path'])
|
||||
support.require(not path.is_absolute() and '..' not in path.parts and str(path) not in paths, 'unique fixed frozen input')
|
||||
paths.add(str(path)); copy_exact(QUALIFICATION / 'source' / path, folder / 'source' / path, item['sha256'], item['bytes'])
|
||||
binary = QUALIFICATION / 'qualified-worker-tests'
|
||||
support.require(receipt['binary'] == dict(filename='qualified-worker-tests', bytes=BINARY_BYTES,
|
||||
sha256=BINARY_SHA, mode='0500', nlink=1), 'fixed original linked artifact')
|
||||
copy_exact(binary, folder / 'worker-census-tests', BINARY_SHA, BINARY_BYTES)
|
||||
transports = {path: sha((ROOT / path).read_bytes()) for path in ('deploy/windows_msi_runtime_acceptance.py', 'deploy/vm_access_check.py')}
|
||||
save_local(folder / 'manifest.json', dict(id=ident, profile=PROFILE, runner_sha256=sha(Path(__file__).read_bytes()),
|
||||
receipt_sha256=RECEIPT_SHA, binary_sha256=BINARY_SHA, binary_bytes=BINARY_BYTES,
|
||||
source_files=original, tests=TESTS, all_tests=ALL_TESTS, test_filter=TEST_FILTER, transport_sources=transports))
|
||||
verify_case(folder)
|
||||
print(json.dumps({'id': ident, 'prepared_locally': True})); return
|
||||
support.require(args.case is not None, 'original --case required')
|
||||
ident = str(uuid.UUID(args.case)); support.require(ident == args.case, 'same canonical original case')
|
||||
folder = STATE / ident; support.private(folder, True); verify_case(folder)
|
||||
payload = dict(id=ident, action=args.action, profile=PROFILE, tests=TESTS, all_tests=ALL_TESTS, test_filter=TEST_FILTER, binary_sha256=BINARY_SHA,
|
||||
receipt_sha256=RECEIPT_SHA, manifest_sha256=sha((folder / 'manifest.json').read_bytes()),
|
||||
agent_sha256=AGENT_SHA, helper_sha256=HELPER_SHA)
|
||||
if args.action == 'execute':
|
||||
save_local(folder / 'execute-entered.json', {'once': True, 'no_retry': True})
|
||||
payload['binary_b64'] = base64.b64encode((folder / 'worker-census-tests').read_bytes()).decode()
|
||||
code = 'import json\n' + inspect.getsource(remote) + '\nprint(json.dumps(remote(' + repr(payload) + ')))\n'
|
||||
response = support.transport(support.access_settings(ACCESS_ROOT, 'linux'), 'python3 -', code.encode(), folder)
|
||||
save_local(folder / (args.action + '-' + str(uuid.uuid4()) + '.json'), response)
|
||||
if args.action == 'read' and response['result'] is not None:
|
||||
support.require(response['result']['source_manifest_sha256'] == sha((folder / 'manifest.json').read_bytes())
|
||||
and response['result']['source_receipt_sha256'] == RECEIPT_SHA
|
||||
and response['result']['binary_sha256'] == BINARY_SHA and response['result']['tests'] == TESTS
|
||||
and response['result']['passed'] == 2 and response['result']['ignored'] == 0 and response['result']['filtered'] == 8
|
||||
and response['result']['listed'] == 10 and response['result']['all_tests'] == ALL_TESTS
|
||||
and response['result']['test_filter'] == TEST_FILTER
|
||||
and response['result']['before'] == response['result']['after']
|
||||
and response['current_witness'] == response['result']['after'], 'same-case retained native result')
|
||||
print(json.dumps({'id': ident, 'action': args.action, 'passed': response.get('passed'),
|
||||
'complete': response.get('result') is not None if args.action == 'read' else True, 'read_only': args.action == 'read'}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,108 @@
|
||||
# Linux-Readercensus: lokaler Quellenstand und geplanter nativer Nachweis
|
||||
|
||||
Stand2026-11-15, Spezifikation1.22. Keine Zielinstallation, Dienständerung,
|
||||
RMM-Ausführung oder Applyabnahme wurde in diesem Arbeitsschritt vorgenommen.
|
||||
Die WebUI-Genehmigungsgrenze bleibt unverändert.
|
||||
|
||||
Registry und Census sind mit der vorhandenen Worker-Enginequelle verbunden.
|
||||
Die Registry bindet Originalrohbytes, Bootstrapreceipt, Readervertrag,
|
||||
Hostnamespaces und exakte Unit-/Dropinkomposition. Aktuelle TGIDs und sämtliche
|
||||
Task-FD-Tabellen werden begrenzt und erneut auf Identität geprüft; auch eine
|
||||
Datei mit geschlossenem FD bleibt über ihren mmap-Inode ein Reader. Unbekannte,
|
||||
unlesbare, wechselnde oder unvollständige Beobachtungen verweigern. Fremde
|
||||
Cmdlines, Umgebungen und map-Pfade werden nicht ausgegeben.
|
||||
|
||||
Der vorhandene Root-Executorflock und die ursprüngliche Agent-Singletonsperre
|
||||
bleiben beide unter dem nicht frei konstruierbaren `ClosedReaders`-Beleg gehalten,
|
||||
bevor der Updater SQLite öffnet. Der Readervertrag fordert außerdem den
|
||||
Roothelperflock vor seinen SQLiteöffnungen und jeder SQL-/Effektoperation und
|
||||
die Agent-Sperre lebenslang vor beiden Agentdatenbanken. Dies ist kein globales
|
||||
Versprechen über zukünftige privilegierte Fremdprozesse.
|
||||
|
||||
## Tatsächlich lokal geprüft
|
||||
|
||||
Im isolierten Offline-Rustcontainer, Quellmount read-only, unveränderte
|
||||
Docker-Seccomp-Policy, eigene tmpfs für `/run`, `/tmp` und `/var/lib`:
|
||||
|
||||
- Locked all-targets Check, Release-Link, Clippy `-D warnings`, Formatcheck: PASS.
|
||||
- Vollständige Release-Workerliste10, tatsächlich10bestanden,0Fehler,
|
||||
0ignoriert,0gefiltert.
|
||||
- Die Prozessfixtures belegen bestehende FDs, anschließend mmap nach FDclose
|
||||
sowie einen Reader in einer privaten FD-Tabelle eines einzelnen Threads.
|
||||
Der TGID-only-Gegenfall findet diesen Threadreader ausdrücklich nicht;
|
||||
die vollständige Taskprüfung findet ihn.
|
||||
|
||||
Der erste Lauf unter `reader-census-ba31b221-79c4-4702-b6d6-09bb94bba7fc`
|
||||
bestand9/10. Der eigene Threadfixture wurde am Docker-Seccomp-Verbot für
|
||||
`unshare(CLONE_FILES)` mit EPERM abgewiesen. Ausschließlich im Testfixture wurde
|
||||
stattdessen `close_range(UINT_MAX,UINT_MAX,CLOSE_RANGE_UNSHARE)` verwendet:
|
||||
die gleiche eigene FD-Tabellenseparation, ohne eine tatsächlich mögliche
|
||||
FDnummer zu schließen. Keine Sandboxregel, Capability oder Produktionsprüfung
|
||||
wurde gelockert. Die Produktionsbytes vor `#[cfg(test)]` blieben identisch.
|
||||
Die Semantik folgt [close_range(2)](https://man7.org/linux/man-pages/man2/close_range.2.html).
|
||||
Der ursprüngliche Fehlerbeleg bleibt erhalten.
|
||||
|
||||
Finaler eingefrorener Privatfall:
|
||||
`devstate/agent-updater-worker/reader-census-final-da31051b-269f-4fb5-947d-94c8ad162c2a/`.
|
||||
Er enthält71Originalinputs mit Vor-/Nachhashprüfung, alle Logs und das tatsächlich
|
||||
lokal ausgeführte Release-Test-ELF. Receipt SHA256
|
||||
`9020992e888d0b22e71db88cab78f255e273be2a4a7856d43616b387c36c74ae`,
|
||||
Inputs SHA256 `382714b09349e448441345abbac6d99c0d523e98bdabaa78290b400768bac8f7`,
|
||||
ELF7.888.096Bytes/SHA256
|
||||
`e83fd334b005d81ac917389de2a1c7486bea3f62ae45d77bccbd331e131e4304`.
|
||||
|
||||
## Geplant, nicht ausgeführt: zwei Cloud-Linux-Prozessguards
|
||||
|
||||
`deploy/updater_reader_census_linux_acceptance.py` ist lokal vorbereitet im
|
||||
Originalfall `168a4171-dbe3-46ef-8978-850797d0625c`. Vor Zielausführung muss Root
|
||||
seinen unabhängigen Runnerreview abschließen. Keine Zugangsdaten wurden für
|
||||
Prepare gelesen, kein Zielaufruf vorgenommen.
|
||||
|
||||
Der Runner prüft zuerst die vollständige Liste aller10Tests des exakt gebundenen
|
||||
ELF. Anschließend läuft ausschließlich der feste Filter `census_process::tests::`:
|
||||
|
||||
- `actual_proc_probe_detects_existing_descriptors_and_mapped_inode_without_exporting_paths`
|
||||
- `private_thread_fd_table_cannot_hide_a_reader_from_the_group_probe`
|
||||
|
||||
Erforderlich sind2bestanden und8gefiltert. Die anderen acht Tests dürfen auf der
|
||||
VM nicht laufen: Einige lokale Fixtures verwenden feste Produktzustandspfade.
|
||||
Die zwei ausgewählten Tests verwenden nur eigene Create-once-UUIDdateien unter
|
||||
`/run`, eigene FDs, eigenen mmap und einen eigenen Fixturethread. Keine SQLopen,
|
||||
Jobs oder Dienststeuerung. Der Runner läuft als Root mit NoNewPrivileges und
|
||||
führt nach einmaligem Eintritt keine Wiederholung aus. Nach verlorener Antwort
|
||||
ist ausschließlich Read des Originalfalls zulässig.
|
||||
|
||||
Vorher/Nachher werden Boot, Ubuntu24.04/x86-64, drei bekannte Dienstgenerationen
|
||||
mit Konten/Images, geschlossener APT-Helfer, vier geschützte Control-Dateien,
|
||||
drei DB-Identitäten sowie ursprünglicher Root- und Agentlock verglichen.
|
||||
Control-Bytes sind gehasht; bei den laufenden DBs werden Identitäten geprüft,
|
||||
keine Bytegleichheit oder vollständige SQL-Historie behauptet. Der begrenzte
|
||||
Prozessnachweis ersetzt weder einen kompletten Hostcensus noch native
|
||||
Full-/Updaterdienstkontexte oder einen Updatejob.
|
||||
|
||||
## Weiterhin offen
|
||||
|
||||
Extern qualifizierte kompatible Bootstrapregistry und geschützter Hostkontext,
|
||||
native Dienst-/Namespace-/Capabilitykontexte, ursprüngliche Full-Admission und
|
||||
Runtimeentrypoint, Staging-/Downloadproducer, gültige passive Updatebeobachtung,
|
||||
Unknown-only-Recordnamespace-Adjudikation, ein vor dem ersten Apply lesbarer
|
||||
V2-Rollbackvertrag sowie tatsächlicher WebUI-genehmigter Linux-Apply mit
|
||||
Health-/Erhaltungsnachweis. V1-Restore bleibt deny. Kein erfolgreicher nativer
|
||||
Apply und keine fertige Updaterbereitschaft folgen aus diesen lokalen Guards.
|
||||
|
||||
## Tatsächlich auf Cloud-Linux ausgeführt
|
||||
|
||||
Originalfall `168a4171-dbe3-46ef-8978-850797d0625c`: vor Ausführung volle
|
||||
10er-Liste verglichen, danach genau beide Prozesscensus-Guards tatsächlich
|
||||
als UID0 bestanden;2PASS/0failed/ignored,8andere ausdrücklich gefiltert.
|
||||
Execute-Receipt
|
||||
`d6bdda0bddac74f9364fa6ec3287ed0cfa9964ae02a98cc174e95929dc94f9d5`.
|
||||
Separater Originalrückabruf bestätigte das Ergebnis und erhaltene aktuelle
|
||||
Runtime-/Control-/State-/Lockidentitäten, Receipt
|
||||
`8cbe7f4d79c238e3ad73a9c7152dcb415decbeeb1a8a1691fcc43ae4ee6c6a47`.
|
||||
|
||||
Die eigenen kurzlebigen Prozess-/Thread-/FD-/mmap-Fixtures wurden geprüft;
|
||||
keine RMM-Dienste gesteuert, keine Projekt-SQLite geöffnet oder Agentdatei
|
||||
ersetzt. Dieser Nachweis qualifiziert weder den vollständigen Host-/
|
||||
Dienstcensus noch Admission, Apply, Record-Unknown-Adjudikation oder Rollback.
|
||||
Die zuvor genannten offenen Gates bleiben offen.
|
||||
@@ -0,0 +1,108 @@
|
||||
# Geschützte Linux-Readerregistry: Quellenbaustein
|
||||
|
||||
Stand2026-11-15, Spezifikation1.22. `worker::reader_registry` implementiert nur
|
||||
Registry-/Unit-/Aktivierungspfadprüfung. Kein Bootstrap, Dienstcontrol, SQLopen,
|
||||
Updaterstart, Apply oder Capability folgt daraus. Die vollständige aktuelle
|
||||
Task-/FD-/maps-Census und die tatsächlich gehaltenen ursprünglichen Root- und
|
||||
Agentlocks sind zusätzlich Pflicht. Die lokale Enginequelle verbindet diese
|
||||
Bausteine inzwischen; ohne extern qualifizierte Bootstrapregistry, tatsächliche
|
||||
Dienst-/Hostkontexte und ursprünglichen Admissionanschluss bleiben die
|
||||
Produktcapabilities `not_configured`. Siehe
|
||||
[aktuellen Readercensusnachweis](agent-updater-reader-census-results.md).
|
||||
|
||||
Der Aufruf `QualifiedRegistry::load(&LocalUpdatePolicy)` liest ausschließlich
|
||||
`/etc/rmm-agent-updater/reader-registry.json` unter root-eigener, gegen fremdes
|
||||
Schreiben geschützter Ancestry. Originalrohbytes höchstens64KiB, root0, regulär,
|
||||
ein Link; deren exakter SHA muss `policy.reader_registry_sha256` entsprechen.
|
||||
Damit bindet der vor WebUI-Genehmigung gespeicherte Policyhash die Registry
|
||||
transitiv. Gehaltene Dateien/Parent-FDs, Rawbytes und aktuelle Metadatastempel
|
||||
bleiben erhalten; `verify_protected()` prüft unveränderte originale Namen,
|
||||
Device/Inodes, Konten/Modi/Linkzahlen, Größe, Zeitstempel und Bytes. Kein Caller-
|
||||
Boolean oder aus einem Registryfeld abgeleitetes Alleinvertrauen.
|
||||
|
||||
Schema1 und Profil `linux_shared_readers_v1` besitzen exakt:
|
||||
|
||||
- `bootstrap_receipt_sha256`: exakt der Bootstrap-Qualificationreceipthash aus
|
||||
`policy.initial_baseline.decode().record.activation_evidence`.
|
||||
- `reader_contract_sha256`: Hash der unveränderlichen öffentlichen Bytekonstante
|
||||
`READER_CONTRACT`, über `reader_contract_sha256()` unabhängig berechenbar.
|
||||
- `host_context`: `census::HostContext` mit extern bootstrapqualifizierten
|
||||
Proc-/User-/PID-/Cgroup-Namespace-Device/Inodes; aktuelle eigene gleiche
|
||||
Metadaten allein sind keine Bootstrapqualifikation.
|
||||
- `units`: die unten festgelegten21 Units in dieser Reihenfolge.
|
||||
- `rollback_timers`: höchstens32 weitere historisch bekannte, sortierte eindeutige
|
||||
`rmm-general-startup-rollback-<kanonische-v4-UUID>.timer`-Einträge.
|
||||
|
||||
Jeder Uniteintrag enthält `unit`, `unit_file_state`, `composition`, `triggers`
|
||||
und `triggered_by`. Beziehungen sind sortierte eindeutige bekannte Registrynamen,
|
||||
keine freie Dateiauswahl oder zukünftige Readererlaubnis. `composition` ist exakt
|
||||
wie im unveränderten OSport die geordnete `Vec<(path, FileProof)>`: Fragment
|
||||
zuerst, dann tatsächliche DropInPaths-Reihenfolge. Der Hash derselben JSON-
|
||||
Bytefolge muss bei den Policydiensten passen; FileProof enthält insbesondere
|
||||
Original-Device/Inode, nicht nur ContentSHA. Geschützte systemd-Fragmente und
|
||||
höchstens16 `.conf`-Dropins werden unter den bekannten systemd-Systemverzeichnissen
|
||||
gebunden, insgesamt höchstens128 Blätter. Global-/Prefixdropins sind möglich,
|
||||
aber kein unbekannter Zusatz wird ignoriert. Leere Komposition und leerer
|
||||
UnitFileState sind ausschließlich bei einem absent/not-found-Nichtreader gültig.
|
||||
|
||||
Die21 Einträge sind zunächst diese7 Services: Agentremote, Helpercloud,
|
||||
Fullmaintenance, Updater, APThelper, Legacy`rmm-agent` und
|
||||
Legacy`rmm-helper-dev-test`. Danach folgen für dieselben7 Basen jeweils `.socket`
|
||||
und `.timer`. Vollständige feste Namen stehen in der Quellkonstante `SERVICES`.
|
||||
`rmm-mvp-test.service` ist eine Wartungsfixture, kein registrierter Reader;
|
||||
dieser Baustein fragt sie nicht ab und steuert sie niemals.
|
||||
|
||||
Der feste Readervertrag bindet: Roothelper erwerben das bestehende
|
||||
`executor.lock` vor SQLiteopen und jeder SQL-/Effektoperation; der Agent hält
|
||||
die vorhandene `agent.lock` schon vor Öffnung beider Agentdatenbanken lebenslang;
|
||||
alle erlaubten Reader verstehen Update-/Handoff-/Inflightdecoder. Registry-
|
||||
Parsing beweist diese Code-/Bootstrapeigenschaften nicht selbst. Die tatsächliche
|
||||
separat qualifizierte Baseline, Originalsignaturen und Census/Locks bleiben
|
||||
Pflicht. Eine Registry oder ein flock allein verspricht keine globale Abwesenheit
|
||||
zukünftiger exec-Aufrufe oder willentlicher vertrauenswürdiger Rootneustarts.
|
||||
|
||||
`verify_admission` verlangt genau Agent/General/Full/Updater loaded/active/running
|
||||
mit echten ServiceMainPIDs, ControlPID0, ohne ausstehenden Start-/Controljob.
|
||||
`verify_stopped` verlangt Agent/General/Full inactive/dead mit tatsächlichen
|
||||
Main-/ControlPIDs0; der Updater bleibt aktiv. Der originale UnitFileState bleibt
|
||||
für alle vier exakt gebunden, enabled oder disabled. Ein aktivierter Full- oder
|
||||
Updaterdienst muss deshalb nicht heimlich enabled werden. APT ist optional nur
|
||||
als tatsächlich gebundener Policydienst vorhanden, bleibt geschlossen und
|
||||
gehört niemals ins Startset. Legacyservices und Gegenstücke sind absent oder
|
||||
loaded/inactive/dead/disabled; aktuelle unbekannte Rollbacktimer verweigern.
|
||||
|
||||
Die read-only Systemdaufrufe sind ausschließlich `/usr/bin/systemctl --system
|
||||
--no-ask-password --no-pager --full show --all` mit festen Properties/Namen und
|
||||
zwei begrenzte `list-units`-/`list-unit-files`-Aufrufe mit festem historischem
|
||||
Rollbacktimerpattern. Kein Shellglob, Pager, Authdialog, start/stop/enable oder
|
||||
freie Commandline. Jede eigene Abfrage hat10s und das zusätzliche ursprüngliche
|
||||
`Budget`; stdout/stderr je16KiB. Nur der eigene gehaltene pidfd-Prozess wird bei
|
||||
Abbruch beendet, keine fremde PID übernommen. Statuswerte und fremde Prozess-
|
||||
oder Mappfade werden nicht in Fehlermeldungen ausgegeben.
|
||||
|
||||
Typen werden nicht erfunden: Service besitzt MainPID und ControlPID, Socket
|
||||
nur ControlPID und eine tatsächliche aktuelle Verbindungsanzahl; Timer besitzt
|
||||
keine PID-Eigenschaft. Fehlende anwendbare Properties verweigern. Timer/dead
|
||||
bedeutet im [Systemd-Primärvertrag](https://github.com/systemd/systemd/blob/main/src/core/timer.c)
|
||||
disarmierte Timereventquellen; Socket/dead ist keine Listenactivation. Es wird
|
||||
kein nicht vorhandenes MainPID als gemessene0 ausgegeben.
|
||||
[DBus-Typvertrag](https://www.freedesktop.org/software/systemd/man/latest/org.freedesktop.systemd1.html).
|
||||
Die ausgewählte `Job`-Property muss vorhanden sein; deren leere Ausgabe mit
|
||||
`--all` ist Systemctls Darstellung des tatsächlichen Nulljobs.
|
||||
[Primärformatter](https://github.com/systemd/systemd/blob/main/src/systemctl/systemctl-show.c).
|
||||
|
||||
`Triggers`/`TriggeredBy` sind strukturelle Beziehungen und werden exakt gegen
|
||||
die Registry gebunden. Ihre Namen allein werden nicht als laufendes Ereignis
|
||||
missverstanden. Alle relevanten registrierten Aktivierungsquellen müssen
|
||||
unabhängig geschlossen sein; offene oder unbekannte Pfade verweigern. Allgemeine
|
||||
WantedBy-Systemtargets werden damit nicht pauschal zu zu stoppenden Readern.
|
||||
Alle Statusfelder werden vor und nach der Prüfung identisch erneut gelesen,
|
||||
Registry/Unitblätter sowie aktueller Hostkontext erneut geprüft. Das ist eine
|
||||
begrenzte Momentaufnahme unter den weiteren Originalgrenzen, kein Futureexec-
|
||||
oder lückenloser Kernel-Snapshotbeweis.
|
||||
|
||||
Dieser Worker hat keine Target-/SSH-/Job-/Scope-/Dienst-/Policyaktion oder
|
||||
Systemdprobe ausgeführt. Compiler-/Format-/Clippyprüfung und unabhängiger
|
||||
Quellenreview werden durch den koordinierenden Owner nach diesem Quellenhandoff
|
||||
ausgeführt und separat berichtet. Die kleine Parserprobe verwendet ausschließlich
|
||||
synthetische Statusbytes, keine tatsächliche Registry oder laufende Units.
|
||||
@@ -135,9 +135,28 @@ unveröffentlicht; kein Cloud-VM-Apply, kein Produktfertig- oder Produktionsnach
|
||||
|
||||
Nach dem gepushten gemeinsamen Checkpoint8e93c9e und dem erhaltenden Mainmerge
|
||||
07d6118 ist die bisher offene Enginefolge als konkrete Workerquelle verbunden.
|
||||
Ihr Eintritt bleibt explizit `UPDATE_READER_CENSUS_NOT_CONFIGURED`; weder
|
||||
Daemonentrypoint noch Job-/Applycapability wird aktiviert. Die genaue
|
||||
Dieser historische Stand sperrte den Eintritt explizit mit
|
||||
`UPDATE_READER_CENSUS_NOT_CONFIGURED`. Die folgende lokale Fortschreibung hat
|
||||
Registry und Readercensus im Quellpfad verbunden; weiterhin wird weder ein
|
||||
Daemonentrypoint noch eine Job-/Applycapability aktiviert. Die genaue
|
||||
Queue-/Reply-/Stop-/Lock-/Swap-/Start-/Healthfolge und vorhandene separate
|
||||
Agent-Singletonsperre stehen in [worker](agent-updater-worker.md). Der neu
|
||||
geprüfte öffentliche Recordbuilder löst die zuvor dort genannte fehlende
|
||||
positive authentisierte Eingangsprobe. Keine reale Applyabnahme folgt daraus.
|
||||
|
||||
|
||||
## Fortschreibung2026-11-15: Readerregistry und vollständige Task-FD-Prüfung
|
||||
|
||||
Der gemeinsame Quellsatz verbindet Registryprüfung, ursprüngliche Agent- und
|
||||
Root-Executorsperre sowie TGID-/TID-FD-/maps-Prüfung mit der bestehenden Engine.
|
||||
Vor SQLiteöffnung verlangt der Ledgerport den nicht frei konstruierbaren
|
||||
`ClosedReaders`-Beleg und den tatsächlich gehaltenen ursprünglichen Rootguard.
|
||||
Das ist ein lokaler Quellen-/Vertragspunkt, kein gestarteter Dispatcher und
|
||||
keine Zusage über zukünftige privilegierte Fremdprozesse.
|
||||
|
||||
Der eingefrorene71-Input-Quellsatz besteht lokal alle10 vorhandenen Workerguards,
|
||||
locked all-targets Check, Release-Link, Clippy mit `-D warnings` und Formatcheck.
|
||||
Ein eigener Runner ist ausschließlich für zwei eigene native Prozessfixtures
|
||||
vorbereitet; er ist noch nicht ausgeführt. Details, frühere fehlgeschlagene
|
||||
Fixtureprüfung und verbleibende MVP-Gates stehen im
|
||||
[Readercensusnachweis](agent-updater-reader-census-results.md).
|
||||
|
||||
@@ -186,14 +186,18 @@ DBclose/Rootlockreturn gehalten und wird vor der festen Startfolge zurückgegebe
|
||||
Der Agent hält schon heute seine ursprüngliche Singletondatei vor beiden
|
||||
Agent-SQLiteöffnungen; keine ACL, Agentdatei oder Sperrrolle wurde geändert.
|
||||
|
||||
**Explizite Sperre dieses Checkpoints:** `Runtime::serve_one` verweigert mit
|
||||
`UPDATE_READER_CENSUS_NOT_CONFIGURED`. Geschützte kompatible Bootstrapregistry
|
||||
plus vollständige aktuelle PID-/FD-/maps-Census und Nachstopbeobachtung unter
|
||||
beiden tatsächlichen Sperren fehlen noch. Eine bekannte Unitliste ersetzt
|
||||
keinen Census. Keine CLI oder RMM-Admission ruft diese Runtime auf; Applycaps
|
||||
bleiben geschlossen. Ebenso offen: Staging-/Downloadproducer, passiver gültiger
|
||||
Der ursprüngliche Quellencheckpoint verweigerte den Eintritt explizit mit
|
||||
`UPDATE_READER_CENSUS_NOT_CONFIGURED`. Die Fortschreibung verbindet jetzt die
|
||||
Registry sowie tatsächliche Task-/FD-/maps-Census vor den Stops und unter beiden
|
||||
gehaltenen ursprünglichen Sperren danach. Diese Quellintegration ist lokal
|
||||
geprüft, jedoch noch nicht als installierter Dienst-/Hostkontext qualifiziert.
|
||||
Eine bekannte Unitliste allein ersetzt keinen Census. Keine CLI oder
|
||||
RMM-Admission ruft diese Runtime auf; Applycaps bleiben geschlossen. Offen sind
|
||||
insbesondere extern qualifizierte kompatible Bootstrapregistry und Hostkontexte,
|
||||
ursprüngliche Full-Admission, Staging-/Downloadproducer, passiver gültiger
|
||||
Updatezustand, V2-Rollbackvertrag vor dem ersten Bootstrap, Unsicherheits-
|
||||
Namespaces, qualifizierte Dienstkontexte und tatsächlicher Linux-Apply.
|
||||
Namespaces und tatsächlicher Linux-Apply. Aktueller Nachweis und enger geplanter
|
||||
nativer Zweierlauf: [Readercensus](agent-updater-reader-census-results.md).
|
||||
|
||||
Lokaler Nachweis liegt unter
|
||||
`devstate/updater-engine-source-6a8bb902-4db4-4d93-8843-450ba1dd5622/`.
|
||||
|
||||
Reference in New Issue
Block a user