Skip to main content

kernel_abi_tools/
container.rs

1//! Runs a program in a container whose seccomp profile simulates a kernel.
2
3use crate::{seccomp_profile, Target};
4use std::env;
5use std::fs;
6use std::path::{Path, PathBuf};
7use std::process::Command;
8use std::time::{SystemTime, UNIX_EPOCH};
9
10/// The container engine and the options added to its command line.
11#[derive(Clone, Debug, PartialEq, Eq)]
12pub struct Engine {
13    /// `podman` or `docker`.
14    pub program: String,
15    /// Options placed before `run`, e.g. `--runtime crun`.
16    pub engine_args: Vec<String>,
17    /// Options added to `run`, e.g. `--network none`.
18    pub run_args: Vec<String>,
19}
20
21impl Engine {
22    /// Reads `CONTAINER_ENGINE` (default `podman`), `KERNEL_ABI_ENGINE_ARGS`,
23    /// and `KERNEL_ABI_RUN_ARGS` (whitespace-separated).
24    pub fn from_env() -> Self {
25        Engine {
26            program: env::var("CONTAINER_ENGINE").unwrap_or_else(|_| "podman".to_string()),
27            engine_args: env_words("KERNEL_ABI_ENGINE_ARGS"),
28            run_args: env_words("KERNEL_ABI_RUN_ARGS"),
29        }
30    }
31}
32
33/// Runs `program` with `args` in `image` under the profile for `target` and
34/// returns its exit status (128 if it was killed by a signal).
35///
36/// The current directory, and `program` if it is a host path outside it, are
37/// mounted at their own absolute paths so relative paths and compile-time
38/// `CARGO_MANIFEST_DIR` values keep working. A bare `program` name (no `/`)
39/// runs from the image. A host program is mounted as a single file, never its
40/// directory, which could hide the image's own `/bin` or `/usr/bin`.
41/// `CARGO*`/`RUST*` variables are forwarded. Suitable for a Cargo runner.
42pub fn run(
43    engine: &Engine,
44    target: &Target,
45    image: &str,
46    program: &str,
47    args: &[String],
48) -> Result<i32, String> {
49    if image.is_empty() {
50        return Err("no container image selected".to_string());
51    }
52    let cwd = env::current_dir().map_err(|e| format!("current directory: {e}"))?;
53    let host_program = program
54        .contains('/')
55        .then(|| absolute(&cwd, Path::new(program)));
56    if let Some(p) = &host_program {
57        if !p.is_file() {
58            return Err(format!("{} is not a file on this host", p.display()));
59        }
60    }
61
62    let profile = TempFile::new("kernel-seccomp", ".json")?;
63    fs::write(&profile.0, seccomp_profile(target))
64        .map_err(|e| format!("{}: {e}", profile.0.display()))?;
65
66    let mut cmd = Command::new(&engine.program);
67    cmd.args(&engine.engine_args);
68    cmd.args(["run", "--rm", "--security-opt"]);
69    cmd.arg(format!("seccomp={}", profile.0.display()));
70    cmd.arg("-v").arg(format!("{0}:{0}:z", cwd.display()));
71    match &host_program {
72        Some(p) if !p.starts_with(&cwd) => {
73            cmd.arg("-v").arg(format!("{0}:{0}:ro,z", p.display()));
74        }
75        _ => {}
76    }
77    cmd.arg("-w").arg(&cwd);
78    cmd.args(["-e", "CARGO*", "-e", "RUST*"]);
79    cmd.args(&engine.run_args);
80    cmd.arg(image);
81    match &host_program {
82        Some(p) => cmd.arg(p),
83        None => cmd.arg(program),
84    };
85    cmd.args(args);
86
87    let status = cmd
88        .status()
89        .map_err(|e| format!("cannot start {}: {e}", engine.program))?;
90    Ok(status.code().unwrap_or(128))
91}
92
93fn env_words(name: &str) -> Vec<String> {
94    env::var(name)
95        .unwrap_or_default()
96        .split_whitespace()
97        .map(str::to_string)
98        .collect()
99}
100
101fn absolute(cwd: &Path, path: &Path) -> PathBuf {
102    if path.is_absolute() {
103        path.to_path_buf()
104    } else {
105        cwd.join(path)
106    }
107}
108
109/// A file in the temporary directory, removed when dropped.
110struct TempFile(PathBuf);
111
112impl TempFile {
113    fn new(prefix: &str, suffix: &str) -> Result<Self, String> {
114        let nanos = SystemTime::now()
115            .duration_since(UNIX_EPOCH)
116            .map(|d| d.as_nanos())
117            .unwrap_or(0);
118        let name = format!("{prefix}-{}-{nanos}{suffix}", std::process::id());
119        let path = env::temp_dir().join(name);
120        fs::OpenOptions::new()
121            .write(true)
122            .create_new(true)
123            .open(&path)
124            .map_err(|e| format!("{}: {e}", path.display()))?;
125        Ok(TempFile(path))
126    }
127}
128
129impl Drop for TempFile {
130    fn drop(&mut self) {
131        let _ = fs::remove_file(&self.0);
132    }
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138    use crate::KernelVersion;
139
140    #[test]
141    fn rejects_missing_image_and_missing_host_program() {
142        let engine = Engine {
143            program: "definitely-not-a-container-engine".to_string(),
144            engine_args: Vec::new(),
145            run_args: Vec::new(),
146        };
147        let target = Target::kernel(KernelVersion::parse("4.12").unwrap());
148        assert!(run(&engine, &target, "", "sh", &[]).is_err());
149        let err = run(&engine, &target, "img", "./no/such/program", &[]).unwrap_err();
150        assert!(err.contains("not a file on this host"), "{err}");
151        let err = run(&engine, &target, "img", "sh", &[]).unwrap_err();
152        assert!(err.contains("cannot start"), "{err}");
153    }
154}