Skip to content

Commit 56c8376

Browse files
committed
fix(cdi): validate exact socket destinations without parent grants
Signed-off-by: Evan Lezar <[email protected]>
1 parent 4cad83e commit 56c8376

8 files changed

Lines changed: 205 additions & 10 deletions

File tree

‎crates/openshell-core/README.md‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,15 @@ retain their existing opening behavior.
8787
Original CDI mount destinations remain separate from expanded library parents.
8888
The workload classifies their effective read-only flags rather than trusting
8989
spec option defaults, and checks original directory mounts for writable
90-
submounts using one mount-table snapshot per pass. A writable destination must
90+
submounts using one mount-table snapshot per pass. An ordinary writable mount destination must
9191
be a single regular file explicitly listed in authored `read_write` paths.
9292
The sequential Landlock pass rechecks mount access on its opened descriptors.
9393
CDI does not add write access to `/proc`; existing thread-name mediation applies.
9494
Supplemental groups must already be supplied by the container runtime.
95+
96+
CDI Unix socket mounts are recorded as exact socket destinations, separately from
97+
ordinary file mounts. Their opened objects must remain Unix sockets at each
98+
launch or exec. They do not derive filesystem grants, expand to parent
99+
directories, or require the writable-file allowlist, regardless of mount flags.
100+
Communication follows the existing Unix IPC and inode permission checks; this
101+
validation does not pin the endpoint for later pathname-based connections.

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,12 +55,14 @@ impl CdiSpecDirectory {
5555
#[derive(Debug, Clone, Default, PartialEq, Eq)]
5656
pub struct CdiDerivedRequirements {
5757
pub device_node_paths: Vec<String>,
58+
/// Exact Unix socket destinations. Never expanded into filesystem grants.
59+
pub socket_paths: Vec<String>,
5860
/// Derived read-only policy paths. Shared-library mounts contribute their
5961
/// parent directory; other read-only mounts contribute their exact path.
6062
pub read_only_paths: Vec<String>,
6163
pub read_write_mount_paths: Vec<String>,
6264
pub additional_gids: Vec<u32>,
63-
/// Original mount destinations, retained separately from library parents.
65+
/// Original ordinary mount destinations, separate from sockets and library parents.
6466
/// Access is confirmed in the workload namespace before enrichment.
6567
pub mounts: Vec<CdiMountRequirement>,
6668
}
@@ -122,6 +124,8 @@ pub enum CdiError {
122124
WritableMountNotFile { path: String, kind: String },
123125
#[error("CDI device node '{path}' must target a character or block device, found {kind}")]
124126
DeviceNodeNotDevice { path: String, kind: String },
127+
#[error("CDI socket '{path}' must target a Unix socket, found {kind}")]
128+
SocketPathNotSocket { path: String, kind: String },
125129
#[error("CDI read-only path '{path}' does not exist in the workload namespace")]
126130
ReadOnlyPathMissing { path: String },
127131
#[error("CDI additionalGids must not contain root GID 0")]

‎crates/openshell-core/src/cdi_linux.rs‎

Lines changed: 82 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ enum CdiPathKind {
2626
Directory,
2727
CharacterDevice,
2828
BlockDevice,
29+
Socket,
2930
Other,
3031
}
3132

@@ -36,6 +37,7 @@ impl fmt::Display for CdiPathKind {
3637
Self::Directory => f.write_str("directory"),
3738
Self::CharacterDevice => f.write_str("character device"),
3839
Self::BlockDevice => f.write_str("block device"),
40+
Self::Socket => f.write_str("Unix socket"),
3941
Self::Other => f.write_str("other"),
4042
}
4143
}
@@ -78,11 +80,15 @@ enum CdiAccess {
7880
struct RequirementAccumulator {
7981
device_node_paths: BTreeSet<String>,
8082
mount_paths: BTreeMap<String, CdiAccess>,
83+
socket_paths: BTreeSet<String>,
8184
additional_gids: BTreeSet<u32>,
8285
}
8386

8487
impl RequirementAccumulator {
8588
fn add_device_node(&mut self, path: String) -> Result<(), CdiError> {
89+
if self.socket_paths.contains(&path) {
90+
return Err(CdiError::ConflictingAccess { path });
91+
}
8692
match self.mount_paths.get(&path).copied() {
8793
Some(CdiAccess::ReadOnly) => Err(CdiError::ConflictingAccess { path }),
8894
Some(CdiAccess::ReadWrite) | None => {
@@ -93,7 +99,9 @@ impl RequirementAccumulator {
9399
}
94100

95101
fn add_mount(&mut self, path: String, access: CdiAccess) -> Result<(), CdiError> {
96-
if access == CdiAccess::ReadOnly && self.device_node_paths.contains(&path) {
102+
if self.socket_paths.contains(&path)
103+
|| (access == CdiAccess::ReadOnly && self.device_node_paths.contains(&path))
104+
{
97105
return Err(CdiError::ConflictingAccess { path });
98106
}
99107
match self.mount_paths.get(&path).copied() {
@@ -106,6 +114,14 @@ impl RequirementAccumulator {
106114
}
107115
}
108116

117+
fn add_socket(&mut self, path: String) -> Result<(), CdiError> {
118+
if self.device_node_paths.contains(&path) || self.mount_paths.contains_key(&path) {
119+
return Err(CdiError::ConflictingAccess { path });
120+
}
121+
self.socket_paths.insert(path);
122+
Ok(())
123+
}
124+
109125
fn add_gid(&mut self, gid: u32) -> Result<(), CdiError> {
110126
if gid == 0 {
111127
return Err(CdiError::RootAdditionalGid);
@@ -133,6 +149,7 @@ impl RequirementAccumulator {
133149
}
134150
Ok(CdiDerivedRequirements {
135151
device_node_paths: self.device_node_paths.into_iter().collect(),
152+
socket_paths: self.socket_paths.into_iter().collect(),
136153
read_only_paths: read_only_paths.into_iter().collect(),
137154
read_write_mount_paths,
138155
additional_gids: self.additional_gids.into_iter().collect(),
@@ -310,13 +327,21 @@ fn classify_cdi_mounts(requirements: &mut CdiDerivedRequirements) -> Result<(),
310327
for gid in &requirements.additional_gids {
311328
accumulator.add_gid(*gid)?;
312329
}
330+
for path in &requirements.socket_paths {
331+
accumulator.add_socket(path.clone())?;
332+
}
313333
for mount in &requirements.mounts {
314334
let fd = rustix::fs::open(
315335
&mount.path,
316336
rustix::fs::OFlags::PATH | rustix::fs::OFlags::CLOEXEC,
317337
rustix::fs::Mode::empty(),
318338
)
319339
.map_err(|error| mount_inspection(&mount.path, error))?;
340+
let stat = rustix::fs::fstat(&fd).map_err(|error| mount_inspection(&mount.path, error))?;
341+
if rustix::fs::FileType::from_raw_mode(stat.st_mode) == rustix::fs::FileType::Socket {
342+
accumulator.add_socket(mount.path.clone())?;
343+
continue;
344+
}
320345
let read_only = table.read_only(&mount.path, &fd)?;
321346
accumulator.add_mount(
322347
mount.path.clone(),
@@ -367,6 +392,15 @@ where
367392
});
368393
}
369394
}
395+
for path in &requirements.socket_paths {
396+
let kind = path_kind(path);
397+
if kind != Some(CdiPathKind::Socket) {
398+
return Err(CdiError::SocketPathNotSocket {
399+
path: path.clone(),
400+
kind: kind.map_or_else(|| "missing".to_string(), |kind| kind.to_string()),
401+
});
402+
}
403+
}
370404
for path in &requirements.read_only_paths {
371405
if path_kind(path).is_none() {
372406
return Err(CdiError::ReadOnlyPathMissing { path: path.clone() });
@@ -572,7 +606,9 @@ fn filesystem_path_kind(path: &str) -> Option<CdiPathKind> {
572606
if file_type.is_block_device() {
573607
return Some(CdiPathKind::BlockDevice);
574608
}
575-
if file_type.is_file() {
609+
if file_type.is_socket() {
610+
Some(CdiPathKind::Socket)
611+
} else if file_type.is_file() {
576612
Some(CdiPathKind::File)
577613
} else if file_type.is_dir() {
578614
Some(CdiPathKind::Directory)
@@ -585,6 +621,50 @@ fn filesystem_path_kind(path: &str) -> Option<CdiPathKind> {
585621
mod tests {
586622
use super::*;
587623

624+
#[test]
625+
fn runtime_resolution_keeps_socket_destinations_exact_without_file_grants() {
626+
let directory = tempfile::tempdir().unwrap();
627+
let specs = directory.path().join("specs");
628+
std::fs::create_dir(&specs).unwrap();
629+
for name in [
630+
"persistenced/socket",
631+
"fabricmanager/socket",
632+
"libdaemon.so.1",
633+
] {
634+
let target = directory.path().join(name);
635+
std::fs::create_dir_all(target.parent().unwrap()).unwrap();
636+
let _listener = std::os::unix::net::UnixListener::bind(&target).unwrap();
637+
for options in ["[]", "[ro, bind]", "[rw, rbind]"] {
638+
write_spec(
639+
&specs,
640+
"socket.yaml",
641+
&format!(
642+
"cdiVersion: 0.7.0\nkind: example.com/device\ndevices:\n - name: test\n containerEdits:\n mounts:\n - hostPath: /host/socket\n containerPath: {}\n options: {}\n",
643+
target.display(),
644+
options,
645+
),
646+
);
647+
let requirements =
648+
resolve_cdi_context(&context(&specs, &["example.com/device=test"])).unwrap();
649+
assert_eq!(requirements.socket_paths, vec![target.to_string_lossy()]);
650+
assert!(requirements.read_only_paths.is_empty());
651+
assert!(requirements.read_write_mount_paths.is_empty());
652+
assert!(requirements.mounts.is_empty());
653+
validate_cdi_requirements(&requirements, &HashSet::<String>::new()).unwrap();
654+
}
655+
let requirements = CdiDerivedRequirements {
656+
socket_paths: vec![target.to_string_lossy().into_owned()],
657+
..Default::default()
658+
};
659+
std::fs::remove_file(&target).unwrap();
660+
std::fs::write(&target, "replacement").unwrap();
661+
assert!(matches!(
662+
validate_cdi_requirements(&requirements, &HashSet::<String>::new()),
663+
Err(CdiError::SocketPathNotSocket { .. })
664+
));
665+
}
666+
}
667+
588668
#[test]
589669
fn runtime_resolution_classifies_a_mount_without_access_options() {
590670
let directory = tempfile::tempdir().unwrap();

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

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ pub(super) struct CdiPaths {
2121
#[derive(Default)]
2222
struct TargetRequirements {
2323
device: bool,
24+
socket: bool,
2425
writable_file: bool,
2526
mount_read_only: Option<bool>,
2627
}
@@ -31,6 +32,9 @@ impl CdiPaths {
3132
for path in &requirements.read_only_paths {
3233
paths.entry(path.into()).or_default();
3334
}
35+
for path in &requirements.socket_paths {
36+
paths.entry(path.into()).or_default().socket = true;
37+
}
3438
for path in &requirements.device_node_paths {
3539
paths.entry(path.into()).or_default().device = true;
3640
}
@@ -57,6 +61,7 @@ impl CdiPaths {
5761
/// Open, validate and consume one target at a time, including targets
5862
/// covered by authored ancestors. `apply` must install any matching rules
5963
/// using the supplied descriptor before this function closes it.
64+
/// Sockets are validated without inserting ordinary filesystem rules.
6065
/// Symlinks remain supported: validation applies to the opened object,
6166
/// without a canonicalize/reopen race.
6267
pub(super) fn process_validated<F: AsFd, S>(
@@ -98,6 +103,12 @@ impl CdiPaths {
98103
));
99104
}
100105
let kind = FileType::from_raw_mode(stat.st_mode);
106+
if requirements.socket && kind != FileType::Socket {
107+
return Err(miette::miette!(
108+
"CDI socket '{}' is not a Unix socket",
109+
path.display()
110+
));
111+
}
101112
if requirements.device
102113
&& !matches!(kind, FileType::CharacterDevice | FileType::BlockDevice)
103114
{
@@ -126,7 +137,9 @@ impl CdiPaths {
126137
));
127138
}
128139
}
129-
state = apply(state, path, &fd)?;
140+
if !requirements.socket {
141+
state = apply(state, path, &fd)?;
142+
}
130143
// The descriptor closes before the next target is opened. Landlock
131144
// retains its object reference after successful rule insertion.
132145
}
@@ -175,6 +188,43 @@ mod tests {
175188
}
176189
}
177190

191+
#[cfg(target_os = "linux")]
192+
#[test]
193+
fn socket_targets_are_exact_and_revalidated_without_filesystem_rules() {
194+
let temp = tempfile::tempdir().unwrap();
195+
let target = temp.path().join("socket");
196+
let _listener = std::os::unix::net::UnixListener::bind(&target).unwrap();
197+
let requirements = CdiDerivedRequirements {
198+
socket_paths: vec![target.to_string_lossy().into_owned()],
199+
..Default::default()
200+
};
201+
let paths = CdiPaths::new(&requirements);
202+
assert!(paths.contains(&target));
203+
assert!(!paths.contains(temp.path()));
204+
let open_socket = |path: &Path| {
205+
rustix::fs::open(
206+
path,
207+
rustix::fs::OFlags::PATH | rustix::fs::OFlags::CLOEXEC,
208+
rustix::fs::Mode::empty(),
209+
)
210+
.into_diagnostic()
211+
};
212+
paths
213+
.process_validated((), open_socket, |(), _, _| {
214+
panic!("socket must not add a filesystem rule")
215+
})
216+
.unwrap();
217+
std::fs::remove_file(&target).unwrap();
218+
std::fs::write(&target, "replacement").unwrap();
219+
assert!(
220+
paths
221+
.process_validated((), open_socket, |(), _, _| Ok(()))
222+
.unwrap_err()
223+
.to_string()
224+
.contains("not a Unix socket")
225+
);
226+
}
227+
178228
#[test]
179229
fn deduplicates_paths_and_keeps_one_descriptor_live() {
180230
let temp = tempfile::tempdir().unwrap();

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

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -654,6 +654,52 @@ mod tests {
654654
}
655655
}
656656

657+
#[test]
658+
fn cdi_socket_communication_does_not_grant_parent_file_access() {
659+
use std::io::{Read, Write};
660+
661+
let availability = probe_availability();
662+
if !matches!(availability, LandlockAvailability::Available { abi } if abi >= 3) {
663+
assert!(
664+
std::env::var_os("OPENSHELL_TEST_REQUIRE_LANDLOCK").is_none(),
665+
"Landlock ABI v3 required: {availability}"
666+
);
667+
return;
668+
}
669+
let temp = tempfile::tempdir().unwrap();
670+
let target = temp.path().join("socket");
671+
let sibling = temp.path().join("secret");
672+
std::fs::write(&sibling, b"secret").unwrap();
673+
let listener = std::os::unix::net::UnixListener::bind(&target).unwrap();
674+
let allowed = temp.path().join("allowed");
675+
std::fs::write(&allowed, b"allowed").unwrap();
676+
let mut policy = hard_requirement_policy(vec![allowed], vec![]);
677+
policy.filesystem.cdi_requirements = Some(openshell_core::cdi::CdiDerivedRequirements {
678+
socket_paths: vec![target.to_string_lossy().into_owned()],
679+
..Default::default()
680+
});
681+
std::thread::spawn(move || {
682+
let prepared = prepare_current_user(&policy, None).unwrap().unwrap();
683+
enforce(prepared).unwrap();
684+
let mut stream = std::os::unix::net::UnixStream::connect(&target).unwrap();
685+
stream.write_all(b"ping").unwrap();
686+
assert_eq!(
687+
std::fs::read(&sibling).unwrap_err().kind(),
688+
std::io::ErrorKind::PermissionDenied
689+
);
690+
assert_eq!(
691+
std::fs::write(&sibling, b"changed").unwrap_err().kind(),
692+
std::io::ErrorKind::PermissionDenied
693+
);
694+
})
695+
.join()
696+
.unwrap();
697+
let (mut stream, _) = listener.accept().unwrap();
698+
let mut message = [0; 4];
699+
stream.read_exact(&mut message).unwrap();
700+
assert_eq!(&message, b"ping");
701+
}
702+
657703
#[test]
658704
fn cdi_rules_remain_pinned_after_symlink_swap() {
659705
let availability = probe_availability();

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,12 @@ read-write parent already covers it. The container runtime supplies CDI `additio
115115
OpenShell verifies that the workload already has those groups and fails startup
116116
if any required group is missing.
117117

118-
Writable CDI mount destinations are fail-closed. OpenShell accepts a writable
118+
Unix socket mounts are validated as sockets at their exact destinations at each
119+
launch or exec. They do not add filesystem grants or parent directory access and
120+
do not require `read_write` entries, regardless of mount flags. Communication
121+
uses the existing Unix IPC and socket permission checks.
122+
123+
Ordinary writable CDI mount destinations are fail-closed. OpenShell accepts a writable
119124
CDI mount only when it targets a single file and that exact path is already
120125
listed in `filesystem_policy.read_write`. Writable CDI directory mounts and CDI
121126
paths such as `/`, `/dev`, `/proc`, `/sys`, `/run`, or `/usr` are rejected

‎docs/how-it-works/sandboxes/overview.mdx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,10 +151,12 @@ updated Docker daemon capability.
151151
For CDI-enabled Docker sandboxes, OpenShell validates the injected filesystem
152152
targets before each launch and exec. Library directories may use symlinks, but
153153
must not resolve to broad roots such as `/`, `/usr`, or `/dev`. Device nodes must
154-
resolve to devices, and writable mounts must resolve to single files explicitly
154+
resolve to devices, and ordinary writable mounts must resolve to single files explicitly
155155
allowed by exact entries in the policy. OpenShell determines mount access from
156156
effective runtime flags, including writable submounts beneath original directory
157-
mounts. CDI does not automatically grant write access to `/proc`. The container
157+
mounts. Unix socket mounts retain their exact socket destinations and must resolve
158+
to sockets at each launch or exec. They do not grant access to parent directories
159+
or require writable-file policy entries. CDI does not automatically grant write access to `/proc`. The container
158160
runtime must supply any supplemental groups required by the CDI spec; missing
159161
groups prevent workload launch. CDI spec projections are checked with resource
160162
admission enabled. Invalid CDI targets or unavailable filesystem enforcement

0 commit comments

Comments
 (0)