Skip to content

Commit c31c5be

Browse files
committed
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.
1 parent 3dd6d51 commit c31c5be

4 files changed

Lines changed: 200 additions & 0 deletions

File tree

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,12 @@ 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+
157163
// Set up process group for signal handling (non-interactive mode only).
158164
// In interactive mode, we inherit the parent's process group to maintain
159165
// proper terminal control for shells and interactive programs.

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

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

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()
79+
.raw_os_error()
80+
.unwrap_or(0);
81+
match errno {
82+
libc::ENOSYS => LandlockAvailability::NotImplemented,
83+
libc::EOPNOTSUPP => LandlockAvailability::NotEnabled,
84+
libc::EPERM => LandlockAvailability::Blocked,
85+
other => LandlockAvailability::Unknown(other),
86+
}
87+
}
88+
}
89+
1590
pub fn apply(policy: &SandboxPolicy, workdir: Option<&str>) -> Result<()> {
1691
let read_only = policy.filesystem.read_only.clone();
1792
let mut read_write = policy.filesystem.read_write.clone();
@@ -311,4 +386,23 @@ mod tests {
311386
let err = PathFd::new("/nonexistent/openshell/classify/test").unwrap_err();
312387
assert_eq!(classify_path_fd_error(&err), "path does not exist");
313388
}
389+
390+
#[test]
391+
fn probe_availability_returns_a_result() {
392+
// The probe should not panic regardless of whether Landlock is available.
393+
// On Linux hosts with Landlock, this returns Available; on Docker Desktop
394+
// linuxkit or older kernels, it returns NotImplemented/NotEnabled/Blocked.
395+
let result = probe_availability();
396+
let display = format!("{result}");
397+
assert!(
398+
!display.is_empty(),
399+
"probe_availability Display should produce output"
400+
);
401+
// Verify the Debug impl works too.
402+
let debug = format!("{result:?}");
403+
assert!(
404+
!debug.is_empty(),
405+
"probe_availability Debug should produce output"
406+
);
407+
}
314408
}

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

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,101 @@ mod seccomp;
99

1010
use crate::policy::SandboxPolicy;
1111
use miette::Result;
12+
use std::path::PathBuf;
13+
use std::sync::Once;
1214

1315
pub fn apply(policy: &SandboxPolicy, workdir: Option<&str>) -> Result<()> {
1416
landlock::apply(policy, workdir)?;
1517
seccomp::apply(policy)?;
1618
Ok(())
1719
}
20+
21+
/// Probe Landlock availability and emit OCSF logs from the parent process.
22+
///
23+
/// This must be called **before** `pre_exec` / `fork()` so that the OCSF events
24+
/// are emitted through the parent's tracing subscriber (the child process after
25+
/// fork does not have a working tracing pipeline).
26+
pub fn log_sandbox_readiness(policy: &SandboxPolicy, workdir: Option<&str>) {
27+
static PROBED: Once = Once::new();
28+
let mut already_probed = true;
29+
PROBED.call_once(|| already_probed = false);
30+
if already_probed {
31+
return;
32+
}
33+
34+
let mut read_write = policy.filesystem.read_write.clone();
35+
let read_only = &policy.filesystem.read_only;
36+
37+
if policy.filesystem.include_workdir {
38+
if let Some(dir) = workdir {
39+
let workdir_path = PathBuf::from(dir);
40+
if !read_write.contains(&workdir_path) {
41+
read_write.push(workdir_path);
42+
}
43+
}
44+
}
45+
46+
let total_paths = read_only.len() + read_write.len();
47+
48+
if total_paths == 0 {
49+
openshell_ocsf::ocsf_emit!(
50+
openshell_ocsf::ConfigStateChangeBuilder::new(crate::ocsf_ctx())
51+
.severity(openshell_ocsf::SeverityId::Informational)
52+
.status(openshell_ocsf::StatusId::Success)
53+
.state(openshell_ocsf::StateId::Other, "skipped")
54+
.message("Landlock filesystem sandbox skipped: no paths configured".to_string())
55+
.build()
56+
);
57+
return;
58+
}
59+
60+
let availability = landlock::probe_availability();
61+
match &availability {
62+
landlock::LandlockAvailability::Available { abi } => {
63+
openshell_ocsf::ocsf_emit!(
64+
openshell_ocsf::ConfigStateChangeBuilder::new(crate::ocsf_ctx())
65+
.severity(openshell_ocsf::SeverityId::Informational)
66+
.status(openshell_ocsf::StatusId::Success)
67+
.state(openshell_ocsf::StateId::Enabled, "probed")
68+
.message(format!(
69+
"Landlock filesystem sandbox available \
70+
[abi:v{abi} compat:{:?} ro:{} rw:{}]",
71+
policy.landlock.compatibility,
72+
read_only.len(),
73+
read_write.len(),
74+
))
75+
.build()
76+
);
77+
}
78+
_ => {
79+
// Landlock is NOT available — this is the critical log that was
80+
// previously invisible because it only fired inside pre_exec.
81+
openshell_ocsf::ocsf_emit!(
82+
openshell_ocsf::DetectionFindingBuilder::new(crate::ocsf_ctx())
83+
.activity(openshell_ocsf::ActivityId::Open)
84+
.severity(openshell_ocsf::SeverityId::High)
85+
.confidence(openshell_ocsf::ConfidenceId::High)
86+
.is_alert(true)
87+
.finding_info(
88+
openshell_ocsf::FindingInfo::new(
89+
"landlock-unavailable",
90+
"Landlock Filesystem Sandbox Unavailable",
91+
)
92+
.with_desc(&format!(
93+
"Sandbox will run WITHOUT filesystem restrictions: {availability}. \
94+
Policy requests {total_paths} path rule(s) \
95+
(ro:{} rw:{}, compat:{:?}) but Landlock cannot enforce them. \
96+
Set landlock.compatibility to 'hard_requirement' to make this fatal.",
97+
read_only.len(),
98+
read_write.len(),
99+
policy.landlock.compatibility,
100+
)),
101+
)
102+
.message(format!(
103+
"Landlock filesystem sandbox unavailable: {availability}"
104+
))
105+
.build()
106+
);
107+
}
108+
}
109+
}

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -898,6 +898,10 @@ fn spawn_pty_shell(
898898
cmd.current_dir(dir);
899899
}
900900

901+
// Probe Landlock availability from the parent process where tracing works.
902+
#[cfg(target_os = "linux")]
903+
crate::sandbox::linux::log_sandbox_readiness(policy, workdir.as_deref());
904+
901905
#[cfg(unix)]
902906
{
903907
unsafe_pty::install_pre_exec(
@@ -1034,6 +1038,10 @@ fn spawn_pipe_exec(
10341038
cmd.current_dir(dir);
10351039
}
10361040

1041+
// Probe Landlock availability from the parent process where tracing works.
1042+
#[cfg(target_os = "linux")]
1043+
crate::sandbox::linux::log_sandbox_readiness(policy, workdir.as_deref());
1044+
10371045
#[cfg(unix)]
10381046
{
10391047
unsafe_pty::install_pre_exec_no_pty(&mut cmd, policy.clone(), workdir.clone(), netns_fd);

0 commit comments

Comments
 (0)