Skip to content
1        10        20        30        40        50        60        70        80        90        1001#![cfg(target_os = "linux")]23use std::error::Error;4use std::ffi::{CStr, CString, OsStr, OsString};5use std::fs;6use std::io::{self, Write};7use std::os::fd::RawFd;8use std::os::unix::ffi::OsStrExt;9use std::path::{Path, PathBuf};10use std::process;1112const CHILD_STACK_SIZE: usize = 1024 * 1024;13const CGROUP2_SUPER_MAGIC: libc::c_long = 0x6367_7270;1415#[derive(Debug)]16struct Options {17    rootfs: PathBuf,18    cgroup_parent: PathBuf,19    memory_max: u64,20    pids_max: u32,21    hostname: CString,22    command: Vec<CString>,23}2425struct Cgroup {26    path: PathBuf,27}2829struct ChildConfig {30    gate_read: RawFd,31    rootfs: CString,32    hostname: CString,33    command: Vec<CString>,34}3536fn main() {37    if let Err(error) = run() {38        eprintln!("mini-container: {error}");39        process::exit(1);40    }41}4243fn run() -> Result<(), Box<dyn Error>> {44    let args = std::env::args_os().skip(1).collect::<Vec<_>>();45    let Some(options) = parse_options(&args)? else {46        print_help();47        return Ok(());48    };4950    let rootfs = fs::canonicalize(&options.rootfs)?;51    if !rootfs.is_dir() {52        return Err(format!("rootfs is not a directory: {}", rootfs.display()).into());53    }54    let rootfs_c = cstring(rootfs.as_os_str(), "rootfs path")?;55    let mut command = options.command;56    command[0] = command_path_in_root(&command[0])?;5758    let mut cgroup = Cgroup::create(&options.cgroup_parent, options.memory_max, options.pids_max)?;59    let mut gate = [-1; 2];60    // SAFETY: `gate` points to two writable descriptors as required by pipe(2).61    if unsafe { libc::pipe2(gate.as_mut_ptr(), libc::O_CLOEXEC) } == -1 {62        return Err(io::Error::last_os_error().into());63    }6465    let mut config = ChildConfig {66        gate_read: gate[0],67        rootfs: rootfs_c,68        hostname: options.hostname,69        command,70    };71    let mut stack = vec![0_u8; CHILD_STACK_SIZE];72    let stack_top = stack.as_mut_ptr().wrapping_add(stack.len()).cast();73    let flags = libc::CLONE_NEWUSER74        | libc::CLONE_NEWNS75        | libc::CLONE_NEWUTS76        | libc::CLONE_NEWIPC77        | libc::CLONE_NEWPID78        | libc::CLONE_NEWNET79        | libc::SIGCHLD;8081    // SAFETY: clone starts a separate process with a dedicated live stack. The callback82    // receives a pointer to `config`, which remains alive until waitpid returns.83    let pid = unsafe { libc::clone(child_entry, stack_top, flags, (&raw mut config).cast()) };84    if pid == -1 {85        close_fd(gate[0]);86        close_fd(gate[1]);87        return Err(io::Error::last_os_error().into());88    }8990    close_fd(gate[0]);91    let setup = (|| -> Result<(), Box<dyn Error>> {92        install_id_maps(pid)?;93        cgroup.attach(pid)?;94        println!(95            "mini-container: child pid {pid}; cgroup {}",96            cgroup.path.display()97        );98        io::stdout().flush()?;99        write_fd(gate[1], &[1])?;100        Ok(())101    })();102    close_fd(gate[1]);103104    if let Err(error) = setup {105        // SAFETY: `pid` is the direct child returned by clone; it is waiting on the gate.106        unsafe {107            libc::kill(pid, libc::SIGKILL);108        }109        let _ = wait_for(pid);110        let _ = cgroup.remove();111        return Err(error);112    }113114    let status = wait_for(pid)?;115    if status != 0 {116        eprintln!("mini-container: child exited with status {status}");117    }118    if let Err(error) = cgroup.remove() {119        eprintln!(120            "mini-container: could not remove cgroup (remaining descendants may still be present): {error}"121        );122    }123    process::exit(status);124}125126fn command_path_in_root(path: &CStr) -> Result<CString, Box<dyn Error>> {127    let bytes = path.to_bytes();128    if bytes.first() != Some(&b'/') {129        return Err("the command must be an absolute path inside the rootfs".into());130    }131    Ok(CString::new(bytes)?)132}133134fn parse_options(args: &[OsString]) -> Result<Option<Options>, Box<dyn Error>> {135    let mut rootfs = None;136    let mut cgroup_parent = PathBuf::from("/sys/fs/cgroup");137    let mut memory_max = 256 * 1024 * 1024;138    let mut pids_max = 64;139    let mut hostname = CString::new("mini-container")?;140    let mut index = 0;141142    while index < args.len() {143        let arg = args[index].to_str().ok_or("options must be valid UTF-8")?;144        if arg == "--" {145            index += 1;146            break;147        }148        if arg == "--help" || arg == "-h" {149            return Ok(None);150        }151        let value = || -> Result<&OsStr, Box<dyn Error>> {152            args.get(index + 1)153                .map(OsString::as_os_str)154                .ok_or_else(|| format!("missing value for {arg}").into())155        };156        match arg {157            "--rootfs" => rootfs = Some(PathBuf::from(value()?)),158            "--cgroup-parent" => cgroup_parent = PathBuf::from(value()?),159            "--memory" => memory_max = parse_positive(value()?, "memory")?,160            "--pids" => {161                pids_max = u32::try_from(parse_positive(value()?, "pids")?)?;162            }163            "--hostname" => hostname = cstring(value()?, "hostname")?,164            _ => return Err(format!("unknown option: {arg}").into()),165        }166        index += 2;167    }168169    let Some(rootfs) = rootfs else {170        if args.is_empty() {171            return Ok(None);172        }173        return Err("--rootfs is required".into());174    };175    if index == args.len() {176        return Err("missing command; supply an absolute executable path after --".into());177    }178    let command = args[index..]179        .iter()180        .map(|arg| cstring(arg, "command argument"))181        .collect::<Result<Vec<_>, _>>()?;182    if command[0].as_bytes().first() != Some(&b'/') {183        return Err("the command must be an absolute path inside the rootfs".into());184    }185    Ok(Some(Options {186        rootfs,187        cgroup_parent,188        memory_max,189        pids_max,190        hostname,191        command,192    }))193}194195fn parse_positive(value: &OsStr, name: &str) -> Result<u64, Box<dyn Error>> {196    let parsed = value197        .to_str()198        .ok_or_else(|| format!("{name} must be a positive integer"))?199        .parse::<u64>()?;200    if parsed == 0 {201        return Err(format!("{name} must be greater than zero").into());202    }203    Ok(parsed)204}205206fn cstring(value: &OsStr, name: &str) -> Result<CString, Box<dyn Error>> {207    CString::new(value.as_bytes()).map_err(|_| format!("{name} contains a NUL byte").into())208}209210fn install_id_maps(pid: libc::pid_t) -> Result<(), Box<dyn Error>> {211    let proc = PathBuf::from(format!("/proc/{pid}"));212    fs::write(213        proc.join("uid_map"),214        format!("0 {} 1\n", unsafe { libc::geteuid() }),215    )?;216    let setgroups = proc.join("setgroups");217    if setgroups.exists() {218        fs::write(setgroups, "deny\n")?;219    }220    fs::write(221        proc.join("gid_map"),222        format!("0 {} 1\n", unsafe { libc::getegid() }),223    )?;224    Ok(())225}226227extern "C" fn child_entry(argument: *mut libc::c_void) -> libc::c_int {228    // SAFETY: parent passes a valid ChildConfig pointer and keeps it alive through waitpid.229    let config = unsafe { &*(argument.cast::<ChildConfig>()) };230    let mut release = [0_u8; 1];231    // SAFETY: this is the child's read end of a pipe; the parent writes one release byte.232    if unsafe { libc::read(config.gate_read, release.as_mut_ptr().cast(), 1) } != 1 {233        return child_error("parent did not release child setup gate");234    }235    close_fd(config.gate_read);236    // SAFETY: close all inherited descriptors except the standard streams before exec.237    if unsafe { libc::syscall(libc::SYS_close_range, 3_u32, u32::MAX, 0_u32) } == -1 {238        return child_errno("close inherited file descriptors (close_range requires Linux 5.9+)");239    }240241    // SAFETY: mount namespace is private to the child; null arguments request propagation change.242    if unsafe {243        libc::mount(244            std::ptr::null(),245            c"/".as_ptr(),246            std::ptr::null(),247            libc::MS_REC | libc::MS_PRIVATE,248            std::ptr::null(),249        )250    } == -1251    {252        return child_errno("make mount propagation private");253    }254    // SAFETY: hostname is a validated, NUL-terminated string; UTS namespace is isolated.255    if unsafe { libc::sethostname(config.hostname.as_ptr(), config.hostname.as_bytes().len()) }256        == -1257    {258        return child_errno("set hostname");259    }260    // SAFETY: canonicalized directory path is NUL-terminated and exists in the host namespace.261    if unsafe { libc::chdir(config.rootfs.as_ptr()) } == -1 {262        return child_errno("enter rootfs");263    }264    // SAFETY: chroot is performed after entering the validated rootfs directory.265    if unsafe { libc::chroot(c".".as_ptr()) } == -1 {266        return child_errno("chroot to rootfs");267    }268    // SAFETY: chdir to the new root prevents the process retaining a cwd outside it.269    if unsafe { libc::chdir(c"/".as_ptr()) } == -1 {270        return child_errno("change directory to container root");271    }272273    let mut argv = config274        .command275        .iter()276        .map(|item| item.as_ptr())277        .collect::<Vec<_>>();278    argv.push(std::ptr::null());279    // SAFETY: argv and every CString remain live; execv uses an absolute container path.280    unsafe { libc::execv(config.command[0].as_ptr(), argv.as_ptr()) };281    child_errno("execute payload")282}283284fn child_errno(action: &str) -> libc::c_int {285    let error = io::Error::last_os_error();286    child_error(&format!("{action}: {error}"))287}288289fn child_error(message: &str) -> libc::c_int {290    let line = format!("mini-container child: {message}\n");291    // SAFETY: write reads the valid byte slice for its duration; stderr is a process descriptor.292    unsafe {293        libc::write(libc::STDERR_FILENO, line.as_ptr().cast(), line.len());294    }295    127296}297298fn close_fd(fd: RawFd) {299    if fd >= 0 {300        // SAFETY: closing an owned descriptor is safe; errors are handled by the caller or ignored.301        unsafe {302            libc::close(fd);303        }304    }305}306307fn write_fd(fd: RawFd, bytes: &[u8]) -> io::Result<()> {308    // SAFETY: bytes points to a valid buffer for the duration of write(2).309    let written = unsafe { libc::write(fd, bytes.as_ptr().cast(), bytes.len()) };310    if written == -1 {311        Err(io::Error::last_os_error())312    } else if written.cast_unsigned() != bytes.len() {313        Err(io::Error::new(314            io::ErrorKind::WriteZero,315            "short write to child gate",316        ))317    } else {318        Ok(())319    }320}321322fn wait_for(pid: libc::pid_t) -> io::Result<i32> {323    let mut status = 0;324    loop {325        // SAFETY: pid is a direct child returned by clone and status is writable.326        if unsafe { libc::waitpid(pid, &raw mut status, 0) } != -1 {327            break;328        }329        let error = io::Error::last_os_error();330        if error.kind() != io::ErrorKind::Interrupted {331            return Err(error);332        }333    }334    if libc::WIFEXITED(status) {335        Ok(libc::WEXITSTATUS(status))336    } else if libc::WIFSIGNALED(status) {337        Ok(128 + libc::WTERMSIG(status))338    } else {339        Ok(1)340    }341}342343impl Cgroup {344    fn create(parent: &Path, memory_max: u64, pids_max: u32) -> Result<Self, Box<dyn Error>> {345        let parent = fs::canonicalize(parent)?;346        let mut stat: libc::statfs = unsafe { std::mem::zeroed() };347        let parent_c = cstring(parent.as_os_str(), "cgroup path")?;348        // SAFETY: statfs fills the provided struct for this NUL-terminated path.349        if unsafe { libc::statfs(parent_c.as_ptr(), &raw mut stat) } == -1 {350            return Err(io::Error::last_os_error().into());351        }352        if stat.f_type != CGROUP2_SUPER_MAGIC {353            return Err(format!("{} is not a cgroup v2 filesystem", parent.display()).into());354        }355        let path = parent.join(format!("mini-container-{}", process::id()));356        fs::create_dir(&path).map_err(|error| {357            format!(358                "cannot create delegated cgroup {} (use a writable cgroup v2 delegation): {error}",359                path.display()360            )361        })?;362        let cgroup = Self { path };363        let setup = (|| -> Result<(), Box<dyn Error>> {364            fs::write(cgroup.path.join("memory.max"), format!("{memory_max}\n"))?;365            fs::write(cgroup.path.join("pids.max"), format!("{pids_max}\n"))?;366            Ok(())367        })();368        if let Err(error) = setup {369            let _ = fs::remove_dir(&cgroup.path);370            return Err(format!("configure cgroup limits: {error}").into());371        }372        Ok(cgroup)373    }374375    fn attach(&mut self, pid: libc::pid_t) -> Result<(), Box<dyn Error>> {376        fs::write(self.path.join("cgroup.procs"), format!("{pid}\n"))?;377        Ok(())378    }379380    fn remove(&mut self) -> io::Result<()> {381        fs::remove_dir(&self.path)382    }383}384385impl Drop for Cgroup {386    fn drop(&mut self) {387        let _ = fs::remove_dir(&self.path);388    }389}390391fn print_help() {392    println!(393        "Usage:\n  mini-container --rootfs DIR [OPTIONS] -- /ABSOLUTE/COMMAND [ARGS...]\n\394         Options:\n\395           --cgroup-parent DIR  Writable delegated cgroup v2 directory (default /sys/fs/cgroup)\n\396           --memory BYTES       cgroup memory.max (default 268435456)\n\397           --pids COUNT         cgroup pids.max (default 64)\n\398           --hostname NAME      UTS namespace hostname (default mini-container)\n\399           -h, --help           Show this help\n\n\400         The child also receives new user, mount, UTS, IPC, PID and network namespaces."401    );402}403404#[cfg(test)]405mod tests {406    use super::*;407408    fn parse(values: &[&str]) -> Result<Option<Options>, Box<dyn Error>> {409        let args = values.iter().map(OsString::from).collect::<Vec<_>>();410        parse_options(&args)411    }412413    #[test]414    fn help_is_available_without_privileges() {415        assert!(parse(&["--help"]).unwrap().is_none());416    }417418    #[test]419    fn parses_command_arguments_without_shell_interpretation() {420        let options = parse(&[421            "--rootfs",422            "/tmp/root",423            "--memory",424            "4096",425            "--pids",426            "3",427            "--",428            "/bin/echo",429            "hello world",430        ])431        .unwrap()432        .unwrap();433        assert_eq!(options.rootfs, PathBuf::from("/tmp/root"));434        assert_eq!(options.memory_max, 4096);435        assert_eq!(options.pids_max, 3);436        assert_eq!(options.command[1].as_bytes(), b"hello world");437    }438439    #[test]440    fn rejects_relative_payload_paths() {441        let result = parse(&["--rootfs", "/tmp/root", "--", "bin/sh"]);442        assert!(result.is_err());443    }444445    #[test]446    fn rejects_zero_resource_limits() {447        let result = parse(&["--rootfs", "/tmp/root", "--memory", "0", "--", "/bin/true"]);448        assert!(result.is_err());449    }450451    #[test]452    fn rejects_missing_command_separator_and_payload() {453        let result = parse(&["--rootfs", "/tmp/root"]);454        assert!(result.is_err());455    }456}