Add gated agent update planning, preserved handoff and Linux worker ports
Rust development slice / linux (push) Failing after 6s

This commit is contained in:
2026-11-14 21:48:21 +01:00
parent dc9cb1b096
commit 1e89c4577f
82 changed files with 25052 additions and 69 deletions
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "rmm-updater-linux"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
anyhow.workspace = true
hex.workspace = true
libc = "0.2.177"
serde.workspace = true
serde_json.workspace = true
sha2.workspace = true
uuid.workspace = true
rmm-domain = { path = "../domain" }
rmm-updater-handoff = { path = "../updater-handoff" }
+613
View File
@@ -0,0 +1,613 @@
//! Capability-relative held files. No network-provided path or global JSON
//! replacement. Existing bound hardlinks are retained; new stages have nlink1.
use crate::{Budget, DurableEffectFence, Effect, digest, valid_digest};
use anyhow::{Context, Result, ensure};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
ffi::{CString, OsStr},
fs::{File, Metadata},
io::{Read, Seek, SeekFrom, Write},
os::{
fd::{AsRawFd, FromRawFd},
unix::{ffi::OsStrExt, fs::MetadataExt},
},
path::{Component, Path, PathBuf},
};
use uuid::Uuid;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Role {
Agent,
Helper,
FullConfig,
FullPin,
}
impl Role {
pub fn handoff_role(self) -> rmm_updater_handoff::FileRole {
match self {
Self::Agent => rmm_updater_handoff::FileRole::AgentBinary,
Self::Helper => rmm_updater_handoff::FileRole::HelperBinary,
Self::FullConfig => rmm_updater_handoff::FileRole::LinuxFullConfig,
Self::FullPin => rmm_updater_handoff::FileRole::LinuxFullPin,
}
}
pub fn target(self) -> &'static str {
match self {
Self::Agent => "/usr/local/libexec/rmm-agent-remote",
Self::Helper => "/usr/local/libexec/rmm-privileged-helper",
Self::FullConfig => "/etc/rmm-remote/helper-full-maintenance.json",
Self::FullPin => "/etc/rmm-remote/full-maintenance-helper-proof.json",
}
}
fn label(self) -> &'static str {
match self {
Self::Agent => "agent",
Self::Helper => "helper",
Self::FullConfig => "full-config",
Self::FullPin => "full-pin",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Identity {
pub device: u64,
pub inode: u64,
pub uid: u32,
pub gid: u32,
pub mode: u32,
pub links: u64,
}
impl Identity {
fn of(m: &Metadata) -> Self {
Self {
device: m.dev(),
inode: m.ino(),
uid: m.uid(),
gid: m.gid(),
mode: m.mode(),
links: m.nlink(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FileProof {
pub identity: Identity,
pub bytes: u64,
pub sha256: String,
}
fn name(value: &OsStr) -> Result<CString> {
let bytes = value.as_bytes();
ensure!(
!bytes.is_empty() && bytes != b"." && bytes != b".." && !bytes.contains(&b'/'),
"UPDATE_BASENAME"
);
Ok(CString::new(bytes)?)
}
fn openat(parent: &File, value: &OsStr, flags: i32, mode: u32) -> Result<File> {
let value = name(value)?;
// SAFETY: valid owned directory fd and NUL-terminated one-component name;
// successful descriptor is immediately transferred into exactly one File.
let fd = unsafe {
libc::openat(
parent.as_raw_fd(),
value.as_ptr(),
flags | libc::O_CLOEXEC | libc::O_NOFOLLOW,
mode,
)
};
ensure!(
fd >= 0,
"UPDATE_OPENAT: {}",
std::io::Error::last_os_error()
);
Ok(unsafe { File::from_raw_fd(fd) })
}
pub struct Directory {
fd: File,
path: PathBuf,
identity: Identity,
}
impl Directory {
/// All ancestors are held while opening their child with O_NOFOLLOW. A
/// writable ancestor (including /tmp) is deliberately not an install root.
pub fn open(path: &Path, owner: u32, private: bool) -> Result<Self> {
ensure!(path.is_absolute(), "UPDATE_ABSOLUTE_DIRECTORY");
let mut fd = File::open("/")?;
let components: Vec<_> = path.components().collect();
for (i, component) in components.iter().enumerate().skip(1) {
let Component::Normal(value) = component else {
anyhow::bail!("UPDATE_DIRECTORY_COMPONENT")
};
fd = openat(&fd, value, libc::O_RDONLY | libc::O_DIRECTORY, 0)?;
let m = fd.metadata()?;
ensure!(
m.is_dir()
&& m.uid() == if i + 1 == components.len() { owner } else { 0 }
&& m.mode() & 0o022 == 0,
"UPDATE_PROTECTED_DIRECTORY"
);
}
let m = fd.metadata()?;
ensure!(
m.uid() == owner && (!private || m.mode() & 0o077 == 0),
"UPDATE_PRIVATE_DIRECTORY"
);
Ok(Self {
identity: Identity::of(&m),
fd,
path: path.to_path_buf(),
})
}
pub fn identity(&self) -> &Identity {
&self.identity
}
pub fn verify(&self) -> Result<()> {
let current = Self::open(&self.path, self.identity.uid, false)?;
ensure!(
current.identity == self.identity
&& Identity::of(&self.fd.metadata()?) == self.identity,
"UPDATE_DIRECTORY_REPLACED"
);
Ok(())
}
pub fn file(&self, basename: &OsStr, expected: &FileProof, max: u64) -> Result<HeldFile> {
self.verify()?;
let mut held = HeldFile {
fd: openat(&self.fd, basename, libc::O_RDONLY | libc::O_NONBLOCK, 0)?,
proof: expected.clone(),
};
held.verify(max)?;
self.named(basename, &held.proof.identity)?;
Ok(held)
}
pub fn inspect(&self, basename: &OsStr, owner: u32, max: u64) -> Result<HeldFile> {
self.verify()?;
let mut fd = openat(&self.fd, basename, libc::O_RDONLY | libc::O_NONBLOCK, 0)?;
let m = fd.metadata()?;
ensure!(
m.is_file()
&& m.uid() == owner
&& m.mode() & 0o022 == 0
&& m.nlink() > 0
&& m.len() <= max,
"UPDATE_PROTECTED_FILE"
);
let hash = hash_file(&mut fd, max)?;
let proof = FileProof {
identity: Identity::of(&m),
bytes: m.len(),
sha256: hash,
};
let mut result = HeldFile { fd, proof };
result.verify(max)?;
self.named(basename, &result.proof.identity)?;
Ok(result)
}
fn named(&self, basename: &OsStr, expected: &Identity) -> Result<()> {
let file = openat(&self.fd, basename, libc::O_PATH, 0)?;
ensure!(
Identity::of(&file.metadata()?) == *expected,
"UPDATE_NAMED_INODE_CHANGED"
);
Ok(())
}
fn absent(&self, basename: &OsStr) -> Result<()> {
let value = name(basename)?;
let mut m = std::mem::MaybeUninit::<libc::stat>::uninit();
// SAFETY: live dirfd, valid basename, properly sized writable stat.
let rc = unsafe {
libc::fstatat(
self.fd.as_raw_fd(),
value.as_ptr(),
m.as_mut_ptr(),
libc::AT_SYMLINK_NOFOLLOW,
)
};
ensure!(
rc < 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ENOENT),
"UPDATE_DESTINATION_EXISTS"
);
Ok(())
}
fn sync(&self) -> Result<()> {
self.fd.sync_all()?;
Ok(())
}
fn rename_new(&self, from: &OsStr, to: &OsStr) -> Result<()> {
let a = name(from)?;
let b = name(to)?;
// SAFETY: same held directory, valid component strings; NOREPLACE
// forbids overwriting an unexpected target including a dangling link.
let rc = unsafe {
libc::renameat2(
self.fd.as_raw_fd(),
a.as_ptr(),
self.fd.as_raw_fd(),
b.as_ptr(),
libc::RENAME_NOREPLACE,
)
};
ensure!(
rc == 0,
"UPDATE_RENAME: {}",
std::io::Error::last_os_error()
);
self.sync()
}
}
pub struct HeldFile {
fd: File,
proof: FileProof,
}
impl HeldFile {
pub fn proof(&self) -> &FileProof {
&self.proof
}
pub fn verify(&mut self, max: u64) -> Result<()> {
let m = self.fd.metadata()?;
ensure!(
m.is_file()
&& Identity::of(&m) == self.proof.identity
&& m.len() == self.proof.bytes
&& self.proof.bytes <= max
&& valid_digest(&self.proof.sha256),
"UPDATE_HELD_FILE_CHANGED"
);
ensure!(
hash_file(&mut self.fd, max)? == self.proof.sha256,
"UPDATE_HELD_HASH_CHANGED"
);
let after = self.fd.metadata()?;
ensure!(
Identity::of(&m) == Identity::of(&after)
&& m.len() == after.len()
&& m.mtime_nsec() == after.mtime_nsec()
&& m.mtime() == after.mtime()
&& m.ctime() == after.ctime()
&& m.ctime_nsec() == after.ctime_nsec(),
"UPDATE_FILE_CHANGED_DURING_HASH"
);
Ok(())
}
pub fn bytes(&mut self, max: u64) -> Result<Vec<u8>> {
self.verify(max)?;
self.fd.seek(SeekFrom::Start(0))?;
let mut bytes = Vec::with_capacity(self.proof.bytes as usize);
Read::by_ref(&mut self.fd)
.take(max + 1)
.read_to_end(&mut bytes)?;
ensure!(
bytes.len() as u64 == self.proof.bytes && digest(&bytes) == self.proof.sha256,
"UPDATE_READ_CHANGED"
);
self.verify(max)?;
Ok(bytes)
}
}
fn hash_file(fd: &mut File, max: u64) -> Result<String> {
ensure!(max <= 256 * 1024 * 1024, "UPDATE_HASH_LIMIT");
fd.seek(SeekFrom::Start(0))?;
let mut hash = Sha256::new();
let mut buffer = [0; 32768];
let mut total = 0u64;
loop {
let n = fd.read(&mut buffer)?;
if n == 0 {
break;
}
total = total.checked_add(n as u64).context("UPDATE_HASH_LIMIT")?;
ensure!(total <= max, "UPDATE_HASH_LIMIT");
hash.update(&buffer[..n]);
}
Ok(hex::encode(hash.finalize()))
}
/// File creation is confined to the SAME held installation directory. The
/// private fields bind successful EOF/hash/mode checking to subsequent swap.
pub struct Staged {
role: Role,
nonce: Uuid,
basename: String,
file: HeldFile,
target: String,
original: FileProof,
}
/// All descriptors remain untrusted input until the exact protected predecessor
/// and the approved target hashes have been independently checked by runtime.
pub struct StageDescriptor<'a> {
pub role: Role,
pub nonce: Uuid,
pub original: &'a FileProof,
pub expected_sha: &'a str,
pub length: u64,
}
impl Staged {
/// Stage only after the embedding agent has a real fixed approved job and
/// authorized download. This function alone grants no stop/swap authority.
pub fn write(
dir: &Directory,
descriptor: StageDescriptor<'_>,
source: &mut impl Read,
budget: &Budget,
) -> Result<Self> {
let StageDescriptor {
role,
nonce,
original,
expected_sha,
length,
} = descriptor;
ensure!(
!nonce.is_nil()
&& valid_digest(expected_sha)
&& length > 0
&& length <= 256 * 1024 * 1024,
"UPDATE_STAGE_DESCRIPTOR"
);
ensure!(
original.identity.uid == 0 && original.identity.mode & 0o022 == 0,
"UPDATE_ORIGINAL_METADATA"
);
let target = Path::new(role.target())
.file_name()
.context("UPDATE_TARGET")?
.to_str()
.context("UPDATE_TARGET")?
.to_owned();
ensure!(
Path::new(role.target()).parent() == Some(dir.path.as_path()),
"UPDATE_FIXED_ROLE_DIRECTORY"
);
dir.file(OsStr::new(&target), original, 256 * 1024 * 1024)?;
let basename = format!(".rmm-update-{nonce}-{}.stage", role.label());
budget.check()?;
let mut fd = openat(
&dir.fd,
OsStr::new(&basename),
libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL,
0o600,
)?;
let mut remaining = length;
let mut hash = Sha256::new();
let mut buffer = [0; 32768];
while remaining > 0 {
budget.check()?;
let take = remaining.min(buffer.len() as u64) as usize;
let n = source.read(&mut buffer[..take])?;
ensure!(n > 0, "UPDATE_STAGE_SHORT");
fd.write_all(&buffer[..n])?;
hash.update(&buffer[..n]);
remaining -= n as u64;
}
let mut tail = [0; 1];
ensure!(
source.read(&mut tail)? == 0 && hex::encode(hash.finalize()) == expected_sha,
"UPDATE_STAGE_HASH_OR_EXCESS"
);
budget.check()?;
// SAFETY: owned regular newly created file. Preserve old owner/group
// and all mode bits; binaries/configs are not made more permissive.
ensure!(
unsafe { libc::fchown(fd.as_raw_fd(), original.identity.uid, original.identity.gid) }
== 0,
"UPDATE_STAGE_OWNER"
);
ensure!(
unsafe { libc::fchmod(fd.as_raw_fd(), original.identity.mode & 0o7777) } == 0,
"UPDATE_STAGE_MODE"
);
fd.sync_all()?;
dir.sync()?;
drop(fd);
let file = dir.inspect(OsStr::new(&basename), 0, 256 * 1024 * 1024)?;
ensure!(
file.proof.identity.links == 1
&& file.proof.sha256 == expected_sha
&& file.proof.bytes == length,
"UPDATE_STAGE_VERIFIED"
);
Ok(Self {
role,
nonce,
basename,
file,
target,
original: original.clone(),
})
}
pub fn proof(&self) -> &FileProof {
self.file.proof()
}
/// Two separately fenced namespace changes; a crash in between leaves the
/// original backup and stage intact. This method NEVER retries or resumes.
pub fn install(
mut self,
dir: &Directory,
guard: &LedgerGuard<'_>,
budget: &Budget,
fence: &mut impl DurableEffectFence,
) -> Result<Installed> {
guard.verify_for_effect(budget)?;
dir.verify()?;
self.file.verify(256 * 1024 * 1024)?;
dir.file(OsStr::new(&self.target), &self.original, 256 * 1024 * 1024)?;
let backup = format!(".rmm-update-{}-{}.previous", self.nonce, self.role.label());
dir.absent(OsStr::new(&backup))?;
let save = Effect::SavePredecessor { role: self.role };
fence.before_effect(&save)?;
guard.verify_for_effect(budget)?;
dir.named(OsStr::new(&self.target), &self.original.identity)?;
dir.named(OsStr::new(&self.basename), &self.file.proof.identity)?;
dir.rename_new(OsStr::new(&self.target), OsStr::new(&backup))?;
dir.file(OsStr::new(&backup), &self.original, 256 * 1024 * 1024)?;
fence.after_effect(&save, &digest(&serde_json::to_vec(&self.original)?))?;
let publish = Effect::PublishReplacement { role: self.role };
fence.before_effect(&publish)?;
guard.verify_for_effect(budget)?;
dir.named(OsStr::new(&self.basename), &self.file.proof.identity)?;
dir.absent(OsStr::new(&self.target))?;
dir.rename_new(OsStr::new(&self.basename), OsStr::new(&self.target))?;
let current = dir.file(
OsStr::new(&self.target),
&self.file.proof,
256 * 1024 * 1024,
)?;
fence.after_effect(&publish, &digest(&serde_json::to_vec(current.proof())?))?;
Ok(Installed {
role: self.role,
target: self.target,
backup,
old: self.original,
new: current.proof,
})
}
}
pub struct Installed {
pub role: Role,
target: String,
backup: String,
old: FileProof,
new: FileProof,
}
impl Installed {
pub fn old(&self) -> &FileProof {
&self.old
}
pub fn new_file(&self) -> &FileProof {
&self.new
}
/// A rollback is NOT inferred from a failed health check. Only a separately
/// bound rollback fence may authorize it; unknown intermediate state denies.
pub fn restore(
self,
dir: &Directory,
guard: &LedgerGuard<'_>,
budget: &Budget,
fence: &mut impl DurableEffectFence,
) -> Result<()> {
guard.verify_for_effect(budget)?;
dir.file(OsStr::new(&self.target), &self.new, 256 * 1024 * 1024)?;
dir.file(OsStr::new(&self.backup), &self.old, 256 * 1024 * 1024)?;
let displaced = self.backup.replace(".previous", ".rejected");
dir.absent(OsStr::new(&displaced))?;
let effect = Effect::RestorePredecessor { role: self.role };
fence.before_effect(&effect)?;
guard.verify_for_effect(budget)?;
dir.rename_new(OsStr::new(&self.target), OsStr::new(&displaced))?;
// No existing target can be overwritten; both code generations remain.
guard.verify_for_effect(budget)?;
dir.rename_new(OsStr::new(&self.backup), OsStr::new(&self.target))?;
dir.file(OsStr::new(&self.target), &self.old, 256 * 1024 * 1024)?;
fence.after_effect(&effect, &digest(&serde_json::to_vec(&self.old)?))
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LedgerIdentity {
pub ledger: Identity,
pub lock: Identity,
}
impl LedgerIdentity {
pub fn sha256(&self) -> Result<String> {
Ok(digest(&serde_json::to_vec(self)?))
}
}
/// Existing lock only: no create, truncate or alternate database. Acquire only
/// after the caller independently confirmed every installed reader stopped.
pub struct LedgerGuard<'a> {
ledger: File,
lock: File,
directory: Directory,
identity: LedgerIdentity,
stopped: &'a crate::services::StoppedServices,
}
impl<'a> LedgerGuard<'a> {
pub fn acquire(
stopped: &'a crate::services::StoppedServices,
identity: &LedgerIdentity,
budget: &Budget,
) -> Result<Self> {
stopped.verify_still_stopped(budget)?;
let directory = Directory::open(Path::new("/var/lib/rmm-helper"), 0, true)?;
let ledger = openat(
&directory.fd,
OsStr::new("consumption.sqlite"),
libc::O_RDONLY | libc::O_NONBLOCK,
0,
)?;
let lock = openat(
&directory.fd,
OsStr::new("executor.lock"),
libc::O_RDWR | libc::O_NONBLOCK,
0,
)?;
let actual = LedgerIdentity {
ledger: Identity::of(&ledger.metadata()?),
lock: Identity::of(&lock.metadata()?),
};
ensure!(
actual == *identity
&& ledger.metadata()?.is_file()
&& lock.metadata()?.is_file()
&& actual.ledger.uid == 0
&& actual.lock.uid == 0,
"UPDATE_LEDGER_IDENTITY"
);
ensure!(
unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0,
"UPDATE_LEDGER_BUSY"
);
let result = Self {
ledger,
lock,
directory,
identity: actual,
stopped,
};
result.verify_for_effect(budget)?;
Ok(result)
}
pub fn identity(&self) -> &LedgerIdentity {
&self.identity
}
pub fn verify(&self) -> Result<()> {
self.directory.verify()?;
ensure!(
Identity::of(&self.ledger.metadata()?) == self.identity.ledger
&& Identity::of(&self.lock.metadata()?) == self.identity.lock,
"UPDATE_LEDGER_HELD_IDENTITY"
);
self.directory
.named(OsStr::new("consumption.sqlite"), &self.identity.ledger)?;
self.directory
.named(OsStr::new("executor.lock"), &self.identity.lock)
}
pub fn verify_for_effect(&self, budget: &Budget) -> Result<()> {
self.verify()?;
self.stopped.verify_still_stopped(budget)
}
/// Caller must first COMMIT the exact LedgerReturnIntent. This consumes the
/// guard, so it cannot be retained accidentally across the helper start.
pub fn release(self, budget: &Budget, fence: &mut impl DurableEffectFence) -> Result<()> {
self.verify_for_effect(budget)?;
fence.before_effect(&Effect::ReturnLedger)?;
self.verify_for_effect(budget)?;
drop(self);
Ok(())
}
}
impl Drop for LedgerGuard<'_> {
fn drop(&mut self) {
unsafe { libc::flock(self.lock.as_raw_fd(), libc::LOCK_UN) };
}
}
+388
View File
@@ -0,0 +1,388 @@
//! One bounded local request, authenticated BEFORE parsing/dispatch. This
//! transport cannot approve, create a grant or choose a path/command/service.
use crate::{
Budget,
files::Directory,
services::{HeldService, Service, Systemd},
};
use anyhow::{Result, ensure};
use rmm_domain::agent_update::ParticipantIdentity;
use serde::{Deserialize, Serialize};
use std::{
fs,
io::{Read, Write},
os::{
fd::AsRawFd,
unix::{
fs::{MetadataExt, PermissionsExt},
net::{UnixListener, UnixStream},
},
},
path::Path,
time::{Duration, Instant},
};
use uuid::Uuid;
const MAX_FRAME: usize = 32768;
const SOCKET: &str = "/run/rmm-agent-updater/control.sock";
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "method", rename_all = "snake_case", deny_unknown_fields)]
pub enum Request {
/// Live service identity only. Not a readiness/approval/start response.
Describe {},
/// Refers to the ORIGINAL immutable handoff already committed together
/// with consumption. Engine must reject a duplicate or unknown dispatch.
Activate {
grant_id: Uuid,
owner_nonce: Uuid,
handoff_sha256: String,
},
Read {
grant_id: Uuid,
owner_nonce: Uuid,
handoff_sha256: String,
},
/// Signed evidence bytes only; Engine independently checks actual local
/// sync/inventory/service/ledger state before the original Outcome CAS.
Health {
grant_id: Uuid,
owner_nonce: Uuid,
handoff_sha256: String,
payload_base64url: String,
signature_base64url: String,
},
}
impl Request {
fn validate(&self) -> Result<()> {
match self {
Self::Describe {} => Ok(()),
Self::Activate {
grant_id,
owner_nonce,
handoff_sha256,
}
| Self::Read {
grant_id,
owner_nonce,
handoff_sha256,
}
| Self::Health {
grant_id,
owner_nonce,
handoff_sha256,
..
} => {
ensure!(
!grant_id.is_nil()
&& !owner_nonce.is_nil()
&& crate::valid_digest(handoff_sha256),
"UPDATE_IPC_BINDING"
);
if let Self::Health {
payload_base64url,
signature_base64url,
..
} = self
{
ensure!(
!payload_base64url.is_empty()
&& payload_base64url.len() <= 21846
&& signature_base64url.len() == 86,
"UPDATE_IPC_HEALTH_LIMIT"
);
ensure!(
payload_base64url
.bytes()
.chain(signature_base64url.bytes())
.all(|b| b.is_ascii_alphanumeric() || b"-_".contains(&b)),
"UPDATE_IPC_BASE64URL"
);
}
Ok(())
}
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Response {
pub schema_version: u32,
pub state: State,
/// Always false: this local protocol never publishes ordinary readiness.
pub ready: bool,
pub updater: ParticipantIdentity,
pub head_sha256: Option<String>,
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum State {
Described,
Inflight,
OutcomePersisted,
Unknown,
NotConfigured,
}
/// Trusted embedding runtime. MUST bind every request to the actual original
/// request/signature/handoff/delegation in the existing helper ledger, enforce
/// one dispatch and its current authenticated participant, and implement all
/// independent clock/trust/health/preservation checks. No default engine.
pub trait Engine {
fn handle(&mut self, peer: &ParticipantIdentity, request: Request) -> Result<Response>;
}
pub struct Listener {
socket: UnixListener,
directory: Directory,
inode: u64,
device: u64,
}
impl Listener {
/// Bootstrap must create the fixed private directory separately. Existing
/// sockets are never unlinked/reused, including after an ambiguous restart.
pub fn bind() -> Result<Self> {
ensure!(
unsafe { libc::geteuid() } == 0,
"UPDATE_IPC_ROOT_SERVICE_REQUIRED"
);
let directory = Directory::open(Path::new("/run/rmm-agent-updater"), 0, true)?;
directory.verify()?;
let socket = UnixListener::bind(SOCKET)?;
fs::set_permissions(SOCKET, fs::Permissions::from_mode(0o600))?;
let m = fs::symlink_metadata(SOCKET)?;
use std::os::unix::fs::FileTypeExt;
ensure!(
m.file_type().is_socket()
&& m.uid() == 0
&& m.mode() & 0o777 == 0o600
&& m.nlink() == 1,
"UPDATE_IPC_PRIVATE_SOCKET"
);
directory.verify()?;
Ok(Self {
socket,
directory,
inode: m.ino(),
device: m.dev(),
})
}
pub fn serve_one(
&self,
helpers: &Systemd,
budget: &Budget,
engine: &mut impl Engine,
) -> Result<()> {
budget.check()?;
self.directory.verify()?;
let m = fs::symlink_metadata(SOCKET)?;
ensure!(
m.dev() == self.device
&& m.ino() == self.inode
&& m.uid() == 0
&& m.mode() & 0o777 == 0o600,
"UPDATE_IPC_SOCKET_CHANGED"
);
// Poll bounds accept independently of whether any helper connects.
let mut poll = libc::pollfd {
fd: self.socket.as_raw_fd(),
events: libc::POLLIN,
revents: 0,
};
let result = unsafe { libc::poll(&mut poll, 1, 100) };
ensure!(
result > 0 && poll.revents == libc::POLLIN,
"UPDATE_IPC_NO_REQUEST"
);
let (stream, _) = self.socket.accept()?;
let peer = helpers.authenticate_helper_peer(&stream, budget)?;
let mut stream = SocketIo::new(stream, budget);
let request = read_request(&mut stream)?;
budget.check()?;
let response = engine.handle(&peer, request)?;
stream.deadline = Instant::now() + Duration::from_secs(5);
ensure!(
response.schema_version == 1
&& !response.ready
&& response.updater.validate()
&& response.updater.role == rmm_domain::agent_update::ParticipantRole::LinuxUpdater
&& response
.head_sha256
.as_ref()
.is_none_or(|h| crate::valid_digest(h)),
"UPDATE_IPC_RESPONSE"
);
let raw = serde_json::to_vec(&response)?;
ensure!(
!raw.is_empty() && raw.len() <= MAX_FRAME,
"UPDATE_IPC_RESPONSE_LIMIT"
);
stream.write_all(&(raw.len() as u32).to_be_bytes())?;
stream.write_all(&raw)?;
stream.flush()?;
Ok(())
}
}
fn read_request(stream: &mut impl Read) -> Result<Request> {
let mut header = [0; 4];
stream.read_exact(&mut header)?;
let length = u32::from_be_bytes(header) as usize;
ensure!(length > 0 && length <= MAX_FRAME, "UPDATE_IPC_FRAME_LIMIT");
let mut raw = vec![0; length];
stream.read_exact(&mut raw)?;
let value: Request = serde_json::from_slice(&raw)?;
value.validate()?;
Ok(value)
}
/// Client transport does not retry a mutating Activate after any IO error.
/// Caller must independently verify updater against the fixed service pins.
pub fn exchange(
stream: UnixStream,
updater: &HeldService,
budget: &Budget,
request: &Request,
) -> Result<Response> {
budget.check()?;
ensure!(
updater.proof().service == Service::Updater,
"UPDATE_IPC_UPDATER_ROLE"
);
let authenticated = updater.authenticate_peer(&stream, budget)?;
request.validate()?;
let raw = serde_json::to_vec(request)?;
ensure!(raw.len() <= MAX_FRAME, "UPDATE_IPC_FRAME_LIMIT");
let mut stream = SocketIo::new(stream, budget);
stream.write_all(&(raw.len() as u32).to_be_bytes())?;
stream.write_all(&raw)?;
stream.flush()?;
let mut length = [0; 4];
stream.read_exact(&mut length)?;
let length = u32::from_be_bytes(length) as usize;
ensure!(
length > 0 && length <= MAX_FRAME,
"UPDATE_IPC_RESPONSE_LIMIT"
);
let mut bytes = vec![0; length];
stream.read_exact(&mut bytes)?;
let response: Response = serde_json::from_slice(&bytes)?;
ensure!(
response.schema_version == 1
&& !response.ready
&& response.updater == authenticated
&& response
.head_sha256
.as_ref()
.is_none_or(|h| crate::valid_digest(h)),
"UPDATE_IPC_NOT_READY_OR_WRONG_UPDATER"
);
updater.verify(budget)?;
Ok(response)
}
/// A kernel timeout restarts after each successful byte. Also bound the whole
/// frame, including a slow sender. The enclosing job budget is never renewed.
struct SocketIo<'a> {
stream: UnixStream,
budget: &'a Budget,
deadline: Instant,
}
impl<'a> SocketIo<'a> {
fn new(stream: UnixStream, budget: &'a Budget) -> Self {
Self {
stream,
budget,
deadline: Instant::now() + Duration::from_secs(5),
}
}
fn remaining(&self) -> std::io::Result<Duration> {
let original = self.budget.remaining().map_err(std::io::Error::other)?;
let duration = self
.deadline
.saturating_duration_since(Instant::now())
.min(original);
if duration.is_zero() {
return Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"UPDATE_IPC_FRAME_DEADLINE",
));
}
Ok(duration)
}
}
impl Read for SocketIo<'_> {
fn read(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
self.stream.set_read_timeout(Some(self.remaining()?))?;
self.stream.read(bytes)
}
}
impl Write for SocketIo<'_> {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.stream.set_write_timeout(Some(self.remaining()?))?;
self.stream.write(bytes)
}
fn flush(&mut self) -> std::io::Result<()> {
self.remaining()?;
self.stream.flush()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn framing_denies_large_duplicate_unknown_and_unbound_requests_before_dispatch() {
let frame = |raw: &[u8]| {
let mut b = (raw.len() as u32).to_be_bytes().to_vec();
b.extend_from_slice(raw);
b
};
assert!(matches!(
read_request(&mut frame(br#"{"method":"describe"}"#).as_slice()).unwrap(),
Request::Describe {}
));
for raw in [br#"{"method":"describe","method":"describe"}"#.as_slice(),br#"{"method":"describe","approved":true}"#.as_slice(),br#"{"method":"execute","command":"anything"}"#.as_slice(),br#"{"method":"activate","grant_id":"00000000-0000-0000-0000-000000000000","owner_nonce":"00000000-0000-0000-0000-000000000000","handoff_sha256":"invalid"}"#.as_slice()]{assert!(read_request(&mut frame(raw).as_slice()).is_err());}
assert!(read_request(&mut 32769u32.to_be_bytes().as_slice()).is_err());
assert!(read_request(&mut 0u32.to_be_bytes().as_slice()).is_err());
}
#[test]
fn partial_socket_frame_does_not_extend_its_total_deadline() {
for (original, frame) in [
(Duration::from_secs(1), Duration::from_millis(5)),
(Duration::from_millis(5), Duration::from_secs(5)),
] {
assert_fragmented_request_expires(original, frame);
}
}
fn assert_fragmented_request_expires(original: Duration, frame: Duration) {
let (left, mut right) = UnixStream::pair().unwrap();
let boot = fs::read_to_string("/proc/sys/kernel/random/boot_id")
.unwrap()
.trim()
.parse()
.unwrap();
let (written, wait_written) = std::sync::mpsc::channel();
let (proceed, wait_proceed) = std::sync::mpsc::channel();
let sender = std::thread::spawn(move || {
let raw = br#"{"method":"describe"}"#;
right.write_all(&(raw.len() as u32).to_be_bytes()).unwrap();
right.write_all(&raw[..1]).unwrap();
written.send(()).unwrap();
wait_proceed.recv().unwrap();
for byte in &raw[1..] {
std::thread::sleep(Duration::from_millis(2));
if right.write_all(&[*byte]).is_err() {
break;
}
}
});
wait_written.recv().unwrap();
let budget = Budget::new(boot, original).unwrap();
let mut receiver = SocketIo::new(left, &budget);
receiver.deadline = Instant::now() + frame;
proceed.send(()).unwrap();
assert!(read_request(&mut receiver).is_err());
drop(receiver);
sender.join().unwrap();
}
}
+90
View File
@@ -0,0 +1,90 @@
//! Linux OS primitives for the separately provisioned stable updater.
//!
//! These are not an approval, executable daemon or update capability. Every
//! mutating primitive requires the embedding worker's durable effect fence;
//! lost replies never resume an operation. No process-name/PID-only fallback.
#![cfg(target_os = "linux")]
pub mod files;
pub mod ipc;
pub mod process;
pub mod services;
use anyhow::{Result, ensure};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::time::{Duration, Instant};
use uuid::Uuid;
/// One original handoff's local deadline. Constructed after independent live
/// approval/clock/signature/boot/participant checks; possession is no authority.
pub struct Budget {
boot_id: Uuid,
until: Instant,
}
impl Budget {
pub fn new(boot_id: Uuid, remaining: Duration) -> Result<Self> {
ensure!(
!boot_id.is_nil() && !remaining.is_zero() && remaining <= Duration::from_secs(600),
"UPDATE_BUDGET"
);
let result = Self {
boot_id,
until: Instant::now()
.checked_add(remaining)
.ok_or_else(|| anyhow::anyhow!("UPDATE_BUDGET"))?,
};
result.check()?;
Ok(result)
}
pub fn check(&self) -> Result<()> {
ensure!(Instant::now() < self.until, "UPDATE_DEADLINE");
ensure!(
std::fs::read_to_string("/proc/sys/kernel/random/boot_id")?
.trim()
.parse::<Uuid>()?
== self.boot_id,
"UPDATE_BOOT_CHANGED"
);
Ok(())
}
pub(crate) fn remaining(&self) -> Result<Duration> {
self.check()?;
let remaining = self.until.saturating_duration_since(Instant::now());
ensure!(!remaining.is_zero(), "UPDATE_DEADLINE");
Ok(remaining)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "effect", rename_all = "snake_case", deny_unknown_fields)]
pub enum Effect {
StopService { service: services::Service },
SavePredecessor { role: files::Role },
PublishReplacement { role: files::Role },
StartService { service: services::Service },
RestorePredecessor { role: files::Role },
ReturnLedger,
}
/// MUST perform fresh original-handoff, owner, clock, boot and retained-file
/// checks and COMMIT a create-once intent before returning. No permissive
/// implementation is provided. Effects are in addition to the core ledger's
/// typed event sequence; they never create/replace the original consumption.
pub trait DurableEffectFence {
fn before_effect(&mut self, effect: &Effect) -> Result<()>;
fn after_effect(&mut self, effect: &Effect, observation_sha256: &str) -> Result<()>;
}
pub(crate) fn digest(bytes: &[u8]) -> String {
hex::encode(Sha256::digest(bytes))
}
pub(crate) fn valid_digest(value: &str) -> bool {
value.len() == 64
&& value
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
#[cfg(test)]
mod tests;
+239
View File
@@ -0,0 +1,239 @@
//! Held Linux process identity: pidfd + proc directory + executable descriptor.
//! A vanished/reused PID is never accepted as the original participant.
use crate::{digest, valid_digest};
use anyhow::{Result, ensure};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
ffi::CString,
fs::File,
io::Read,
os::{
fd::{AsRawFd, FromRawFd},
unix::fs::{FileExt, MetadataExt},
},
};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProcessProof {
pub pid: u32,
pub birth: u64,
pub uid: u32,
pub gid: u32,
pub image_sha256: String,
}
pub struct HeldProcess {
pidfd: File,
proc: File,
image: File,
proof: ProcessProof,
}
fn proc_file(dir: &File, name: &str) -> Result<File> {
let name = CString::new(name)?;
let fd = unsafe {
libc::openat(
dir.as_raw_fd(),
name.as_ptr(),
libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW,
)
};
ensure!(
fd >= 0,
"UPDATE_PROCESS_READ: {}",
std::io::Error::last_os_error()
);
Ok(unsafe { File::from_raw_fd(fd) })
}
fn bytes(dir: &File, name: &str) -> Result<Vec<u8>> {
let fd = proc_file(dir, name)?;
let mut raw = Vec::new();
fd.take(65537).read_to_end(&mut raw)?;
ensure!(raw.len() <= 65536, "UPDATE_PROC_LIMIT");
Ok(raw)
}
fn birth(dir: &File) -> Result<u64> {
let raw = bytes(dir, "stat")?;
let raw = std::str::from_utf8(&raw)?;
let (_, fields) = raw
.rsplit_once(") ")
.ok_or_else(|| anyhow::anyhow!("UPDATE_PROC_STAT"))?;
let birth = fields
.split_ascii_whitespace()
.nth(19)
.ok_or_else(|| anyhow::anyhow!("UPDATE_PROC_STAT"))?
.parse()?;
ensure!(birth > 0, "UPDATE_PROCESS_BIRTH");
Ok(birth)
}
fn ids(dir: &File) -> Result<(u32, u32)> {
let raw = bytes(dir, "status")?;
let raw = std::str::from_utf8(&raw)?;
let row = |key: &str| -> Result<u32> {
let rows: Vec<_> = raw
.lines()
.filter_map(|line| line.strip_prefix(key))
.collect();
ensure!(rows.len() == 1, "UPDATE_PROCESS_IDS");
let values: Vec<u32> = rows[0]
.split_ascii_whitespace()
.map(str::parse)
.collect::<std::result::Result<_, _>>()?;
ensure!(
values.len() == 4 && values.iter().all(|v| *v == values[0]),
"UPDATE_PROCESS_IDS"
);
Ok(values[0])
};
Ok((row("Uid:")?, row("Gid:")?))
}
fn image_hash(image: &File) -> Result<String> {
let m = image.metadata()?;
ensure!(
m.is_file() && m.uid() == 0 && m.mode() & 0o022 == 0 && m.len() <= 256 * 1024 * 1024,
"UPDATE_PROCESS_IMAGE"
);
let mut hash = Sha256::new();
let mut buf = [0; 32768];
let mut n = 0u64;
loop {
let read = image.read_at(&mut buf, n)?;
if read == 0 {
break;
}
n += read as u64;
ensure!(n <= 256 * 1024 * 1024, "UPDATE_PROCESS_IMAGE_LIMIT");
hash.update(&buf[..read]);
}
let after = image.metadata()?;
ensure!(
m.dev() == after.dev()
&& m.ino() == after.ino()
&& m.len() == after.len()
&& m.mtime() == after.mtime()
&& m.mtime_nsec() == after.mtime_nsec()
&& m.ctime() == after.ctime()
&& m.ctime_nsec() == after.ctime_nsec(),
"UPDATE_PROCESS_IMAGE_CHANGED"
);
Ok(hex::encode(hash.finalize()))
}
fn process_image(proc: &File) -> Result<File> {
// Follow only this kernel magic link through the already held proc dir.
let exe = CString::new("exe")?;
let fd = unsafe {
libc::openat(
proc.as_raw_fd(),
exe.as_ptr(),
libc::O_RDONLY | libc::O_CLOEXEC,
)
};
ensure!(fd >= 0, "UPDATE_PROCESS_IMAGE_OPEN");
Ok(unsafe { File::from_raw_fd(fd) })
}
fn same_image(left: &File, right: &File) -> Result<bool> {
let a = left.metadata()?;
let b = right.metadata()?;
Ok(a.dev() == b.dev() && a.ino() == b.ino())
}
impl HeldProcess {
pub fn open(pid: u32, uid: u32, gid: u32, expected_image: &str) -> Result<Self> {
ensure!(
pid > 1 && valid_digest(expected_image),
"UPDATE_PROCESS_DESCRIPTOR"
);
// SAFETY: pidfd_open returns a new descriptor or -1. Unsupported
// kernels fail closed; no fallback to kill(pid) or name matching.
let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) };
ensure!(
fd >= 0,
"UPDATE_PIDFD_UNAVAILABLE: {}",
std::io::Error::last_os_error()
);
let pidfd = unsafe { File::from_raw_fd(fd as i32) };
let path = CString::new(format!("/proc/{pid}"))?;
let fd = unsafe {
libc::open(
path.as_ptr(),
libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
)
};
ensure!(fd >= 0, "UPDATE_PROC_DIRECTORY");
let proc = unsafe { File::from_raw_fd(fd) };
let start = birth(&proc)?;
let actual_ids = ids(&proc)?;
// /proc/PID/exe is deliberately followed only through this held kernel
// proc directory; it is not a caller-controlled filesystem symlink.
let image = process_image(&proc)?;
let sha = image_hash(&image)?;
ensure!(
actual_ids == (uid, gid) && sha == expected_image && birth(&proc)? == start,
"UPDATE_PROCESS_BINDING"
);
let result = Self {
pidfd,
proc,
image,
proof: ProcessProof {
pid,
birth: start,
uid,
gid,
image_sha256: sha,
},
};
result.verify()?;
Ok(result)
}
pub fn proof(&self) -> &ProcessProof {
&self.proof
}
pub fn exited(&self) -> Result<bool> {
let mut p = libc::pollfd {
fd: self.pidfd.as_raw_fd(),
events: libc::POLLIN,
revents: 0,
};
let result = unsafe { libc::poll(&mut p, 1, 0) };
ensure!(
result >= 0 && p.revents & (libc::POLLNVAL | libc::POLLERR) == 0,
"UPDATE_PIDFD_POLL"
);
Ok(result > 0 && p.revents & (libc::POLLIN | libc::POLLHUP) != 0)
}
pub fn verify(&self) -> Result<()> {
ensure!(
!self.exited()?
&& birth(&self.proc)? == self.proof.birth
&& ids(&self.proc)? == (self.proof.uid, self.proof.gid),
"UPDATE_PROCESS_EXITED_OR_CHANGED"
);
// pidfd, creation time and credentials all survive execve(). Rebind
// BOTH before and after hashing to the executable currently selected
// by this exact held proc directory, never merely the old image FD.
let current = process_image(&self.proc)?;
ensure!(
same_image(&current, &self.image)?
&& image_hash(&self.image)? == self.proof.image_sha256
&& image_hash(&current)? == self.proof.image_sha256,
"UPDATE_PROCESS_IMAGE_CHANGED"
);
let after = process_image(&self.proc)?;
ensure!(
same_image(&after, &current)?
&& same_image(&after, &self.image)?
&& !self.exited()?
&& birth(&self.proc)? == self.proof.birth
&& ids(&self.proc)? == (self.proof.uid, self.proof.gid),
"UPDATE_PROCESS_IMAGE_CHANGED"
);
Ok(())
}
pub fn sha256(&self) -> Result<String> {
self.verify()?;
Ok(digest(&serde_json::to_vec(&self.proof)?))
}
}
+552
View File
@@ -0,0 +1,552 @@
//! Closed systemd service set; status is corroborated with held kernel process
//! identity. No shell, enable/reboot, global kill or repeated stop/start.
use crate::{
Budget, DurableEffectFence, Effect, digest,
process::{HeldProcess, ProcessProof},
};
use anyhow::{Result, ensure};
use serde::{Deserialize, Serialize};
use std::{
collections::BTreeMap,
fs::File,
io::Read,
os::fd::{AsRawFd, FromRawFd},
os::unix::net::UnixStream,
process::{Child, Command, Stdio},
thread,
time::{Duration, Instant},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Service {
Agent,
General,
Full,
Apt,
Updater,
}
impl Service {
fn handoff_service(self) -> Result<rmm_updater_handoff::Service> {
Ok(match self {
Self::Agent => rmm_updater_handoff::Service::LinuxAgent,
Self::General => rmm_updater_handoff::Service::LinuxGeneralHelper,
Self::Full => rmm_updater_handoff::Service::LinuxFullHelper,
Self::Apt => rmm_updater_handoff::Service::LinuxAptHelper,
Self::Updater => anyhow::bail!("UPDATE_UPDATER_NOT_IN_TARGET_SET"),
})
}
pub fn unit(self) -> &'static str {
match self {
Self::Agent => "rmm-agent-remote.service",
Self::General => "rmm-helper-cloud.service",
Self::Full => "rmm-full-maintenance-helper.service",
Self::Apt => "rmm-apt-helper.service",
Self::Updater => "rmm-agent-updater.service",
}
}
fn uid(self) -> u32 {
if self == Self::Agent { 993 } else { 0 }
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ServiceProof {
pub service: Service,
pub invocation_id: String,
pub enabled: String,
pub process: ProcessProof,
pub unit_sha256: String,
}
pub struct HeldService {
proof: ServiceProof,
process: HeldProcess,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ServicePolicy {
pub service: Service,
pub image_sha256: String,
pub unit_sha256: String,
}
pub struct Systemd {
policies: Vec<ServicePolicy>,
}
impl Systemd {
pub fn observe_updater(pin: ServicePolicy, budget: &Budget) -> Result<HeldService> {
ensure!(
pin.service == Service::Updater
&& crate::valid_digest(&pin.image_sha256)
&& crate::valid_digest(&pin.unit_sha256),
"UPDATE_UPDATER_PINS"
);
Self {
policies: vec![pin],
}
.observe(Service::Updater, budget)
}
/// Full is an ordinary required participant in the current Linux topology;
/// APT may additionally be installed but is never in the restart set.
pub fn new(policies: Vec<ServicePolicy>) -> Result<Self> {
let services: Vec<_> = policies.iter().map(|p| p.service).collect();
ensure!(
services == [Service::Agent, Service::General, Service::Full]
|| services
== [
Service::Agent,
Service::General,
Service::Full,
Service::Apt
],
"UPDATE_CLOSED_SERVICE_SET"
);
ensure!(
policies.iter().all(
|p| crate::valid_digest(&p.image_sha256) && crate::valid_digest(&p.unit_sha256)
),
"UPDATE_SERVICE_PINS"
);
ensure!(
policies[1].image_sha256 == policies[2].image_sha256,
"UPDATE_HELPER_PAIR_MISMATCH"
);
Ok(Self { policies })
}
pub fn authenticate_helper_peer(
&self,
socket: &UnixStream,
budget: &Budget,
) -> Result<rmm_domain::agent_update::ParticipantIdentity> {
for service in [Service::General, Service::Full] {
let held = self.observe(service, budget)?;
if let Ok(peer) = held.authenticate_peer(socket, budget) {
return Ok(peer);
}
}
anyhow::bail!("UPDATE_HELPER_PEER_NOT_BOUND")
}
fn status(service: Service, budget: &Budget) -> Result<BTreeMap<String, String>> {
budget.check()?;
let output = command(
&[
"show",
service.unit(),
"-p",
"LoadState",
"-p",
"ActiveState",
"-p",
"MainPID",
"-p",
"InvocationID",
"-p",
"UnitFileState",
"-p",
"FragmentPath",
"-p",
"DropInPaths",
],
budget,
)?;
let text = std::str::from_utf8(&output)?;
let mut fields = BTreeMap::new();
for row in text.lines() {
let (k, v) = row
.split_once('=')
.ok_or_else(|| anyhow::anyhow!("UPDATE_SYSTEMD_RESPONSE"))?;
ensure!(
fields.insert(k.into(), v.into()).is_none(),
"UPDATE_SYSTEMD_DUPLICATE"
);
}
ensure!(
fields.len() == 8 && fields.get("LoadState").is_some_and(|v| v == "loaded"),
"UPDATE_SYSTEMD_LOADED"
);
Ok(fields)
}
pub fn observe(&self, service: Service, budget: &Budget) -> Result<HeldService> {
let pin = self
.policies
.iter()
.find(|p| p.service == service)
.ok_or_else(|| anyhow::anyhow!("UPDATE_SERVICE_NOT_PINNED"))?;
let first = Self::status(service, budget)?;
ensure!(
first.get("ActiveState").is_some_and(|s| s == "active"),
"UPDATE_SERVICE_INACTIVE"
);
let pid = first
.get("MainPID")
.ok_or_else(|| anyhow::anyhow!("UPDATE_SERVICE_PID"))?
.parse()?;
let invocation_id = first
.get("InvocationID")
.ok_or_else(|| anyhow::anyhow!("UPDATE_SERVICE_INSTANCE"))?
.to_owned();
ensure!(
invocation_id.len() == 32 && invocation_id.bytes().all(|b| b.is_ascii_hexdigit()),
"UPDATE_SERVICE_INSTANCE"
);
// Unit composition must be independently provisioned. No unrecognized
// drop-in is silently ignored or inherited as an update permission.
let unit_sha = unit_composition(&first)?;
ensure!(unit_sha == pin.unit_sha256, "UPDATE_UNIT_CHANGED");
let process = HeldProcess::open(
pid,
service.uid(),
if service == Service::Updater { 0 } else { 984 },
&pin.image_sha256,
)?;
ensure!(
Self::status(service, budget)? == first,
"UPDATE_SERVICE_CHANGED_DURING_OBSERVATION"
);
process.verify()?;
Ok(HeldService {
proof: ServiceProof {
service,
invocation_id,
enabled: first["UnitFileState"].clone(),
process: process.proof().clone(),
unit_sha256: unit_sha,
},
process,
})
}
pub fn stop_all(
self,
budget: &Budget,
fence: &mut impl DurableEffectFence,
) -> Result<StoppedServices> {
let mut original = Vec::new();
for pin in &self.policies {
if pin.service == Service::Apt {
let s = Self::status(Service::Apt, budget)?;
ensure!(
s["ActiveState"] == "inactive"
&& s["MainPID"] == "0"
&& s["UnitFileState"] == "disabled"
&& unit_composition(&s)? == pin.unit_sha256,
"UPDATE_APT_MUST_REMAIN_CLOSED"
);
} else {
original.push(self.observe(pin.service, budget)?);
}
}
for held in &original {
held.process.verify()?;
let effect = Effect::StopService {
service: held.proof.service,
};
fence.before_effect(&effect)?;
budget.check()?;
command(&["--no-block", "stop", held.proof.service.unit()], budget)?;
loop {
budget.check()?;
let state = Self::status(held.proof.service, budget)?;
if state["ActiveState"] == "inactive"
&& state["MainPID"] == "0"
&& held.process.exited()?
{
break;
}
ensure!(
state["MainPID"] == "0"
|| state["MainPID"] == held.proof.process.pid.to_string(),
"UPDATE_STOP_PID_CHANGED"
);
thread::sleep(Duration::from_millis(20));
}
fence.after_effect(&effect, &digest(&serde_json::to_vec(&held.proof)?))?;
}
let result = StoppedServices {
systemd: self,
original,
};
result.verify_still_stopped(budget)?;
Ok(result)
}
}
impl HeldService {
pub fn started_proof(&self, budget: &Budget) -> Result<rmm_updater_handoff::StartedService> {
self.verify(budget)?;
ensure!(
self.proof.service != Service::Apt,
"UPDATE_APT_NOT_IN_START_SET"
);
Ok(rmm_updater_handoff::StartedService {
service: self.proof.service.handoff_service()?,
process: rmm_updater_handoff::Process {
pid: self.proof.process.pid,
birth: self.proof.process.birth,
image_sha256: self.proof.process.image_sha256.clone(),
},
})
}
pub fn proof(&self) -> &ServiceProof {
&self.proof
}
pub fn verify(&self, budget: &Budget) -> Result<()> {
self.process.verify()?;
let current = Systemd::status(self.proof.service, budget)?;
ensure!(
current["ActiveState"] == "active"
&& current["MainPID"] == self.proof.process.pid.to_string()
&& current["InvocationID"] == self.proof.invocation_id
&& current["UnitFileState"] == self.proof.enabled
&& unit_composition(&current)? == self.proof.unit_sha256,
"UPDATE_SERVICE_BINDING_CHANGED"
);
self.process.verify()
}
/// Authenticate the actual local connection independently of request JSON.
/// Root alone is insufficient; the fixed service's held pidfd must match.
pub fn authenticate_peer(
&self,
socket: &UnixStream,
budget: &Budget,
) -> Result<rmm_domain::agent_update::ParticipantIdentity> {
use rmm_domain::agent_update::{ParticipantIdentity, ParticipantRole};
self.verify(budget)?;
let mut peer = std::mem::MaybeUninit::<libc::ucred>::uninit();
let mut len = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
// SAFETY: live Unix socket, correctly sized writable ucred and length.
let result = unsafe {
libc::getsockopt(
socket.as_raw_fd(),
libc::SOL_SOCKET,
libc::SO_PEERCRED,
peer.as_mut_ptr().cast(),
&mut len,
)
};
ensure!(
result == 0 && len as usize == std::mem::size_of::<libc::ucred>(),
"UPDATE_PEER_CREDENTIALS"
);
let peer = unsafe { peer.assume_init() };
ensure!(
peer.pid > 0
&& peer.pid as u32 == self.proof.process.pid
&& peer.uid == 0
&& peer.gid == self.proof.process.gid,
"UPDATE_PEER_SERVICE_BINDING"
);
let role = match self.proof.service {
Service::Updater => ParticipantRole::LinuxUpdater,
Service::General => ParticipantRole::LinuxGeneralHelper,
Service::Full => ParticipantRole::LinuxFullHelper,
_ => anyhow::bail!("UPDATE_PARTICIPANT_ROLE"),
};
self.verify(budget)?;
Ok(ParticipantIdentity {
role,
pid: self.proof.process.pid,
birth: self.proof.process.birth,
image_sha256: self.proof.process.image_sha256.clone(),
security_principal: "uid:0".into(),
service_instance_sha256: digest(&serde_json::to_vec(&self.proof)?),
})
}
}
pub struct StoppedServices {
systemd: Systemd,
original: Vec<HeldService>,
}
impl StoppedServices {
pub fn verify_still_stopped(&self, budget: &Budget) -> Result<()> {
for pin in &self.systemd.policies {
let s = Systemd::status(pin.service, budget)?;
ensure!(
s["ActiveState"] == "inactive"
&& s["MainPID"] == "0"
&& unit_composition(&s)? == pin.unit_sha256,
"UPDATE_READER_NOT_STOPPED"
);
if pin.service == Service::Apt {
ensure!(
s["UnitFileState"] == "disabled",
"UPDATE_APT_MUST_REMAIN_CLOSED"
);
}
}
ensure!(
self.original
.iter()
.all(|s| s.process.exited().unwrap_or(false)),
"UPDATE_OLD_PROCESS_STILL_LIVE"
);
Ok(())
}
pub fn proofs(&self) -> Vec<ServiceProof> {
self.original.iter().map(|s| s.proof.clone()).collect()
}
/// The embedding fence MUST verify the exact PairVerified and durable
/// LedgerReturnIntent, released same guard and new target hashes first.
pub fn start_once(
self,
new: Systemd,
budget: &Budget,
fence: &mut impl DurableEffectFence,
) -> Result<Vec<HeldService>> {
self.verify_still_stopped(budget)?;
ensure!(
self.systemd
.policies
.iter()
.map(|p| p.service)
.eq(new.policies.iter().map(|p| p.service)),
"UPDATE_START_SET_CHANGED"
);
let mut started = Vec::new();
for service in [Service::General, Service::Full, Service::Agent] {
let effect = Effect::StartService { service };
fence.before_effect(&effect)?;
budget.check()?;
command(&["--no-block", "start", service.unit()], budget)?;
loop {
budget.check()?;
let state = Systemd::status(service, budget)?;
if state["ActiveState"] == "active" && state["MainPID"] != "0" {
let held = new.observe(service, budget)?;
ensure!(
!self
.original
.iter()
.any(|old| old.proof.process.pid == held.proof.process.pid),
"UPDATE_PROCESS_REUSE"
);
fence.after_effect(&effect, &digest(&serde_json::to_vec(&held.proof)?))?;
started.push(held);
break;
}
ensure!(
state["ActiveState"] == "activating" || state["ActiveState"] == "active",
"UPDATE_START_UNPROVEN"
);
thread::sleep(Duration::from_millis(20));
}
}
// Return in the canonical Handoff stop-set order, not actual start order.
started.sort_by_key(|s| s.proof.service);
Ok(started)
}
}
fn unit_composition(fields: &BTreeMap<String, String>) -> Result<String> {
use crate::files::Directory;
use std::{ffi::OsStr, path::Path};
let fragment = fields
.get("FragmentPath")
.ok_or_else(|| anyhow::anyhow!("UPDATE_UNIT_FRAGMENT"))?;
let mut paths = vec![fragment.as_str()];
paths.extend(
fields
.get("DropInPaths")
.ok_or_else(|| anyhow::anyhow!("UPDATE_UNIT_DROPINS"))?
.split_ascii_whitespace(),
);
let mut proof = Vec::new();
for path in paths {
let path = Path::new(path);
ensure!(path.is_absolute(), "UPDATE_UNIT_PATH");
let directory = Directory::open(
path.parent()
.ok_or_else(|| anyhow::anyhow!("UPDATE_UNIT_PARENT"))?,
0,
false,
)?;
let file = directory.inspect(path.file_name().unwrap_or(OsStr::new("")), 0, 65536)?;
proof.push((path.to_string_lossy().into_owned(), file.proof().clone()));
}
Ok(digest(&serde_json::to_vec(&proof)?))
}
struct OwnedCommand {
child: Child,
pidfd: File,
}
impl Drop for OwnedCommand {
fn drop(&mut self) {
// Signal this exact retained kernel process, including on every early
// error. An exited child cannot turn the descriptor into another PID.
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, buffer: &mut Vec<u8>) -> Result<()> {
let mut bytes = [0; 1024];
loop {
match stream.read(&mut bytes) {
Ok(0) => break,
Ok(n) => {
ensure!(buffer.len() + n <= 16384, "UPDATE_COMMAND_OUTPUT_LIMIT");
buffer.extend_from_slice(&bytes[..n]);
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
Err(e) => return Err(e.into()),
}
}
Ok(())
}
fn command(args: &[&str], budget: &Budget) -> Result<Vec<u8>> {
budget.check()?;
let mut child = Command::new("/usr/bin/systemctl")
.args(["--system", "--no-ask-password", "--no-pager"])
.args(args)
.env_clear()
.env("PATH", "/usr/bin:/bin")
.env("LC_ALL", "C")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
// A live Child has not been reaped, so this pidfd cannot target a reused PID.
let raw = unsafe { libc::syscall(libc::SYS_pidfd_open, child.id(), 0) };
if raw < 0 {
let _ = child.kill();
let _ = child.wait();
anyhow::bail!("UPDATE_COMMAND_PIDFD_UNAVAILABLE");
}
let pidfd = unsafe { File::from_raw_fd(raw as i32) };
let mut owned = OwnedCommand { child, pidfd };
let deadline = Instant::now() + Duration::from_secs(10);
let mut stdout = owned.child.stdout.take().unwrap();
let mut stderr = owned.child.stderr.take().unwrap();
for fd in [stdout.as_raw_fd(), stderr.as_raw_fd()] {
ensure!(
unsafe { libc::fcntl(fd, libc::F_SETFL, libc::O_NONBLOCK) } >= 0,
"UPDATE_COMMAND_NONBLOCK"
);
}
let mut out = Vec::new();
let mut error = Vec::new();
loop {
drain(&mut stdout, &mut out)?;
drain(&mut stderr, &mut error)?;
if let Some(status) = owned.child.try_wait()? {
drain(&mut stdout, &mut out)?;
drain(&mut stderr, &mut error)?;
ensure!(status.success(), "UPDATE_SYSTEMD_COMMAND_FAILED");
return Ok(out);
}
if budget.check().is_err() || Instant::now() >= deadline {
// Kill only our held systemctl client. A request may already have
// reached systemd: the embedding worker must record Unknown.
anyhow::bail!("UPDATE_SYSTEMD_REPLY_UNKNOWN");
}
thread::sleep(Duration::from_millis(5));
}
}
+158
View File
@@ -0,0 +1,158 @@
//! Real OS adverse cases, confined to a new /run unit fixture and owned sleep
//! child. Never calls systemctl, real install paths, RMM ledger or networking.
use crate::{
Budget, digest,
files::{Directory, FileProof},
process::HeldProcess,
};
use std::{
ffi::OsStr,
fs::{self, OpenOptions},
io::Write,
os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt, symlink},
path::PathBuf,
process::{Command, Stdio},
time::{Duration, Instant},
};
use uuid::Uuid;
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
assert_eq!(
unsafe { libc::geteuid() },
0,
"Run OS contract tests in the isolated root-owned test container, never as a host daemon"
);
let path = PathBuf::from(format!("/run/rmm-updater-os-unit-{}", Uuid::new_v4()));
fs::create_dir(&path).unwrap();
fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap();
Self(path)
}
fn dir(&self) -> Directory {
Directory::open(&self.0, 0, true).unwrap()
}
fn file(&self, name: &str, bytes: &[u8]) {
let mut file = OpenOptions::new()
.create_new(true)
.write(true)
.mode(0o600)
.open(self.0.join(name))
.unwrap();
file.write_all(bytes).unwrap();
file.sync_all().unwrap();
}
}
impl Drop for Fixture {
fn drop(&mut self) {
fs::remove_dir_all(&self.0).unwrap();
}
}
#[test]
fn held_file_rejects_symlink_and_replaced_name_but_preserves_bound_hardlinks() {
let f = Fixture::new();
f.file("original", b"original-public-fixture");
fs::hard_link(f.0.join("original"), f.0.join("historical-alias")).unwrap();
let dir = f.dir();
let mut held = dir.inspect(OsStr::new("original"), 0, 1024).unwrap();
assert_eq!(held.proof().identity.links, 2);
let proof: FileProof = held.proof().clone();
assert_eq!(held.bytes(1024).unwrap(), b"original-public-fixture");
symlink("original", f.0.join("symlink")).unwrap();
assert!(dir.inspect(OsStr::new("symlink"), 0, 1024).is_err());
fs::rename(f.0.join("original"), f.0.join("retained")).unwrap();
f.file("original", b"replacement");
assert!(dir.file(OsStr::new("original"), &proof, 1024).is_err());
assert_eq!(held.bytes(1024).unwrap(), b"original-public-fixture");
assert_eq!(
fs::metadata(f.0.join("retained")).unwrap().ino(),
proof.identity.inode
);
assert_eq!(
fs::read(f.0.join("historical-alias")).unwrap(),
b"original-public-fixture"
);
fs::set_permissions(f.0.join("original"), fs::Permissions::from_mode(0o622)).unwrap();
assert!(dir.inspect(OsStr::new("original"), 0, 1024).is_err());
assert!(Directory::open(&f.0.join("symlink"), 0, true).is_err());
}
#[test]
fn pidfd_image_birth_account_and_exit_are_independently_observed() {
let image = fs::read("/usr/bin/sleep").unwrap();
let sha = digest(&image);
let mut child = Command::new("/usr/bin/sleep").arg("60").spawn().unwrap();
let process = HeldProcess::open(child.id(), 0, 0, &sha).unwrap();
process.verify().unwrap();
assert!(!process.exited().unwrap());
assert!(HeldProcess::open(child.id(), 1, 0, &sha).is_err());
assert!(HeldProcess::open(child.id(), 0, 0, &"0".repeat(64)).is_err());
let before = process.proof().clone();
child.kill().unwrap();
child.wait().unwrap();
let deadline = Instant::now() + Duration::from_secs(2);
while !process.exited().unwrap() {
assert!(Instant::now() < deadline);
std::thread::yield_now();
}
assert!(process.verify().is_err());
assert_eq!(process.proof(), &before);
let boot = fs::read_to_string("/proc/sys/kernel/random/boot_id")
.unwrap()
.trim()
.parse()
.unwrap();
assert!(Budget::new(Uuid::nil(), Duration::from_secs(1)).is_err());
assert!(Budget::new(boot, Duration::from_secs(601)).is_err());
let budget = Budget::new(boot, Duration::from_millis(100)).unwrap();
std::thread::sleep(Duration::from_millis(150));
assert!(budget.check().is_err());
}
#[test]
fn same_pid_exec_rejects_changed_image_despite_retained_pidfd_birth_and_credentials() {
struct ChildCleanup(std::process::Child);
impl Drop for ChildCleanup {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
let old_image = fs::read("/usr/bin/bash").unwrap();
let new_image = fs::read("/usr/bin/sleep").unwrap();
let mut child = ChildCleanup(
Command::new("/usr/bin/bash")
.env_clear()
.args(["-c", "read -r token; exec /usr/bin/sleep 60"])
.stdin(Stdio::piped())
.spawn()
.unwrap(),
);
let held = HeldProcess::open(child.0.id(), 0, 0, &digest(&old_image)).unwrap();
let before = held.proof().clone();
held.verify().unwrap();
child.0.stdin.take().unwrap().write_all(b"go\n").unwrap();
let deadline = Instant::now() + Duration::from_secs(3);
let fresh = loop {
assert!(
Instant::now() < deadline,
"owned fixture child never completed exec"
);
match HeldProcess::open(child.0.id(), 0, 0, &digest(&new_image)) {
Ok(process) => break process,
Err(_) => std::thread::yield_now(),
}
};
assert_eq!(fresh.proof().pid, before.pid);
assert_eq!(fresh.proof().birth, before.birth);
assert_eq!(
(fresh.proof().uid, fresh.proof().gid),
(before.uid, before.gid)
);
assert_ne!(fresh.proof().image_sha256, before.image_sha256);
assert!(!held.exited().unwrap());
assert!(held.verify().is_err());
child.0.kill().unwrap();
child.0.wait().unwrap();
}