Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/openshell-sandbox/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ tracing-subscriber = { workspace = true }

[target.'cfg(unix)'.dependencies]
libc = "0.2"
rustix = { workspace = true, features = ["termios", "fs", "process", "net", "event"] }
rustix = { workspace = true, features = ["termios", "fs", "process", "net", "event", "pipe"] }
russh-sftp = "3.0"
uuid = { workspace = true }

Expand Down
92 changes: 80 additions & 12 deletions crates/openshell-sandbox/src/boundary_exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,23 +252,32 @@ impl LocalBoundaryExec {
#[cfg(target_os = "linux")]
let child_hardening = crate::linux::child_seccomp::prepare(std::process::id())
.map_err(|error| BackendError::Process(error.to_string()))?;
#[cfg(target_os = "linux")]
let landlock_report = crate::sandbox::linux::LandlockReportPipe::new()
.map_err(|error| BackendError::Process(error.to_string()))?;
#[cfg(target_os = "linux")]
let landlock_report_fd = landlock_report.child_fd();
crate::pty::install_dedicated_process_group(&mut command);
crate::pty::install_pre_exec_no_pty(
&mut command,
self.policy.clone(),
effective_workdir.map(str::to_string),
#[cfg(target_os = "linux")]
prepared,
#[cfg(target_os = "linux")]
child_hardening,
crate::sandbox::linux::ChildSandboxInstall::new(
prepared,
child_hardening,
landlock_report_fd,
),
)
.map_err(|error| BackendError::Process(error.to_string()))?;
#[cfg(target_os = "linux")]
let mut child_registry = crate::managed_children::lock();
#[cfg(target_os = "linux")]
let mut child =
crate::process::spawn_std_command_with_workload_launcher(&self.launcher, command)
.map_err(|error| BackendError::Process(error.to_string()))?;
let mut child = landlock_report
.spawn_and_drain(|| {
crate::process::spawn_std_command_with_workload_launcher(&self.launcher, command)
})
.map_err(|error| BackendError::Process(error.to_string()))?;
#[cfg(not(target_os = "linux"))]
let mut child = command
.spawn()
Expand Down Expand Up @@ -392,23 +401,32 @@ impl LocalBoundaryExec {
#[cfg(target_os = "linux")]
let child_hardening = crate::linux::child_seccomp::prepare(std::process::id())
.map_err(|error| BackendError::Process(error.to_string()))?;
#[cfg(target_os = "linux")]
let landlock_report = crate::sandbox::linux::LandlockReportPipe::new()
.map_err(|error| BackendError::Process(error.to_string()))?;
#[cfg(target_os = "linux")]
let landlock_report_fd = landlock_report.child_fd();
crate::pty::install_pre_exec(
&mut command,
self.policy.clone(),
effective_workdir.map(str::to_string),
slave_fd,
#[cfg(target_os = "linux")]
prepared,
#[cfg(target_os = "linux")]
child_hardening,
crate::sandbox::linux::ChildSandboxInstall::new(
prepared,
child_hardening,
landlock_report_fd,
),
)
.map_err(|error| BackendError::Process(error.to_string()))?;
#[cfg(target_os = "linux")]
let mut child_registry = crate::managed_children::lock();
#[cfg(target_os = "linux")]
let mut child =
crate::process::spawn_std_command_with_workload_launcher(&self.launcher, command)
.map_err(|error| BackendError::Process(error.to_string()))?;
let mut child = landlock_report
.spawn_and_drain(|| {
crate::process::spawn_std_command_with_workload_launcher(&self.launcher, command)
})
.map_err(|error| BackendError::Process(error.to_string()))?;
#[cfg(not(target_os = "linux"))]
let mut child = command
.spawn()
Expand Down Expand Up @@ -1366,6 +1384,56 @@ mod tests {
assert_eq!(runtime.registered_process_group_count(), 0);
}

/// A failed spawn must return promptly with the Landlock report drain
/// already run. Every spawn surface drains through
/// `LandlockReportPipe::spawn_and_drain`, which drops the parent's write
/// end and drains on both spawn outcomes before the error is mapped, so
/// the error path cannot stall on a never-EOF pipe (a drain that never
/// drops the parent's write end blocks forever). Forcing a real
/// `restrict_self` degradation through this public
/// spawn API is not possible — the blocking seccomp filter used in the
/// landlock tests can only be installed in a forked child — so this pins
/// the closest observable contract: both spawn surfaces return the spawn
/// error instead of hanging. Each exec runs on a dedicated thread waited
/// with a channel timeout, so a stalled drain fails the test cleanly
/// instead of deadlocking the test runtime's shutdown.
#[test]
fn failed_exec_drains_the_landlock_report_pipe_before_returning() {
for pty in [false, true] {
let mut executor = executor();
// Best-effort Landlock over a real path, so the forked child
// prepares and enforces a ruleset before the exec failure.
let root = tempfile::tempdir().unwrap();
executor.policy.filesystem.read_only = vec![root.path().to_path_buf()];
executor.policy.landlock.compatibility =
openshell_core::policy::LandlockCompatibility::BestEffort;
let spec = ExecSpec {
program: "/definitely/missing/openshell-exec".to_string(),
args: vec![],
shell: None,
runtime_helper: None,
env: vec![],
workdir: None,
pty,
};
let (result_tx, result_rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("build exec runtime");
let _ = result_tx.send(runtime.block_on(executor.exec(spec)));
});
let result = result_rx
.recv_timeout(std::time::Duration::from_secs(10))
.expect("exec must return instead of stalling on the Landlock report pipe");
assert!(
matches!(result, Err(BackendError::Process(_))),
"the missing entrypoint must surface as the spawn error"
);
}
}

#[tokio::test]
async fn exec_records_its_launch_and_exit() {
use openshell_sandbox_backend::boundary_protocol::{ExitStatusWire, ProcessEventKindWire};
Expand Down
136 changes: 117 additions & 19 deletions crates/openshell-sandbox/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,23 +336,25 @@ fn compose_canonical_process_environment(
}

#[cfg(unix)]
pub fn harden_child_process() -> Result<()> {
pub fn harden_child_process() -> std::io::Result<()> {
use rustix::process::{Resource, Rlimit, setrlimit};

// Called between fork and exec: errors must stay errno-based and
// allocation-free so std's pre_exec error pipe carries the real errno
// to the parent instead of the EINVAL fallback for non-os errors.
setrlimit(
Resource::Core,
Rlimit {
current: Some(0),
maximum: Some(0),
},
)
.map_err(|e| miette::miette!("Failed to disable core dumps: {e}"))?;
.map_err(std::io::Error::from)?;

#[cfg(target_os = "linux")]
{
use rustix::process::{DumpableBehavior, set_dumpable_behavior};
set_dumpable_behavior(DumpableBehavior::NotDumpable)
.map_err(|e| miette::miette!("Failed to set PR_SET_DUMPABLE=0: {e}"))?;
set_dumpable_behavior(DumpableBehavior::NotDumpable).map_err(std::io::Error::from)?;
}

Ok(())
Expand Down Expand Up @@ -616,18 +618,37 @@ impl ProcessHandle {
let prepared_sandbox = prepare_child_sandbox(policy, workspace.root(), &runtime_read_only)
.map_err(|err| miette::miette!("Failed to prepare sandbox: {err}"))?;
#[cfg(target_os = "linux")]
let mut child_hardening = crate::linux::child_seccomp::prepare(std::process::id())
let child_hardening = crate::linux::child_seccomp::prepare(std::process::id())
.map_err(|error| miette::miette!("prepare child self-protection filter: {error}"))?;
// Landlock best-effort degradation is reported to this thread over a
// CLOEXEC pipe instead of being logged from the forked child.
let landlock_report = sandbox::linux::LandlockReportPipe::new()
.map_err(|error| miette::miette!("create Landlock report pipe: {error}"))?;
let landlock_report_fd = landlock_report.child_fd();
#[cfg(target_os = "linux")]
let child_install = sandbox::linux::ChildSandboxInstall::new(
prepared_sandbox,
child_hardening,
landlock_report_fd,
);
// Set up process group for signal handling (non-interactive mode only).
// In interactive mode, we inherit the parent's process group to maintain
// proper terminal control for shells and interactive programs.
// SAFETY: pre_exec runs after fork but before exec in the child process.
// setpgid and setns are async-signal-safe and safe to call in this context.
// SAFETY: pre_exec runs after fork but before exec in the child of a
// multithreaded process. The hook uses raw session/process-group and
// TTY syscalls plus harden_child_process (rlimit/prctl), then installs
// only parent-prebuilt sandbox state; a best-effort Landlock failure
// crosses to the parent as one fixed-size pipe record. The success and
// degradation paths allocate nothing and emit no tracing or OCSF; a
// hard error returns an errno-based io::Error, which std reports
// across the fork pipe without allocating (it forwards the raw errno
// and falls back to EINVAL for non-os errors).
{
// Wrap in Option so we can .take() it out of the FnMut closure.
// Rebind as mut so the FnMut closure can run the install, which
// takes the prepared sandbox out of its Option.
// pre_exec is only called once (after fork, before exec).
#[cfg(target_os = "linux")]
let mut prepared_sandbox = prepared_sandbox;
let mut child_install = child_install;
#[allow(unsafe_code)]
// SAFETY: pre_exec only registers the hook; the closure runs
// post-fork and pre-exec in the child process, never in the
Expand All @@ -643,30 +664,32 @@ impl ProcessHandle {
return Err(std::io::Error::last_os_error());
}

harden_child_process().map_err(|err| std::io::Error::other(err.to_string()))?;
harden_child_process()?;

// Phase 2 (as unprivileged user): Enforce the prepared
// Landlock ruleset via restrict_self() + apply seccomp.
// Landlock ruleset via restrict_self() and install the
// prebuilt seccomp filters.
// restrict_self() does not require root.
#[cfg(target_os = "linux")]
if let Some(prepared) = prepared_sandbox.take() {
sandbox::linux::enforce_capability_free(prepared, &mut child_hardening)
.map_err(|err| std::io::Error::other(err.to_string()))?;
}
child_install.enforce()?;

Ok(())
});
}
}

// The registry lock is held across spawn and the Landlock report
// drain so a child exiting during the drain is registered before
// the orphan reaper can consider it.
#[cfg(target_os = "linux")]
let mut child_registry = managed_children::lock();
// Name the program in the error: a bare "No such file or directory"
// here is otherwise indistinguishable from a missing working directory
// or interpreter, and is a common failure on images that lack the
// requested shell/binary (e.g. bash on Alpine).
#[cfg(target_os = "linux")]
let mut child_registry = managed_children::lock();
#[cfg(target_os = "linux")]
let mut child = spawn_command_with_workload_launcher(launcher, cmd)
let mut child = landlock_report
.spawn_and_drain(|| spawn_command_with_workload_launcher(launcher, cmd))
.into_diagnostic()
.wrap_err_with(|| format!("failed to spawn sandbox entrypoint process '{program}'"))?;
#[cfg(not(target_os = "linux"))]
Expand Down Expand Up @@ -781,7 +804,7 @@ impl ProcessHandle {
return Err(std::io::Error::last_os_error());
}

harden_child_process().map_err(|err| std::io::Error::other(err.to_string()))?;
harden_child_process()?;
sandbox::apply(&policy, workdir.as_deref())
.map_err(|err| std::io::Error::other(err.to_string()))?;

Expand Down Expand Up @@ -1754,6 +1777,81 @@ mod tests {
assert_eq!(probe_hardened_child(dumpable_flag_probe), 0);
}

/// `ProcessHandle::spawn` must drain the Landlock report pipe after
/// `spawn` returns but before mapping the spawn error, so a failed spawn
/// still returns promptly instead of stalling on a never-EOF pipe (the
/// drain blocks forever if the parent's write end is never dropped).
/// Forcing a real `restrict_self` degradation through this
/// public spawn API is not possible — the blocking seccomp filter used
/// in the landlock tests can only be installed in a forked child — so
/// this pins the closest observable contract: the failed spawn returns
/// its entrypoint error rather than hanging. The spawn runs on a
/// dedicated thread waited with a channel timeout, so a stalled drain
/// fails the test cleanly instead of deadlocking a runtime shutdown.
#[cfg(target_os = "linux")]
#[test]
fn failed_spawn_drains_the_landlock_report_pipe_before_returning() {
if sandbox::linux::require_landlock_abi().is_err() {
return;
}
let (launcher, listener) =
crate::linux::workload_launcher::start().expect("start test workload launcher");
std::thread::spawn(move || {
while let Ok(notification) = listener.receive() {
let syscall = i64::from(notification.syscall);
if syscall == libc::SYS_openat || syscall == libc::SYS_openat2 {
let _ = listener.respond_continue(notification.id);
} else {
#[cfg(target_arch = "x86_64")]
if syscall == libc::SYS_open {
let _ = listener.respond_continue(notification.id);
continue;
}
let _ = listener.respond_errno(notification.id, libc::EPERM);
}
}
});
let root = tempfile::tempdir().unwrap();
let mut policy = policy_with_process(ProcessPolicy::default());
policy.filesystem.read_only = vec![root.path().to_path_buf()];
policy.landlock = LandlockPolicy {
compatibility: openshell_core::policy::LandlockCompatibility::BestEffort,
};
let provider_env = HashMap::new();
let (result_tx, result_rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("build spawn runtime");
let _entered = runtime.enter();
let _ = result_tx.send(ProcessHandle::spawn(
&launcher,
"/definitely/missing/openshell-entrypoint",
&[],
&ResolvedWorkspace::default(),
false,
&policy,
None,
child_env::TlsEnvironmentMode::Override,
&provider_env,
false,
));
});
let result = result_rx
.recv_timeout(std::time::Duration::from_secs(10))
.expect("spawn must return instead of stalling on the Landlock report pipe");
let Err(error) = result else {
panic!("the missing entrypoint must fail the spawn");
};
assert!(
error
.to_string()
.contains("failed to spawn sandbox entrypoint"),
"the error must come from the entrypoint spawn, not an earlier step: {error}"
);
}

#[test]
#[cfg(target_os = "linux")]
fn parse_pids_max_detects_limited_runtime() {
Expand Down
Loading
Loading