Skip to content

Commit 2f8185f

Browse files
committed
fix(sandbox): two-phase Landlock to fix privilege ordering (#803)
Split Landlock apply into prepare() and enforce(): - prepare() runs as root before drop_privileges: opens PathFds, creates ruleset, adds rules. Root-only paths (mode 700) now succeed instead of silently failing as uid 998. - enforce() runs after drop_privileges: calls restrict_self() which does not require root. This fixes the root cause of #803 where drop_privileges() ran before sandbox::apply(), causing PathFd::new() to fail on root-only paths. In best_effort mode this silently dropped all Landlock restrictions. The fix applies to all three spawn paths: entrypoint (process.rs), SSH PTY (ssh.rs), and SSH pipe exec (ssh.rs). Removes xfail marker from e2e test that now passes.
1 parent a178fc9 commit 2f8185f

5 files changed

Lines changed: 184 additions & 111 deletions

File tree

‎crates/openshell-sandbox/src/process.rs‎

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -160,14 +160,24 @@ impl ProcessHandle {
160160
#[cfg(target_os = "linux")]
161161
sandbox::linux::log_sandbox_readiness(policy, workdir);
162162

163+
// Phase 1 (as root): Prepare Landlock ruleset by opening PathFds.
164+
// This MUST happen before drop_privileges() so that root-only paths
165+
// (e.g. mode 700 directories) can be opened. See issue #803.
166+
#[cfg(target_os = "linux")]
167+
let prepared_sandbox = sandbox::linux::prepare(policy, workdir)
168+
.map_err(|err| miette::miette!("Failed to prepare sandbox: {err}"))?;
169+
163170
// Set up process group for signal handling (non-interactive mode only).
164171
// In interactive mode, we inherit the parent's process group to maintain
165172
// proper terminal control for shells and interactive programs.
166173
// SAFETY: pre_exec runs after fork but before exec in the child process.
167174
// setpgid and setns are async-signal-safe and safe to call in this context.
168175
{
169176
let policy = policy.clone();
170-
let workdir = workdir.map(str::to_string);
177+
// Wrap in Option so we can .take() it out of the FnMut closure.
178+
// pre_exec is only called once (after fork, before exec).
179+
#[cfg(target_os = "linux")]
180+
let mut prepared_sandbox = Some(prepared_sandbox);
171181
#[allow(unsafe_code)]
172182
unsafe {
173183
cmd.pre_exec(move || {
@@ -184,14 +194,20 @@ impl ProcessHandle {
184194
}
185195
}
186196

187-
// Drop privileges before applying sandbox restrictions.
188-
// initgroups/setgid/setuid need access to /etc/group and /etc/passwd
189-
// which may be blocked by Landlock.
197+
// Drop privileges. initgroups/setgid/setuid need access to
198+
// /etc/group and /etc/passwd which would be blocked if
199+
// Landlock were already enforced.
190200
drop_privileges(&policy)
191201
.map_err(|err| std::io::Error::other(err.to_string()))?;
192202

193-
sandbox::apply(&policy, workdir.as_deref())
194-
.map_err(|err| std::io::Error::other(err.to_string()))?;
203+
// Phase 2 (as unprivileged user): Enforce the prepared
204+
// Landlock ruleset via restrict_self() + apply seccomp.
205+
// restrict_self() does not require root.
206+
#[cfg(target_os = "linux")]
207+
if let Some(prepared) = prepared_sandbox.take() {
208+
sandbox::linux::enforce(prepared)
209+
.map_err(|err| std::io::Error::other(err.to_string()))?;
210+
}
195211

196212
Ok(())
197213
});

‎crates/openshell-sandbox/src/sandbox/linux/landlock.rs‎

Lines changed: 65 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -75,9 +75,7 @@ pub fn probe_availability() -> LandlockAvailability {
7575
#[allow(clippy::cast_possible_truncation)]
7676
LandlockAvailability::Available { abi: ret as i32 }
7777
} else {
78-
let errno = std::io::Error::last_os_error()
79-
.raw_os_error()
80-
.unwrap_or(0);
78+
let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
8179
match errno {
8280
libc::ENOSYS => LandlockAvailability::NotImplemented,
8381
libc::EOPNOTSUPP => LandlockAvailability::NotEnabled,
@@ -87,7 +85,23 @@ pub fn probe_availability() -> LandlockAvailability {
8785
}
8886
}
8987

90-
pub fn apply(policy: &SandboxPolicy, workdir: Option<&str>) -> Result<()> {
88+
/// A prepared Landlock ruleset ready to be enforced via `restrict_self()`.
89+
///
90+
/// Created by [`prepare`] while running as root (so `PathFd::new()` can open
91+
/// any path regardless of DAC permissions). Enforced by [`enforce`] after
92+
/// `drop_privileges()` — `restrict_self()` does not require elevated privileges.
93+
pub struct PreparedRuleset {
94+
ruleset: landlock::RulesetCreated,
95+
}
96+
97+
/// Phase 1: Open PathFds and build the Landlock ruleset **as root**.
98+
///
99+
/// This must run before `drop_privileges()` so that `PathFd::new()` can open
100+
/// paths that are only accessible to root (e.g. mode 700 directories).
101+
///
102+
/// Returns `None` if there are no filesystem paths to restrict (no-op).
103+
/// Returns `Some(PreparedRuleset)` on success, or an error.
104+
pub fn prepare(policy: &SandboxPolicy, workdir: Option<&str>) -> Result<Option<PreparedRuleset>> {
91105
let read_only = policy.filesystem.read_only.clone();
92106
let mut read_write = policy.filesystem.read_write.clone();
93107

@@ -101,7 +115,7 @@ pub fn apply(policy: &SandboxPolicy, workdir: Option<&str>) -> Result<()> {
101115
}
102116

103117
if read_only.is_empty() && read_write.is_empty() {
104-
return Ok(());
118+
return Ok(None);
105119
}
106120

107121
let total_paths = read_only.len() + read_write.len();
@@ -122,7 +136,7 @@ pub fn apply(policy: &SandboxPolicy, workdir: Option<&str>) -> Result<()> {
122136

123137
let compatibility = &policy.landlock.compatibility;
124138

125-
let result: Result<()> = (|| {
139+
let result: Result<PreparedRuleset> = (|| {
126140
let access_all = AccessFs::from_all(abi);
127141
let access_read = AccessFs::from_read(abi);
128142

@@ -175,36 +189,57 @@ pub fn apply(policy: &SandboxPolicy, workdir: Option<&str>) -> Result<()> {
175189
.build()
176190
);
177191

178-
ruleset.restrict_self().into_diagnostic()?;
179-
Ok(())
192+
Ok(PreparedRuleset { ruleset })
180193
})();
181194

182-
if let Err(err) = result {
183-
if matches!(compatibility, LandlockCompatibility::BestEffort) {
184-
openshell_ocsf::ocsf_emit!(
185-
openshell_ocsf::DetectionFindingBuilder::new(crate::ocsf_ctx())
186-
.activity(openshell_ocsf::ActivityId::Open)
187-
.severity(openshell_ocsf::SeverityId::High)
188-
.confidence(openshell_ocsf::ConfidenceId::High)
189-
.is_alert(true)
190-
.finding_info(
191-
openshell_ocsf::FindingInfo::new(
192-
"landlock-unavailable",
193-
"Landlock Filesystem Sandbox Unavailable",
195+
match result {
196+
Ok(prepared) => Ok(Some(prepared)),
197+
Err(err) => {
198+
if matches!(compatibility, LandlockCompatibility::BestEffort) {
199+
openshell_ocsf::ocsf_emit!(
200+
openshell_ocsf::DetectionFindingBuilder::new(crate::ocsf_ctx())
201+
.activity(openshell_ocsf::ActivityId::Open)
202+
.severity(openshell_ocsf::SeverityId::High)
203+
.confidence(openshell_ocsf::ConfidenceId::High)
204+
.is_alert(true)
205+
.finding_info(
206+
openshell_ocsf::FindingInfo::new(
207+
"landlock-unavailable",
208+
"Landlock Filesystem Sandbox Unavailable",
209+
)
210+
.with_desc(&format!(
211+
"Running WITHOUT filesystem restrictions: {err}. \
212+
Set landlock.compatibility to 'hard_requirement' to make this fatal."
213+
)),
194214
)
195-
.with_desc(&format!(
196-
"Running WITHOUT filesystem restrictions: {err}. \
197-
Set landlock.compatibility to 'hard_requirement' to make this fatal."
198-
)),
199-
)
200-
.message(format!("Landlock filesystem sandbox unavailable: {err}"))
201-
.build()
202-
);
203-
return Ok(());
215+
.message(format!("Landlock filesystem sandbox unavailable: {err}"))
216+
.build()
217+
);
218+
Ok(None)
219+
} else {
220+
Err(err)
221+
}
204222
}
205-
return Err(err);
206223
}
224+
}
225+
226+
/// Phase 2: Enforce a prepared Landlock ruleset by calling `restrict_self()`.
227+
///
228+
/// This runs **after** `drop_privileges()`. The `restrict_self()` syscall does
229+
/// not require root — it only restricts the calling thread (and its future
230+
/// children), which is always permitted.
231+
pub fn enforce(prepared: PreparedRuleset) -> Result<()> {
232+
prepared.ruleset.restrict_self().into_diagnostic()?;
233+
Ok(())
234+
}
207235

236+
/// Legacy single-phase apply. Kept for non-Linux platforms and tests.
237+
/// On Linux, callers should use [`prepare`] + [`enforce`] for correct
238+
/// privilege ordering.
239+
pub fn apply(policy: &SandboxPolicy, workdir: Option<&str>) -> Result<()> {
240+
if let Some(prepared) = prepare(policy, workdir)? {
241+
enforce(prepared)?;
242+
}
208243
Ok(())
209244
}
210245

‎crates/openshell-sandbox/src/sandbox/linux/mod.rs‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,39 @@ use miette::Result;
1212
use std::path::PathBuf;
1313
use std::sync::Once;
1414

15+
/// Opaque handle to a prepared-but-not-yet-enforced sandbox.
16+
/// Holds the Landlock ruleset with PathFds opened as root.
17+
pub struct PreparedSandbox {
18+
landlock: Option<landlock::PreparedRuleset>,
19+
policy: SandboxPolicy,
20+
}
21+
22+
/// Phase 1: Prepare sandbox restrictions **as root** (before `drop_privileges`).
23+
///
24+
/// Opens Landlock PathFds while the process still has root privileges,
25+
/// ensuring paths like mode-700 directories are accessible.
26+
pub fn prepare(policy: &SandboxPolicy, workdir: Option<&str>) -> Result<PreparedSandbox> {
27+
let landlock = landlock::prepare(policy, workdir)?;
28+
Ok(PreparedSandbox {
29+
landlock,
30+
policy: policy.clone(),
31+
})
32+
}
33+
34+
/// Phase 2: Enforce prepared sandbox restrictions (after `drop_privileges`).
35+
///
36+
/// Calls `restrict_self()` for Landlock and applies seccomp filters.
37+
/// Neither operation requires root privileges.
38+
pub fn enforce(prepared: PreparedSandbox) -> Result<()> {
39+
if let Some(ruleset) = prepared.landlock {
40+
landlock::enforce(ruleset)?;
41+
}
42+
seccomp::apply(&prepared.policy)?;
43+
Ok(())
44+
}
45+
46+
/// Legacy single-phase apply. Kept for backward compatibility.
47+
/// New callers should use [`prepare`] + [`enforce`] for correct privilege ordering.
1548
pub fn apply(policy: &SandboxPolicy, workdir: Option<&str>) -> Result<()> {
1649
landlock::apply(policy, workdir)?;
1750
seccomp::apply(policy)?;

‎crates/openshell-sandbox/src/ssh.rs‎

Lines changed: 64 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -900,7 +900,12 @@ fn spawn_pty_shell(
900900

901901
// Probe Landlock availability from the parent process where tracing works.
902902
#[cfg(target_os = "linux")]
903-
crate::sandbox::linux::log_sandbox_readiness(policy, workdir.as_deref());
903+
sandbox::linux::log_sandbox_readiness(policy, workdir.as_deref());
904+
905+
// Phase 1 (as root): Prepare Landlock ruleset before drop_privileges.
906+
#[cfg(target_os = "linux")]
907+
let prepared_sandbox = sandbox::linux::prepare(policy, workdir.as_deref())
908+
.map_err(|err| anyhow::anyhow!("Failed to prepare sandbox: {err}"))?;
904909

905910
#[cfg(unix)]
906911
{
@@ -910,6 +915,8 @@ fn spawn_pty_shell(
910915
workdir.clone(),
911916
slave_fd,
912917
netns_fd,
918+
#[cfg(target_os = "linux")]
919+
prepared_sandbox,
913920
);
914921
}
915922

@@ -1040,11 +1047,23 @@ fn spawn_pipe_exec(
10401047

10411048
// Probe Landlock availability from the parent process where tracing works.
10421049
#[cfg(target_os = "linux")]
1043-
crate::sandbox::linux::log_sandbox_readiness(policy, workdir.as_deref());
1050+
sandbox::linux::log_sandbox_readiness(policy, workdir.as_deref());
1051+
1052+
// Phase 1 (as root): Prepare Landlock ruleset before drop_privileges.
1053+
#[cfg(target_os = "linux")]
1054+
let prepared_sandbox = sandbox::linux::prepare(policy, workdir.as_deref())
1055+
.map_err(|err| anyhow::anyhow!("Failed to prepare sandbox: {err}"))?;
10441056

10451057
#[cfg(unix)]
10461058
{
1047-
unsafe_pty::install_pre_exec_no_pty(&mut cmd, policy.clone(), workdir.clone(), netns_fd);
1059+
unsafe_pty::install_pre_exec_no_pty(
1060+
&mut cmd,
1061+
policy.clone(),
1062+
workdir.clone(),
1063+
netns_fd,
1064+
#[cfg(target_os = "linux")]
1065+
prepared_sandbox,
1066+
);
10481067
}
10491068

10501069
let mut child = cmd.spawn()?;
@@ -1139,7 +1158,9 @@ fn spawn_pipe_exec(
11391158
}
11401159

11411160
mod unsafe_pty {
1142-
use super::{Command, RawFd, SandboxPolicy, Winsize, drop_privileges, sandbox, setsid};
1161+
#[cfg(not(target_os = "linux"))]
1162+
use super::sandbox;
1163+
use super::{Command, RawFd, SandboxPolicy, Winsize, drop_privileges, setsid};
11431164
#[cfg(unix)]
11441165
use std::os::unix::process::CommandExt;
11451166

@@ -1165,16 +1186,26 @@ mod unsafe_pty {
11651186
pub fn install_pre_exec(
11661187
cmd: &mut Command,
11671188
policy: SandboxPolicy,
1168-
workdir: Option<String>,
1189+
_workdir: Option<String>,
11691190
slave_fd: RawFd,
11701191
netns_fd: Option<RawFd>,
1192+
#[cfg(target_os = "linux")] prepared: crate::sandbox::linux::PreparedSandbox,
11711193
) {
1194+
// Wrap in Option so we can .take() it out of the FnMut closure.
1195+
// pre_exec is only called once (after fork, before exec).
1196+
#[cfg(target_os = "linux")]
1197+
let mut prepared = Some(prepared);
11721198
unsafe {
11731199
cmd.pre_exec(move || {
11741200
setsid().map_err(|err| std::io::Error::other(err.to_string()))?;
11751201
set_controlling_tty(slave_fd)?;
11761202

1177-
enter_netns_and_sandbox(netns_fd, &policy, workdir.as_deref())
1203+
enter_netns_and_sandbox(
1204+
netns_fd,
1205+
&policy,
1206+
#[cfg(target_os = "linux")]
1207+
prepared.take(),
1208+
)
11781209
});
11791210
}
11801211
}
@@ -1186,18 +1217,28 @@ mod unsafe_pty {
11861217
pub fn install_pre_exec_no_pty(
11871218
cmd: &mut Command,
11881219
policy: SandboxPolicy,
1189-
workdir: Option<String>,
1220+
_workdir: Option<String>,
11901221
netns_fd: Option<RawFd>,
1222+
#[cfg(target_os = "linux")] prepared: crate::sandbox::linux::PreparedSandbox,
11911223
) {
1224+
#[cfg(target_os = "linux")]
1225+
let mut prepared = Some(prepared);
11921226
unsafe {
1193-
cmd.pre_exec(move || enter_netns_and_sandbox(netns_fd, &policy, workdir.as_deref()));
1227+
cmd.pre_exec(move || {
1228+
enter_netns_and_sandbox(
1229+
netns_fd,
1230+
&policy,
1231+
#[cfg(target_os = "linux")]
1232+
prepared.take(),
1233+
)
1234+
});
11941235
}
11951236
}
11961237

11971238
fn enter_netns_and_sandbox(
11981239
netns_fd: Option<RawFd>,
11991240
policy: &SandboxPolicy,
1200-
workdir: Option<&str>,
1241+
#[cfg(target_os = "linux")] prepared: Option<crate::sandbox::linux::PreparedSandbox>,
12011242
) -> std::io::Result<()> {
12021243
// Enter network namespace before dropping privileges.
12031244
// This ensures SSH shell processes are isolated to the same
@@ -1215,11 +1256,21 @@ mod unsafe_pty {
12151256
#[cfg(not(target_os = "linux"))]
12161257
let _ = netns_fd;
12171258

1218-
// Drop privileges before applying sandbox restrictions.
1219-
// initgroups/setgid/setuid need access to /etc/group and /etc/passwd
1220-
// which may be blocked by Landlock.
1259+
// Drop privileges. initgroups/setgid/setuid need /etc/group and
1260+
// /etc/passwd which would be blocked if Landlock were already enforced.
12211261
drop_privileges(policy).map_err(|err| std::io::Error::other(err.to_string()))?;
1222-
sandbox::apply(policy, workdir).map_err(|err| std::io::Error::other(err.to_string()))?;
1262+
1263+
// Phase 2: Enforce the prepared Landlock ruleset + seccomp.
1264+
// restrict_self() does not require root.
1265+
#[cfg(target_os = "linux")]
1266+
if let Some(prepared) = prepared {
1267+
crate::sandbox::linux::enforce(prepared)
1268+
.map_err(|err| std::io::Error::other(err.to_string()))?;
1269+
}
1270+
1271+
#[cfg(not(target_os = "linux"))]
1272+
sandbox::apply(policy, None).map_err(|err| std::io::Error::other(err.to_string()))?;
1273+
12231274
Ok(())
12241275
}
12251276
}

0 commit comments

Comments
 (0)