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    if !spec.sysctls.is_empty() {
502        linux["sysctl"] = spec
503            .sysctls
504            .iter()
505            .map(|(k, v)| (k.clone(), json!(v)))
506            .collect::<serde_json::Map<_, _>>()
507            .into();
508    }
509    Ok(json!({
510        "ociVersion": "1.0.2",
511        "process": {
512            "terminal": spec.tty,
513            "user": {"uid": user.uid, "gid": user.gid, "additionalGids": user.extra},
514            "args": p.args,
515            "env": p.env,
516            "cwd": p.cwd,
517            "capabilities": {"bounding": caps, "effective": caps, "permitted": caps},
518            "rlimits": [{"type": "RLIMIT_NOFILE", "hard": 1048576u64, "soft": 1048576u64}],
519            "noNewPrivileges": !spec.allow_privilege_escalation,
520        },
521        "root": {"path": "rootfs", "readonly": spec.read_only_root},
522        "hostname": spec.hostname.clone().unwrap_or_default(),
523        "mounts": spec_mounts(spec, b)?,
524        "linux": linux,
525    }))
526}
527
528pub fn resolv_conf(host: &str, search: &[String], options: &[String]) -> String {
529    let mut out = String::new();
530    for l in host.lines() {
531        let l = l.trim();
532        if l.starts_with("nameserver ") {
533            out.push_str(l);
534            out.push('\n');
535        }
536    }
537    if out.is_empty() {
538        out.push_str("nameserver 1.1.1.1\n");
539    }
540    let clean = |v: &[String]| -> Vec<String> {
541        v.iter()
542            .filter(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_graphic()))
543            .cloned()
544            .collect()
545    };
546    let s = clean(search);
547    if !s.is_empty() {
548        out.push_str(&format!("search {}\n", s.join(" ")));
549    }
550    let o = clean(options);
551    if !o.is_empty() {
552        out.push_str(&format!("options {}\n", o.join(" ")));
553    }
554    out
555}
556
557pub fn hosts_file(hostname: &str, aliases: &[String]) -> String {
558    let pairs: Vec<(String, String)> = aliases
559        .iter()
560        .map(|a| ("127.0.0.1".to_string(), a.clone()))
561        .collect();
562    pod_hosts(hostname, "127.0.0.1", &pairs)
563}
564
565pub fn pod_hosts(hostname: &str, ip: &str, pairs: &[(String, String)]) -> String {
566    pod_hosts_with(hostname, ip, pairs, &[])
567}
568
569pub fn pod_hosts_with(
570    hostname: &str,
571    ip: &str,
572    pairs: &[(String, String)],
573    host_aliases: &[(String, String)],
574) -> String {
575    let ok = |s: &str| {
576        !s.is_empty()
577            && s.len() <= 253
578            && s.bytes()
579                .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'.')
580    };
581    let ip_ok = |s: &str| s.parse::<std::net::Ipv4Addr>().is_ok();
582    let mut out = String::from(
583        "# Kubernetes-managed hosts file.\n127.0.0.1\tlocalhost\n::1\tlocalhost ip6-localhost ip6-loopback\n",
584    );
585    let mut seen: Vec<(&str, &str)> = Vec::new();
586    if ok(hostname) && ip_ok(ip) {
587        seen.push((ip, hostname));
588    }
589    for (a, n) in pairs {
590        if ok(n) && ip_ok(a) && n != hostname && !seen.contains(&(a.as_str(), n.as_str())) {
591            seen.push((a, n));
592        }
593    }
594    for (a, n) in seen {
595        out.push_str(&format!("{a}\t{n}\n"));
596    }
597    let mut grouped: Vec<(&str, Vec<&str>)> = Vec::new();
598    for (a, n) in host_aliases {
599        if !ok(n) || !ip_ok(a) {
600            continue;
601        }
602        match grouped.iter_mut().find(|(x, _)| *x == a.as_str()) {
603            Some((_, names)) => {
604                if !names.contains(&n.as_str()) {
605                    names.push(n);
606                }
607            }
608            None => grouped.push((a, vec![n])),
609        }
610    }
611    if !grouped.is_empty() {
612        out.push_str("\n# Entries added by HostAliases.\n");
613        for (a, names) in grouped {
614            out.push_str(&format!("{a}\t{}\n", names.join("\t")));
615        }
616    }
617    out
618}
619
620#[cfg(test)]
621mod tests {
622    use super::*;
623    use std::fs;
624    use std::path::PathBuf;
625
626    fn tmpdir(tag: &str) -> PathBuf {
627        let d = std::env::temp_dir().join(format!("krab-oci-seccomp-{tag}-{}", std::process::id()));
628        let _ = fs::remove_dir_all(&d);
629        fs::create_dir_all(&d).unwrap();
630        d
631    }
632
633    fn img() -> ImageConfig {
634        serde_json::from_value(json!({
635            "Entrypoint": ["/docker-entrypoint.sh"],
636            "Cmd": ["nginx", "-g", "daemon off;"],
637            "Env": ["PATH=/usr/bin:/bin", "NGINX_VERSION=1.27"],
638            "WorkingDir": "/srv",
639            "User": "nginx"
640        }))
641        .unwrap()
642    }
643
644    #[test]
645    fn merge_like_docker() {
646        let spec = ContainerSpec {
647            env: vec!["NGINX_VERSION=2".into(), "A=b=c".into()],
648            hostname: Some("web".into()),
649            ..Default::default()
650        };
651        let p = merge(&spec, &img()).unwrap();
652        assert_eq!(
653            p.args,
654            vec!["/docker-entrypoint.sh", "nginx", "-g", "daemon off;"]
655        );
656        assert_eq!(
657            p.env,
658            vec![
659                "PATH=/usr/bin:/bin",
660                "NGINX_VERSION=2",
661                "A=b=c",
662                "HOSTNAME=web"
663            ]
664        );
665        assert_eq!(p.cwd, "/srv");
666        assert_eq!(p.user, "nginx");
667        let spec = ContainerSpec {
668            args: vec!["-v".into()],
669            ..Default::default()
670        };
671        assert_eq!(
672            merge(&spec, &img()).unwrap().args,
673            vec!["/docker-entrypoint.sh", "-v"]
674        );
675        let spec = ContainerSpec {
676            command: vec!["sh".into()],
677            working_dir: Some("/w".into()),
678            user: Some("1000".into()),
679            tty: true,
680            ..Default::default()
681        };
682        let p = merge(&spec, &img()).unwrap();
683        assert_eq!(p.args, vec!["sh"]);
684        assert_eq!(p.cwd, "/w");
685        assert_eq!(p.user, "1000");
686        assert!(p.env.contains(&"TERM=xterm".to_string()));
687        let p = merge(
688            &ContainerSpec::default(),
689            &ImageConfig {
690                cmd: Some(vec!["sh".into()]),
691                ..Default::default()
692            },
693        )
694        .unwrap();
695        assert_eq!(p.env[0], DEFAULT_PATH);
696        assert_eq!(p.cwd, "/");
697        assert!(merge(&ContainerSpec::default(), &ImageConfig::default()).is_err());
698    }
699
700    #[test]
701    fn users_resolve() {
702        let pw =
703            "root:x:0:0:root:/root:/bin/sh\nnginx:x:101:101:nginx:/var/cache/nginx:/sbin/nologin\n";
704        let gr = "root:x:0:\nnginx:x:101:nginx\nwww:x:33:nginx,other\n";
705        assert_eq!(resolve_user("", pw, gr).unwrap(), User::default());
706        assert_eq!(
707            resolve_user("nginx", pw, gr).unwrap(),
708            User {
709                uid: 101,
710                gid: 101,
711                extra: vec![33]
712            }
713        );
714        assert_eq!(resolve_user("1000", pw, gr).unwrap().gid, 0);
715        assert_eq!(resolve_user("101:www", pw, gr).unwrap().gid, 33);
716        assert_eq!(resolve_user("nginx:5", pw, gr).unwrap().gid, 5);
717        assert!(resolve_user("nobody", pw, gr).is_err());
718        assert!(resolve_user("nginx:nogroup", pw, gr).is_err());
719    }
720
721    #[test]
722    fn home_from_passwd() {
723        let pw =
724            "root:x:0:0:root:/root:/bin/sh\nnginx:x:101:101:nginx:/var/cache/nginx:/sbin/nologin\n";
725        let mut env = vec![DEFAULT_PATH.to_string()];
726        set_home(&mut env, 101, pw);
727        assert_eq!(env[1], "HOME=/var/cache/nginx");
728        let mut env = Vec::new();
729        set_home(&mut env, 0, pw);
730        assert_eq!(env, vec!["HOME=/root"]);
731        let mut env = Vec::new();
732        set_home(&mut env, 1000, pw);
733        assert_eq!(env, vec!["HOME=/"]);
734        let mut env = vec!["HOME=/custom".to_string()];
735        set_home(&mut env, 0, pw);
736        assert_eq!(env, vec!["HOME=/custom"]);
737    }
738
739    #[test]
740    fn config_json_is_hardened() {
741        let spec = ContainerSpec {
742            name: "krab_default_p_c".into(),
743            hostname: Some("p".into()),
744            memory_bytes: Some(64 << 20),
745            nano_cpus: Some(250_000_000),
746            mounts: vec![
747                Mount::Bind {
748                    src: "/data/x".into(),
749                    dst: "/x".into(),
750                    read_only: true,
751                },
752                Mount::Volume {
753                    name: "krab_u_v".into(),
754                    dst: "/v".into(),
755                    read_only: false,
756                },
757                Mount::Tmpfs { dst: "/t".into() },
758            ],
759            ..Default::default()
760        };
761        let p = Process {
762            args: vec!["sh".into()],
763            env: vec![DEFAULT_PATH.into()],
764            cwd: "/".into(),
765            user: String::new(),
766        };
767        let root = PathBuf::from("/r");
768        let b = Bundle {
769            cgroups_path: "/krab/default_p/c",
770            hosts: &root.join("hosts"),
771            resolv: &root.join("resolv.conf"),
772            hostname_file: &root.join("hostname"),
773            volume_root: &root.join("volumes"),
774            netns: None,
775            seccomp: None,
776        };
777        let c = config_json(&spec, &p, &User::default(), &b).unwrap();
778        assert_eq!(c["process"]["noNewPrivileges"], true);
779        let caps = c["process"]["capabilities"]["bounding"].as_array().unwrap();
780        assert!(
781            !caps
782                .iter()
783                .any(|x| x == "CAP_NET_RAW" || x == "CAP_SYS_ADMIN")
784        );
785        assert_eq!(caps.len(), 13);
786        assert_eq!(c["linux"]["cgroupsPath"], "/krab/default_p/c");
787        assert_eq!(c["linux"]["resources"]["memory"]["limit"], 64 << 20);
788        assert_eq!(c["linux"]["resources"]["memory"]["swap"], 64 << 20);
789        assert_eq!(c["linux"]["resources"]["cpu"]["quota"], 25_000);
790        assert!(
791            !c["linux"]["namespaces"]
792                .as_array()
793                .unwrap()
794                .iter()
795                .any(|n| n["type"] == "network" || n["type"] == "user")
796        );
797        assert!(
798            c["linux"]["maskedPaths"]
799                .as_array()
800                .unwrap()
801                .iter()
802                .any(|m| m == "/proc/kcore")
803        );
804        let mounts = c["mounts"].as_array().unwrap();
805        let find = |d: &str| {
806            mounts
807                .iter()
808                .find(|m| m["destination"] == d)
809                .unwrap()
810                .clone()
811        };
812        assert_eq!(find("/x")["source"], "/data/x");
813        assert!(
814            find("/x")["options"]
815                .as_array()
816                .unwrap()
817                .iter()
818                .any(|o| o == "ro")
819        );
820        assert_eq!(find("/v")["source"], "/r/volumes/krab_u_v");
821        assert_eq!(find("/t")["type"], "tmpfs");
822        assert_eq!(find("/etc/hosts")["source"], "/r/hosts");
823        let ns = PathBuf::from("/run/netns/krab-0123456789");
824        let with_net = Bundle {
825            netns: Some(&ns),
826            ..b
827        };
828        let c2 = config_json(&spec, &p, &User::default(), &with_net).unwrap();
829        let nss = c2["linux"]["namespaces"].as_array().unwrap();
830        assert!(
831            nss.iter()
832                .any(|n| n["type"] == "network" && n["path"] == "/run/netns/krab-0123456789")
833        );
834        assert!(!nss.iter().any(|n| n["type"] == "user"));
835        assert_eq!(c["root"]["path"], "rootfs");
836        let mut bad = spec.clone();
837        bad.mounts = vec![Mount::Tmpfs {
838            dst: "/a/../etc".into(),
839        }];
840        assert!(config_json(&bad, &p, &User::default(), &b).is_err());
841        bad.mounts = vec![Mount::Tmpfs { dst: "/".into() }];
842        assert!(config_json(&bad, &p, &User::default(), &b).is_err());
843        bad.mounts = vec![Mount::Volume {
844            name: "../x".into(),
845            dst: "/v".into(),
846            read_only: false,
847        }];
848        assert!(config_json(&bad, &p, &User::default(), &b).is_err());
849    }
850
851    #[test]
852    fn dns_files() {
853        let r = resolv_conf(
854            "# c\nnameserver 127.0.0.53\noptions edns0\nsearch lan\n",
855            &["default.svc.cluster.local".into(), "bad name".into()],
856            &["ndots:5".into()],
857        );
858        assert_eq!(
859            r,
860            "nameserver 127.0.0.53\nsearch default.svc.cluster.local\noptions ndots:5\n"
861        );
862        let h = hosts_file(
863            "web",
864            &[
865                "db".into(),
866                "db.default.svc.cluster.local".into(),
867                "x y".into(),
868                "web".into(),
869            ],
870        );
871        assert!(h.contains("127.0.0.1\tweb\n"));
872        assert!(h.contains("127.0.0.1\tdb.default.svc.cluster.local\n"));
873        assert!(!h.contains("x y"));
874        assert_eq!(h.matches("\tweb\n").count(), 1);
875        let p = pod_hosts(
876            "web-1",
877            "10.88.0.2",
878            &[
879                ("10.88.0.2".into(), "web".into()),
880                ("10.88.0.3".into(), "web".into()),
881                ("10.88.0.3".into(), "web".into()),
882                ("10.88.0.4".into(), "web-1".into()),
883                ("bad".into(), "db".into()),
884                ("10.88.0.5".into(), "x y".into()),
885            ],
886        );
887        assert_eq!(
888            p,
889            "# Kubernetes-managed hosts file.\n127.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"
890        );
891    }
892
893    #[test]
894    fn seccomp_profile_lands_in_linux() {
895        let d = tmpdir("assign");
896        let body = json!({
897            "defaultAction": "SCMP_ACT_ERRNO",
898            "architectures": ["SCMP_ARCH_X86_64"],
899            "syscalls": [{"names": ["read", "write"], "action": "SCMP_ACT_ALLOW"}]
900        });
901        let file = d.join("profile.json");
902        fs::write(&file, body.to_string()).unwrap();
903        let p = Profile::load(&file).unwrap();
904        let root = PathBuf::from("/r");
905        let spec = ContainerSpec {
906            name: "krab_default_p_c".into(),
907            ..Default::default()
908        };
909        let proc = Process {
910            args: vec!["sh".into()],
911            env: vec![DEFAULT_PATH.into()],
912            cwd: "/".into(),
913            user: String::new(),
914        };
915        let b = Bundle {
916            cgroups_path: "/krab/default_p/c",
917            hosts: &root.join("hosts"),
918            resolv: &root.join("resolv.conf"),
919            hostname_file: &root.join("hostname"),
920            volume_root: &root.join("volumes"),
921            netns: None,
922            seccomp: Some(p.value()),
923        };
924        let c = config_json(&spec, &proc, &User::default(), &b).unwrap();
925        assert_eq!(c["linux"]["seccomp"], body);
926        assert_eq!(c["linux"]["cgroupsPath"], "/krab/default_p/c");
927        let plain = Bundle { seccomp: None, ..b };
928        let c = config_json(&spec, &proc, &User::default(), &plain).unwrap();
929        assert!(c["linux"].get("seccomp").is_none());
930        fs::remove_dir_all(&d).unwrap();
931    }
932
933    #[test]
934    fn seccomp_profile_loads_restrictive_defaults() {
935        let d = tmpdir("ok");
936        for a in RESTRICTIVE_ACTIONS {
937            let f = d.join(format!("ok-{a}.json"));
938            fs::write(
939                &f,
940                format!(
941                    r#"{{"defaultAction":"{a}","syscalls":[{{"names":["read"],"action":"SCMP_ACT_ALLOW"}}]}}"#
942                ),
943            )
944            .unwrap();
945            assert!(Profile::load(&f).is_ok(), "{a}");
946        }
947        fs::remove_dir_all(&d).unwrap();
948    }
949
950    #[test]
951    fn seccomp_profile_rejects_bad_input() {
952        let d = tmpdir("bad");
953        let load = |name: &str, body: &str| {
954            let f = d.join(name);
955            fs::write(&f, body).unwrap();
956            Profile::load(&f).unwrap_err()
957        };
958        let cases = [
959            ("arr.json", "[]"),
960            ("str.json", "\"x\""),
961            ("num.json", "123"),
962            ("nul.json", "null"),
963            ("empty.json", "{}"),
964            (
965                "missing-syscall-action.json",
966                r#"{"defaultAction":"SCMP_ACT_ERRNO","syscalls":[{"names":["read"]}]}"#,
967            ),
968            (
969                "non-oci-conditions.json",
970                r#"{"defaultAction":"SCMP_ACT_ERRNO","syscalls":[{"names":["read"],"action":"SCMP_ACT_ALLOW","includes":{}}]}"#,
971            ),
972            ("broken.json", r#"{"defaultAction":"#),
973            ("allow.json", r#"{"defaultAction":"SCMP_ACT_ALLOW"}"#),
974            ("log.json", r#"{"defaultAction":"SCMP_ACT_LOG"}"#),
975            ("kill.json", r#"{"defaultAction":"SCMP_ACT_KILL"}"#),
976            ("dflnotify.json", r#"{"defaultAction":"SCMP_ACT_NOTIFY"}"#),
977            ("dnum.json", r#"{"defaultAction":1}"#),
978            (
979                "notify.json",
980                r#"{"defaultAction":"SCMP_ACT_ERRNO","notify":{"timeout":1000}}"#,
981            ),
982            (
983                "notifyopts.json",
984                r#"{"defaultAction":"SCMP_ACT_ERRNO","notifyOpts":{}}"#,
985            ),
986            (
987                "notifysys.json",
988                r#"{"defaultAction":"SCMP_ACT_ERRNO","syscalls":[{"names":["read"],"action":"SCMP_ACT_NOTIFY"}]}"#,
989            ),
990            (
991                "listener.json",
992                r#"{"defaultAction":"SCMP_ACT_ERRNO","flags":["SECCOMP_FILTER_FLAG_NEW_LISTENER"]}"#,
993            ),
994        ];
995        for (name, body) in cases {
996            let e = load(name, body);
997            assert_eq!(e.kind(), io::ErrorKind::InvalidInput, "{name}: {e}");
998            assert!(
999                e.to_string().contains("seccomp profile") && e.to_string().contains(name),
1000                "{name}: {e}"
1001            );
1002        }
1003        let big = format!(
1004            r#"{{"defaultAction":"SCMP_ACT_ERRNO","pad":"{}"}}"#,
1005            "x".repeat(MAX_PROFILE as usize)
1006        );
1007        let e = load("big.json", &big);
1008        assert_eq!(e.kind(), io::ErrorKind::InvalidInput);
1009        assert!(e.to_string().contains("larger than"), "{e}");
1010        let e = Profile::load(&d.join("missing.json")).unwrap_err();
1011        assert_eq!(e.kind(), io::ErrorKind::NotFound);
1012        assert!(e.to_string().contains("seccomp profile"), "{e}");
1013        fs::remove_dir_all(&d).unwrap();
1014    }
1015
1016    #[test]
1017    fn host_aliases_are_grouped_by_ip() {
1018        let h = pod_hosts_with(
1019            "web",
1020            "10.0.0.2",
1021            &[],
1022            &[
1023                ("123.45.67.89".into(), "foo".into()),
1024                ("123.45.67.89".into(), "bar".into()),
1025                ("bad".into(), "x".into()),
1026            ],
1027        );
1028        assert!(h.contains("\n# Entries added by HostAliases.\n123.45.67.89\tfoo\tbar\n"));
1029        assert!(!h.contains("bad"));
1030    }
1031}