Skip to content

Commit 29a3b1c

Browse files
authored
fix(sandbox): two-phase Landlock to fix privilege ordering and add enforcement tests (#810)
* fix(sandbox): add parent-side Landlock availability probe logging Landlock status was only logged from inside the pre_exec child process where the tracing/OCSF pipeline is non-functional after fork. This made Landlock failures completely invisible in sandbox logs. Add a probe_availability() function that issues the raw landlock_create_ruleset syscall to check kernel support, and call it from the parent process before fork in all three spawn paths (entrypoint, SSH PTY, SSH pipe). Uses std::sync::Once to emit exactly once per sandbox lifetime. WIP - addresses logging gap from #803. * test(e2e): add Landlock filesystem enforcement tests Verify Landlock availability logging and enforcement in e2e: - OCSF probe event appears in sandbox logs - Read-only paths block writes, allow reads - Read-write paths allow both - Paths outside policy are denied entirely - User-owned paths outside policy are still blocked (proves Landlock enforces independently of Unix DAC permissions) Requires Linux host with Landlock support (GitHub Actions runners, Docker Desktop linuxkit). Related to #803. * test(e2e): add xfail tests proving #803 privilege ordering bug Two strict xfail tests that demonstrate the root cause of #803: - PathFd::new() runs as uid 998 after drop_privileges, so root-only paths (mode 700) silently fail and Landlock degrades - When ALL paths fail, best_effort silently drops Landlock entirely These tests will pass after the two-phase Landlock fix (open PathFds as root before drop_privileges, restrict_self after). * fix(test): fix Landlock e2e tests based on test run results - Remove log-reading tests: the Landlock probe logs to the supervisor's container stdout, not the in-sandbox file appender at /var/log/openshell*.log* - Replace broken xfail test (checked for child-process log messages that never reach the file appender) with a stat()-based test that verifies /root is actually in the Landlock allowlist - Keep enforcement tests (all passing) and the root-only policy xfail test (correctly proves #803 bug) * fix(test): remove mixed-policy xfail test Landlock doesn't restrict stat(), so the test passed unexpectedly. In the mixed policy case where /root is silently skipped, Landlock still applies (using other paths) and blocks /root even harder (not in allowlist = denied). The observable security degradation only occurs when ALL paths fail, which the existing xfail test already covers. * 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. * fix(sandbox): address PR review feedback - enforce() now respects best_effort: if restrict_self() fails and policy is best_effort, log and degrade instead of aborting startup - log_sandbox_readiness distinguishes best_effort (degraded) from hard_requirement (will fail) in OCSF messages
1 parent 9e721df commit 29a3b1c

5 files changed

Lines changed: 627 additions & 27 deletions

File tree

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

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -154,14 +154,30 @@ impl ProcessHandle {
154154
}
155155
}
156156

157+
// Probe Landlock availability and emit OCSF logs from the parent
158+
// process where the tracing subscriber is functional. The child's
159+
// pre_exec context cannot reliably emit structured logs.
160+
#[cfg(target_os = "linux")]
161+
sandbox::linux::log_sandbox_readiness(policy, workdir);
162+
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+
157170
// Set up process group for signal handling (non-interactive mode only).
158171
// In interactive mode, we inherit the parent's process group to maintain
159172
// proper terminal control for shells and interactive programs.
160173
// SAFETY: pre_exec runs after fork but before exec in the child process.
161174
// setpgid and setns are async-signal-safe and safe to call in this context.
162175
{
163176
let policy = policy.clone();
164-
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);
165181
#[allow(unsafe_code)]
166182
unsafe {
167183
cmd.pre_exec(move || {
@@ -178,14 +194,20 @@ impl ProcessHandle {
178194
}
179195
}
180196

181-
// Drop privileges before applying sandbox restrictions.
182-
// initgroups/setgid/setuid need access to /etc/group and /etc/passwd
183-
// 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.
184200
drop_privileges(&policy)
185201
.map_err(|err| std::io::Error::other(err.to_string()))?;
186202

187-
sandbox::apply(&policy, workdir.as_deref())
188-
.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+
}
189211

190212
Ok(())
191213
});

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

Lines changed: 175 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,97 @@ use miette::{IntoDiagnostic, Result};
1212
use std::path::{Path, PathBuf};
1313
use tracing::debug;
1414

15-
pub fn apply(policy: &SandboxPolicy, workdir: Option<&str>) -> Result<()> {
15+
/// Result of probing the kernel for Landlock support.
16+
#[derive(Debug)]
17+
pub enum LandlockAvailability {
18+
/// Landlock is available with the given ABI version.
19+
Available { abi: i32 },
20+
/// Kernel does not implement Landlock (ENOSYS).
21+
NotImplemented,
22+
/// Landlock is compiled in but not enabled at boot (EOPNOTSUPP).
23+
NotEnabled,
24+
/// Landlock syscall is blocked, likely by a container seccomp profile (EPERM).
25+
Blocked,
26+
/// Unexpected error from the probe syscall.
27+
Unknown(i32),
28+
}
29+
30+
impl std::fmt::Display for LandlockAvailability {
31+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32+
match self {
33+
Self::Available { abi } => write!(f, "available (ABI v{abi})"),
34+
Self::NotImplemented => {
35+
write!(f, "not implemented (kernel lacks CONFIG_SECURITY_LANDLOCK)")
36+
}
37+
Self::NotEnabled => write!(
38+
f,
39+
"not enabled (Landlock built into kernel but not in active LSM list)"
40+
),
41+
Self::Blocked => write!(
42+
f,
43+
"blocked (container seccomp profile denies Landlock syscalls)"
44+
),
45+
Self::Unknown(errno) => write!(f, "unexpected probe error (errno {errno})"),
46+
}
47+
}
48+
}
49+
50+
/// Probe the kernel for Landlock support by issuing the `landlock_create_ruleset`
51+
/// syscall with the version-check flag.
52+
///
53+
/// This is safe to call from the parent process and does not create any file
54+
/// descriptors or modify process state.
55+
pub fn probe_availability() -> LandlockAvailability {
56+
// landlock_create_ruleset syscall number (same on x86_64 and aarch64).
57+
const SYS_LANDLOCK_CREATE_RULESET: libc::c_long = 444;
58+
// Flag: return the highest supported ABI version instead of creating a ruleset.
59+
const LANDLOCK_CREATE_RULESET_VERSION: libc::c_uint = 1 << 0;
60+
61+
// SAFETY: landlock_create_ruleset(NULL, 0, LANDLOCK_CREATE_RULESET_VERSION)
62+
// is a read-only probe that returns the ABI version or an error code.
63+
// It does not allocate file descriptors or modify process state.
64+
#[allow(unsafe_code)]
65+
let ret = unsafe {
66+
libc::syscall(
67+
SYS_LANDLOCK_CREATE_RULESET,
68+
std::ptr::null::<libc::c_void>(),
69+
0_usize,
70+
LANDLOCK_CREATE_RULESET_VERSION,
71+
)
72+
};
73+
74+
if ret >= 0 {
75+
#[allow(clippy::cast_possible_truncation)]
76+
LandlockAvailability::Available { abi: ret as i32 }
77+
} else {
78+
let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
79+
match errno {
80+
libc::ENOSYS => LandlockAvailability::NotImplemented,
81+
libc::EOPNOTSUPP => LandlockAvailability::NotEnabled,
82+
libc::EPERM => LandlockAvailability::Blocked,
83+
other => LandlockAvailability::Unknown(other),
84+
}
85+
}
86+
}
87+
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+
compatibility: LandlockCompatibility,
96+
}
97+
98+
/// Phase 1: Open PathFds and build the Landlock ruleset **as root**.
99+
///
100+
/// This must run before `drop_privileges()` so that `PathFd::new()` can open
101+
/// paths that are only accessible to root (e.g. mode 700 directories).
102+
///
103+
/// Returns `None` if there are no filesystem paths to restrict (no-op).
104+
/// Returns `Some(PreparedRuleset)` on success, or an error.
105+
pub fn prepare(policy: &SandboxPolicy, workdir: Option<&str>) -> Result<Option<PreparedRuleset>> {
16106
let read_only = policy.filesystem.read_only.clone();
17107
let mut read_write = policy.filesystem.read_write.clone();
18108

@@ -26,7 +116,7 @@ pub fn apply(policy: &SandboxPolicy, workdir: Option<&str>) -> Result<()> {
26116
}
27117

28118
if read_only.is_empty() && read_write.is_empty() {
29-
return Ok(());
119+
return Ok(None);
30120
}
31121

32122
let total_paths = read_only.len() + read_write.len();
@@ -47,7 +137,7 @@ pub fn apply(policy: &SandboxPolicy, workdir: Option<&str>) -> Result<()> {
47137

48138
let compatibility = &policy.landlock.compatibility;
49139

50-
let result: Result<()> = (|| {
140+
let result: Result<PreparedRuleset> = (|| {
51141
let access_all = AccessFs::from_all(abi);
52142
let access_read = AccessFs::from_read(abi);
53143

@@ -100,12 +190,56 @@ pub fn apply(policy: &SandboxPolicy, workdir: Option<&str>) -> Result<()> {
100190
.build()
101191
);
102192

103-
ruleset.restrict_self().into_diagnostic()?;
104-
Ok(())
193+
Ok(PreparedRuleset {
194+
ruleset,
195+
compatibility: compatibility.clone(),
196+
})
105197
})();
106198

199+
match result {
200+
Ok(prepared) => Ok(Some(prepared)),
201+
Err(err) => {
202+
if matches!(compatibility, LandlockCompatibility::BestEffort) {
203+
openshell_ocsf::ocsf_emit!(
204+
openshell_ocsf::DetectionFindingBuilder::new(crate::ocsf_ctx())
205+
.activity(openshell_ocsf::ActivityId::Open)
206+
.severity(openshell_ocsf::SeverityId::High)
207+
.confidence(openshell_ocsf::ConfidenceId::High)
208+
.is_alert(true)
209+
.finding_info(
210+
openshell_ocsf::FindingInfo::new(
211+
"landlock-unavailable",
212+
"Landlock Filesystem Sandbox Unavailable",
213+
)
214+
.with_desc(&format!(
215+
"Running WITHOUT filesystem restrictions: {err}. \
216+
Set landlock.compatibility to 'hard_requirement' to make this fatal."
217+
)),
218+
)
219+
.message(format!("Landlock filesystem sandbox unavailable: {err}"))
220+
.build()
221+
);
222+
Ok(None)
223+
} else {
224+
Err(err)
225+
}
226+
}
227+
}
228+
}
229+
230+
/// Phase 2: Enforce a prepared Landlock ruleset by calling `restrict_self()`.
231+
///
232+
/// This runs **after** `drop_privileges()`. The `restrict_self()` syscall does
233+
/// not require root — it only restricts the calling thread (and its future
234+
/// children), which is always permitted.
235+
///
236+
/// Respects the same `best_effort` / `hard_requirement` compatibility as
237+
/// [`prepare`]: if `restrict_self()` fails and the policy is `best_effort`,
238+
/// the error is logged and the sandbox continues without Landlock.
239+
pub fn enforce(prepared: PreparedRuleset) -> Result<()> {
240+
let result = prepared.ruleset.restrict_self().into_diagnostic();
107241
if let Err(err) = result {
108-
if matches!(compatibility, LandlockCompatibility::BestEffort) {
242+
if matches!(prepared.compatibility, LandlockCompatibility::BestEffort) {
109243
openshell_ocsf::ocsf_emit!(
110244
openshell_ocsf::DetectionFindingBuilder::new(crate::ocsf_ctx())
111245
.activity(openshell_ocsf::ActivityId::Open)
@@ -114,22 +248,34 @@ pub fn apply(policy: &SandboxPolicy, workdir: Option<&str>) -> Result<()> {
114248
.is_alert(true)
115249
.finding_info(
116250
openshell_ocsf::FindingInfo::new(
117-
"landlock-unavailable",
118-
"Landlock Filesystem Sandbox Unavailable",
251+
"landlock-enforce-failed",
252+
"Landlock restrict_self Failed",
119253
)
120254
.with_desc(&format!(
121-
"Running WITHOUT filesystem restrictions: {err}. \
255+
"Ruleset was prepared but restrict_self() failed: {err}. \
256+
Running WITHOUT filesystem restrictions. \
122257
Set landlock.compatibility to 'hard_requirement' to make this fatal."
123258
)),
124259
)
125-
.message(format!("Landlock filesystem sandbox unavailable: {err}"))
260+
.message(format!(
261+
"Landlock restrict_self failed (best_effort): {err}"
262+
))
126263
.build()
127264
);
128265
return Ok(());
129266
}
130267
return Err(err);
131268
}
269+
Ok(())
270+
}
132271

272+
/// Legacy single-phase apply. Kept for non-Linux platforms and tests.
273+
/// On Linux, callers should use [`prepare`] + [`enforce`] for correct
274+
/// privilege ordering.
275+
pub fn apply(policy: &SandboxPolicy, workdir: Option<&str>) -> Result<()> {
276+
if let Some(prepared) = prepare(policy, workdir)? {
277+
enforce(prepared)?;
278+
}
133279
Ok(())
134280
}
135281

@@ -311,4 +457,23 @@ mod tests {
311457
let err = PathFd::new("/nonexistent/openshell/classify/test").unwrap_err();
312458
assert_eq!(classify_path_fd_error(&err), "path does not exist");
313459
}
460+
461+
#[test]
462+
fn probe_availability_returns_a_result() {
463+
// The probe should not panic regardless of whether Landlock is available.
464+
// On Linux hosts with Landlock, this returns Available; on Docker Desktop
465+
// linuxkit or older kernels, it returns NotImplemented/NotEnabled/Blocked.
466+
let result = probe_availability();
467+
let display = format!("{result}");
468+
assert!(
469+
!display.is_empty(),
470+
"probe_availability Display should produce output"
471+
);
472+
// Verify the Debug impl works too.
473+
let debug = format!("{result:?}");
474+
assert!(
475+
!debug.is_empty(),
476+
"probe_availability Debug should produce output"
477+
);
478+
}
314479
}

0 commit comments

Comments
 (0)