Skip to content

Commit 555c132

Browse files
committed
refactor(sandbox): consolidate CDI admission validation
Signed-off-by: Evan Lezar <elezar@nvidia.com>
1 parent 8fd1926 commit 555c132

7 files changed

Lines changed: 27 additions & 203 deletions

File tree

‎crates/openshell-sandbox/README.md‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,10 @@ The workload resolves trusted CDI context into filesystem requirements. Library
2424
mounts expand to their parent directory; the expanded path must pass the same
2525
broad-root rejection as other CDI destinations. Specs are trusted host
2626
administrator input. A shared-library parent grant also makes sibling files
27-
readable, so administrators must choose library directories accordingly.
27+
readable, so administrators must choose library directories accordingly, including
28+
when a spec places libraries under `/etc`, `/home`, or `/root`. These checks do
29+
not turn administrator-authored specs into an untrusted-input interface.
30+
CDI enrichment adds only spec-derived paths; it does not grant all of `/sys`.
2831

2932
`WorkloadLaunchContext` retains derived filesystem requirements and required GIDs
3033
separately from the authored policy. The initial process launcher and retained
@@ -52,7 +55,9 @@ The workload classifies their effective read-only flags rather than trusting
5255
spec option defaults, and checks original directory mounts for writable
5356
submounts using one mount-table snapshot per pass. An ordinary writable mount destination must
5457
be a single regular file explicitly listed in authored `read_write` paths.
55-
The sequential Landlock pass rechecks mount access on its opened descriptors.
58+
The sequential Landlock pass checks object types and rechecks mount access on
59+
its opened descriptors. The earlier requirements check only verifies the authored
60+
writable-file allowlist; it does not repeat pathname-based metadata checks.
5661
CDI does not add write access to `/proc`; existing thread-name mediation applies.
5762
Required groups must already be supplied by the container runtime. The sandbox
5863
checks membership before both the initial process launch and subsequent execs.

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

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -160,9 +160,6 @@ mod linux {
160160
.iter()
161161
.map(std::path::PathBuf::from)
162162
.collect::<Vec<_>>();
163-
if Path::new("/sys").exists() {
164-
read_only.push("/sys".into());
165-
}
166163
read_only.sort_by(path_depth_order);
167164
read_only.dedup();
168165

@@ -3935,7 +3932,7 @@ mod linux {
39353932
assert!(policy.filesystem.read_only.contains(&"/usr".into()));
39363933
assert!(!policy.filesystem.read_only.contains(&"/usr/lib".into()));
39373934
assert!(policy.filesystem.read_only.contains(&"/etc/hosts".into()));
3938-
assert!(policy.filesystem.read_only.contains(&"/sys".into()));
3935+
assert!(!policy.filesystem.read_only.contains(&"/sys".into()));
39393936
assert!(policy.filesystem.read_write.contains(&"/dev/null".into()));
39403937
assert!(!policy.filesystem.read_write.contains(&"/proc".into()));
39413938

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

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ use openshell_core::cdi::{CDI_CONTEXT_VERSION, CdiContext, CdiSpecDirectory};
99

1010
use crate::launch::{CdiDerivedRequirements, CdiMountRequirement};
1111

12+
/// Roots that CDI destinations and expanded library parents must not grant.
13+
pub const FORBIDDEN_CDI_ROOTS: &[&str] = &["/", "/dev", "/proc", "/sys", "/run", "/usr"];
14+
1215
#[derive(Debug, thiserror::Error)]
1316
pub enum CdiError {
1417
#[error("failed to inspect effective CDI mount '{path}': {error}")]
@@ -44,14 +47,6 @@ pub enum CdiError {
4447
"CDI writable mount '{path}' is not explicitly listed in the sandbox policy read_write paths"
4548
)]
4649
WritableMountNotAllowed { path: String },
47-
#[error("CDI writable mount '{path}' must target a single file, found {kind}")]
48-
WritableMountNotFile { path: String, kind: String },
49-
#[error("CDI device node '{path}' must target a character or block device, found {kind}")]
50-
DeviceNodeNotDevice { path: String, kind: String },
51-
#[error("CDI socket '{path}' must target a Unix socket, found {kind}")]
52-
SocketPathNotSocket { path: String, kind: String },
53-
#[error("CDI read-only path '{path}' does not exist in the workload namespace")]
54-
ReadOnlyPathMissing { path: String },
5550
#[error("CDI additionalGids must not contain root GID 0")]
5651
RootAdditionalGid,
5752
#[error("CDI mount '{path}' has conflicting ro/rw options")]

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

Lines changed: 6 additions & 182 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ use serde::Deserialize;
1717
use std::collections::{BTreeMap, BTreeSet, HashSet};
1818
use std::fmt;
1919
use std::hash::BuildHasher;
20-
use std::os::unix::fs::FileTypeExt;
2120
use std::path::{Component, Path};
2221

2322
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -30,19 +29,6 @@ enum CdiPathKind {
3029
Other,
3130
}
3231

33-
impl fmt::Display for CdiPathKind {
34-
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35-
match self {
36-
Self::File => f.write_str("file"),
37-
Self::Directory => f.write_str("directory"),
38-
Self::CharacterDevice => f.write_str("character device"),
39-
Self::BlockDevice => f.write_str("block device"),
40-
Self::Socket => f.write_str("Unix socket"),
41-
Self::Other => f.write_str("other"),
42-
}
43-
}
44-
}
45-
4632
// Temporary view over upstream-resolved CDI edits. The Rust CDI crate currently
4733
// keeps some spec-model fields crate-private even though they are serialized and
4834
// public in specs-go, so OpenShell serializes the merged upstream model and
@@ -339,67 +325,19 @@ fn inspect_cdi_mount(
339325
Ok(CdiMountState { kind, access })
340326
}
341327

328+
/// Check authored opt-in; object types are validated on enforcement descriptors.
342329
pub fn validate_cdi_requirements<S: BuildHasher>(
343330
requirements: &CdiDerivedRequirements,
344331
writable_file_allowlist: &HashSet<String, S>,
345332
) -> Result<(), CdiError> {
346-
validate_cdi_requirements_with_path_kind(
347-
requirements,
348-
writable_file_allowlist,
349-
filesystem_path_kind,
350-
)
351-
}
352-
353-
fn validate_cdi_requirements_with_path_kind<F, S>(
354-
requirements: &CdiDerivedRequirements,
355-
writable_file_allowlist: &HashSet<String, S>,
356-
path_kind: F,
357-
) -> Result<(), CdiError>
358-
where
359-
F: Fn(&str) -> Option<CdiPathKind>,
360-
S: BuildHasher,
361-
{
362333
let normalized_allowlist = writable_file_allowlist
363334
.iter()
364335
.map(|path| normalize_path(path))
365336
.collect::<HashSet<_>>();
366-
for path in &requirements.device_node_paths {
367-
let kind = path_kind(path);
368-
if !matches!(
369-
kind,
370-
Some(CdiPathKind::CharacterDevice | CdiPathKind::BlockDevice)
371-
) {
372-
return Err(CdiError::DeviceNodeNotDevice {
373-
path: path.clone(),
374-
kind: kind.map_or_else(|| "missing".to_string(), |kind| kind.to_string()),
375-
});
376-
}
377-
}
378-
for path in &requirements.socket_paths {
379-
let kind = path_kind(path);
380-
if kind != Some(CdiPathKind::Socket) {
381-
return Err(CdiError::SocketPathNotSocket {
382-
path: path.clone(),
383-
kind: kind.map_or_else(|| "missing".to_string(), |kind| kind.to_string()),
384-
});
385-
}
386-
}
387-
for path in &requirements.read_only_paths {
388-
if path_kind(path).is_none() {
389-
return Err(CdiError::ReadOnlyPathMissing { path: path.clone() });
390-
}
391-
}
392337
for path in &requirements.read_write_mount_paths {
393338
if !normalized_allowlist.contains(path) {
394339
return Err(CdiError::WritableMountNotAllowed { path: path.clone() });
395340
}
396-
let kind = path_kind(path);
397-
if kind != Some(CdiPathKind::File) {
398-
return Err(CdiError::WritableMountNotFile {
399-
path: path.clone(),
400-
kind: kind.map_or_else(|| "missing".to_string(), |kind| kind.to_string()),
401-
});
402-
}
403341
}
404342
Ok(())
405343
}
@@ -525,10 +463,7 @@ fn normalize_policy_path(path: &str) -> Result<String, CdiError> {
525463
reason,
526464
})?;
527465
let normalized = normalize_path(path);
528-
if matches!(
529-
normalized.as_str(),
530-
"/" | "/dev" | "/proc" | "/sys" | "/run" | "/usr"
531-
) {
466+
if super::FORBIDDEN_CDI_ROOTS.contains(&normalized.as_str()) {
532467
return Err(CdiError::UnsafePolicyPath {
533468
path: path.to_string(),
534469
reason: "broad root path is not allowed",
@@ -553,26 +488,6 @@ fn validate_absolute_no_parent(path: &str) -> Result<(), &'static str> {
553488
Ok(())
554489
}
555490

556-
fn filesystem_path_kind(path: &str) -> Option<CdiPathKind> {
557-
let metadata = std::fs::metadata(path).ok()?;
558-
let file_type = metadata.file_type();
559-
if file_type.is_char_device() {
560-
return Some(CdiPathKind::CharacterDevice);
561-
}
562-
if file_type.is_block_device() {
563-
return Some(CdiPathKind::BlockDevice);
564-
}
565-
if file_type.is_socket() {
566-
Some(CdiPathKind::Socket)
567-
} else if file_type.is_file() {
568-
Some(CdiPathKind::File)
569-
} else if file_type.is_dir() {
570-
Some(CdiPathKind::Directory)
571-
} else {
572-
Some(CdiPathKind::Other)
573-
}
574-
}
575-
576491
#[cfg(test)]
577492
mod tests {
578493
use super::*;
@@ -608,16 +523,6 @@ mod tests {
608523
assert!(requirements.mounts.is_empty());
609524
validate_cdi_requirements(&requirements, &HashSet::<String>::new()).unwrap();
610525
}
611-
let requirements = CdiDerivedRequirements {
612-
socket_paths: vec![target.to_string_lossy().into_owned()],
613-
..Default::default()
614-
};
615-
std::fs::remove_file(&target).unwrap();
616-
std::fs::write(&target, "replacement").unwrap();
617-
assert!(matches!(
618-
validate_cdi_requirements(&requirements, &HashSet::<String>::new()),
619-
Err(CdiError::SocketPathNotSocket { .. })
620-
));
621526
}
622527
}
623528

@@ -696,7 +601,7 @@ mod tests {
696601
}
697602

698603
#[test]
699-
fn effective_writable_directory_and_missing_mount_fail_closed() {
604+
fn effective_writable_directory_requires_allowlist_and_missing_mount_fails() {
700605
let directory = tempfile::tempdir().unwrap();
701606
for path in [
702607
directory.path().to_string_lossy().into_owned(),
@@ -710,8 +615,8 @@ mod tests {
710615
if Path::new(&path).exists() {
711616
let requirements = resolve_cdi_context(&context).unwrap();
712617
assert!(matches!(
713-
validate_cdi_requirements(&requirements, &HashSet::from([path])),
714-
Err(CdiError::WritableMountNotFile { .. })
618+
validate_cdi_requirements(&requirements, &HashSet::<String>::new()),
619+
Err(CdiError::WritableMountNotAllowed { .. })
715620
));
716621
} else {
717622
assert!(matches!(
@@ -773,7 +678,7 @@ mod tests {
773678
let kind = kind(path).ok_or_else(|| mount_inspection(path, "missing fixture mount"))?;
774679
Ok(CdiMountState { kind, access })
775680
})?;
776-
validate_cdi_requirements_with_path_kind(&requirements, &writable_file_allowlist, kind)?;
681+
validate_cdi_requirements(&requirements, &writable_file_allowlist)?;
777682
Ok(requirements)
778683
}
779684

@@ -1096,36 +1001,6 @@ devices:
10961001
);
10971002
}
10981003

1099-
#[test]
1100-
fn rejects_writable_directory_mount() {
1101-
let dir = tempfile::tempdir().unwrap();
1102-
write_spec(
1103-
dir.path(),
1104-
"rw-dir.yaml",
1105-
r#"
1106-
cdiVersion: 1.1.0
1107-
kind: nvidia.com/gpu
1108-
devices:
1109-
- name: "0"
1110-
containerEdits:
1111-
mounts:
1112-
- hostPath: /host/nvidia/cache
1113-
containerPath: /opt/nvidia/cache
1114-
options: [rw]
1115-
"#,
1116-
);
1117-
1118-
let err = resolve_with_kind_and_access(
1119-
&context(dir.path(), &["nvidia.com/gpu=0"]),
1120-
&["/opt/nvidia/cache"],
1121-
CdiAccess::ReadWrite,
1122-
|path| (path == "/opt/nvidia/cache").then_some(CdiPathKind::Directory),
1123-
)
1124-
.unwrap_err();
1125-
1126-
assert!(matches!(err, CdiError::WritableMountNotFile { .. }));
1127-
}
1128-
11291004
#[test]
11301005
fn rejects_missing_selected_device() {
11311006
let dir = tempfile::tempdir().unwrap();
@@ -1340,55 +1215,4 @@ devices:
13401215

13411216
assert!(matches!(err, CdiError::RootAdditionalGid));
13421217
}
1343-
1344-
#[test]
1345-
fn validates_read_only_paths_in_the_workload_namespace() {
1346-
let requirements = CdiDerivedRequirements {
1347-
read_only_paths: vec!["/opt/nvidia/runtime.json".to_string()],
1348-
..CdiDerivedRequirements::default()
1349-
};
1350-
let writable_file_allowlist = HashSet::<String>::new();
1351-
1352-
let err = validate_cdi_requirements_with_path_kind(
1353-
&requirements,
1354-
&writable_file_allowlist,
1355-
always_missing,
1356-
)
1357-
.unwrap_err();
1358-
assert!(matches!(
1359-
err,
1360-
CdiError::ReadOnlyPathMissing { path }
1361-
if path == "/opt/nvidia/runtime.json"
1362-
));
1363-
1364-
validate_cdi_requirements_with_path_kind(&requirements, &writable_file_allowlist, |_| {
1365-
Some(CdiPathKind::File)
1366-
})
1367-
.unwrap();
1368-
}
1369-
1370-
#[test]
1371-
fn rejects_device_node_that_is_not_device() {
1372-
let dir = tempfile::tempdir().unwrap();
1373-
write_spec(
1374-
dir.path(),
1375-
"regular-file-node.yaml",
1376-
r#"
1377-
cdiVersion: 1.1.0
1378-
kind: nvidia.com/gpu
1379-
devices:
1380-
- name: "0"
1381-
containerEdits:
1382-
deviceNodes:
1383-
- path: /opt/nvidia/not-a-device
1384-
"#,
1385-
);
1386-
1387-
let err = resolve_with_kind(&context(dir.path(), &["nvidia.com/gpu=0"]), &[], |path| {
1388-
(path == "/opt/nvidia/not-a-device").then_some(CdiPathKind::File)
1389-
})
1390-
.unwrap_err();
1391-
1392-
assert!(matches!(err, CdiError::DeviceNodeNotDevice { .. }));
1393-
}
13941218
}

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

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ impl CdiPaths {
7575
}
7676
// Retain only root identities. Each root descriptor closes immediately.
7777
let mut broad_roots = Vec::new();
78-
for root in ["/", "/dev", "/proc", "/sys", "/run", "/usr"] {
78+
for root in crate::cdi::FORBIDDEN_CDI_ROOTS {
7979
match open(Path::new(root)) {
8080
Ok(fd) => broad_roots.push(fstat(&fd).into_diagnostic()?),
8181
Err(_) if !Path::new(root).exists() => {}
@@ -324,7 +324,7 @@ mod tests {
324324
fn rejects_symlink_aliases_to_broad_roots() {
325325
let temp = tempfile::tempdir().unwrap();
326326
let alias = temp.path().join("library-parent");
327-
for root in ["/", "/dev", "/proc", "/sys", "/run", "/usr"] {
327+
for root in crate::cdi::FORBIDDEN_CDI_ROOTS {
328328
if !Path::new(root).exists() {
329329
continue;
330330
}
@@ -369,6 +369,9 @@ mod tests {
369369
..Default::default()
370370
};
371371
assert!(validate(&requirements, open).is_ok());
372+
// Read-only targets still have to exist when enforcement opens them.
373+
let missing = temp.path().join("missing");
374+
assert!(validate(&read_only(&missing), open).is_err());
372375
let requirements = CdiDerivedRequirements {
373376
device_node_paths: vec!["/dev/null".into()],
374377
..Default::default()

‎docs/how-it-works/policies/default-policy.mdx‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -125,11 +125,9 @@ listed in `filesystem_policy.read_write`. Writable CDI directory mounts and CDI
125125
paths such as `/`, `/dev`, `/proc`, `/sys`, `/run`, or `/usr` are rejected
126126
during sandbox startup.
127127

128-
CDI-enabled GPU sandboxes also receive read-only access to the container runtime's
129-
`/sys` tree for CUDA hardware and driver topology discovery. This permission is a
130-
runtime-owned compatibility baseline. CDI specs
131-
cannot request broad sysfs access, and non-GPU sandboxes do not receive this
132-
baseline.
128+
CDI does not add a blanket `/sys` grant. If an application needs sysfs paths
129+
that the selected CDI spec does not supply, include those paths in your authored
130+
filesystem policy.
133131

134132
### Protected Paths
135133

‎skills/debug-openshell-cluster/SKILL.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,8 @@ Common findings:
324324
- Docker rejects a CDI spec-directory bind: every directory reported in `docker info --format '{{json .CDISpecDirs}}'` must exist on the daemon host. OpenShell uses structured binds that reject missing sources and do not create directories or relabel existing ones. Configure Docker to report only existing CDI spec directories. On SELinux hosts, ensure the host policy permits containers to read them without automatic relabeling. The projections are private to the trusted runtime under `/.openshell/cdi-specs`; the mandatory baseline prevents agent access even with broad authored grants.
325325
- CDI spec projection admission fails: inspect the workload container's `HostConfig.DeviceRequests` and `Mounts`. Each daemon-discovered CDI spec directory must appear at its assigned `/.openshell/cdi-specs/<index>` destination as a read-only bind with private propagation and the expected host source. Missing, changed, duplicate, and additional unrelated bind mounts are rejected with admission enabled. Correct the projection or runtime configuration; do not disable resource admission for GPU workloads.
326326
- CDI writable mount validation fails despite omitted options or `ro` in the spec: OpenShell checks effective mount flags inside the workload. Original directory destinations are also checked for writable submounts. Ordinary writable destinations must be single regular files with exact entries in policy `read_write`; expanded shared-library parents are not treated as original directory mounts.
327+
- CUDA topology discovery fails: CDI does not add blanket read access to `/sys`. Check the paths requested by the application and add the required sysfs paths to its authored filesystem policy when the selected CDI spec does not supply them.
328+
327329
- CDI socket validation fails: verify the exact destination is a Unix socket inside the workload. Socket destinations (including GPU daemon endpoints) do not expand to their parents or require writable-file allowlist entries. A socket replaced by a regular file or directory fails launch or subsequent exec.
328330
- The workload runtime did not supply required CDI groups: compare the selected spec's `additionalGids` with the container process's actual supplemental groups (`id -G` or `/proc/<pid>/status`). Verify the container runtime applies CDI groups and preserves them through launch. Numeric groups need no matching group name. OpenShell validates membership before initial launch and subsequent execs and does not inject missing groups; use a runtime/toolkit combination that supplies the required groups.
329331

0 commit comments

Comments
 (0)