Skip to main content

krab_runtime/native/
oci.rs

1use crate::{ContainerSpec, Mount};
2use serde::{Deserialize, Serialize};
3use serde_json::{Value, json};
4use std::io::{self, Read};
5use std::path::{Component, Path};
6
7const DEFAULT_PATH: &str = "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
8
9const CAPS: [&str; 13] = [
10    "CAP_CHOWN",
11    "CAP_DAC_OVERRIDE",
12    "CAP_FSETID",
13    "CAP_FOWNER",
14    "CAP_MKNOD",
15    "CAP_SETGID",
16    "CAP_SETUID",
17    "CAP_SETFCAP",
18    "CAP_SETPCAP",
19    "CAP_NET_BIND_SERVICE",
20    "CAP_SYS_CHROOT",
21    "CAP_KILL",
22    "CAP_AUDIT_WRITE",
23];
24
25const MASKED: [&str; 11] = [
26    "/proc/asound",
27    "/proc/acpi",
28    "/proc/kcore",
29    "/proc/keys",
30    "/proc/latency_stats",
31    "/proc/timer_list",
32    "/proc/timer_stats",
33    "/proc/sched_debug",
34    "/proc/scsi",
35    "/sys/firmware",
36    "/sys/devices/virtual/powercap",
37];
38
39const READONLY: [&str; 5] = [
40    "/proc/bus",
41    "/proc/fs",
42    "/proc/irq",
43    "/proc/sys",
44    "/proc/sysrq-trigger",
45];
46
47#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
48#[serde(rename_all = "PascalCase")]
49pub struct ImageConfig {
50    #[serde(default)]
51    pub entrypoint: Option<Vec<String>>,
52    #[serde(default)]
53    pub cmd: Option<Vec<String>>,
54    #[serde(default)]
55    pub env: Option<Vec<String>>,
56    #[serde(default)]
57    pub working_dir: Option<String>,
58    #[serde(default)]
59    pub user: Option<String>,
60}
61
62#[derive(Clone, Debug, PartialEq)]
63pub struct Process {
64    pub args: Vec<String>,
65    pub env: Vec<String>,
66    pub cwd: String,
67    pub user: String,
68}
69
70fn invalid(msg: impl Into<String>) -> io::Error {
71    io::Error::new(io::ErrorKind::InvalidInput, msg.into())
72}
73
74pub fn merge(spec: &ContainerSpec, img: &ImageConfig) -> io::Result<Process> {
75    let (entry, cmd) = if spec.command.is_empty() {
76        let cmd = if spec.args.is_empty() {
77            img.cmd.clone().unwrap_or_default()
78        } else {
79            spec.args.clone()
80        };
81        (img.entrypoint.clone().unwrap_or_default(), cmd)
82    } else {
83        (spec.command.clone(), spec.args.clone())
84    };
85    let args: Vec<String> = entry.into_iter().chain(cmd).collect();
86    if args.is_empty() || args[0].is_empty() {
87        return Err(invalid("no command specified"));
88    }
89    let mut env: Vec<String> = Vec::new();
90    for e in img.env.iter().flatten().chain(spec.env.iter()) {
91        let key = e.split_once('=').map_or(e.as_str(), |(k, _)| k);
92        env.retain(|x| x.split_once('=').map_or(x.as_str(), |(k, _)| k) != key);
93        env.push(e.clone());
94    }
95    if !env.iter().any(|e| e.starts_with("PATH=")) {
96        env.insert(0, DEFAULT_PATH.into());
97    }
98    if let Some(h) = &spec.hostname
99        && !env.iter().any(|e| e.starts_with("HOSTNAME="))
100    {
101        env.push(format!("HOSTNAME={h}"));
102    }
103    if spec.tty && !env.iter().any(|e| e.starts_with("TERM=")) {
104        env.push("TERM=xterm".into());
105    }
106    let cwd = spec
107        .working_dir
108        .clone()
109        .filter(|w| !w.is_empty())
110        .or_else(|| img.working_dir.clone().filter(|w| !w.is_empty()))
111        .unwrap_or_else(|| "/".into());
112    if !cwd.starts_with('/') {
113        return Err(invalid(format!("working dir {cwd:?} must be absolute")));
114    }
115    let user = spec
116        .user
117        .clone()
118        .or_else(|| img.user.clone())
119        .unwrap_or_default();
120    Ok(Process {
121        args,
122        env,
123        cwd,
124        user,
125    })
126}
127
128#[derive(Clone, Debug, Default, PartialEq)]
129pub struct User {
130    pub uid: u32,
131    pub gid: u32,
132    pub extra: Vec<u32>,
133}
134
135pub fn resolve_user(user: &str, passwd: &str, group: &str) -> io::Result<User> {
136    if user.is_empty() {
137        return Ok(User::default());
138    }
139    let (u, g) = match user.split_once(':') {
140        Some((u, g)) => (u, Some(g)),
141        None => (user, None),
142    };
143    let pw = passwd.lines().find_map(|l| {
144        let f: Vec<&str> = l.split(':').collect();
145        if f.len() < 4 {
146            return None;
147        }
148        let hit = match u.parse::<u32>() {
149            Ok(n) => f[2].parse::<u32>().ok() == Some(n),
150            Err(_) => f[0] == u,
151        };
152        hit.then(|| {
153            (
154                f[0].to_string(),
155                f[2].parse::<u32>().ok(),
156                f[3].parse::<u32>().ok(),
157            )
158        })
159    });
160    let (name, uid, pgid) = match (u.parse::<u32>(), pw) {
161        (Ok(n), Some((name, _, gid))) => (name, n, gid.unwrap_or(0)),
162        (Ok(n), None) => (String::new(), n, 0),
163        (Err(_), Some((name, Some(uid), gid))) => (name, uid, gid.unwrap_or(0)),
164        _ => return Err(invalid(format!("unable to find user {u}"))),
165    };
166    let gid = match g {
167        None => pgid,
168        Some(g) => match g.parse::<u32>() {
169            Ok(n) => n,
170            Err(_) => group
171                .lines()
172                .find_map(|l| {
173                    let f: Vec<&str> = l.split(':').collect();
174                    (f.len() >= 3 && f[0] == g).then(|| f[2].parse::<u32>().ok())?
175                })
176                .ok_or_else(|| invalid(format!("unable to find group {g}")))?,
177        },
178    };
179    let mut extra = Vec::new();
180    if !name.is_empty() {
181        for l in group.lines() {
182            let f: Vec<&str> = l.split(':').collect();
183            if f.len() >= 4
184                && f[3].split(',').any(|m| m == name)
185                && let Ok(n) = f[2].parse::<u32>()
186                && n != gid
187                && !extra.contains(&n)
188            {
189                extra.push(n);
190            }
191        }
192    }
193    Ok(User { uid, gid, extra })
194}
195
196pub fn set_home(env: &mut Vec<String>, uid: u32, passwd: &str) {
197    if env.iter().any(|e| e.starts_with("HOME=")) {
198        return;
199    }
200    let home = passwd
201        .lines()
202        .find_map(|l| {
203            let f: Vec<&str> = l.split(':').collect();
204            (f.len() >= 6 && f[2].parse::<u32>().ok() == Some(uid) && !f[5].is_empty())
205                .then(|| f[5].to_string())
206        })
207        .unwrap_or_else(|| "/".into());
208    env.push(format!("HOME={home}"));
209}
210
211pub fn dest_ok(dst: &str) -> bool {
212    let p = Path::new(dst);
213    p.is_absolute()
214        && dst.len() <= 4096
215        && !dst.contains('\0')
216        && p.components()
217            .all(|c| matches!(c, Component::RootDir | Component::Normal(_)))
218        && p.components().count() > 1
219}
220
221pub struct Bundle<'a> {
222    pub cgroups_path: &'a str,
223    pub hosts: &'a Path,
224    pub resolv: &'a Path,
225    pub hostname_file: &'a Path,
226    pub volume_root: &'a Path,
227    pub netns: Option<&'a Path>,
228    pub seccomp: Option<&'a Value>,
229}
230
231const MAX_PROFILE: u64 = 1 << 20;
232const RESTRICTIVE_ACTIONS: [&str; 3] = [
233    "SCMP_ACT_ERRNO",
234    "SCMP_ACT_KILL_PROCESS",
235    "SCMP_ACT_KILL_THREAD",
236];
237
238#[derive(Clone, Debug)]
239pub struct Profile {
240    value: Value,
241}
242
243fn has_notify(value: &Value) -> bool {
244    match value {
245        Value::Object(map) => map
246            .iter()
247            .any(|(k, v)| matches!(k.as_str(), "notify" | "notifyOpts") || has_notify(v)),
248        Value::Array(items) => items.iter().any(has_notify),
249        Value::String(s) => matches!(
250            s.as_str(),
251            "SCMP_ACT_NOTIFY" | "SECCOMP_FILTER_FLAG_NEW_LISTENER"
252        ),
253        _ => false,
254    }
255}
256
257fn validate(ctx: &str, value: &Value) -> io::Result<()> {
258    let object = value
259        .as_object()
260        .ok_or_else(|| invalid(format!("{ctx}: must be a JSON object")))?;
261    if object.keys().any(|k| {
262        !matches!(
263            k.as_str(),
264            "defaultAction" | "defaultErrnoRet" | "architectures" | "flags" | "syscalls"
265        )
266    }) {
267        return Err(invalid(format!("{ctx}: unsupported OCI seccomp field")));
268    }
269    if let Some(syscalls) = object.get("syscalls") {
270        let syscalls = syscalls
271            .as_array()
272            .ok_or_else(|| invalid(format!("{ctx}: syscalls must be an array")))?;
273        for syscall in syscalls {
274            if !syscall.as_object().is_some_and(|s| {
275                s.keys()
276                    .all(|k| matches!(k.as_str(), "names" | "action" | "errnoRet" | "args"))
277                    && s.get("action").and_then(Value::as_str).is_some()
278                    && s.get("names")
279                        .and_then(Value::as_array)
280                        .is_some_and(|names| {
281                            !names.is_empty()
282                                && names
283                                    .iter()
284                                    .all(|n| n.as_str().is_some_and(|n| !n.is_empty()))
285                        })
286            }) {
287                return Err(invalid(format!("{ctx}: invalid OCI seccomp syscall rule")));
288            }
289        }
290    }
291    let action = value.get("defaultAction").and_then(Value::as_str);
292    if !RESTRICTIVE_ACTIONS.contains(&action.unwrap_or("")) {
293        return Err(invalid(format!(
294            "{ctx}: defaultAction {action:?} must be SCMP_ACT_ERRNO, SCMP_ACT_KILL_PROCESS or SCMP_ACT_KILL_THREAD"
295        )));
296    }
297    if has_notify(value) {
298        return Err(invalid(format!(
299            "{ctx}: user notification is not supported"
300        )));
301    }
302    Ok(())
303}
304
305impl Profile {
306    pub fn load(path: &Path) -> io::Result<Self> {
307        let ctx = format!("seccomp profile {}", path.display());
308        let f = std::fs::File::open(path)
309            .map_err(|e| io::Error::new(e.kind(), format!("{ctx}: {e}")))?;
310        let mut buf = Vec::new();
311        f.take(MAX_PROFILE + 1)
312            .read_to_end(&mut buf)
313            .map_err(|e| io::Error::new(e.kind(), format!("{ctx}: {e}")))?;
314        if buf.len() as u64 > MAX_PROFILE {
315            return Err(invalid(format!("{ctx}: larger than {MAX_PROFILE} bytes")));
316        }
317        let value: Value =
318            serde_json::from_slice(&buf).map_err(|e| invalid(format!("{ctx}: {e}")))?;
319        validate(&ctx, &value)?;
320        Ok(Self { value })
321    }
322
323    pub fn value(&self) -> &Value {
324        &self.value
325    }
326}
327
328fn mnt(dst: &str, ty: &str, src: &str, opts: &[&str]) -> Value {
329    json!({"destination": dst, "type": ty, "source": src, "options": opts})
330}
331
332fn bind(dst: &str, src: &str, ro: bool) -> Value {
333    mnt(
334        dst,
335        "bind",
336        src,
337        &[
338            "rbind",
339            "rprivate",
340            "nosuid",
341            "nodev",
342            if ro { "ro" } else { "rw" },
343        ],
344    )
345}
346
347pub fn spec_mounts(spec: &ContainerSpec, b: &Bundle) -> io::Result<Vec<Value>> {
348    let mut out = vec![
349        mnt("/proc", "proc", "proc", &["nosuid", "noexec", "nodev"]),
350        mnt(
351            "/dev",
352            "tmpfs",
353            "tmpfs",
354            &["nosuid", "strictatime", "mode=755", "size=65536k"],
355        ),
356        mnt(
357            "/dev/pts",
358            "devpts",
359            "devpts",
360            &[
361                "nosuid",
362                "noexec",
363                "newinstance",
364                "ptmxmode=0666",
365                "mode=0620",
366                "gid=5",
367            ],
368        ),
369        mnt(
370            "/dev/shm",
371            "tmpfs",
372            "shm",
373            &["nosuid", "noexec", "nodev", "mode=1777", "size=65536k"],
374        ),
375        mnt(
376            "/dev/mqueue",
377            "mqueue",
378            "mqueue",
379            &["nosuid", "noexec", "nodev"],
380        ),
381        mnt(
382            "/sys",
383            "sysfs",
384            "sysfs",
385            &["nosuid", "noexec", "nodev", "ro"],
386        ),
387        mnt(
388            "/sys/fs/cgroup",
389            "cgroup",
390            "cgroup",
391            &["nosuid", "noexec", "nodev", "relatime", "ro"],
392        ),
393    ];
394    let mut user_dsts = Vec::new();
395    for m in &spec.mounts {
396        let (dst, v) = match m {
397            Mount::Bind {
398                src,
399                dst,
400                read_only,
401            } => {
402                if !Path::new(src).is_absolute() || src.contains('\0') {
403                    return Err(invalid(format!("bind source {src:?} must be absolute")));
404                }
405                (dst, bind(dst, src, *read_only))
406            }
407            Mount::Volume {
408                name,
409                dst,
410                read_only,
411            } => {
412                if !crate::policy::data_key_ok(name) || name.starts_with('.') {
413                    return Err(invalid(format!("bad volume name {name:?}")));
414                }
415                let src = b.volume_root.join(name);
416                (dst, bind(dst, &src.to_string_lossy(), *read_only))
417            }
418            Mount::Tmpfs { dst } => (
419                dst,
420                mnt(dst, "tmpfs", "tmpfs", &["nosuid", "nodev", "mode=1777"]),
421            ),
422        };
423        if !dest_ok(dst) {
424            return Err(invalid(format!("bad mount destination {dst:?}")));
425        }
426        user_dsts.push(dst.clone());
427        out.push(v);
428    }
429    for (dst, src) in [
430        ("/etc/hosts", b.hosts),
431        ("/etc/resolv.conf", b.resolv),
432        ("/etc/hostname", b.hostname_file),
433    ] {
434        if !user_dsts.iter().any(|d| d == dst) {
435            out.push(bind(dst, &src.to_string_lossy(), false));
436        }
437    }
438    Ok(out)
439}
440
441fn dev(path: &str, major: i64, minor: i64) -> Value {
442    json!({"path": path, "type": "c", "major": major, "minor": minor, "fileMode": 0o666, "uid": 0, "gid": 0})
443}
444
445fn allow(major: Option<i64>, minor: Option<i64>, access: &str) -> Value {
446    json!({"allow": true, "type": "c", "major": major, "minor": minor, "access": access})
447}
448
449pub fn config_json(
450    spec: &ContainerSpec,
451    p: &Process,
452    user: &User,
453    b: &Bundle,
454) -> io::Result<Value> {
455    let caps = &CAPS[..];
456    let mut resources = json!({
457        "pids": {"limit": 4096},
458        "devices": [
459            {"allow": false, "access": "rwm"},
460            {"allow": true, "type": "c", "access": "m"},
461            {"allow": true, "type": "b", "access": "m"},
462            allow(Some(1), Some(3), "rwm"),
463            allow(Some(1), Some(5), "rwm"),
464            allow(Some(1), Some(7), "rwm"),
465            allow(Some(1), Some(8), "rwm"),
466            allow(Some(1), Some(9), "rwm"),
467            allow(Some(5), Some(0), "rwm"),
468            allow(Some(5), Some(1), "rwm"),
469            allow(Some(5), Some(2), "rwm"),
470            allow(Some(136), None, "rwm"),
471        ],
472    });
473    if let Some(m) = spec.memory_bytes.filter(|m| *m > 0) {
474        resources["memory"] = json!({"limit": m, "swap": m});
475    }
476    if let Some(n) = spec.nano_cpus.filter(|n| *n > 0) {
477        let period: i64 = 100_000;
478        resources["cpu"] = json!({"quota": (n.saturating_mul(period) / 1_000_000_000).max(1000), "period": period});
479    }
480    let mut namespaces = vec![
481        json!({"type": "pid"}),
482        json!({"type": "ipc"}),
483        json!({"type": "uts"}),
484        json!({"type": "mount"}),
485        json!({"type": "cgroup"}),
486    ];
487    if let Some(p) = b.netns {
488        namespaces.push(json!({"type": "network", "path": p}));
489    }
490    let mut linux = json!({
491        "cgroupsPath": b.cgroups_path,
492        "resources": resources,
493        "namespaces": namespaces,
494        "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)],
495        "maskedPaths": MASKED,
496        "readonlyPaths": READONLY,
497    });
498    if let Some(p) = b.seccomp {
499        linux["seccomp"] = p.clone();
500    }
501    Ok(json!({
502        "ociVersion": "1.0.2",
503        "process": {
504            "terminal": spec.tty,
505            "user": {"uid": user.uid, "gid": user.gid, "additionalGids": user.extra},
506            "args": p.args,
507            "env": p.env,
508            "cwd": p.cwd,
509            "capabilities": {"bounding": caps, "effective": caps, "permitted": caps},
510            "rlimits": [{"type": "RLIMIT_NOFILE", "hard": 1048576u64, "soft": 1048576u64}],
511            "noNewPrivileges": !spec.allow_privilege_escalation,
512        },
513        "root": {"path": "rootfs", "readonly": spec.read_only_root},
514        "hostname": spec.hostname.clone().unwrap_or_default(),
515        "mounts": spec_mounts(spec, b)?,
516        "linux": linux,
517    }))
518}
519
520pub fn resolv_conf(host: &str, search: &[String], options: &[String]) -> String {
521    let mut out = String::new();
522    for l in host.lines() {
523        let l = l.trim();
524        if l.starts_with("nameserver ") {
525            out.push_str(l);
526            out.push('\n');
527        }
528    }
529    if out.is_empty() {
530        out.push_str("nameserver 1.1.1.1\n");
531    }
532    let clean = |v: &[String]| -> Vec<String> {
533        v.iter()
534            .filter(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_graphic()))
535            .cloned()
536            .collect()
537    };
538    let s = clean(search);
539    if !s.is_empty() {
540        out.push_str(&format!("search {}\n", s.join(" ")));
541    }
542    let o = clean(options);
543    if !o.is_empty() {
544        out.push_str(&format!("options {}\n", o.join(" ")));
545    }
546    out
547}
548
549pub fn hosts_file(hostname: &str, aliases: &[String]) -> String {
550    let pairs: Vec<(String, String)> = aliases
551        .iter()
552        .map(|a| ("127.0.0.1".to_string(), a.clone()))
553        .collect();
554    pod_hosts(hostname, "127.0.0.1", &pairs)
555}
556
557pub fn pod_hosts(hostname: &str, ip: &str, pairs: &[(String, String)]) -> String {
558    let ok = |s: &str| {
559        !s.is_empty()
560            && s.len() <= 253
561            && s.bytes()
562                .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'.')
563    };
564    let ip_ok = |s: &str| s.parse::<std::net::Ipv4Addr>().is_ok();
565    let mut out = String::from("127.0.0.1\tlocalhost\n::1\tlocalhost ip6-localhost ip6-loopback\n");
566    let mut seen: Vec<(&str, &str)> = Vec::new();
567    if ok(hostname) && ip_ok(ip) {
568        seen.push((ip, hostname));
569    }
570    for (a, n) in pairs {
571        if ok(n) && ip_ok(a) && n != hostname && !seen.contains(&(a.as_str(), n.as_str())) {
572            seen.push((a, n));
573        }
574    }
575    for (a, n) in seen {
576        out.push_str(&format!("{a}\t{n}\n"));
577    }
578    out
579}
580
581#[cfg(test)]
582mod tests {
583    use super::*;
584    use std::fs;
585    use std::path::PathBuf;
586
587    fn tmpdir(tag: &str) -> PathBuf {
588        let d = std::env::temp_dir().join(format!("krab-oci-seccomp-{tag}-{}", std::process::id()));
589        let _ = fs::remove_dir_all(&d);
590        fs::create_dir_all(&d).unwrap();
591        d
592    }
593
594    fn img() -> ImageConfig {
595        serde_json::from_value(json!({
596            "Entrypoint": ["/docker-entrypoint.sh"],
597            "Cmd": ["nginx", "-g", "daemon off;"],
598            "Env": ["PATH=/usr/bin:/bin", "NGINX_VERSION=1.27"],
599            "WorkingDir": "/srv",
600            "User": "nginx"
601        }))
602        .unwrap()
603    }
604
605    #[test]
606    fn merge_like_docker() {
607        let spec = ContainerSpec {
608            env: vec!["NGINX_VERSION=2".into(), "A=b=c".into()],
609            hostname: Some("web".into()),
610            ..Default::default()
611        };
612        let p = merge(&spec, &img()).unwrap();
613        assert_eq!(
614            p.args,
615            vec!["/docker-entrypoint.sh", "nginx", "-g", "daemon off;"]
616        );
617        assert_eq!(
618            p.env,
619            vec![
620                "PATH=/usr/bin:/bin",
621                "NGINX_VERSION=2",
622                "A=b=c",
623                "HOSTNAME=web"
624            ]
625        );
626        assert_eq!(p.cwd, "/srv");
627        assert_eq!(p.user, "nginx");
628        let spec = ContainerSpec {
629            args: vec!["-v".into()],
630            ..Default::default()
631        };
632        assert_eq!(
633            merge(&spec, &img()).unwrap().args,
634            vec!["/docker-entrypoint.sh", "-v"]
635        );
636        let spec = ContainerSpec {
637            command: vec!["sh".into()],
638            working_dir: Some("/w".into()),
639            user: Some("1000".into()),
640            tty: true,
641            ..Default::default()
642        };
643        let p = merge(&spec, &img()).unwrap();
644        assert_eq!(p.args, vec!["sh"]);
645        assert_eq!(p.cwd, "/w");
646        assert_eq!(p.user, "1000");
647        assert!(p.env.contains(&"TERM=xterm".to_string()));
648        let p = merge(
649            &ContainerSpec::default(),
650            &ImageConfig {
651                cmd: Some(vec!["sh".into()]),
652                ..Default::default()
653            },
654        )
655        .unwrap();
656        assert_eq!(p.env[0], DEFAULT_PATH);
657        assert_eq!(p.cwd, "/");
658        assert!(merge(&ContainerSpec::default(), &ImageConfig::default()).is_err());
659    }
660
661    #[test]
662    fn users_resolve() {
663        let pw =
664            "root:x:0:0:root:/root:/bin/sh\nnginx:x:101:101:nginx:/var/cache/nginx:/sbin/nologin\n";
665        let gr = "root:x:0:\nnginx:x:101:nginx\nwww:x:33:nginx,other\n";
666        assert_eq!(resolve_user("", pw, gr).unwrap(), User::default());
667        assert_eq!(
668            resolve_user("nginx", pw, gr).unwrap(),
669            User {
670                uid: 101,
671                gid: 101,
672                extra: vec![33]
673            }
674        );
675        assert_eq!(resolve_user("1000", pw, gr).unwrap().gid, 0);
676        assert_eq!(resolve_user("101:www", pw, gr).unwrap().gid, 33);
677        assert_eq!(resolve_user("nginx:5", pw, gr).unwrap().gid, 5);
678        assert!(resolve_user("nobody", pw, gr).is_err());
679        assert!(resolve_user("nginx:nogroup", pw, gr).is_err());
680    }
681
682    #[test]
683    fn home_from_passwd() {
684        let pw =
685            "root:x:0:0:root:/root:/bin/sh\nnginx:x:101:101:nginx:/var/cache/nginx:/sbin/nologin\n";
686        let mut env = vec![DEFAULT_PATH.to_string()];
687        set_home(&mut env, 101, pw);
688        assert_eq!(env[1], "HOME=/var/cache/nginx");
689        let mut env = Vec::new();
690        set_home(&mut env, 0, pw);
691        assert_eq!(env, vec!["HOME=/root"]);
692        let mut env = Vec::new();
693        set_home(&mut env, 1000, pw);
694        assert_eq!(env, vec!["HOME=/"]);
695        let mut env = vec!["HOME=/custom".to_string()];
696        set_home(&mut env, 0, pw);
697        assert_eq!(env, vec!["HOME=/custom"]);
698    }
699
700    #[test]
701    fn config_json_is_hardened() {
702        let spec = ContainerSpec {
703            name: "krab_default_p_c".into(),
704            hostname: Some("p".into()),
705            memory_bytes: Some(64 << 20),
706            nano_cpus: Some(250_000_000),
707            mounts: vec![
708                Mount::Bind {
709                    src: "/data/x".into(),
710                    dst: "/x".into(),
711                    read_only: true,
712                },
713                Mount::Volume {
714                    name: "krab_u_v".into(),
715                    dst: "/v".into(),
716                    read_only: false,
717                },
718                Mount::Tmpfs { dst: "/t".into() },
719            ],
720            ..Default::default()
721        };
722        let p = Process {
723            args: vec!["sh".into()],
724            env: vec![DEFAULT_PATH.into()],
725            cwd: "/".into(),
726            user: String::new(),
727        };
728        let root = PathBuf::from("/r");
729        let b = Bundle {
730            cgroups_path: "/krab/default_p/c",
731            hosts: &root.join("hosts"),
732            resolv: &root.join("resolv.conf"),
733            hostname_file: &root.join("hostname"),
734            volume_root: &root.join("volumes"),
735            netns: None,
736            seccomp: None,
737        };
738        let c = config_json(&spec, &p, &User::default(), &b).unwrap();
739        assert_eq!(c["process"]["noNewPrivileges"], true);
740        let caps = c["process"]["capabilities"]["bounding"].as_array().unwrap();
741        assert!(
742            !caps
743                .iter()
744                .any(|x| x == "CAP_NET_RAW" || x == "CAP_SYS_ADMIN")
745        );
746        assert_eq!(caps.len(), 13);
747        assert_eq!(c["linux"]["cgroupsPath"], "/krab/default_p/c");
748        assert_eq!(c["linux"]["resources"]["memory"]["limit"], 64 << 20);
749        assert_eq!(c["linux"]["resources"]["memory"]["swap"], 64 << 20);
750        assert_eq!(c["linux"]["resources"]["cpu"]["quota"], 25_000);
751        assert!(
752            !c["linux"]["namespaces"]
753                .as_array()
754                .unwrap()
755                .iter()
756                .any(|n| n["type"] == "network" || n["type"] == "user")
757        );
758        assert!(
759            c["linux"]["maskedPaths"]
760                .as_array()
761                .unwrap()
762                .iter()
763                .any(|m| m == "/proc/kcore")
764        );
765        let mounts = c["mounts"].as_array().unwrap();
766        let find = |d: &str| {
767            mounts
768                .iter()
769                .find(|m| m["destination"] == d)
770                .unwrap()
771                .clone()
772        };
773        assert_eq!(find("/x")["source"], "/data/x");
774        assert!(
775            find("/x")["options"]
776                .as_array()
777                .unwrap()
778                .iter()
779                .any(|o| o == "ro")
780        );
781        assert_eq!(find("/v")["source"], "/r/volumes/krab_u_v");
782        assert_eq!(find("/t")["type"], "tmpfs");
783        assert_eq!(find("/etc/hosts")["source"], "/r/hosts");
784        let ns = PathBuf::from("/run/netns/krab-0123456789");
785        let with_net = Bundle {
786            netns: Some(&ns),
787            ..b
788        };
789        let c2 = config_json(&spec, &p, &User::default(), &with_net).unwrap();
790        let nss = c2["linux"]["namespaces"].as_array().unwrap();
791        assert!(
792            nss.iter()
793                .any(|n| n["type"] == "network" && n["path"] == "/run/netns/krab-0123456789")
794        );
795        assert!(!nss.iter().any(|n| n["type"] == "user"));
796        assert_eq!(c["root"]["path"], "rootfs");
797        let mut bad = spec.clone();
798        bad.mounts = vec![Mount::Tmpfs {
799            dst: "/a/../etc".into(),
800        }];
801        assert!(config_json(&bad, &p, &User::default(), &b).is_err());
802        bad.mounts = vec![Mount::Tmpfs { dst: "/".into() }];
803        assert!(config_json(&bad, &p, &User::default(), &b).is_err());
804        bad.mounts = vec![Mount::Volume {
805            name: "../x".into(),
806            dst: "/v".into(),
807            read_only: false,
808        }];
809        assert!(config_json(&bad, &p, &User::default(), &b).is_err());
810    }
811
812    #[test]
813    fn dns_files() {
814        let r = resolv_conf(
815            "# c\nnameserver 127.0.0.53\noptions edns0\nsearch lan\n",
816            &["default.svc.cluster.local".into(), "bad name".into()],
817            &["ndots:5".into()],
818        );
819        assert_eq!(
820            r,
821            "nameserver 127.0.0.53\nsearch default.svc.cluster.local\noptions ndots:5\n"
822        );
823        let h = hosts_file(
824            "web",
825            &[
826                "db".into(),
827                "db.default.svc.cluster.local".into(),
828                "x y".into(),
829                "web".into(),
830            ],
831        );
832        assert!(h.contains("127.0.0.1\tweb\n"));
833        assert!(h.contains("127.0.0.1\tdb.default.svc.cluster.local\n"));
834        assert!(!h.contains("x y"));
835        assert_eq!(h.matches("\tweb\n").count(), 1);
836        let p = pod_hosts(
837            "web-1",
838            "10.88.0.2",
839            &[
840                ("10.88.0.2".into(), "web".into()),
841                ("10.88.0.3".into(), "web".into()),
842                ("10.88.0.3".into(), "web".into()),
843                ("10.88.0.4".into(), "web-1".into()),
844                ("bad".into(), "db".into()),
845                ("10.88.0.5".into(), "x y".into()),
846            ],
847        );
848        assert_eq!(
849            p,
850            "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"
851        );
852    }
853
854    #[test]
855    fn seccomp_profile_lands_in_linux() {
856        let d = tmpdir("assign");
857        let body = json!({
858            "defaultAction": "SCMP_ACT_ERRNO",
859            "architectures": ["SCMP_ARCH_X86_64"],
860            "syscalls": [{"names": ["read", "write"], "action": "SCMP_ACT_ALLOW"}]
861        });
862        let file = d.join("profile.json");
863        fs::write(&file, body.to_string()).unwrap();
864        let p = Profile::load(&file).unwrap();
865        let root = PathBuf::from("/r");
866        let spec = ContainerSpec {
867            name: "krab_default_p_c".into(),
868            ..Default::default()
869        };
870        let proc = Process {
871            args: vec!["sh".into()],
872            env: vec![DEFAULT_PATH.into()],
873            cwd: "/".into(),
874            user: String::new(),
875        };
876        let b = Bundle {
877            cgroups_path: "/krab/default_p/c",
878            hosts: &root.join("hosts"),
879            resolv: &root.join("resolv.conf"),
880            hostname_file: &root.join("hostname"),
881            volume_root: &root.join("volumes"),
882            netns: None,
883            seccomp: Some(p.value()),
884        };
885        let c = config_json(&spec, &proc, &User::default(), &b).unwrap();
886        assert_eq!(c["linux"]["seccomp"], body);
887        assert_eq!(c["linux"]["cgroupsPath"], "/krab/default_p/c");
888        let plain = Bundle { seccomp: None, ..b };
889        let c = config_json(&spec, &proc, &User::default(), &plain).unwrap();
890        assert!(c["linux"].get("seccomp").is_none());
891        fs::remove_dir_all(&d).unwrap();
892    }
893
894    #[test]
895    fn seccomp_profile_loads_restrictive_defaults() {
896        let d = tmpdir("ok");
897        for a in RESTRICTIVE_ACTIONS {
898            let f = d.join(format!("ok-{a}.json"));
899            fs::write(
900                &f,
901                format!(
902                    r#"{{"defaultAction":"{a}","syscalls":[{{"names":["read"],"action":"SCMP_ACT_ALLOW"}}]}}"#
903                ),
904            )
905            .unwrap();
906            assert!(Profile::load(&f).is_ok(), "{a}");
907        }
908        fs::remove_dir_all(&d).unwrap();
909    }
910
911    #[test]
912    fn seccomp_profile_rejects_bad_input() {
913        let d = tmpdir("bad");
914        let load = |name: &str, body: &str| {
915            let f = d.join(name);
916            fs::write(&f, body).unwrap();
917            Profile::load(&f).unwrap_err()
918        };
919        let cases = [
920            ("arr.json", "[]"),
921            ("str.json", "\"x\""),
922            ("num.json", "123"),
923            ("nul.json", "null"),
924            ("empty.json", "{}"),
925            (
926                "missing-syscall-action.json",
927                r#"{"defaultAction":"SCMP_ACT_ERRNO","syscalls":[{"names":["read"]}]}"#,
928            ),
929            (
930                "non-oci-conditions.json",
931                r#"{"defaultAction":"SCMP_ACT_ERRNO","syscalls":[{"names":["read"],"action":"SCMP_ACT_ALLOW","includes":{}}]}"#,
932            ),
933            ("broken.json", r#"{"defaultAction":"#),
934            ("allow.json", r#"{"defaultAction":"SCMP_ACT_ALLOW"}"#),
935            ("log.json", r#"{"defaultAction":"SCMP_ACT_LOG"}"#),
936            ("kill.json", r#"{"defaultAction":"SCMP_ACT_KILL"}"#),
937            ("dflnotify.json", r#"{"defaultAction":"SCMP_ACT_NOTIFY"}"#),
938            ("dnum.json", r#"{"defaultAction":1}"#),
939            (
940                "notify.json",
941                r#"{"defaultAction":"SCMP_ACT_ERRNO","notify":{"timeout":1000}}"#,
942            ),
943            (
944                "notifyopts.json",
945                r#"{"defaultAction":"SCMP_ACT_ERRNO","notifyOpts":{}}"#,
946            ),
947            (
948                "notifysys.json",
949                r#"{"defaultAction":"SCMP_ACT_ERRNO","syscalls":[{"names":["read"],"action":"SCMP_ACT_NOTIFY"}]}"#,
950            ),
951            (
952                "listener.json",
953                r#"{"defaultAction":"SCMP_ACT_ERRNO","flags":["SECCOMP_FILTER_FLAG_NEW_LISTENER"]}"#,
954            ),
955        ];
956        for (name, body) in cases {
957            let e = load(name, body);
958            assert_eq!(e.kind(), io::ErrorKind::InvalidInput, "{name}: {e}");
959            assert!(
960                e.to_string().contains("seccomp profile") && e.to_string().contains(name),
961                "{name}: {e}"
962            );
963        }
964        let big = format!(
965            r#"{{"defaultAction":"SCMP_ACT_ERRNO","pad":"{}"}}"#,
966            "x".repeat(MAX_PROFILE as usize)
967        );
968        let e = load("big.json", &big);
969        assert_eq!(e.kind(), io::ErrorKind::InvalidInput);
970        assert!(e.to_string().contains("larger than"), "{e}");
971        let e = Profile::load(&d.join("missing.json")).unwrap_err();
972        assert_eq!(e.kind(), io::ErrorKind::NotFound);
973        assert!(e.to_string().contains("seccomp profile"), "{e}");
974        fs::remove_dir_all(&d).unwrap();
975    }
976}