Skip to content

Commit 5ca2670

Browse files
committed
fix(sandbox): attest CDI mount projection
Signed-off-by: Evan Lezar <elezar@nvidia.com>
1 parent 72bbf1b commit 5ca2670

1 file changed

Lines changed: 172 additions & 3 deletions

File tree

  • crates/openshell-sandbox/src

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

Lines changed: 172 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1871,7 +1871,7 @@ fn resolve_cdi_requirements_from_env(
18711871
emit_cdi_validation_failure(&err.to_string());
18721872
miette::miette!("Failed to load CDI context from {context_path}: {err}")
18731873
})?;
1874-
validate_cdi_context_mount_roots(&context)?;
1874+
validate_cdi_context_projection(&context)?;
18751875
ocsf_emit!(
18761876
ConfigStateChangeBuilder::new(ocsf_ctx())
18771877
.severity(SeverityId::Informational)
@@ -1893,9 +1893,23 @@ fn resolve_cdi_requirements_from_env(
18931893
Ok(Some(requirements))
18941894
}
18951895

1896-
fn validate_cdi_context_mount_roots(context: &openshell_core::cdi::CdiContext) -> Result<()> {
1896+
fn validate_cdi_context_projection(context: &openshell_core::cdi::CdiContext) -> Result<()> {
1897+
if !context
1898+
.selected_devices
1899+
.iter()
1900+
.any(|device| !device.trim().is_empty())
1901+
{
1902+
let message = "CDI context must select at least one device";
1903+
emit_cdi_validation_failure(message);
1904+
return Err(miette::miette!(message));
1905+
}
1906+
if context.spec_dirs.is_empty() {
1907+
let message = "CDI context must list at least one spec directory";
1908+
emit_cdi_validation_failure(message);
1909+
return Err(miette::miette!(message));
1910+
}
18971911
let expected_prefix = format!("{}/", openshell_core::cdi::CDI_SPEC_DIR_BASE);
1898-
for spec_dir in &context.spec_dirs {
1912+
for (index, spec_dir) in context.spec_dirs.iter().enumerate() {
18991913
let normalized = openshell_core::paths::normalize_path(&spec_dir.path);
19001914
if !normalized.starts_with(&expected_prefix) {
19011915
let message = format!(
@@ -1906,10 +1920,119 @@ fn validate_cdi_context_mount_roots(context: &openshell_core::cdi::CdiContext) -
19061920
emit_cdi_validation_failure(&message);
19071921
return Err(miette::miette!("{message}"));
19081922
}
1923+
let expected_path = cdi_spec_mount_path(index);
1924+
if spec_dir.path != expected_path {
1925+
let message = format!(
1926+
"CDI spec dir at index {index} must be '{expected_path}', got '{}'",
1927+
spec_dir.path
1928+
);
1929+
emit_cdi_validation_failure(&message);
1930+
return Err(miette::miette!("{message}"));
1931+
}
1932+
}
1933+
validate_cdi_projection_mounts(context)
1934+
}
1935+
1936+
#[cfg(target_os = "linux")]
1937+
fn validate_cdi_projection_mounts(context: &openshell_core::cdi::CdiContext) -> Result<()> {
1938+
let mounts = read_mount_info()?;
1939+
validate_cdi_projection_mounts_with(context, &mounts)
1940+
}
1941+
1942+
#[cfg(target_os = "linux")]
1943+
fn validate_cdi_projection_mounts_with(
1944+
context: &openshell_core::cdi::CdiContext,
1945+
mounts: &[MountInfoEntry],
1946+
) -> Result<()> {
1947+
let mut expected_mounts = Vec::with_capacity(context.spec_dirs.len() + 1);
1948+
expected_mounts.push(openshell_core::cdi::CDI_CONTEXT_PATH);
1949+
expected_mounts.extend(
1950+
context
1951+
.spec_dirs
1952+
.iter()
1953+
.map(|spec_dir| spec_dir.path.as_str()),
1954+
);
1955+
1956+
for expected_path in expected_mounts {
1957+
let Some(mount) = mounts
1958+
.iter()
1959+
.find(|mount| mount.mount_point == expected_path)
1960+
else {
1961+
let message = format!("CDI projection path '{expected_path}' is not a mount");
1962+
emit_cdi_validation_failure(&message);
1963+
return Err(miette::miette!("{message}"));
1964+
};
1965+
if !mount.read_only {
1966+
let message = format!("CDI projection mount '{expected_path}' must be read-only");
1967+
emit_cdi_validation_failure(&message);
1968+
return Err(miette::miette!("{message}"));
1969+
}
19091970
}
19101971
Ok(())
19111972
}
19121973

1974+
#[cfg(not(target_os = "linux"))]
1975+
fn validate_cdi_projection_mounts(_context: &openshell_core::cdi::CdiContext) -> Result<()> {
1976+
Ok(())
1977+
}
1978+
1979+
fn cdi_spec_mount_path(index: usize) -> String {
1980+
format!("{}/{index}", openshell_core::cdi::CDI_SPEC_DIR_BASE)
1981+
}
1982+
1983+
#[cfg(target_os = "linux")]
1984+
#[derive(Debug, PartialEq, Eq)]
1985+
struct MountInfoEntry {
1986+
mount_point: String,
1987+
read_only: bool,
1988+
}
1989+
1990+
#[cfg(target_os = "linux")]
1991+
fn read_mount_info() -> Result<Vec<MountInfoEntry>> {
1992+
let mount_info = std::fs::read_to_string("/proc/self/mountinfo")
1993+
.into_diagnostic()
1994+
.wrap_err("read /proc/self/mountinfo")?;
1995+
mount_info.lines().map(parse_mount_info_entry).collect()
1996+
}
1997+
1998+
#[cfg(target_os = "linux")]
1999+
fn parse_mount_info_entry(line: &str) -> Result<MountInfoEntry> {
2000+
let fields = line.split_whitespace().collect::<Vec<_>>();
2001+
let mount_point = fields
2002+
.get(4)
2003+
.ok_or_else(|| miette::miette!("mountinfo entry is missing a mount point: {line}"))?;
2004+
let mount_options = fields
2005+
.get(5)
2006+
.ok_or_else(|| miette::miette!("mountinfo entry is missing mount options: {line}"))?;
2007+
Ok(MountInfoEntry {
2008+
mount_point: unescape_mount_info_path(mount_point)?,
2009+
read_only: mount_options.split(',').any(|option| option == "ro"),
2010+
})
2011+
}
2012+
2013+
#[cfg(target_os = "linux")]
2014+
fn unescape_mount_info_path(path: &str) -> Result<String> {
2015+
let mut decoded = Vec::with_capacity(path.len());
2016+
let bytes = path.as_bytes();
2017+
let mut index = 0;
2018+
while index < bytes.len() {
2019+
if bytes[index] != b'\\' {
2020+
decoded.push(bytes[index]);
2021+
index += 1;
2022+
continue;
2023+
}
2024+
let octal = bytes
2025+
.get(index + 1..index + 4)
2026+
.ok_or_else(|| miette::miette!("invalid mountinfo path escape in '{path}'"))?;
2027+
if !octal.iter().all(|byte| matches!(byte, b'0'..=b'7')) {
2028+
return Err(miette::miette!("invalid mountinfo path escape in '{path}'"));
2029+
}
2030+
decoded.push((octal[0] - b'0') * 64 + (octal[1] - b'0') * 8 + (octal[2] - b'0'));
2031+
index += 4;
2032+
}
2033+
String::from_utf8(decoded).into_diagnostic()
2034+
}
2035+
19132036
fn emit_cdi_validation_failure(message: &str) {
19142037
ocsf_emit!(
19152038
DetectionFindingBuilder::new(ocsf_ctx())
@@ -4655,6 +4778,52 @@ mod tests {
46554778
}
46564779
}
46574780

4781+
#[cfg(target_os = "linux")]
4782+
#[test]
4783+
fn cdi_projection_requires_read_only_context_and_spec_mounts() {
4784+
let context = openshell_core::cdi::CdiContext::new(
4785+
vec!["nvidia.com/gpu=0".to_string()],
4786+
vec![openshell_core::cdi::CdiSpecDirectory::new(
4787+
cdi_spec_mount_path(0),
4788+
"/host/cdi",
4789+
)],
4790+
);
4791+
let mounts = vec![
4792+
MountInfoEntry {
4793+
mount_point: openshell_core::cdi::CDI_CONTEXT_PATH.to_string(),
4794+
read_only: true,
4795+
},
4796+
MountInfoEntry {
4797+
mount_point: cdi_spec_mount_path(0),
4798+
read_only: true,
4799+
},
4800+
];
4801+
4802+
validate_cdi_projection_mounts_with(&context, &mounts)
4803+
.expect("read-only CDI context and spec mounts should be accepted");
4804+
4805+
let mut writable_mounts = mounts;
4806+
writable_mounts[1].read_only = false;
4807+
let err = validate_cdi_projection_mounts_with(&context, &writable_mounts)
4808+
.expect_err("writable CDI spec mount must be rejected");
4809+
assert!(err.to_string().contains("must be read-only"));
4810+
}
4811+
4812+
#[cfg(target_os = "linux")]
4813+
#[test]
4814+
fn parse_mount_info_entry_decodes_mount_path_and_access_mode() {
4815+
let mount = parse_mount_info_entry(
4816+
"42 35 0:42 / /run/openshell/supervisor/cdi-specs/0\\040with-space ro,nosuid - tmpfs tmpfs rw",
4817+
)
4818+
.expect("mountinfo fixture should parse");
4819+
4820+
assert_eq!(
4821+
mount.mount_point,
4822+
"/run/openshell/supervisor/cdi-specs/0 with-space"
4823+
);
4824+
assert!(mount.read_only);
4825+
}
4826+
46584827
#[test]
46594828
fn sidecar_process_policy_sets_loopback_proxy_addr() {
46604829
let policy = proxy_policy(None);

0 commit comments

Comments
 (0)