use crate::{ContainerSpec, Mount};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::io::{self, Read};
use std::path::{Component, Path};
const DEFAULT_PATH: &str = "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
const CAPS: [&str; 13] = [
"CAP_CHOWN",
"CAP_DAC_OVERRIDE",
"CAP_FSETID",
"CAP_FOWNER",
"CAP_MKNOD",
"CAP_SETGID",
"CAP_SETUID",
"CAP_SETFCAP",
"CAP_SETPCAP",
"CAP_NET_BIND_SERVICE",
"CAP_SYS_CHROOT",
"CAP_KILL",
"CAP_AUDIT_WRITE",
];
const MASKED: [&str; 11] = [
"/proc/asound",
"/proc/acpi",
"/proc/kcore",
"/proc/keys",
"/proc/latency_stats",
"/proc/timer_list",
"/proc/timer_stats",
"/proc/sched_debug",
"/proc/scsi",
"/sys/firmware",
"/sys/devices/virtual/powercap",
];
const READONLY: [&str; 5] = [
"/proc/bus",
"/proc/fs",
"/proc/irq",
"/proc/sys",
"/proc/sysrq-trigger",
];
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct ImageConfig {
#[serde(default)]
pub entrypoint: Option<Vec<String>>,
#[serde(default)]
pub cmd: Option<Vec<String>>,
#[serde(default)]
pub env: Option<Vec<String>>,
#[serde(default)]
pub working_dir: Option<String>,
#[serde(default)]
pub user: Option<String>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Process {
pub args: Vec<String>,
pub env: Vec<String>,
pub cwd: String,
pub user: String,
}
fn invalid(msg: impl Into<String>) -> io::Error {
io::Error::new(io::ErrorKind::InvalidInput, msg.into())
}
pub fn merge(spec: &ContainerSpec, img: &ImageConfig) -> io::Result<Process> {
let (entry, cmd) = if spec.command.is_empty() {
let cmd = if spec.args.is_empty() {
img.cmd.clone().unwrap_or_default()
} else {
spec.args.clone()
};
(img.entrypoint.clone().unwrap_or_default(), cmd)
} else {
(spec.command.clone(), spec.args.clone())
};
let args: Vec<String> = entry.into_iter().chain(cmd).collect();
if args.is_empty() || args[0].is_empty() {
return Err(invalid("no command specified"));
}
let mut env: Vec<String> = Vec::new();
for e in img.env.iter().flatten().chain(spec.env.iter()) {
let key = e.split_once('=').map_or(e.as_str(), |(k, _)| k);
env.retain(|x| x.split_once('=').map_or(x.as_str(), |(k, _)| k) != key);
env.push(e.clone());
}
if !env.iter().any(|e| e.starts_with("PATH=")) {
env.insert(0, DEFAULT_PATH.into());
}
if let Some(h) = &spec.hostname
&& !env.iter().any(|e| e.starts_with("HOSTNAME="))
{
env.push(format!("HOSTNAME={h}"));
}
if spec.tty && !env.iter().any(|e| e.starts_with("TERM=")) {
env.push("TERM=xterm".into());
}
let cwd = spec
.working_dir
.clone()
.filter(|w| !w.is_empty())
.or_else(|| img.working_dir.clone().filter(|w| !w.is_empty()))
.unwrap_or_else(|| "/".into());
if !cwd.starts_with('/') {
return Err(invalid(format!("working dir {cwd:?} must be absolute")));
}
let user = spec
.user
.clone()
.or_else(|| img.user.clone())
.unwrap_or_default();
Ok(Process {
args,
env,
cwd,
user,
})
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct User {
pub uid: u32,
pub gid: u32,
pub extra: Vec<u32>,
}
pub fn resolve_user(user: &str, passwd: &str, group: &str) -> io::Result<User> {
if user.is_empty() {
return Ok(User::default());
}
let (u, g) = match user.split_once(':') {
Some((u, g)) => (u, Some(g)),
None => (user, None),
};
let pw = passwd.lines().find_map(|l| {
let f: Vec<&str> = l.split(':').collect();
if f.len() < 4 {
return None;
}
let hit = match u.parse::<u32>() {
Ok(n) => f[2].parse::<u32>().ok() == Some(n),
Err(_) => f[0] == u,
};
hit.then(|| {
(
f[0].to_string(),
f[2].parse::<u32>().ok(),
f[3].parse::<u32>().ok(),
)
})
});
let (name, uid, pgid) = match (u.parse::<u32>(), pw) {
(Ok(n), Some((name, _, gid))) => (name, n, gid.unwrap_or(0)),
(Ok(n), None) => (String::new(), n, 0),
(Err(_), Some((name, Some(uid), gid))) => (name, uid, gid.unwrap_or(0)),
_ => return Err(invalid(format!("unable to find user {u}"))),
};
let gid = match g {
None => pgid,
Some(g) => match g.parse::<u32>() {
Ok(n) => n,
Err(_) => group
.lines()
.find_map(|l| {
let f: Vec<&str> = l.split(':').collect();
(f.len() >= 3 && f[0] == g).then(|| f[2].parse::<u32>().ok())?
})
.ok_or_else(|| invalid(format!("unable to find group {g}")))?,
},
};
let mut extra = Vec::new();
if !name.is_empty() {
for l in group.lines() {
let f: Vec<&str> = l.split(':').collect();
if f.len() >= 4
&& f[3].split(',').any(|m| m == name)
&& let Ok(n) = f[2].parse::<u32>()
&& n != gid
&& !extra.contains(&n)
{
extra.push(n);
}
}
}
Ok(User { uid, gid, extra })
}
pub fn set_home(env: &mut Vec<String>, uid: u32, passwd: &str) {
if env.iter().any(|e| e.starts_with("HOME=")) {
return;
}
let home = passwd
.lines()
.find_map(|l| {
let f: Vec<&str> = l.split(':').collect();
(f.len() >= 6 && f[2].parse::<u32>().ok() == Some(uid) && !f[5].is_empty())
.then(|| f[5].to_string())
})
.unwrap_or_else(|| "/".into());
env.push(format!("HOME={home}"));
}
pub fn dest_ok(dst: &str) -> bool {
let p = Path::new(dst);
p.is_absolute()
&& dst.len() <= 4096
&& !dst.contains('\0')
&& p.components()
.all(|c| matches!(c, Component::RootDir | Component::Normal(_)))
&& p.components().count() > 1
}
pub struct Bundle<'a> {
pub cgroups_path: &'a str,
pub hosts: &'a Path,
pub resolv: &'a Path,
pub hostname_file: &'a Path,
pub volume_root: &'a Path,
pub netns: Option<&'a Path>,
pub seccomp: Option<&'a Value>,
}
const MAX_PROFILE: u64 = 1 << 20;
const RESTRICTIVE_ACTIONS: [&str; 3] = [
"SCMP_ACT_ERRNO",
"SCMP_ACT_KILL_PROCESS",
"SCMP_ACT_KILL_THREAD",
];
#[derive(Clone, Debug)]
pub struct Profile {
value: Value,
}
fn has_notify(value: &Value) -> bool {
match value {
Value::Object(map) => map
.iter()
.any(|(k, v)| matches!(k.as_str(), "notify" | "notifyOpts") || has_notify(v)),
Value::Array(items) => items.iter().any(has_notify),
Value::String(s) => matches!(
s.as_str(),
"SCMP_ACT_NOTIFY" | "SECCOMP_FILTER_FLAG_NEW_LISTENER"
),
_ => false,
}
}
fn validate(ctx: &str, value: &Value) -> io::Result<()> {
let object = value
.as_object()
.ok_or_else(|| invalid(format!("{ctx}: must be a JSON object")))?;
if object.keys().any(|k| {
!matches!(
k.as_str(),
"defaultAction" | "defaultErrnoRet" | "architectures" | "flags" | "syscalls"
)
}) {
return Err(invalid(format!("{ctx}: unsupported OCI seccomp field")));
}
if let Some(syscalls) = object.get("syscalls") {
let syscalls = syscalls
.as_array()
.ok_or_else(|| invalid(format!("{ctx}: syscalls must be an array")))?;
for syscall in syscalls {
if !syscall.as_object().is_some_and(|s| {
s.keys()
.all(|k| matches!(k.as_str(), "names" | "action" | "errnoRet" | "args"))
&& s.get("action").and_then(Value::as_str).is_some()
&& s.get("names")
.and_then(Value::as_array)
.is_some_and(|names| {
!names.is_empty()
&& names
.iter()
.all(|n| n.as_str().is_some_and(|n| !n.is_empty()))
})
}) {
return Err(invalid(format!("{ctx}: invalid OCI seccomp syscall rule")));
}
}
}
let action = value.get("defaultAction").and_then(Value::as_str);
if !RESTRICTIVE_ACTIONS.contains(&action.unwrap_or("")) {
return Err(invalid(format!(
"{ctx}: defaultAction {action:?} must be SCMP_ACT_ERRNO, SCMP_ACT_KILL_PROCESS or SCMP_ACT_KILL_THREAD"
)));
}
if has_notify(value) {
return Err(invalid(format!(
"{ctx}: user notification is not supported"
)));
}
Ok(())
}
impl Profile {
pub fn load(path: &Path) -> io::Result<Self> {
let ctx = format!("seccomp profile {}", path.display());
let f = std::fs::File::open(path)
.map_err(|e| io::Error::new(e.kind(), format!("{ctx}: {e}")))?;
let mut buf = Vec::new();
f.take(MAX_PROFILE + 1)
.read_to_end(&mut buf)
.map_err(|e| io::Error::new(e.kind(), format!("{ctx}: {e}")))?;
if buf.len() as u64 > MAX_PROFILE {
return Err(invalid(format!("{ctx}: larger than {MAX_PROFILE} bytes")));
}
let value: Value =
serde_json::from_slice(&buf).map_err(|e| invalid(format!("{ctx}: {e}")))?;
validate(&ctx, &value)?;
Ok(Self { value })
}
pub fn value(&self) -> &Value {
&self.value
}
}
fn mnt(dst: &str, ty: &str, src: &str, opts: &[&str]) -> Value {
json!({"destination": dst, "type": ty, "source": src, "options": opts})
}
fn bind(dst: &str, src: &str, ro: bool) -> Value {
mnt(
dst,
"bind",
src,
&[
"rbind",
"rprivate",
"nosuid",
"nodev",
if ro { "ro" } else { "rw" },
],
)
}
pub fn spec_mounts(spec: &ContainerSpec, b: &Bundle) -> io::Result<Vec<Value>> {
let mut out = vec![
mnt("/proc", "proc", "proc", &["nosuid", "noexec", "nodev"]),
mnt(
"/dev",
"tmpfs",
"tmpfs",
&["nosuid", "strictatime", "mode=755", "size=65536k"],
),
mnt(
"/dev/pts",
"devpts",
"devpts",
&[
"nosuid",
"noexec",
"newinstance",
"ptmxmode=0666",
"mode=0620",
"gid=5",
],
),
mnt(
"/dev/shm",
"tmpfs",
"shm",
&["nosuid", "noexec", "nodev", "mode=1777", "size=65536k"],
),
mnt(
"/dev/mqueue",
"mqueue",
"mqueue",
&["nosuid", "noexec", "nodev"],
),
mnt(
"/sys",
"sysfs",
"sysfs",
&["nosuid", "noexec", "nodev", "ro"],
),
mnt(
"/sys/fs/cgroup",
"cgroup",
"cgroup",
&["nosuid", "noexec", "nodev", "relatime", "ro"],
),
];
let mut user_dsts = Vec::new();
for m in &spec.mounts {
let (dst, v) = match m {
Mount::Bind {
src,
dst,
read_only,
} => {
if !Path::new(src).is_absolute() || src.contains('\0') {
return Err(invalid(format!("bind source {src:?} must be absolute")));
}
(dst, bind(dst, src, *read_only))
}
Mount::Volume {
name,
dst,
read_only,
} => {
if !crate::policy::data_key_ok(name) || name.starts_with('.') {
return Err(invalid(format!("bad volume name {name:?}")));
}
let src = b.volume_root.join(name);
(dst, bind(dst, &src.to_string_lossy(), *read_only))
}
Mount::Tmpfs { dst } => (
dst,
mnt(dst, "tmpfs", "tmpfs", &["nosuid", "nodev", "mode=1777"]),
),
};
if !dest_ok(dst) {
return Err(invalid(format!("bad mount destination {dst:?}")));
}
user_dsts.push(dst.clone());
out.push(v);
}
for (dst, src) in [
("/etc/hosts", b.hosts),
("/etc/resolv.conf", b.resolv),
("/etc/hostname", b.hostname_file),
] {
if !user_dsts.iter().any(|d| d == dst) {
out.push(bind(dst, &src.to_string_lossy(), false));
}
}
Ok(out)
}
fn dev(path: &str, major: i64, minor: i64) -> Value {
json!({"path": path, "type": "c", "major": major, "minor": minor, "fileMode": 0o666, "uid": 0, "gid": 0})
}
fn allow(major: Option<i64>, minor: Option<i64>, access: &str) -> Value {
json!({"allow": true, "type": "c", "major": major, "minor": minor, "access": access})
}
pub fn config_json(
spec: &ContainerSpec,
p: &Process,
user: &User,
b: &Bundle,
) -> io::Result<Value> {
let caps = &CAPS[..];
let mut resources = json!({
"pids": {"limit": 4096},
"devices": [
{"allow": false, "access": "rwm"},
{"allow": true, "type": "c", "access": "m"},
{"allow": true, "type": "b", "access": "m"},
allow(Some(1), Some(3), "rwm"),
allow(Some(1), Some(5), "rwm"),
allow(Some(1), Some(7), "rwm"),
allow(Some(1), Some(8), "rwm"),
allow(Some(1), Some(9), "rwm"),
allow(Some(5), Some(0), "rwm"),
allow(Some(5), Some(1), "rwm"),
allow(Some(5), Some(2), "rwm"),
allow(Some(136), None, "rwm"),
],
});
if let Some(m) = spec.memory_bytes.filter(|m| *m > 0) {
resources["memory"] = json!({"limit": m, "swap": m});
}
if let Some(n) = spec.nano_cpus.filter(|n| *n > 0) {
let period: i64 = 100_000;
resources["cpu"] = json!({"quota": (n.saturating_mul(period) / 1_000_000_000).max(1000), "period": period});
}
let mut namespaces = vec![
json!({"type": "pid"}),
json!({"type": "ipc"}),
json!({"type": "uts"}),
json!({"type": "mount"}),
json!({"type": "cgroup"}),
];
if let Some(p) = b.netns {
namespaces.push(json!({"type": "network", "path": p}));
}
let mut linux = json!({
"cgroupsPath": b.cgroups_path,
"resources": resources,
"namespaces": namespaces,
"devices": [dev("/dev/null", 1, 3), dev("/dev/zero", 1, 5), dev("/dev/full", 1, 7), dev("/dev/random", 1, 8), dev("/dev/urandom", 1, 9), dev("/dev/tty", 5, 0)],
"maskedPaths": MASKED,
"readonlyPaths": READONLY,
});
if let Some(p) = b.seccomp {
linux["seccomp"] = p.clone();
}
Ok(json!({
"ociVersion": "1.0.2",
"process": {
"terminal": spec.tty,
"user": {"uid": user.uid, "gid": user.gid, "additionalGids": user.extra},
"args": p.args,
"env": p.env,
"cwd": p.cwd,
"capabilities": {"bounding": caps, "effective": caps, "permitted": caps},
"rlimits": [{"type": "RLIMIT_NOFILE", "hard": 1048576u64, "soft": 1048576u64}],
"noNewPrivileges": !spec.allow_privilege_escalation,
},
"root": {"path": "rootfs", "readonly": spec.read_only_root},
"hostname": spec.hostname.clone().unwrap_or_default(),
"mounts": spec_mounts(spec, b)?,
"linux": linux,
}))
}
pub fn resolv_conf(host: &str, search: &[String], options: &[String]) -> String {
let mut out = String::new();
for l in host.lines() {
let l = l.trim();
if l.starts_with("nameserver ") {
out.push_str(l);
out.push('\n');
}
}
if out.is_empty() {
out.push_str("nameserver 1.1.1.1\n");
}
let clean = |v: &[String]| -> Vec<String> {
v.iter()
.filter(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_graphic()))
.cloned()
.collect()
};
let s = clean(search);
if !s.is_empty() {
out.push_str(&format!("search {}\n", s.join(" ")));
}
let o = clean(options);
if !o.is_empty() {
out.push_str(&format!("options {}\n", o.join(" ")));
}
out
}
pub fn hosts_file(hostname: &str, aliases: &[String]) -> String {
let pairs: Vec<(String, String)> = aliases
.iter()
.map(|a| ("127.0.0.1".to_string(), a.clone()))
.collect();
pod_hosts(hostname, "127.0.0.1", &pairs)
}
pub fn pod_hosts(hostname: &str, ip: &str, pairs: &[(String, String)]) -> String {
let ok = |s: &str| {
!s.is_empty()
&& s.len() <= 253
&& s.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'.')
};
let ip_ok = |s: &str| s.parse::<std::net::Ipv4Addr>().is_ok();
let mut out = String::from("127.0.0.1\tlocalhost\n::1\tlocalhost ip6-localhost ip6-loopback\n");
let mut seen: Vec<(&str, &str)> = Vec::new();
if ok(hostname) && ip_ok(ip) {
seen.push((ip, hostname));
}
for (a, n) in pairs {
if ok(n) && ip_ok(a) && n != hostname && !seen.contains(&(a.as_str(), n.as_str())) {
seen.push((a, n));
}
}
for (a, n) in seen {
out.push_str(&format!("{a}\t{n}\n"));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::path::PathBuf;
fn tmpdir(tag: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("krab-oci-seccomp-{tag}-{}", std::process::id()));
let _ = fs::remove_dir_all(&d);
fs::create_dir_all(&d).unwrap();
d
}
fn img() -> ImageConfig {
serde_json::from_value(json!({
"Entrypoint": ["/docker-entrypoint.sh"],
"Cmd": ["nginx", "-g", "daemon off;"],
"Env": ["PATH=/usr/bin:/bin", "NGINX_VERSION=1.27"],
"WorkingDir": "/srv",
"User": "nginx"
}))
.unwrap()
}
#[test]
fn merge_like_docker() {
let spec = ContainerSpec {
env: vec!["NGINX_VERSION=2".into(), "A=b=c".into()],
hostname: Some("web".into()),
..Default::default()
};
let p = merge(&spec, &img()).unwrap();
assert_eq!(
p.args,
vec!["/docker-entrypoint.sh", "nginx", "-g", "daemon off;"]
);
assert_eq!(
p.env,
vec![
"PATH=/usr/bin:/bin",
"NGINX_VERSION=2",
"A=b=c",
"HOSTNAME=web"
]
);
assert_eq!(p.cwd, "/srv");
assert_eq!(p.user, "nginx");
let spec = ContainerSpec {
args: vec!["-v".into()],
..Default::default()
};
assert_eq!(
merge(&spec, &img()).unwrap().args,
vec!["/docker-entrypoint.sh", "-v"]
);
let spec = ContainerSpec {
command: vec!["sh".into()],
working_dir: Some("/w".into()),
user: Some("1000".into()),
tty: true,
..Default::default()
};
let p = merge(&spec, &img()).unwrap();
assert_eq!(p.args, vec!["sh"]);
assert_eq!(p.cwd, "/w");
assert_eq!(p.user, "1000");
assert!(p.env.contains(&"TERM=xterm".to_string()));
let p = merge(
&ContainerSpec::default(),
&ImageConfig {
cmd: Some(vec!["sh".into()]),
..Default::default()
},
)
.unwrap();
assert_eq!(p.env[0], DEFAULT_PATH);
assert_eq!(p.cwd, "/");
assert!(merge(&ContainerSpec::default(), &ImageConfig::default()).is_err());
}
#[test]
fn users_resolve() {
let pw =
"root:x:0:0:root:/root:/bin/sh\nnginx:x:101:101:nginx:/var/cache/nginx:/sbin/nologin\n";
let gr = "root:x:0:\nnginx:x:101:nginx\nwww:x:33:nginx,other\n";
assert_eq!(resolve_user("", pw, gr).unwrap(), User::default());
assert_eq!(
resolve_user("nginx", pw, gr).unwrap(),
User {
uid: 101,
gid: 101,
extra: vec![33]
}
);
assert_eq!(resolve_user("1000", pw, gr).unwrap().gid, 0);
assert_eq!(resolve_user("101:www", pw, gr).unwrap().gid, 33);
assert_eq!(resolve_user("nginx:5", pw, gr).unwrap().gid, 5);
assert!(resolve_user("nobody", pw, gr).is_err());
assert!(resolve_user("nginx:nogroup", pw, gr).is_err());
}
#[test]
fn home_from_passwd() {
let pw =
"root:x:0:0:root:/root:/bin/sh\nnginx:x:101:101:nginx:/var/cache/nginx:/sbin/nologin\n";
let mut env = vec![DEFAULT_PATH.to_string()];
set_home(&mut env, 101, pw);
assert_eq!(env[1], "HOME=/var/cache/nginx");
let mut env = Vec::new();
set_home(&mut env, 0, pw);
assert_eq!(env, vec!["HOME=/root"]);
let mut env = Vec::new();
set_home(&mut env, 1000, pw);
assert_eq!(env, vec!["HOME=/"]);
let mut env = vec!["HOME=/custom".to_string()];
set_home(&mut env, 0, pw);
assert_eq!(env, vec!["HOME=/custom"]);
}
#[test]
fn config_json_is_hardened() {
let spec = ContainerSpec {
name: "krab_default_p_c".into(),
hostname: Some("p".into()),
memory_bytes: Some(64 << 20),
nano_cpus: Some(250_000_000),
mounts: vec![
Mount::Bind {
src: "/data/x".into(),
dst: "/x".into(),
read_only: true,
},
Mount::Volume {
name: "krab_u_v".into(),
dst: "/v".into(),
read_only: false,
},
Mount::Tmpfs { dst: "/t".into() },
],
..Default::default()
};
let p = Process {
args: vec!["sh".into()],
env: vec![DEFAULT_PATH.into()],
cwd: "/".into(),
user: String::new(),
};
let root = PathBuf::from("/r");
let b = Bundle {
cgroups_path: "/krab/default_p/c",
hosts: &root.join("hosts"),
resolv: &root.join("resolv.conf"),
hostname_file: &root.join("hostname"),
volume_root: &root.join("volumes"),
netns: None,
seccomp: None,
};
let c = config_json(&spec, &p, &User::default(), &b).unwrap();
assert_eq!(c["process"]["noNewPrivileges"], true);
let caps = c["process"]["capabilities"]["bounding"].as_array().unwrap();
assert!(
!caps
.iter()
.any(|x| x == "CAP_NET_RAW" || x == "CAP_SYS_ADMIN")
);
assert_eq!(caps.len(), 13);
assert_eq!(c["linux"]["cgroupsPath"], "/krab/default_p/c");
assert_eq!(c["linux"]["resources"]["memory"]["limit"], 64 << 20);
assert_eq!(c["linux"]["resources"]["memory"]["swap"], 64 << 20);
assert_eq!(c["linux"]["resources"]["cpu"]["quota"], 25_000);
assert!(
!c["linux"]["namespaces"]
.as_array()
.unwrap()
.iter()
.any(|n| n["type"] == "network" || n["type"] == "user")
);
assert!(
c["linux"]["maskedPaths"]
.as_array()
.unwrap()
.iter()
.any(|m| m == "/proc/kcore")
);
let mounts = c["mounts"].as_array().unwrap();
let find = |d: &str| {
mounts
.iter()
.find(|m| m["destination"] == d)
.unwrap()
.clone()
};
assert_eq!(find("/x")["source"], "/data/x");
assert!(
find("/x")["options"]
.as_array()
.unwrap()
.iter()
.any(|o| o == "ro")
);
assert_eq!(find("/v")["source"], "/r/volumes/krab_u_v");
assert_eq!(find("/t")["type"], "tmpfs");
assert_eq!(find("/etc/hosts")["source"], "/r/hosts");
let ns = PathBuf::from("/run/netns/krab-0123456789");
let with_net = Bundle {
netns: Some(&ns),
..b
};
let c2 = config_json(&spec, &p, &User::default(), &with_net).unwrap();
let nss = c2["linux"]["namespaces"].as_array().unwrap();
assert!(
nss.iter()
.any(|n| n["type"] == "network" && n["path"] == "/run/netns/krab-0123456789")
);
assert!(!nss.iter().any(|n| n["type"] == "user"));
assert_eq!(c["root"]["path"], "rootfs");
let mut bad = spec.clone();
bad.mounts = vec![Mount::Tmpfs {
dst: "/a/../etc".into(),
}];
assert!(config_json(&bad, &p, &User::default(), &b).is_err());
bad.mounts = vec![Mount::Tmpfs { dst: "/".into() }];
assert!(config_json(&bad, &p, &User::default(), &b).is_err());
bad.mounts = vec![Mount::Volume {
name: "../x".into(),
dst: "/v".into(),
read_only: false,
}];
assert!(config_json(&bad, &p, &User::default(), &b).is_err());
}
#[test]
fn dns_files() {
let r = resolv_conf(
"# c\nnameserver 127.0.0.53\noptions edns0\nsearch lan\n",
&["default.svc.cluster.local".into(), "bad name".into()],
&["ndots:5".into()],
);
assert_eq!(
r,
"nameserver 127.0.0.53\nsearch default.svc.cluster.local\noptions ndots:5\n"
);
let h = hosts_file(
"web",
&[
"db".into(),
"db.default.svc.cluster.local".into(),
"x y".into(),
"web".into(),
],
);
assert!(h.contains("127.0.0.1\tweb\n"));
assert!(h.contains("127.0.0.1\tdb.default.svc.cluster.local\n"));
assert!(!h.contains("x y"));
assert_eq!(h.matches("\tweb\n").count(), 1);
let p = pod_hosts(
"web-1",
"10.88.0.2",
&[
("10.88.0.2".into(), "web".into()),
("10.88.0.3".into(), "web".into()),
("10.88.0.3".into(), "web".into()),
("10.88.0.4".into(), "web-1".into()),
("bad".into(), "db".into()),
("10.88.0.5".into(), "x y".into()),
],
);
assert_eq!(
p,
"127.0.0.1\tlocalhost\n::1\tlocalhost ip6-localhost ip6-loopback\n10.88.0.2\tweb-1\n10.88.0.2\tweb\n10.88.0.3\tweb\n"
);
}
#[test]
fn seccomp_profile_lands_in_linux() {
let d = tmpdir("assign");
let body = json!({
"defaultAction": "SCMP_ACT_ERRNO",
"architectures": ["SCMP_ARCH_X86_64"],
"syscalls": [{"names": ["read", "write"], "action": "SCMP_ACT_ALLOW"}]
});
let file = d.join("profile.json");
fs::write(&file, body.to_string()).unwrap();
let p = Profile::load(&file).unwrap();
let root = PathBuf::from("/r");
let spec = ContainerSpec {
name: "krab_default_p_c".into(),
..Default::default()
};
let proc = Process {
args: vec!["sh".into()],
env: vec![DEFAULT_PATH.into()],
cwd: "/".into(),
user: String::new(),
};
let b = Bundle {
cgroups_path: "/krab/default_p/c",
hosts: &root.join("hosts"),
resolv: &root.join("resolv.conf"),
hostname_file: &root.join("hostname"),
volume_root: &root.join("volumes"),
netns: None,
seccomp: Some(p.value()),
};
let c = config_json(&spec, &proc, &User::default(), &b).unwrap();
assert_eq!(c["linux"]["seccomp"], body);
assert_eq!(c["linux"]["cgroupsPath"], "/krab/default_p/c");
let plain = Bundle { seccomp: None, ..b };
let c = config_json(&spec, &proc, &User::default(), &plain).unwrap();
assert!(c["linux"].get("seccomp").is_none());
fs::remove_dir_all(&d).unwrap();
}
#[test]
fn seccomp_profile_loads_restrictive_defaults() {
let d = tmpdir("ok");
for a in RESTRICTIVE_ACTIONS {
let f = d.join(format!("ok-{a}.json"));
fs::write(
&f,
format!(
r#"{{"defaultAction":"{a}","syscalls":[{{"names":["read"],"action":"SCMP_ACT_ALLOW"}}]}}"#
),
)
.unwrap();
assert!(Profile::load(&f).is_ok(), "{a}");
}
fs::remove_dir_all(&d).unwrap();
}
#[test]
fn seccomp_profile_rejects_bad_input() {
let d = tmpdir("bad");
let load = |name: &str, body: &str| {
let f = d.join(name);
fs::write(&f, body).unwrap();
Profile::load(&f).unwrap_err()
};
let cases = [
("arr.json", "[]"),
("str.json", "\"x\""),
("num.json", "123"),
("nul.json", "null"),
("empty.json", "{}"),
(
"missing-syscall-action.json",
r#"{"defaultAction":"SCMP_ACT_ERRNO","syscalls":[{"names":["read"]}]}"#,
),
(
"non-oci-conditions.json",
r#"{"defaultAction":"SCMP_ACT_ERRNO","syscalls":[{"names":["read"],"action":"SCMP_ACT_ALLOW","includes":{}}]}"#,
),
("broken.json", r#"{"defaultAction":"#),
("allow.json", r#"{"defaultAction":"SCMP_ACT_ALLOW"}"#),
("log.json", r#"{"defaultAction":"SCMP_ACT_LOG"}"#),
("kill.json", r#"{"defaultAction":"SCMP_ACT_KILL"}"#),
("dflnotify.json", r#"{"defaultAction":"SCMP_ACT_NOTIFY"}"#),
("dnum.json", r#"{"defaultAction":1}"#),
(
"notify.json",
r#"{"defaultAction":"SCMP_ACT_ERRNO","notify":{"timeout":1000}}"#,
),
(
"notifyopts.json",
r#"{"defaultAction":"SCMP_ACT_ERRNO","notifyOpts":{}}"#,
),
(
"notifysys.json",
r#"{"defaultAction":"SCMP_ACT_ERRNO","syscalls":[{"names":["read"],"action":"SCMP_ACT_NOTIFY"}]}"#,
),
(
"listener.json",
r#"{"defaultAction":"SCMP_ACT_ERRNO","flags":["SECCOMP_FILTER_FLAG_NEW_LISTENER"]}"#,
),
];
for (name, body) in cases {
let e = load(name, body);
assert_eq!(e.kind(), io::ErrorKind::InvalidInput, "{name}: {e}");
assert!(
e.to_string().contains("seccomp profile") && e.to_string().contains(name),
"{name}: {e}"
);
}
let big = format!(
r#"{{"defaultAction":"SCMP_ACT_ERRNO","pad":"{}"}}"#,
"x".repeat(MAX_PROFILE as usize)
);
let e = load("big.json", &big);
assert_eq!(e.kind(), io::ErrorKind::InvalidInput);
assert!(e.to_string().contains("larger than"), "{e}");
let e = Profile::load(&d.join("missing.json")).unwrap_err();
assert_eq!(e.kind(), io::ErrorKind::NotFound);
assert!(e.to_string().contains("seccomp profile"), "{e}");
fs::remove_dir_all(&d).unwrap();
}
}