use std::io;
use std::path::{Component, Path, PathBuf};
const DENY: [&str; 11] = [
"/proc",
"/sys",
"/dev",
"/etc",
"/root",
"/run",
"/var/run",
"/boot",
"/var/lib/docker",
"/private/etc",
"/private/var/run",
];
pub fn dns_label(s: &str) -> bool {
let b = s.as_bytes();
!b.is_empty()
&& b.len() <= 63
&& b.iter()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-')
&& b[0].is_ascii_alphanumeric()
&& b[b.len() - 1].is_ascii_alphanumeric()
}
pub fn rel_path_ok(p: &str) -> bool {
!p.is_empty()
&& p.len() <= 4096
&& !p.contains('\0')
&& p.split('/').all(|c| !c.is_empty() && c != "." && c != "..")
}
pub fn data_key_ok(k: &str) -> bool {
!k.is_empty()
&& k.len() <= 253
&& k != "."
&& k != ".."
&& k.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
}
fn socket_like(s: &str) -> bool {
s.contains("docker.sock") || s.contains("containerd.sock")
}
fn resolve(p: &Path) -> io::Result<PathBuf> {
let mut base = p.to_path_buf();
let mut rest = Vec::new();
loop {
match std::fs::canonicalize(&base) {
Ok(mut c) => {
for r in rest.iter().rev() {
c.push(r);
}
return Ok(c);
}
Err(e) if e.kind() == io::ErrorKind::NotFound => {
if std::fs::symlink_metadata(&base).is_ok() {
return Err(io::Error::other("dangling symlink"));
}
let Some(name) = base.file_name().map(|n| n.to_os_string()) else {
return Err(e);
};
rest.push(name);
if !base.pop() {
return Err(e);
}
}
Err(e) => return Err(e),
}
}
}
pub fn host_path(path: &str, allow: &[PathBuf]) -> Result<PathBuf, String> {
let p = Path::new(path);
if !p.is_absolute()
|| path.contains(':')
|| path.contains('\0')
|| !p
.components()
.all(|c| matches!(c, Component::RootDir | Component::Normal(_)))
{
return Err(format!(
"hostPath {path:?} must be an absolute path without '..' or ':'"
));
}
if socket_like(path) {
return Err(format!(
"hostPath {path:?} is forbidden: container runtime sockets may not be mounted"
));
}
let real = resolve(p).map_err(|e| format!("hostPath {path:?}: {e}"))?;
if socket_like(&real.to_string_lossy()) {
return Err(format!(
"hostPath {path:?} is forbidden: container runtime sockets may not be mounted"
));
}
if real == Path::new("/") || DENY.iter().any(|d| real.starts_with(d)) {
return Err(format!(
"hostPath {path:?} is forbidden: system directories may not be mounted"
));
}
let inside = allow.iter().any(|a| {
std::fs::canonicalize(a)
.map(|ca| real.starts_with(ca))
.unwrap_or(false)
});
if !inside {
return Err(format!(
"hostPath {path:?} is forbidden: allowed only inside directories passed with --allow-host-path"
));
}
Ok(real)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rel_paths_and_keys() {
for ok in ["a", "a/b.conf", "..data2", "x..y"] {
assert!(rel_path_ok(ok), "{ok}");
}
for bad in ["", "/etc/x", "a/../b", "..", "a//b", "a/./b", "a/"] {
assert!(!rel_path_ok(bad), "{bad}");
}
assert!(data_key_ok("app.conf"));
for bad in ["/etc/x", "..", ".", "a/b", "", "a b"] {
assert!(!data_key_ok(bad), "{bad}");
}
assert!(dns_label("html"));
assert!(!dns_label("/"));
assert!(!dns_label("../etc"));
}
#[test]
fn host_path_policy() {
let root = std::env::temp_dir().join(format!("krab-policy-{}", std::process::id()));
let allowed = root.join("data");
std::fs::create_dir_all(allowed.join("sub")).unwrap();
let allow = vec![allowed.clone()];
let a = allowed.to_string_lossy().into_owned();
assert!(host_path(&format!("{a}/sub"), &allow).is_ok());
assert!(host_path(&format!("{a}/new/dir"), &allow).is_ok());
assert!(host_path("/", &allow).is_err());
assert!(host_path("/", &[PathBuf::from("/")]).is_err());
assert!(host_path("/etc", &[PathBuf::from("/")]).is_err());
assert!(host_path("/var/run/docker.sock", &[PathBuf::from("/")]).is_err());
assert!(host_path(&format!("{a}/../x"), &allow).is_err());
assert!(host_path(&format!("{a}/x:rw"), &allow).is_err());
assert!(host_path("relative", &allow).is_err());
assert!(host_path(&a, &[]).is_err());
#[cfg(unix)]
{
std::os::unix::fs::symlink(&root, allowed.join("escape")).unwrap();
assert!(host_path(&format!("{a}/escape"), &allow).is_err());
std::os::unix::fs::symlink("/tmp/docker.sock", allowed.join("s")).unwrap();
assert!(host_path(&format!("{a}/s"), &allow).is_err());
}
std::fs::remove_dir_all(&root).unwrap();
}
}