Skip to main content

krab_runtime/
policy.rs

1use std::io;
2use std::path::{Component, Path, PathBuf};
3
4const DENY: [&str; 11] = [
5    "/proc",
6    "/sys",
7    "/dev",
8    "/etc",
9    "/root",
10    "/run",
11    "/var/run",
12    "/boot",
13    "/var/lib/docker",
14    "/private/etc",
15    "/private/var/run",
16];
17
18pub fn dns_label(s: &str) -> bool {
19    let b = s.as_bytes();
20    !b.is_empty()
21        && b.len() <= 63
22        && b.iter()
23            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-')
24        && b[0].is_ascii_alphanumeric()
25        && b[b.len() - 1].is_ascii_alphanumeric()
26}
27
28pub fn rel_path_ok(p: &str) -> bool {
29    !p.is_empty()
30        && p.len() <= 4096
31        && !p.contains('\0')
32        && p.split('/').all(|c| !c.is_empty() && c != "." && c != "..")
33}
34
35pub fn data_key_ok(k: &str) -> bool {
36    !k.is_empty()
37        && k.len() <= 253
38        && k != "."
39        && k != ".."
40        && k.bytes()
41            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
42}
43
44fn socket_like(s: &str) -> bool {
45    s.contains("docker.sock") || s.contains("containerd.sock")
46}
47
48fn resolve(p: &Path) -> io::Result<PathBuf> {
49    let mut base = p.to_path_buf();
50    let mut rest = Vec::new();
51    loop {
52        match std::fs::canonicalize(&base) {
53            Ok(mut c) => {
54                for r in rest.iter().rev() {
55                    c.push(r);
56                }
57                return Ok(c);
58            }
59            Err(e) if e.kind() == io::ErrorKind::NotFound => {
60                if std::fs::symlink_metadata(&base).is_ok() {
61                    return Err(io::Error::other("dangling symlink"));
62                }
63                let Some(name) = base.file_name().map(|n| n.to_os_string()) else {
64                    return Err(e);
65                };
66                rest.push(name);
67                if !base.pop() {
68                    return Err(e);
69                }
70            }
71            Err(e) => return Err(e),
72        }
73    }
74}
75
76pub fn host_path(path: &str, allow: &[PathBuf]) -> Result<PathBuf, String> {
77    let p = Path::new(path);
78    if !p.is_absolute()
79        || path.contains(':')
80        || path.contains('\0')
81        || !p
82            .components()
83            .all(|c| matches!(c, Component::RootDir | Component::Normal(_)))
84    {
85        return Err(format!(
86            "hostPath {path:?} must be an absolute path without '..' or ':'"
87        ));
88    }
89    if socket_like(path) {
90        return Err(format!(
91            "hostPath {path:?} is forbidden: container runtime sockets may not be mounted"
92        ));
93    }
94    let real = resolve(p).map_err(|e| format!("hostPath {path:?}: {e}"))?;
95    if socket_like(&real.to_string_lossy()) {
96        return Err(format!(
97            "hostPath {path:?} is forbidden: container runtime sockets may not be mounted"
98        ));
99    }
100    if real == Path::new("/") || DENY.iter().any(|d| real.starts_with(d)) {
101        return Err(format!(
102            "hostPath {path:?} is forbidden: system directories may not be mounted"
103        ));
104    }
105    let inside = allow.iter().any(|a| {
106        std::fs::canonicalize(a)
107            .map(|ca| real.starts_with(ca))
108            .unwrap_or(false)
109    });
110    if !inside {
111        return Err(format!(
112            "hostPath {path:?} is forbidden: allowed only inside directories passed with --allow-host-path"
113        ));
114    }
115    Ok(real)
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    #[test]
123    fn rel_paths_and_keys() {
124        for ok in ["a", "a/b.conf", "..data2", "x..y"] {
125            assert!(rel_path_ok(ok), "{ok}");
126        }
127        for bad in ["", "/etc/x", "a/../b", "..", "a//b", "a/./b", "a/"] {
128            assert!(!rel_path_ok(bad), "{bad}");
129        }
130        assert!(data_key_ok("app.conf"));
131        for bad in ["/etc/x", "..", ".", "a/b", "", "a b"] {
132            assert!(!data_key_ok(bad), "{bad}");
133        }
134        assert!(dns_label("html"));
135        assert!(!dns_label("/"));
136        assert!(!dns_label("../etc"));
137    }
138
139    #[test]
140    fn host_path_policy() {
141        let root = std::env::temp_dir().join(format!("krab-policy-{}", std::process::id()));
142        let allowed = root.join("data");
143        std::fs::create_dir_all(allowed.join("sub")).unwrap();
144        let allow = vec![allowed.clone()];
145        let a = allowed.to_string_lossy().into_owned();
146        assert!(host_path(&format!("{a}/sub"), &allow).is_ok());
147        assert!(host_path(&format!("{a}/new/dir"), &allow).is_ok());
148        assert!(host_path("/", &allow).is_err());
149        assert!(host_path("/", &[PathBuf::from("/")]).is_err());
150        assert!(host_path("/etc", &[PathBuf::from("/")]).is_err());
151        assert!(host_path("/var/run/docker.sock", &[PathBuf::from("/")]).is_err());
152        assert!(host_path(&format!("{a}/../x"), &allow).is_err());
153        assert!(host_path(&format!("{a}/x:rw"), &allow).is_err());
154        assert!(host_path("relative", &allow).is_err());
155        assert!(host_path(&a, &[]).is_err());
156        #[cfg(unix)]
157        {
158            std::os::unix::fs::symlink(&root, allowed.join("escape")).unwrap();
159            assert!(host_path(&format!("{a}/escape"), &allow).is_err());
160            std::os::unix::fs::symlink("/tmp/docker.sock", allowed.join("s")).unwrap();
161            assert!(host_path(&format!("{a}/s"), &allow).is_err());
162        }
163        std::fs::remove_dir_all(&root).unwrap();
164    }
165}