Add fail-closed Linux process and descriptor primitives
This commit is contained in:
parent
b34421efa1
commit
1468f6b841
7 changed files with 1725 additions and 15 deletions
34
crates/lazaret-linux/src/bin/lazaret-launch-wrapper.rs
Normal file
34
crates/lazaret-linux/src/bin/lazaret-launch-wrapper.rs
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
use std::ffi::OsString;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use lazaret_linux::process::{
|
||||
BarrierWait, arm_parent_death_and_recheck, exec_target, parse_wrapper_arguments,
|
||||
};
|
||||
use rustix::process::Signal;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match run() {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(error) => {
|
||||
eprintln!("lazaret launch wrapper refused: {error}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run() -> std::io::Result<()> {
|
||||
let arguments = std::env::args_os().skip(1).collect::<Vec<OsString>>();
|
||||
if arguments == [OsString::from("--trace-self-test")] {
|
||||
let (release, wait) = lazaret_linux::process::launch_barrier()?;
|
||||
release.release()?;
|
||||
wait.wait()?;
|
||||
return Err(exec_target(lazaret_linux::process::TargetCommand::new(
|
||||
"/bin/true",
|
||||
)));
|
||||
}
|
||||
let (expected_parent, target) = parse_wrapper_arguments(arguments)?;
|
||||
BarrierWait::from_stdin()?.wait()?;
|
||||
rustix::io::fcntl_setfd(std::io::stdin(), rustix::io::FdFlags::CLOEXEC)?;
|
||||
arm_parent_death_and_recheck(Signal::KILL, expected_parent)?;
|
||||
Err(exec_target(target))
|
||||
}
|
||||
98
crates/lazaret-linux/src/capability.rs
Normal file
98
crates/lazaret-linux/src/capability.rs
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
use std::io;
|
||||
|
||||
use rustix::thread::{
|
||||
CapabilitySet, CapabilitySets, capabilities, capability_is_in_ambient_set,
|
||||
capability_is_in_bounding_set, configure_capability_in_ambient_set,
|
||||
remove_capability_from_bounding_set, set_capabilities,
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct CapabilityState {
|
||||
pub sets: CapabilitySets,
|
||||
pub ambient: bool,
|
||||
pub bounding: bool,
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Returns an error when any kernel capability set cannot be inspected.
|
||||
pub fn inspect(capability: CapabilitySet) -> io::Result<CapabilityState> {
|
||||
Ok(CapabilityState {
|
||||
sets: capabilities(None)?,
|
||||
ambient: capability_is_in_ambient_set(capability)?,
|
||||
bounding: capability_is_in_bounding_set(capability)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Refuses any incomplete set, bounding, ambient, or secure-bit transition.
|
||||
pub fn irreversibly_drop(capability: CapabilitySet) -> io::Result<()> {
|
||||
require_single_threaded_process()?;
|
||||
let before = inspect(capability)?;
|
||||
if before.bounding && !before.sets.effective.contains(CapabilitySet::SETPCAP) {
|
||||
return Err(io::Error::from_raw_os_error(1));
|
||||
}
|
||||
if before.ambient {
|
||||
configure_capability_in_ambient_set(capability, false)?;
|
||||
}
|
||||
if before.bounding {
|
||||
remove_capability_from_bounding_set(capability)?;
|
||||
}
|
||||
let mut sets = before.sets;
|
||||
sets.effective.remove(capability);
|
||||
sets.permitted.remove(capability);
|
||||
sets.inheritable.remove(capability);
|
||||
if sets != before.sets {
|
||||
set_capabilities(None, sets)?;
|
||||
}
|
||||
let observed = inspect(capability)?;
|
||||
if observed.sets.effective.intersects(capability)
|
||||
|| observed.sets.permitted.intersects(capability)
|
||||
|| observed.sets.inheritable.intersects(capability)
|
||||
|| observed.ambient
|
||||
|| observed.bounding
|
||||
{
|
||||
return Err(io::Error::other(
|
||||
"capability remained available after irreversible drop",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_single_threaded_process() -> io::Result<()> {
|
||||
let mut tasks = std::fs::read_dir("/proc/self/task")?;
|
||||
if tasks.next().transpose()?.is_some() && tasks.next().transpose()?.is_none() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::other(
|
||||
"capability transition requires a single-threaded process",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use rustix::thread::CapabilitySet;
|
||||
|
||||
use super::{inspect, irreversibly_drop};
|
||||
|
||||
#[test]
|
||||
fn inspects_current_capability_sets() {
|
||||
let state = inspect(CapabilitySet::NET_ADMIN).unwrap();
|
||||
assert_eq!(
|
||||
state.sets.effective.contains(CapabilitySet::NET_ADMIN),
|
||||
state.sets.effective.intersects(CapabilitySet::NET_ADMIN)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multithreaded_process_refuses_before_transition() {
|
||||
let before = inspect(CapabilitySet::NET_ADMIN).unwrap();
|
||||
let waiting = std::sync::Arc::new(std::sync::Barrier::new(2));
|
||||
let child_waiting = std::sync::Arc::clone(&waiting);
|
||||
let child = std::thread::spawn(move || child_waiting.wait());
|
||||
assert!(irreversibly_drop(CapabilitySet::NET_ADMIN).is_err());
|
||||
assert_eq!(inspect(CapabilitySet::NET_ADMIN).unwrap(), before);
|
||||
waiting.wait();
|
||||
child.join().unwrap();
|
||||
}
|
||||
}
|
||||
268
crates/lazaret-linux/src/filesystem.rs
Normal file
268
crates/lazaret-linux/src/filesystem.rs
Normal file
|
|
@ -0,0 +1,268 @@
|
|||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{self, Seek, SeekFrom, Write};
|
||||
use std::os::fd::AsFd;
|
||||
use std::os::unix::ffi::{OsStrExt, OsStringExt};
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use lazaret_core::identity::{DeviceId, InodeId, MountId, MountIdentity, NamespaceIdentity};
|
||||
use rustix::fs::{
|
||||
AtFlags, FlockOperation, MemfdFlags, SealFlags, StatxFlags, fcntl_add_seals, fcntl_get_seals,
|
||||
flock, fstat, makedev, memfd_create, statx,
|
||||
};
|
||||
|
||||
static TEMPORARY_SEQUENCE: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
const REQUIRED_SEALS: SealFlags = SealFlags::SHRINK
|
||||
.union(SealFlags::GROW)
|
||||
.union(SealFlags::WRITE)
|
||||
.union(SealFlags::SEAL);
|
||||
|
||||
/// # Errors
|
||||
/// Returns an error on incomplete writes, sealing failures, or seal mismatch.
|
||||
pub fn sealed_memfd(name: &str, bytes: &[u8]) -> io::Result<File> {
|
||||
let fd = memfd_create(name, MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING)?;
|
||||
let mut file = File::from(fd);
|
||||
file.write_all(bytes)?;
|
||||
file.flush()?;
|
||||
file.seek(SeekFrom::Start(0))?;
|
||||
fcntl_add_seals(file.as_fd(), REQUIRED_SEALS)?;
|
||||
require_write_sealed(file.as_fd())?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Refuses descriptors without the complete immutable seal set.
|
||||
pub fn require_write_sealed(fd: impl AsFd) -> io::Result<()> {
|
||||
let seals = fcntl_get_seals(fd)?;
|
||||
if seals.contains(REQUIRED_SEALS) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::other("memfd lacks required immutable seals"))
|
||||
}
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Returns an error when the nonblocking exclusive lock is unavailable.
|
||||
pub fn try_exclusive_flock(file: File) -> io::Result<ExclusiveFileLock> {
|
||||
flock(file.as_fd(), FlockOperation::NonBlockingLockExclusive)?;
|
||||
Ok(ExclusiveFileLock(file))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ExclusiveFileLock(File);
|
||||
|
||||
impl AsFd for ExclusiveFileLock {
|
||||
fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
|
||||
self.0.as_fd()
|
||||
}
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Returns an error unless the replacement and containing directory are synced.
|
||||
pub fn atomic_replace(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
atomic_replace_with(path, |temporary| temporary.write_all(bytes))
|
||||
}
|
||||
|
||||
fn atomic_replace_with<Write>(path: &Path, write: Write) -> io::Result<()>
|
||||
where
|
||||
Write: FnOnce(&mut File) -> io::Result<()>,
|
||||
{
|
||||
let parent = path
|
||||
.parent()
|
||||
.ok_or_else(|| io::Error::other("replacement path has no parent"))?;
|
||||
let file_name = path
|
||||
.file_name()
|
||||
.ok_or_else(|| io::Error::other("replacement path has no file name"))?;
|
||||
let mut temporary = None;
|
||||
for _ in 0..128 {
|
||||
let sequence = TEMPORARY_SEQUENCE.fetch_add(1, Ordering::Relaxed);
|
||||
let mut name = Vec::with_capacity(file_name.as_bytes().len() + 48);
|
||||
name.extend_from_slice(b".");
|
||||
name.extend_from_slice(file_name.as_bytes());
|
||||
name.extend_from_slice(format!(".lazaret-{}-{sequence}", std::process::id()).as_bytes());
|
||||
let path = parent.join(std::ffi::OsString::from_vec(name));
|
||||
match OpenOptions::new().create_new(true).write(true).open(&path) {
|
||||
Ok(file) => {
|
||||
temporary = Some((path, file));
|
||||
break;
|
||||
}
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
let (temporary_path, mut temporary_file) =
|
||||
temporary.ok_or_else(|| io::Error::other("temporary replacement name exhausted"))?;
|
||||
let result = (|| {
|
||||
write(&mut temporary_file)?;
|
||||
temporary_file.sync_all()?;
|
||||
std::fs::rename(&temporary_path, parent.join(file_name))?;
|
||||
OpenOptions::new().read(true).open(parent)?.sync_all()
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = std::fs::remove_file(temporary_path);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Returns an error when the namespace descriptor cannot be opened or inspected.
|
||||
pub fn namespace_identity(path: &Path) -> io::Result<NamespaceIdentity> {
|
||||
let file = OpenOptions::new().read(true).open(path)?;
|
||||
let stat = fstat(file.as_fd())?;
|
||||
Ok(NamespaceIdentity {
|
||||
device: DeviceId::new(stat.st_dev),
|
||||
inode: InodeId::new(stat.st_ino),
|
||||
})
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Returns an error when the path has no exact readable mount identity.
|
||||
pub fn current_mount_identity(path: &Path) -> io::Result<MountIdentity> {
|
||||
let file = OpenOptions::new().read(true).open(path)?;
|
||||
mount_identity(file.as_fd())
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Refuses when `statx(AT_EMPTY_PATH)` cannot return complete same-descriptor evidence.
|
||||
pub fn mount_identity(fd: impl AsFd) -> io::Result<MountIdentity> {
|
||||
let stat = statx(
|
||||
fd.as_fd(),
|
||||
"",
|
||||
AtFlags::EMPTY_PATH,
|
||||
StatxFlags::BASIC_STATS | StatxFlags::MNT_ID,
|
||||
)?;
|
||||
let mask = StatxFlags::from_bits_retain(stat.stx_mask);
|
||||
if !mask.contains(StatxFlags::INO | StatxFlags::MNT_ID) {
|
||||
return Err(io::Error::other(
|
||||
"statx omitted required mount identity evidence",
|
||||
));
|
||||
}
|
||||
Ok(MountIdentity {
|
||||
mount_id: MountId::new(stat.stx_mnt_id),
|
||||
device: DeviceId::new(makedev(stat.stx_dev_major, stat.stx_dev_minor)),
|
||||
inode: InodeId::new(stat.stx_ino),
|
||||
})
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Refuses missing, unreadable, replaced, renamed, or remounted path identity.
|
||||
pub fn require_mount_identity(path: &Path, expected: MountIdentity) -> io::Result<()> {
|
||||
if current_mount_identity(path)? == expected {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::other("mount identity mismatch"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use rustix::fs::{MemfdFlags, memfd_create};
|
||||
|
||||
use super::{
|
||||
atomic_replace, current_mount_identity, namespace_identity, require_mount_identity,
|
||||
require_write_sealed, sealed_memfd, try_exclusive_flock,
|
||||
};
|
||||
|
||||
fn test_directory(name: &str) -> std::path::PathBuf {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"lazaret-linux-{name}-{}-{}",
|
||||
std::process::id(),
|
||||
super::TEMPORARY_SEQUENCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
|
||||
));
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seals_memfd_after_complete_write() {
|
||||
let mut file = sealed_memfd("policy", b"complete bytes").unwrap();
|
||||
let mut bytes = Vec::new();
|
||||
file.read_to_end(&mut bytes).unwrap();
|
||||
assert_eq!(bytes, b"complete bytes");
|
||||
assert!(file.write_all(b"mutation").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_unsealed_memfd() {
|
||||
let fd = memfd_create("unsealed", MemfdFlags::ALLOW_SEALING).unwrap();
|
||||
assert!(require_write_sealed(fd).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn atomically_replaces_and_identifies_mount() {
|
||||
let directory = test_directory("replace");
|
||||
let path = directory.join("record");
|
||||
OpenOptions::new()
|
||||
.create_new(true)
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.unwrap()
|
||||
.write_all(b"old")
|
||||
.unwrap();
|
||||
atomic_replace(&path, b"new").unwrap();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"new");
|
||||
assert!(current_mount_identity(&path).is_ok());
|
||||
std::fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_replacement_write_preserves_durable_old_file() {
|
||||
let directory = test_directory("partial-replace");
|
||||
let path = directory.join("record");
|
||||
std::fs::write(&path, b"old").unwrap();
|
||||
let result = super::atomic_replace_with(&path, |temporary| {
|
||||
temporary.write_all(b"partial")?;
|
||||
Err(std::io::Error::other("injected partial write"))
|
||||
});
|
||||
assert!(result.is_err());
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"old");
|
||||
assert_eq!(std::fs::read_dir(&directory).unwrap().count(), 1);
|
||||
std::fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exclusive_flock_refuses_competing_open_description() {
|
||||
let directory = test_directory("flock");
|
||||
let path = directory.join("lock");
|
||||
let first = OpenOptions::new()
|
||||
.create_new(true)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.unwrap();
|
||||
let second = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.unwrap();
|
||||
let held = try_exclusive_flock(first).unwrap();
|
||||
assert!(try_exclusive_flock(second).is_err());
|
||||
drop(held);
|
||||
std::fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn namespace_identity_is_stable_for_same_namespace() {
|
||||
let first = namespace_identity(std::path::Path::new("/proc/self/ns/mnt")).unwrap();
|
||||
let second = namespace_identity(std::path::Path::new("/proc/self/ns/mnt")).unwrap();
|
||||
assert_eq!(first, second);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mount_identity_refuses_replaced_and_renamed_objects() {
|
||||
let directory = test_directory("mount-race");
|
||||
let path = directory.join("object");
|
||||
std::fs::write(&path, b"first").unwrap();
|
||||
let expected = current_mount_identity(&path).unwrap();
|
||||
let old = directory.join("old");
|
||||
std::fs::rename(&path, &old).unwrap();
|
||||
std::fs::write(&path, b"replacement").unwrap();
|
||||
assert!(require_mount_identity(&path, expected).is_err());
|
||||
assert!(require_mount_identity(&old, expected).is_ok());
|
||||
std::fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
}
|
||||
36
crates/lazaret-linux/src/ipc.rs
Normal file
36
crates/lazaret-linux/src/ipc.rs
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
use std::os::fd::OwnedFd;
|
||||
|
||||
use rustix::net::{AddressFamily, SocketFlags, SocketType, socketpair};
|
||||
|
||||
/// # Errors
|
||||
/// Returns an error when the private sequenced-packet pair cannot be created.
|
||||
pub fn private_seqpacket_pair() -> std::io::Result<(OwnedFd, OwnedFd)> {
|
||||
socketpair(
|
||||
AddressFamily::UNIX,
|
||||
SocketType::SEQPACKET,
|
||||
SocketFlags::CLOEXEC,
|
||||
None,
|
||||
)
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::os::fd::AsFd;
|
||||
|
||||
use rustix::net::{RecvFlags, SendFlags, recv, send};
|
||||
|
||||
use super::private_seqpacket_pair;
|
||||
|
||||
#[test]
|
||||
fn preserves_message_boundaries() {
|
||||
let (left, right) = private_seqpacket_pair().unwrap();
|
||||
send(left.as_fd(), b"first", SendFlags::empty()).unwrap();
|
||||
send(left.as_fd(), b"second", SendFlags::empty()).unwrap();
|
||||
let mut buffer = [0_u8; 16];
|
||||
let (_, first) = recv(right.as_fd(), &mut buffer, RecvFlags::empty()).unwrap();
|
||||
assert_eq!(&buffer[..first], b"first");
|
||||
let (_, second) = recv(right.as_fd(), &mut buffer, RecvFlags::empty()).unwrap();
|
||||
assert_eq!(&buffer[..second], b"second");
|
||||
}
|
||||
}
|
||||
8
crates/lazaret-linux/src/lib.rs
Normal file
8
crates/lazaret-linux/src/lib.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
#![doc = "Safe Linux x86-64 operating-system primitives used by Lazaret processes."]
|
||||
#![cfg(target_os = "linux")]
|
||||
|
||||
pub mod capability;
|
||||
pub mod filesystem;
|
||||
pub mod ipc;
|
||||
pub mod platform;
|
||||
pub mod process;
|
||||
123
crates/lazaret-linux/src/platform.rs
Normal file
123
crates/lazaret-linux/src/platform.rs
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
use std::fmt;
|
||||
|
||||
pub const MINIMUM_KERNEL_MAJOR: u64 = 6;
|
||||
pub const MINIMUM_KERNEL_MINOR: u64 = 9;
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct PlatformObservation<'a> {
|
||||
pub operating_system: &'a str,
|
||||
pub architecture: &'a str,
|
||||
pub kernel_release: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum PlatformRefusal {
|
||||
OperatingSystem(String),
|
||||
Architecture(String),
|
||||
KernelRelease(String),
|
||||
KernelFloor { major: u64, minor: u64 },
|
||||
}
|
||||
|
||||
impl fmt::Display for PlatformRefusal {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::OperatingSystem(value) => {
|
||||
write!(formatter, "unsupported operating system {value}")
|
||||
}
|
||||
Self::Architecture(value) => write!(formatter, "unsupported architecture {value}"),
|
||||
Self::KernelRelease(value) => write!(formatter, "invalid Linux kernel release {value}"),
|
||||
Self::KernelFloor { major, minor } => write!(
|
||||
formatter,
|
||||
"Linux kernel {major}.{minor} is below the required 6.9 floor"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for PlatformRefusal {}
|
||||
|
||||
/// # Errors
|
||||
/// Refuses unsupported operating systems, architectures, and kernel releases.
|
||||
pub fn check_platform(observation: &PlatformObservation<'_>) -> Result<(), PlatformRefusal> {
|
||||
if observation.operating_system != "linux" {
|
||||
return Err(PlatformRefusal::OperatingSystem(
|
||||
observation.operating_system.into(),
|
||||
));
|
||||
}
|
||||
if observation.architecture != "x86_64" {
|
||||
return Err(PlatformRefusal::Architecture(
|
||||
observation.architecture.into(),
|
||||
));
|
||||
}
|
||||
let (major, minor) = parse_kernel_release(observation.kernel_release)?;
|
||||
if (major, minor) < (MINIMUM_KERNEL_MAJOR, MINIMUM_KERNEL_MINOR) {
|
||||
return Err(PlatformRefusal::KernelFloor { major, minor });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Refuses releases without numeric major and minor components.
|
||||
pub fn parse_kernel_release(release: &str) -> Result<(u64, u64), PlatformRefusal> {
|
||||
let mut components = release.split('.');
|
||||
let major = components
|
||||
.next()
|
||||
.and_then(|value| value.parse().ok())
|
||||
.ok_or_else(|| PlatformRefusal::KernelRelease(release.into()))?;
|
||||
let minor = components
|
||||
.next()
|
||||
.and_then(|value| {
|
||||
value
|
||||
.split_once('-')
|
||||
.map_or(value, |(number, _)| number)
|
||||
.parse()
|
||||
.ok()
|
||||
})
|
||||
.ok_or_else(|| PlatformRefusal::KernelRelease(release.into()))?;
|
||||
Ok((major, minor))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{PlatformObservation, PlatformRefusal, check_platform};
|
||||
|
||||
#[test]
|
||||
fn accepts_floor_and_newer_linux_x86_64() {
|
||||
for release in ["6.9.0", "6.9.12-custom", "6.10.0", "7.0"] {
|
||||
check_platform(&PlatformObservation {
|
||||
operating_system: "linux",
|
||||
architecture: "x86_64",
|
||||
kernel_release: release,
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_older_kernel_and_other_platforms() {
|
||||
let old = check_platform(&PlatformObservation {
|
||||
operating_system: "linux",
|
||||
architecture: "x86_64",
|
||||
kernel_release: "6.8.14",
|
||||
});
|
||||
assert_eq!(
|
||||
old,
|
||||
Err(PlatformRefusal::KernelFloor { major: 6, minor: 8 })
|
||||
);
|
||||
|
||||
for observation in [
|
||||
PlatformObservation {
|
||||
operating_system: "freebsd",
|
||||
architecture: "x86_64",
|
||||
kernel_release: "14.0",
|
||||
},
|
||||
PlatformObservation {
|
||||
operating_system: "linux",
|
||||
architecture: "aarch64",
|
||||
kernel_release: "6.9.0",
|
||||
},
|
||||
] {
|
||||
assert!(check_platform(&observation).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
698
crates/lazaret-linux/src/process.rs
Normal file
698
crates/lazaret-linux/src/process.rs
Normal file
|
|
@ -0,0 +1,698 @@
|
|||
use std::ffi::{OsStr, OsString};
|
||||
use std::fs::File;
|
||||
use std::io::{self, Read, Write};
|
||||
use std::os::fd::{AsFd, OwnedFd};
|
||||
use std::path::Path;
|
||||
use std::process::Stdio;
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
use lazaret_core::identity::{
|
||||
BootId, HostPidLocator, PidfsDeviceId, PidfsInodeId, PidfsProcessAuthorityV1,
|
||||
PidfsProcessIdentityV1, ProcessStartTimeTicks,
|
||||
};
|
||||
use rustix::event::{PollFd, PollFlags, Timespec, poll};
|
||||
use rustix::fs::{fstat, fstatfs};
|
||||
use rustix::io::{FdFlags, fcntl_setfd};
|
||||
use rustix::pipe::{PipeFlags, pipe_with};
|
||||
use rustix::process::{Pid, PidfdFlags, Signal, WaitId, WaitIdOptions};
|
||||
|
||||
pub const PID_FS_MAGIC: i64 = 0x5049_4446;
|
||||
const BARRIER_RELEASE: &[u8; 32] = b"LAZARET-CAUSAL-BARRIER-RELEASE!!";
|
||||
static CHILD_BROKER: OnceLock<ChildBroker> = OnceLock::new();
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct TargetCommand {
|
||||
program: OsString,
|
||||
arguments: Vec<OsString>,
|
||||
}
|
||||
|
||||
impl TargetCommand {
|
||||
#[must_use]
|
||||
pub fn new(program: impl Into<OsString>) -> Self {
|
||||
Self {
|
||||
program: program.into(),
|
||||
arguments: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn argument(mut self, argument: impl Into<OsString>) -> Self {
|
||||
self.arguments.push(argument.into());
|
||||
self
|
||||
}
|
||||
|
||||
#[allow(clippy::disallowed_types)]
|
||||
fn append_to(&self, command: &mut std::process::Command) {
|
||||
command.arg("--").arg(&self.program).args(&self.arguments);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct RetainedProcess {
|
||||
pidfd: OwnedFd,
|
||||
identity: PidfsProcessIdentityV1,
|
||||
}
|
||||
|
||||
impl RetainedProcess {
|
||||
#[must_use]
|
||||
pub const fn identity(&self) -> PidfsProcessIdentityV1 {
|
||||
self.identity
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Returns an error when the exact retained-pidfd action fails.
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
pub fn send_signal(&self, signal: Signal) -> io::Result<()> {
|
||||
rustix::process::pidfd_send_signal(self.pidfd.as_fd(), signal).map_err(Into::into)
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Returns an error when polling the retained pidfd fails.
|
||||
pub fn has_exited(&self) -> io::Result<bool> {
|
||||
let mut descriptors = [PollFd::new(&self.pidfd, PollFlags::IN)];
|
||||
poll(&mut descriptors, Some(&Timespec::default()))?;
|
||||
Ok(descriptors[0]
|
||||
.revents()
|
||||
.intersects(PollFlags::IN | PollFlags::HUP))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ChildBroker {
|
||||
exclusion: Mutex<()>,
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn child_broker() -> &'static ChildBroker {
|
||||
CHILD_BROKER.get_or_init(|| ChildBroker {
|
||||
exclusion: Mutex::new(()),
|
||||
})
|
||||
}
|
||||
|
||||
impl ChildBroker {
|
||||
/// Spawns the repository wrapper, stages exact ownership, accepts its acknowledgment,
|
||||
/// and only then releases target execution.
|
||||
///
|
||||
/// # Errors
|
||||
/// Refuses and reaps the blocked wrapper on every failed acquisition or callback.
|
||||
#[allow(clippy::disallowed_methods, clippy::disallowed_types)]
|
||||
pub fn acquire<S, Stage, Acknowledge>(
|
||||
&self,
|
||||
wrapper: &Path,
|
||||
expected_parent: PidfsProcessIdentityV1,
|
||||
target: &TargetCommand,
|
||||
stage: Stage,
|
||||
acknowledge: Acknowledge,
|
||||
) -> io::Result<RetainedProcess>
|
||||
where
|
||||
Stage: FnOnce(PidfsProcessIdentityV1) -> io::Result<S>,
|
||||
Acknowledge: FnOnce(&S, PidfsProcessIdentityV1) -> io::Result<()>,
|
||||
{
|
||||
let _guard = self
|
||||
.exclusion
|
||||
.lock()
|
||||
.map_err(|_| io::Error::other("child broker lock poisoned"))?;
|
||||
require_default_sigchld()?;
|
||||
let (release, wait) = launch_barrier()?;
|
||||
let mut command = std::process::Command::new(wrapper);
|
||||
append_parent_identity(&mut command, expected_parent);
|
||||
target.append_to(&mut command);
|
||||
command.stdin(wait.into_stdio());
|
||||
let mut child = command.spawn()?;
|
||||
let host_pid = child.id();
|
||||
let acquired = acquire_spawned_child(host_pid);
|
||||
let process = match acquired {
|
||||
Ok(process) => process,
|
||||
Err(error) => return fail_before_pidfd(release, &mut child, error),
|
||||
};
|
||||
let staged = match stage(process.identity) {
|
||||
Ok(staged) => staged,
|
||||
Err(error) => return fail_after_pidfd(release, process, error),
|
||||
};
|
||||
if let Err(error) = acknowledge(&staged, process.identity) {
|
||||
return fail_after_pidfd(release, process, error);
|
||||
}
|
||||
if let Err(error) = release.release() {
|
||||
return fail_after_pidfd_closed(process, error);
|
||||
}
|
||||
drop(child);
|
||||
Ok(process)
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Returns an error when serialization or exact pidfd reaping fails.
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
pub fn reap(&self, process: RetainedProcess) -> io::Result<()> {
|
||||
let _guard = self
|
||||
.exclusion
|
||||
.lock()
|
||||
.map_err(|_| io::Error::other("child broker lock poisoned"))?;
|
||||
rustix::process::waitid(WaitId::PidFd(process.pidfd.as_fd()), WaitIdOptions::EXITED)?;
|
||||
drop(process);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
fn acquire_spawned_child(host_pid: u32) -> io::Result<RetainedProcess> {
|
||||
let raw_pid = i32::try_from(host_pid)
|
||||
.map_err(|_| io::Error::other("spawn returned out-of-range child PID"))?;
|
||||
let pid = Pid::from_raw(raw_pid)
|
||||
.ok_or_else(|| io::Error::other("spawn returned invalid child PID"))?;
|
||||
require_host_pid_namespace(host_pid)?;
|
||||
let pidfd = rustix::process::pidfd_open(pid, PidfdFlags::empty())?;
|
||||
verify_direct_child_pidfd(pidfd.as_fd())?;
|
||||
let authority = authority_from_pidfd(pidfd.as_fd(), read_boot_id()?)?;
|
||||
let start_time = read_start_time(host_pid)?;
|
||||
Ok(RetainedProcess {
|
||||
pidfd,
|
||||
identity: PidfsProcessIdentityV1::new(
|
||||
authority,
|
||||
HostPidLocator::new(host_pid),
|
||||
ProcessStartTimeTicks::new(start_time),
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Refuses descriptors that do not name a waitable direct child of this broker process.
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
pub fn verify_direct_child_pidfd(pidfd: impl AsFd) -> io::Result<()> {
|
||||
rustix::process::waitid(
|
||||
WaitId::PidFd(pidfd.as_fd()),
|
||||
WaitIdOptions::EXITED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(clippy::disallowed_methods, clippy::disallowed_types)]
|
||||
fn fail_before_pidfd(
|
||||
release: BarrierRelease,
|
||||
child: &mut std::process::Child,
|
||||
error: io::Error,
|
||||
) -> io::Result<RetainedProcess> {
|
||||
drop(release);
|
||||
child.wait()?;
|
||||
Err(error)
|
||||
}
|
||||
|
||||
fn fail_after_pidfd(
|
||||
release: BarrierRelease,
|
||||
process: RetainedProcess,
|
||||
error: io::Error,
|
||||
) -> io::Result<RetainedProcess> {
|
||||
drop(release);
|
||||
fail_after_pidfd_closed(process, error)
|
||||
}
|
||||
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
fn fail_after_pidfd_closed(
|
||||
process: RetainedProcess,
|
||||
error: io::Error,
|
||||
) -> io::Result<RetainedProcess> {
|
||||
rustix::process::waitid(WaitId::PidFd(process.pidfd.as_fd()), WaitIdOptions::EXITED)?;
|
||||
drop(process);
|
||||
Err(error)
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Refuses before PID lookup on boot mismatch and before action on every later mismatch.
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
pub fn recover_process(identity: PidfsProcessIdentityV1) -> io::Result<RetainedProcess> {
|
||||
recover_process_with(identity, read_boot_id, |host_pid| {
|
||||
let raw_pid = i32::try_from(host_pid)
|
||||
.map_err(|_| io::Error::other("stored PID locator is out of range"))?;
|
||||
let pid = Pid::from_raw(raw_pid)
|
||||
.ok_or_else(|| io::Error::other("stored PID locator is invalid"))?;
|
||||
require_host_pid_namespace(host_pid)?;
|
||||
rustix::process::pidfd_open(pid, PidfdFlags::empty()).map_err(Into::into)
|
||||
})
|
||||
}
|
||||
|
||||
fn recover_process_with<Boot, Open>(
|
||||
identity: PidfsProcessIdentityV1,
|
||||
boot: Boot,
|
||||
open: Open,
|
||||
) -> io::Result<RetainedProcess>
|
||||
where
|
||||
Boot: FnOnce() -> io::Result<BootId>,
|
||||
Open: FnOnce(u32) -> io::Result<OwnedFd>,
|
||||
{
|
||||
let current_boot = boot()?;
|
||||
if current_boot != identity.authority().boot_id {
|
||||
return Err(io::Error::other(
|
||||
"stored process authority belongs to another boot",
|
||||
));
|
||||
}
|
||||
let host_pid = identity.host_pid().get();
|
||||
let pidfd = open(host_pid)?;
|
||||
let observed = authority_from_pidfd(pidfd.as_fd(), current_boot)?;
|
||||
if observed != identity.authority() {
|
||||
return Err(io::Error::other("pidfs process authority mismatch"));
|
||||
}
|
||||
if read_start_time(host_pid)? != identity.start_time_ticks().get() {
|
||||
return Err(io::Error::other("process start time mismatch"));
|
||||
}
|
||||
Ok(RetainedProcess { pidfd, identity })
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Refuses if arming fails or the exact parent changes during the recheck.
|
||||
pub fn arm_parent_death_and_recheck(
|
||||
signal: Signal,
|
||||
expected_parent: PidfsProcessIdentityV1,
|
||||
) -> io::Result<RetainedProcess> {
|
||||
rustix::process::set_parent_process_death_signal(Some(signal))?;
|
||||
let parent = recover_process(expected_parent)?;
|
||||
let observed_parent = rustix::process::getppid()
|
||||
.map(Pid::as_raw_nonzero)
|
||||
.map(i32::from)
|
||||
.and_then(|pid| u32::try_from(pid).ok());
|
||||
if observed_parent != Some(expected_parent.host_pid().get()) {
|
||||
return Err(io::Error::other(
|
||||
"parent changed while arming parent-death action",
|
||||
));
|
||||
}
|
||||
Ok(parent)
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Returns an error if the current process cannot form a same-pidfd identity.
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
pub fn current_process_identity() -> io::Result<PidfsProcessIdentityV1> {
|
||||
let pid = rustix::process::getpid();
|
||||
let host_pid = u32::try_from(i32::from(pid.as_raw_nonzero()))
|
||||
.map_err(|_| io::Error::other("current PID is out of range"))?;
|
||||
require_host_pid_namespace(host_pid)?;
|
||||
let pidfd = rustix::process::pidfd_open(pid, PidfdFlags::empty())?;
|
||||
let authority = authority_from_pidfd(pidfd.as_fd(), read_boot_id()?)?;
|
||||
Ok(PidfsProcessIdentityV1::new(
|
||||
authority,
|
||||
HostPidLocator::new(host_pid),
|
||||
ProcessStartTimeTicks::new(read_start_time(host_pid)?),
|
||||
))
|
||||
}
|
||||
|
||||
fn authority_from_pidfd(pidfd: impl AsFd, boot_id: BootId) -> io::Result<PidfsProcessAuthorityV1> {
|
||||
authority_from_pidfd_with(
|
||||
pidfd,
|
||||
boot_id,
|
||||
|fd| Ok(fstatfs(fd)?.f_type as i64),
|
||||
|fd| {
|
||||
let stat = fstat(fd)?;
|
||||
Ok((stat.st_dev, stat.st_ino))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn authority_from_pidfd_with<Fs, Stat>(
|
||||
pidfd: impl AsFd,
|
||||
boot_id: BootId,
|
||||
filesystem: Fs,
|
||||
stat: Stat,
|
||||
) -> io::Result<PidfsProcessAuthorityV1>
|
||||
where
|
||||
Fs: FnOnce(std::os::fd::BorrowedFd<'_>) -> io::Result<i64>,
|
||||
Stat: FnOnce(std::os::fd::BorrowedFd<'_>) -> io::Result<(u64, u64)>,
|
||||
{
|
||||
require_pidfs_magic(filesystem(pidfd.as_fd())?)?;
|
||||
let (device, inode) = stat(pidfd.as_fd())?;
|
||||
Ok(PidfsProcessAuthorityV1 {
|
||||
boot_id,
|
||||
pidfs_st_dev: PidfsDeviceId::new(device),
|
||||
pidfs_st_ino: PidfsInodeId::new(inode),
|
||||
})
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Refuses every filesystem magic other than `PID_FS_MAGIC`.
|
||||
pub fn require_pidfs_magic(magic: i64) -> io::Result<()> {
|
||||
if magic == PID_FS_MAGIC {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::other("descriptor is not a pidfs process handle"))
|
||||
}
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Refuses unreadable or non-canonical boot identifiers.
|
||||
pub fn read_boot_id() -> io::Result<BootId> {
|
||||
parse_boot_id(&std::fs::read_to_string("/proc/sys/kernel/random/boot_id")?)
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Refuses every non-canonical UUID spelling.
|
||||
pub fn parse_boot_id(value: &str) -> io::Result<BootId> {
|
||||
let value = value.strip_suffix('\n').unwrap_or(value);
|
||||
if value.len() != 36
|
||||
|| value.as_bytes()[8] != b'-'
|
||||
|| value.as_bytes()[13] != b'-'
|
||||
|| value.as_bytes()[18] != b'-'
|
||||
|| value.as_bytes()[23] != b'-'
|
||||
|| value
|
||||
.bytes()
|
||||
.enumerate()
|
||||
.any(|(index, byte)| !matches!(index, 8 | 13 | 18 | 23) && !byte.is_ascii_hexdigit())
|
||||
{
|
||||
return Err(io::Error::other("boot ID is not a canonical UUID"));
|
||||
}
|
||||
let compact = value.replace('-', "");
|
||||
let mut bytes = [0_u8; 16];
|
||||
for (index, byte) in bytes.iter_mut().enumerate() {
|
||||
*byte = u8::from_str_radix(&compact[index * 2..index * 2 + 2], 16)
|
||||
.map_err(|_| io::Error::other("boot ID is not a canonical UUID"))?;
|
||||
}
|
||||
Ok(BootId::new(bytes))
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Refuses unreadable or malformed process statistics.
|
||||
pub fn read_start_time(host_pid: u32) -> io::Result<u64> {
|
||||
let stat = std::fs::read_to_string(format!("/proc/{host_pid}/stat"))?;
|
||||
let command_end = stat
|
||||
.rfind(") ")
|
||||
.ok_or_else(|| io::Error::other("process stat has no command terminator"))?;
|
||||
stat[command_end + 2..]
|
||||
.split_whitespace()
|
||||
.nth(19)
|
||||
.and_then(|value| value.parse().ok())
|
||||
.ok_or_else(|| io::Error::other("process stat has no valid start time"))
|
||||
}
|
||||
|
||||
fn require_host_pid_namespace(host_pid: u32) -> io::Result<()> {
|
||||
let status = std::fs::read_to_string(format!("/proc/{host_pid}/status"))?;
|
||||
let nspid = status
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("NSpid:"))
|
||||
.ok_or_else(|| io::Error::other("process status has no PID namespace mapping"))?;
|
||||
if nspid.trim() == host_pid.to_string() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::other(
|
||||
"PID locator is not unambiguous in the host PID namespace",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn require_default_sigchld() -> io::Result<()> {
|
||||
let status = std::fs::read_to_string("/proc/self/status")?;
|
||||
let ignored = signal_mask(&status, "SigIgn:")?;
|
||||
let caught = signal_mask(&status, "SigCgt:")?;
|
||||
let sigchld = 1_u128 << (17 - 1);
|
||||
if ignored & sigchld == 0 && caught & sigchld == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::other("SIGCHLD is not at default disposition"))
|
||||
}
|
||||
}
|
||||
|
||||
fn signal_mask(status: &str, name: &str) -> io::Result<u128> {
|
||||
status
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix(name))
|
||||
.and_then(|value| u128::from_str_radix(value.trim(), 16).ok())
|
||||
.ok_or_else(|| io::Error::other("process status has no valid signal mask"))
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Returns an error when the fail-closed pipe cannot be created.
|
||||
pub fn launch_barrier() -> io::Result<(BarrierRelease, BarrierWait)> {
|
||||
let (reader, writer) = pipe_with(PipeFlags::empty())?;
|
||||
fcntl_setfd(writer.as_fd(), FdFlags::CLOEXEC)?;
|
||||
Ok((
|
||||
BarrierRelease(File::from(writer)),
|
||||
BarrierWait(File::from(reader)),
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct BarrierRelease(File);
|
||||
|
||||
impl BarrierRelease {
|
||||
/// # Errors
|
||||
/// Returns an error unless the complete release token is written.
|
||||
pub fn release(mut self) -> io::Result<()> {
|
||||
self.0.write_all(BARRIER_RELEASE)?;
|
||||
self.0.flush()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct BarrierWait(File);
|
||||
|
||||
impl BarrierWait {
|
||||
#[must_use]
|
||||
pub fn into_stdio(self) -> Stdio {
|
||||
Stdio::from(self.0)
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Returns an error when the inherited standard-input descriptor cannot be duplicated.
|
||||
pub fn from_stdin() -> io::Result<Self> {
|
||||
Ok(Self(File::open("/proc/self/fd/0")?))
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Refuses EOF, partial, altered, or overlong releases.
|
||||
pub fn wait(mut self) -> io::Result<()> {
|
||||
let mut release = [0_u8; BARRIER_RELEASE.len()];
|
||||
self.0.read_exact(&mut release)?;
|
||||
let mut excess = [0_u8; 1];
|
||||
if release != *BARRIER_RELEASE || self.0.read(&mut excess)? != 0 {
|
||||
return Err(io::Error::other("malformed launch-barrier release"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::disallowed_types)]
|
||||
pub fn append_parent_identity(
|
||||
command: &mut std::process::Command,
|
||||
identity: PidfsProcessIdentityV1,
|
||||
) {
|
||||
let authority = identity.authority();
|
||||
command
|
||||
.arg("--parent-boot")
|
||||
.arg(hex(authority.boot_id.as_bytes()))
|
||||
.arg("--parent-device")
|
||||
.arg(authority.pidfs_st_dev.get().to_string())
|
||||
.arg("--parent-inode")
|
||||
.arg(authority.pidfs_st_ino.get().to_string())
|
||||
.arg("--parent-pid")
|
||||
.arg(identity.host_pid().get().to_string())
|
||||
.arg("--parent-start")
|
||||
.arg(identity.start_time_ticks().get().to_string());
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Refuses missing, reordered, malformed, or incomplete wrapper arguments.
|
||||
pub fn parse_wrapper_arguments(
|
||||
arguments: impl IntoIterator<Item = OsString>,
|
||||
) -> io::Result<(PidfsProcessIdentityV1, TargetCommand)> {
|
||||
let mut arguments = arguments.into_iter();
|
||||
let boot = named_argument(&mut arguments, "--parent-boot")?;
|
||||
let device = number_argument(&mut arguments, "--parent-device")?;
|
||||
let inode = number_argument(&mut arguments, "--parent-inode")?;
|
||||
let pid = number_argument(&mut arguments, "--parent-pid")?;
|
||||
let start = number_argument(&mut arguments, "--parent-start")?;
|
||||
if arguments.next().as_deref() != Some(OsStr::new("--")) {
|
||||
return Err(io::Error::other("wrapper target separator is missing"));
|
||||
}
|
||||
let program = arguments
|
||||
.next()
|
||||
.ok_or_else(|| io::Error::other("wrapper target is missing"))?;
|
||||
let target = TargetCommand {
|
||||
program,
|
||||
arguments: arguments.collect(),
|
||||
};
|
||||
let boot = parse_boot_hex(&boot)?;
|
||||
Ok((
|
||||
PidfsProcessIdentityV1::new(
|
||||
PidfsProcessAuthorityV1 {
|
||||
boot_id: boot,
|
||||
pidfs_st_dev: PidfsDeviceId::new(device),
|
||||
pidfs_st_ino: PidfsInodeId::new(inode),
|
||||
},
|
||||
HostPidLocator::new(
|
||||
u32::try_from(pid).map_err(|_| io::Error::other("parent PID is out of range"))?,
|
||||
),
|
||||
ProcessStartTimeTicks::new(start),
|
||||
),
|
||||
target,
|
||||
))
|
||||
}
|
||||
|
||||
fn named_argument(
|
||||
arguments: &mut impl Iterator<Item = OsString>,
|
||||
name: &str,
|
||||
) -> io::Result<OsString> {
|
||||
if arguments.next().as_deref() != Some(OsStr::new(name)) {
|
||||
return Err(io::Error::other(format!(
|
||||
"wrapper argument {name} is missing"
|
||||
)));
|
||||
}
|
||||
arguments
|
||||
.next()
|
||||
.ok_or_else(|| io::Error::other(format!("wrapper argument {name} has no value")))
|
||||
}
|
||||
|
||||
fn number_argument(arguments: &mut impl Iterator<Item = OsString>, name: &str) -> io::Result<u64> {
|
||||
named_argument(arguments, name)?
|
||||
.to_str()
|
||||
.and_then(|value| value.parse().ok())
|
||||
.ok_or_else(|| io::Error::other(format!("wrapper argument {name} is invalid")))
|
||||
}
|
||||
|
||||
fn parse_boot_hex(value: &OsStr) -> io::Result<BootId> {
|
||||
let value = value
|
||||
.to_str()
|
||||
.ok_or_else(|| io::Error::other("parent boot ID is not UTF-8"))?;
|
||||
if value.len() != 32 || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
|
||||
return Err(io::Error::other("parent boot ID is invalid"));
|
||||
}
|
||||
let mut bytes = [0_u8; 16];
|
||||
for (index, byte) in bytes.iter_mut().enumerate() {
|
||||
*byte = u8::from_str_radix(&value[index * 2..index * 2 + 2], 16)
|
||||
.map_err(|_| io::Error::other("parent boot ID is invalid"))?;
|
||||
}
|
||||
Ok(BootId::new(bytes))
|
||||
}
|
||||
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
use std::fmt::Write as _;
|
||||
|
||||
bytes.iter().fold(String::new(), |mut output, byte| {
|
||||
write!(output, "{byte:02x}").expect("writing to a String cannot fail");
|
||||
output
|
||||
})
|
||||
}
|
||||
|
||||
#[allow(clippy::disallowed_methods, clippy::disallowed_types)]
|
||||
#[must_use]
|
||||
pub fn exec_target(target: TargetCommand) -> io::Error {
|
||||
use std::os::unix::process::CommandExt;
|
||||
|
||||
std::process::Command::new(target.program)
|
||||
.args(target.arguments)
|
||||
.exec()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::cell::Cell;
|
||||
use std::os::fd::{AsFd, AsRawFd};
|
||||
use std::rc::Rc;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn broker_is_process_global() {
|
||||
assert!(std::ptr::eq(child_broker(), child_broker()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn barrier_reader_is_inheritable_and_writer_is_close_on_exec() {
|
||||
let (release, wait) = launch_barrier().unwrap();
|
||||
let reader_flags = rustix::io::fcntl_getfd(wait.0.as_fd()).unwrap();
|
||||
let writer_flags = rustix::io::fcntl_getfd(release.0.as_fd()).unwrap();
|
||||
assert!(!reader_flags.contains(FdFlags::CLOEXEC));
|
||||
assert!(writer_flags.contains(FdFlags::CLOEXEC));
|
||||
assert_ne!(wait.0.as_raw_fd(), release.0.as_raw_fd());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boot_id_requires_exact_canonical_uuid_syntax() {
|
||||
parse_boot_id("00112233-4455-6677-8899-aabbccddeeff\n").unwrap();
|
||||
for invalid in [
|
||||
"00112233445566778899aabbccddeeff",
|
||||
"00112233_4455-6677-8899-aabbccddeeff",
|
||||
"00112233-4455-6677-8899-aabbccddeeff-extra",
|
||||
"00112233-4455-6677-8899-aabbccddeefg",
|
||||
"00112233-4455-6677-8899-aabbccddeeff\n\n",
|
||||
] {
|
||||
assert!(parse_boot_id(invalid).is_err(), "accepted {invalid}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recovery_checks_boot_before_pid_lookup() {
|
||||
let identity = PidfsProcessIdentityV1::new(
|
||||
PidfsProcessAuthorityV1 {
|
||||
boot_id: BootId::new([1; 16]),
|
||||
pidfs_st_dev: PidfsDeviceId::new(1),
|
||||
pidfs_st_ino: PidfsInodeId::new(1),
|
||||
},
|
||||
HostPidLocator::new(1),
|
||||
ProcessStartTimeTicks::new(1),
|
||||
);
|
||||
let opened = Cell::new(false);
|
||||
let result = recover_process_with(
|
||||
identity,
|
||||
|| Ok(BootId::new([2; 16])),
|
||||
|_| {
|
||||
opened.set(true);
|
||||
unreachable!()
|
||||
},
|
||||
);
|
||||
assert!(result.is_err());
|
||||
assert!(!opened.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pidfs_magic_precedes_same_descriptor_stat_and_errors_refuse() {
|
||||
let file = File::open("/dev/null").unwrap();
|
||||
let raw = file.as_raw_fd();
|
||||
let events = Rc::new(std::cell::RefCell::new(Vec::new()));
|
||||
let filesystem_events = Rc::clone(&events);
|
||||
let stat_events = Rc::clone(&events);
|
||||
let authority = authority_from_pidfd_with(
|
||||
file.as_fd(),
|
||||
BootId::new([1; 16]),
|
||||
move |fd| {
|
||||
filesystem_events
|
||||
.borrow_mut()
|
||||
.push(("fstatfs", fd.as_raw_fd()));
|
||||
Ok(PID_FS_MAGIC)
|
||||
},
|
||||
move |fd| {
|
||||
stat_events.borrow_mut().push(("fstat", fd.as_raw_fd()));
|
||||
Ok((7, 9))
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(&*events.borrow(), &[("fstatfs", raw), ("fstat", raw)]);
|
||||
assert_eq!(authority.pidfs_st_dev.get(), 7);
|
||||
assert_eq!(authority.pidfs_st_ino.get(), 9);
|
||||
|
||||
for filesystem_error in [false, true] {
|
||||
let stat_called = Cell::new(false);
|
||||
let result = authority_from_pidfd_with(
|
||||
file.as_fd(),
|
||||
BootId::new([1; 16]),
|
||||
|_| {
|
||||
if filesystem_error {
|
||||
Err(io::Error::other("injected fstatfs error"))
|
||||
} else {
|
||||
Ok(0)
|
||||
}
|
||||
},
|
||||
|_| {
|
||||
stat_called.set(true);
|
||||
Ok((1, 1))
|
||||
},
|
||||
);
|
||||
assert!(result.is_err());
|
||||
assert!(!stat_called.get());
|
||||
}
|
||||
|
||||
assert!(
|
||||
authority_from_pidfd_with(
|
||||
file.as_fd(),
|
||||
BootId::new([1; 16]),
|
||||
|_| Ok(PID_FS_MAGIC),
|
||||
|_| Err(io::Error::other("injected fstat error")),
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue