Files
rust-discovery/crates/updater-linux/src/process.rs
T
2026-11-14 21:48:21 +01:00

240 lines
7.7 KiB
Rust

//! 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)?))
}
}