Skip to content

Commit ce3cc87

Browse files
committed
fix(supervisor): tailor Landlock rights by inode type
Closes #2218 Signed-off-by: Drew Newberry <[email protected]>
1 parent 745512e commit ce3cc87

3 files changed

Lines changed: 197 additions & 4 deletions

File tree

‎architecture/security-policy.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,13 @@ enrichment adds existing GPU device nodes as read-write paths and promotes
2828
`/proc` to read-write because CUDA workloads write thread metadata under
2929
`/proc/<pid>/task/<tid>/comm`.
3030

31+
Landlock rules are tailored to the inode type reported by the already-opened
32+
path descriptor. Directories retain the requested directory and file rights;
33+
regular files, device nodes, sockets, and other non-directories retain only
34+
file-compatible rights. This avoids rejecting valid mixed-path policies without
35+
weakening `hard_requirement`: genuine unsupported ABI capabilities and
36+
preparation failures still fail sandbox startup.
37+
3138
## Network Decisions
3239

3340
Ordinary network traffic follows this order:

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

Lines changed: 116 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,12 @@
44
//! Landlock filesystem sandboxing.
55
66
use landlock::{
7-
ABI, Access, AccessFs, CompatLevel, Compatible, PathBeneath, PathFd, PathFdError, Ruleset,
8-
RulesetAttr, RulesetCreatedAttr,
7+
ABI, Access, AccessFs, BitFlags, CompatLevel, Compatible, PathBeneath, PathFd, PathFdError,
8+
Ruleset, RulesetAttr, RulesetCreatedAttr,
99
};
1010
use miette::{IntoDiagnostic, Result};
1111
use openshell_core::policy::{LandlockCompatibility, SandboxPolicy};
12+
use std::os::fd::AsFd;
1213
use std::path::{Path, PathBuf};
1314
use tracing::debug;
1415

@@ -216,19 +217,21 @@ fn prepare_with_path_open_mode(
216217

217218
for path in &read_only {
218219
if let Some(path_fd) = try_open_path(path, compatibility, path_open_mode)? {
220+
let allowed_access = access_for_path_fd(&path_fd, access_read, abi)?;
219221
debug!(path = %path.display(), "Landlock allow read-only");
220222
ruleset = ruleset
221-
.add_rule(PathBeneath::new(path_fd, access_read))
223+
.add_rule(PathBeneath::new(path_fd, allowed_access))
222224
.into_diagnostic()?;
223225
rules_applied += 1;
224226
}
225227
}
226228

227229
for path in &read_write {
228230
if let Some(path_fd) = try_open_path(path, compatibility, path_open_mode)? {
231+
let allowed_access = access_for_path_fd(&path_fd, access_all, abi)?;
229232
debug!(path = %path.display(), "Landlock allow read-write");
230233
ruleset = ruleset
231-
.add_rule(PathBeneath::new(path_fd, access_all))
234+
.add_rule(PathBeneath::new(path_fd, allowed_access))
232235
.into_diagnostic()?;
233236
rules_applied += 1;
234237
}
@@ -344,6 +347,23 @@ pub fn apply(policy: &SandboxPolicy, workdir: Option<&str>) -> Result<()> {
344347
Ok(())
345348
}
346349

350+
/// Tailor a rule's access mask to the inode referenced by its already-open FD.
351+
///
352+
/// Landlock directory-only rights such as `ReadDir` are invalid for regular
353+
/// files and device nodes in hard-requirement mode. Classifying through the
354+
/// same `PathFd` used by the rule avoids a pathname TOCTOU race.
355+
fn access_for_path_fd(
356+
path_fd: &PathFd,
357+
requested_access: BitFlags<AccessFs>,
358+
abi: ABI,
359+
) -> Result<BitFlags<AccessFs>> {
360+
let stat = rustix::fs::fstat(path_fd.as_fd()).into_diagnostic()?;
361+
Ok(match rustix::fs::FileType::from_raw_mode(stat.st_mode) {
362+
rustix::fs::FileType::Directory => requested_access,
363+
_ => requested_access & AccessFs::from_file(abi),
364+
})
365+
}
366+
347367
/// Attempt to open a path for Landlock rule creation.
348368
///
349369
/// In `BestEffort` mode, inaccessible paths (missing, permission denied, symlink
@@ -468,6 +488,98 @@ fn compat_level(level: &LandlockCompatibility) -> CompatLevel {
468488
#[cfg(test)]
469489
mod tests {
470490
use super::*;
491+
use openshell_core::policy::{FilesystemPolicy, LandlockPolicy, NetworkPolicy, ProcessPolicy};
492+
493+
fn hard_requirement_policy(read_only: Vec<PathBuf>, read_write: Vec<PathBuf>) -> SandboxPolicy {
494+
SandboxPolicy {
495+
version: 1,
496+
filesystem: FilesystemPolicy {
497+
read_only,
498+
read_write,
499+
include_workdir: false,
500+
},
501+
network: NetworkPolicy::default(),
502+
landlock: LandlockPolicy {
503+
compatibility: LandlockCompatibility::HardRequirement,
504+
},
505+
process: ProcessPolicy::default(),
506+
}
507+
}
508+
509+
#[test]
510+
fn prepare_hard_requirement_accepts_device_paths() {
511+
if !matches!(probe_availability(), LandlockAvailability::Available { .. }) {
512+
return;
513+
}
514+
515+
let policy = hard_requirement_policy(
516+
vec![PathBuf::from("/tmp"), PathBuf::from("/dev/urandom")],
517+
vec![PathBuf::from("/dev/null")],
518+
);
519+
520+
let result = prepare(&policy, None);
521+
if let Err(err) = result {
522+
panic!("hard_requirement should accept mixed directory and device paths: {err}");
523+
}
524+
}
525+
fn tailored_access(path: &Path, requested_access: BitFlags<AccessFs>) -> BitFlags<AccessFs> {
526+
let path_fd = PathFd::new(path).unwrap();
527+
access_for_path_fd(&path_fd, requested_access, ABI::V2).unwrap()
528+
}
529+
530+
#[test]
531+
fn access_for_path_fd_preserves_directory_access() {
532+
let dir = tempfile::tempdir().unwrap();
533+
let requested_access = AccessFs::from_all(ABI::V2);
534+
535+
assert_eq!(
536+
tailored_access(dir.path(), requested_access),
537+
requested_access
538+
);
539+
}
540+
541+
#[test]
542+
fn access_for_path_fd_limits_regular_file_access() {
543+
let file = tempfile::NamedTempFile::new().unwrap();
544+
let requested_access = AccessFs::from_all(ABI::V2);
545+
546+
assert_eq!(
547+
tailored_access(file.path(), requested_access),
548+
requested_access & AccessFs::from_file(ABI::V2)
549+
);
550+
}
551+
552+
#[test]
553+
fn access_for_path_fd_limits_character_device_access() {
554+
let requested_read = AccessFs::from_read(ABI::V2);
555+
let requested_write = AccessFs::from_all(ABI::V2);
556+
557+
assert_eq!(
558+
tailored_access(Path::new("/dev/urandom"), requested_read),
559+
requested_read & AccessFs::from_file(ABI::V2)
560+
);
561+
assert_eq!(
562+
tailored_access(Path::new("/dev/null"), requested_write),
563+
requested_write & AccessFs::from_file(ABI::V2)
564+
);
565+
}
566+
567+
#[test]
568+
fn access_for_path_fd_classifies_symlink_target() {
569+
use std::os::unix::fs::symlink;
570+
571+
let dir = tempfile::tempdir().unwrap();
572+
let target = dir.path().join("target");
573+
let link = dir.path().join("link");
574+
std::fs::File::create(&target).unwrap();
575+
symlink(&target, &link).unwrap();
576+
577+
let requested_access = AccessFs::from_all(ABI::V2);
578+
assert_eq!(
579+
tailored_access(&link, requested_access),
580+
requested_access & AccessFs::from_file(ABI::V2)
581+
);
582+
}
471583

472584
#[test]
473585
fn try_open_path_best_effort_returns_none_for_missing_path() {

‎e2e/rust/tests/landlock.rs‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
#![cfg(feature = "e2e")]
5+
6+
//! End-to-end coverage for Landlock filesystem enforcement.
7+
8+
use std::io::Write;
9+
10+
use openshell_e2e::harness::sandbox::SandboxGuard;
11+
use tempfile::NamedTempFile;
12+
13+
const SUCCESS_MARKER: &str = "landlock-hard-requirement-ok";
14+
15+
fn write_hard_requirement_policy() -> Result<NamedTempFile, String> {
16+
let mut file =
17+
NamedTempFile::new().map_err(|error| format!("create temporary policy: {error}"))?;
18+
let policy = r#"version: 1
19+
20+
filesystem_policy:
21+
include_workdir: true
22+
read_only:
23+
- /usr
24+
- /lib
25+
- /etc
26+
- /proc
27+
read_write:
28+
- /sandbox
29+
- /tmp
30+
31+
landlock:
32+
compatibility: hard_requirement
33+
34+
process:
35+
run_as_user: sandbox
36+
run_as_group: sandbox
37+
38+
network_policies:
39+
landlock_regression:
40+
name: landlock_regression
41+
endpoints:
42+
- host: example.com
43+
port: 443
44+
binaries:
45+
- path: "/**"
46+
"#;
47+
48+
file.write_all(policy.as_bytes())
49+
.map_err(|error| format!("write temporary policy: {error}"))?;
50+
file.flush()
51+
.map_err(|error| format!("flush temporary policy: {error}"))?;
52+
Ok(file)
53+
}
54+
55+
#[tokio::test]
56+
async fn hard_requirement_accepts_enriched_device_path() {
57+
let policy = write_hard_requirement_policy().expect("write hard-requirement policy");
58+
let policy_path = policy.path().to_string_lossy().into_owned();
59+
let script = concat!(
60+
"set -eu; ",
61+
"bytes=$(head -c 16 /dev/urandom | wc -c); ",
62+
"test \"$bytes\" -eq 16; ",
63+
"printf landlock-ok > /tmp/landlock-check; ",
64+
"test \"$(cat /tmp/landlock-check)\" = landlock-ok; ",
65+
"echo landlock-hard-requirement-ok",
66+
);
67+
68+
let mut sandbox = SandboxGuard::create(&["--policy", &policy_path, "--", "sh", "-lc", script])
69+
.await
70+
.expect("hard_requirement should accept the enriched /dev/urandom path");
71+
72+
assert!(sandbox.create_output.contains(SUCCESS_MARKER));
73+
sandbox.cleanup().await;
74+
}

0 commit comments

Comments
 (0)