Skip to content

Commit 03e46ec

Browse files
committed
fix(podman): bound image metadata inspection and reject dangling roots
Signed-off-by: Drew Newberry <anewberry@nvidia.com>
1 parent f1f183a commit 03e46ec

3 files changed

Lines changed: 292 additions & 29 deletions

File tree

‎crates/openshell-driver-podman/README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# openshell-driver-podman
22

3+
Image admission checks the reserved `/.openshell` path using archive metadata
4+
only. Downloads of `/etc/passwd` and `/etc/group` are limited to 1 MiB each,
5+
including tar overhead, and extracted file sizes are checked independently.
6+
37
The Podman compute driver runs inside the gateway and uses the native libpod
48
REST API over a Unix socket. Each sandbox has two independent containers:
59

‎crates/openshell-driver-podman/src/client.rs‎

Lines changed: 261 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ const API_TIMEOUT: Duration = Duration::from_secs(30);
2626
/// Maximum allowed size for the event stream line buffer (1 MB).
2727
const MAX_EVENT_BUFFER: usize = 1_048_576;
2828

29+
/// Image account databases are metadata, not unrestricted archive downloads.
30+
const MAX_IMAGE_ACCOUNT_BYTES: usize = 1_048_576;
31+
2932
#[derive(Debug, thiserror::Error)]
3033
pub enum PodmanApiError {
3134
#[error("podman API not found (404): {0}")]
@@ -281,6 +284,38 @@ pub struct SecurityInfo {
281284

282285
// ── Client ───────────────────────────────────────────────────────────────
283286

287+
fn extract_image_account_file(archive: &[u8]) -> Result<Vec<u8>, PodmanApiError> {
288+
use std::io::Read as _;
289+
290+
let invalid = |error: std::io::Error| {
291+
PodmanApiError::InvalidInput(format!("invalid image account archive: {error}"))
292+
};
293+
let mut archive = tar::Archive::new(archive);
294+
let mut entries = archive.entries().map_err(invalid)?;
295+
let entry = entries
296+
.next()
297+
.ok_or_else(|| PodmanApiError::InvalidInput("empty image account archive".into()))?
298+
.map_err(invalid)?;
299+
if !entry.header().entry_type().is_file() || entry.size() > MAX_IMAGE_ACCOUNT_BYTES as u64 {
300+
return Err(PodmanApiError::InvalidInput(format!(
301+
"image account must be a regular file of at most {MAX_IMAGE_ACCOUNT_BYTES} bytes"
302+
)));
303+
}
304+
let mut bytes = Vec::new();
305+
// Bound extraction independently: sparse/PAX tar metadata must not expand
306+
// a small wire archive into an unbounded account database.
307+
entry
308+
.take(MAX_IMAGE_ACCOUNT_BYTES as u64 + 1)
309+
.read_to_end(&mut bytes)
310+
.map_err(invalid)?;
311+
if bytes.len() > MAX_IMAGE_ACCOUNT_BYTES {
312+
return Err(PodmanApiError::InvalidInput(
313+
"image account payload exceeds size limit".into(),
314+
));
315+
}
316+
Ok(bytes)
317+
}
318+
284319
/// Async Podman REST API client communicating over a Unix socket.
285320
#[derive(Debug, Clone)]
286321
pub struct PodmanClient {
@@ -628,6 +663,94 @@ impl PodmanClient {
628663
}
629664
}
630665

666+
/// Fetch archive metadata without reading an image-controlled response body.
667+
pub(crate) async fn container_path_exists(
668+
&self,
669+
name: &str,
670+
path: &str,
671+
) -> Result<bool, PodmanApiError> {
672+
let response = self
673+
.image_metadata_response(name, path, hyper::Method::HEAD)
674+
.await?;
675+
// Libpod returns 404 for a dangling symlink, but still supplies its
676+
// lstat metadata. Such a path exists and must never pass admission.
677+
if response
678+
.headers()
679+
.contains_key("x-docker-container-path-stat")
680+
{
681+
return Ok(true);
682+
}
683+
match response.status().as_u16() {
684+
200 => Ok(true),
685+
404 => Ok(false),
686+
status => Err(PodmanApiError::Api {
687+
status,
688+
message: "container image path metadata probe failed".into(),
689+
}),
690+
}
691+
}
692+
693+
/// Bound both the wire archive and its extracted account-file payload.
694+
pub(crate) async fn copy_image_account_file(
695+
&self,
696+
name: &str,
697+
path: &str,
698+
) -> Result<Vec<u8>, PodmanApiError> {
699+
let response = self
700+
.image_metadata_response(name, path, hyper::Method::GET)
701+
.await?;
702+
let status = response.status();
703+
if status == hyper::StatusCode::NOT_FOUND {
704+
return Ok(Vec::new());
705+
}
706+
if !status.is_success() {
707+
return Err(PodmanApiError::Api {
708+
status: status.as_u16(),
709+
message: "container image account download failed".into(),
710+
});
711+
}
712+
let archive = tokio::time::timeout(
713+
API_TIMEOUT,
714+
http_body_util::Limited::new(response.into_body(), MAX_IMAGE_ACCOUNT_BYTES).collect(),
715+
)
716+
.await
717+
.map_err(|_| PodmanApiError::Timeout(API_TIMEOUT))?
718+
.map_err(|error| {
719+
PodmanApiError::InvalidInput(format!(
720+
"image account archive must fit within {MAX_IMAGE_ACCOUNT_BYTES} bytes: {error}"
721+
))
722+
})?
723+
.to_bytes();
724+
extract_image_account_file(&archive)
725+
}
726+
727+
async fn image_metadata_response(
728+
&self,
729+
name: &str,
730+
path: &str,
731+
method: hyper::Method,
732+
) -> Result<hyper::Response<hyper::body::Incoming>, PodmanApiError> {
733+
validate_name(name)?;
734+
let request = Self::build_request(
735+
method,
736+
&format!(
737+
"/{API_VERSION}/libpod/containers/{name}/archive?path={}",
738+
url_encode(path)
739+
),
740+
Full::new(Bytes::new()),
741+
None,
742+
);
743+
tokio::time::timeout(API_TIMEOUT, async {
744+
let mut sender = self.connect().await?;
745+
sender
746+
.send_request(request)
747+
.await
748+
.map_err(|error| PodmanApiError::Connection(error.to_string()))
749+
})
750+
.await
751+
.map_err(|_| PodmanApiError::Timeout(API_TIMEOUT))?
752+
}
753+
631754
/// Inspect a container by name or ID.
632755
pub async fn inspect_container(&self, name: &str) -> Result<ContainerInspect, PodmanApiError> {
633756
validate_name(name)?;
@@ -1001,6 +1124,144 @@ mod tests {
10011124
use crate::test_utils::{StubResponse, spawn_podman_stub};
10021125
use hyper::StatusCode;
10031126

1127+
#[tokio::test]
1128+
async fn image_path_probe_uses_head_and_fails_closed_on_server_errors() {
1129+
let (path, requests, server) = spawn_podman_stub(
1130+
"image-path-head",
1131+
vec![
1132+
StubResponse::new(StatusCode::OK, vec![0; MAX_IMAGE_ACCOUNT_BYTES + 1]),
1133+
StubResponse::new(StatusCode::NOT_FOUND, ""),
1134+
StubResponse::new(StatusCode::INTERNAL_SERVER_ERROR, ""),
1135+
],
1136+
);
1137+
let client = PodmanClient::new(path);
1138+
assert!(
1139+
client
1140+
.container_path_exists("image", "/.openshell")
1141+
.await
1142+
.unwrap()
1143+
);
1144+
assert!(
1145+
!client
1146+
.container_path_exists("image", "/.openshell")
1147+
.await
1148+
.unwrap()
1149+
);
1150+
assert!(
1151+
client
1152+
.container_path_exists("image", "/.openshell")
1153+
.await
1154+
.is_err()
1155+
);
1156+
server.await.unwrap();
1157+
assert!(
1158+
requests.lock().unwrap().iter().all(|request| request
1159+
== "HEAD /v5.0.0/libpod/containers/image/archive?path=%2F.openshell")
1160+
);
1161+
}
1162+
1163+
#[tokio::test]
1164+
async fn image_path_probe_rejects_dangling_symlink_metadata_on_404() {
1165+
let path = crate::test_utils::unique_socket_path("dangling-root-head");
1166+
let listener = tokio::net::UnixListener::bind(&path).unwrap();
1167+
let server = tokio::spawn(async move {
1168+
let (stream, _) = listener.accept().await.unwrap();
1169+
let _ = hyper::server::conn::http1::Builder::new()
1170+
.serve_connection(
1171+
TokioIo::new(stream),
1172+
hyper::service::service_fn(|request| async move {
1173+
assert_eq!(request.method(), hyper::Method::HEAD);
1174+
Ok::<_, std::convert::Infallible>(
1175+
hyper::Response::builder()
1176+
.status(StatusCode::NOT_FOUND)
1177+
// Its contents need not be decoded: any stat metadata
1178+
// proves this is not an absent directory entry.
1179+
.header("x-docker-container-path-stat", "present")
1180+
.body(Full::new(Bytes::new()))
1181+
.unwrap(),
1182+
)
1183+
}),
1184+
)
1185+
.await;
1186+
});
1187+
let client = PodmanClient::new(path.clone());
1188+
assert!(
1189+
client
1190+
.container_path_exists("image", "/.openshell")
1191+
.await
1192+
.unwrap()
1193+
);
1194+
server.await.unwrap();
1195+
std::fs::remove_file(path).unwrap();
1196+
}
1197+
1198+
#[tokio::test]
1199+
async fn image_account_download_rejects_oversized_archive() {
1200+
let (path, _, server) = spawn_podman_stub(
1201+
"account-wire-limit",
1202+
vec![StubResponse::new(
1203+
StatusCode::OK,
1204+
vec![0; MAX_IMAGE_ACCOUNT_BYTES + 1],
1205+
)],
1206+
);
1207+
let client = PodmanClient::new(path);
1208+
let error = client
1209+
.copy_image_account_file("image", "/etc/passwd")
1210+
.await
1211+
.unwrap_err();
1212+
assert!(error.to_string().contains("archive must fit within"));
1213+
server.await.unwrap();
1214+
}
1215+
1216+
#[test]
1217+
fn image_account_extraction_rejects_oversized_header_before_allocating_payload() {
1218+
let mut header = tar::Header::new_gnu();
1219+
header.set_entry_type(tar::EntryType::Regular);
1220+
header.set_path("passwd").unwrap();
1221+
header.set_mode(0o644);
1222+
header.set_size(u64::MAX / 2);
1223+
header.set_cksum();
1224+
let error = extract_image_account_file(header.as_bytes()).unwrap_err();
1225+
assert!(error.to_string().contains("regular file of at most"));
1226+
}
1227+
1228+
#[tokio::test]
1229+
async fn image_account_download_accepts_regular_file_and_missing_database() {
1230+
let mut archive = tar::Builder::new(Vec::new());
1231+
let payload = b"agent:x:1000:1000::/sandbox:/bin/sh\n";
1232+
let mut header = tar::Header::new_gnu();
1233+
header.set_entry_type(tar::EntryType::Regular);
1234+
header.set_mode(0o644);
1235+
header.set_size(payload.len() as u64);
1236+
header.set_cksum();
1237+
archive
1238+
.append_data(&mut header, "passwd", payload.as_slice())
1239+
.unwrap();
1240+
let (path, _, server) = spawn_podman_stub(
1241+
"account-regular",
1242+
vec![
1243+
StubResponse::new(StatusCode::OK, archive.into_inner().unwrap()),
1244+
StubResponse::new(StatusCode::NOT_FOUND, ""),
1245+
],
1246+
);
1247+
let client = PodmanClient::new(path);
1248+
assert_eq!(
1249+
client
1250+
.copy_image_account_file("image", "/etc/passwd")
1251+
.await
1252+
.unwrap(),
1253+
payload
1254+
);
1255+
assert!(
1256+
client
1257+
.copy_image_account_file("image", "/etc/group")
1258+
.await
1259+
.unwrap()
1260+
.is_empty()
1261+
);
1262+
server.await.unwrap();
1263+
}
1264+
10041265
#[test]
10051266
fn url_encode_encodes_special_characters() {
10061267
assert_eq!(url_encode("hello world"), "hello%20world");

‎crates/openshell-driver-podman/src/driver.rs‎

Lines changed: 27 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1099,36 +1099,32 @@ impl PodmanComputeDriver {
10991099
image,
11001100
})
11011101
.await?;
1102-
let result =
1103-
async {
1104-
// Do not let image-controlled symlinks alias the protected channel
1105-
// into an agent-readable subtree before Podman mounts it.
1106-
match self.client.copy_from_container(&id, "/.openshell").await {
1107-
Err(PodmanApiError::NotFound(_)) => {}
1108-
Ok(_) => return Err(ComputeDriverError::Precondition(
1109-
"workload images must not prepopulate the reserved /.openshell hierarchy"
1110-
.into(),
1111-
)),
1112-
Err(error) => return Err(error.into()),
1113-
}
1114-
let mut accounts = Vec::new();
1115-
for path in ["/etc/passwd", "/etc/group"] {
1116-
let content = match self.client.copy_from_container(&id, path).await {
1117-
Ok(archive) => extract_first_tar_entry(&archive)
1118-
.map_err(ComputeDriverError::Precondition)?,
1119-
Err(PodmanApiError::NotFound(_)) => Vec::new(),
1120-
Err(error) => return Err(error.into()),
1121-
};
1122-
accounts.push(content);
1123-
}
1124-
let [passwd, group] = accounts.as_slice() else {
1125-
return Err(ComputeDriverError::Precondition(
1126-
"image account inspection was incomplete".into(),
1127-
));
1128-
};
1129-
crate::isolation::resolve_identity(sandbox, image, image_user, passwd, group)
1102+
let result = async {
1103+
// Do not let image-controlled symlinks alias the protected channel
1104+
// into an agent-readable subtree before Podman mounts it.
1105+
if self
1106+
.client
1107+
.container_path_exists(&id, "/.openshell")
1108+
.await?
1109+
{
1110+
return Err(ComputeDriverError::Precondition(
1111+
"workload images must not prepopulate the reserved /.openshell hierarchy"
1112+
.into(),
1113+
));
11301114
}
1131-
.await;
1115+
let mut accounts = Vec::new();
1116+
for path in ["/etc/passwd", "/etc/group"] {
1117+
let content = self.client.copy_image_account_file(&id, path).await?;
1118+
accounts.push(content);
1119+
}
1120+
let [passwd, group] = accounts.as_slice() else {
1121+
return Err(ComputeDriverError::Precondition(
1122+
"image account inspection was incomplete".into(),
1123+
));
1124+
};
1125+
crate::isolation::resolve_identity(sandbox, image, image_user, passwd, group)
1126+
}
1127+
.await;
11321128
let cleanup = self.client.remove_container(&id, 0).await;
11331129
if let Err(error) = cleanup {
11341130
warn!(container = %id, %error, "Failed to remove stopped identity inspection container");
@@ -3290,6 +3286,8 @@ mod tests {
32903286
.unwrap_err();
32913287
assert!(error.to_string().contains("reserved /.openshell"));
32923288
handle.await.unwrap();
3289+
assert!(requests.lock().unwrap().iter().any(|request| request
3290+
== "HEAD /v5.0.0/libpod/containers/identity-reader/archive?path=%2F.openshell"));
32933291
assert!(
32943292
!requests
32953293
.lock()

0 commit comments

Comments
 (0)