artifactize-foundation 0.27.0

Native file, path and executable primitives for Artifactize.
Documentation
use super::super::private::file_identity;
#[cfg(not(target_os = "linux"))]
use super::super::private::{create_private_file, private_tempdir_in};
use super::{Executable, ImageKind, Launch, Prepared, ResolvedCommand};
use std::{
    ffi::OsStr,
    fs::File,
    io,
    os::{fd::AsRawFd, unix::process::CommandExt},
    path::Path,
    process::Stdio,
};
use tokio::process::Command;

/// Open a regular file without following a final link. This does not verify a launch;
/// use [`super::Executable`] to bind the file's bytes to a subsequent spawn.
pub fn open_executable(path: &Path) -> io::Result<File> {
    super::super::files::open_regular(path)
}

/// Open a verified working directory without following a final link, so the child can bind to
/// that exact directory via `fchdir`.
pub fn open_verified_directory(path: &Path) -> io::Result<File> {
    use std::os::unix::fs::OpenOptionsExt;

    let file = std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC)
        .open(super::super::files::terminal_component(path).0)?;
    if file.metadata()?.is_dir() {
        Ok(file)
    } else {
        Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "not a directory",
        ))
    }
}

/// Whether `path` currently resolves (without following a link in its final component) to the
/// exact same regular file inode as `file`.
pub fn same_file(file: &File, path: &Path) -> io::Result<bool> {
    let current = open_executable(path)?;
    Ok(file_identity(file)? == file_identity(&current)?)
}

/// Whether `path` currently resolves (without following a link in its final component) to the
/// exact same directory inode as `dir`.
pub fn same_directory(dir: &File, path: &Path) -> io::Result<bool> {
    let current = open_verified_directory(path)?;
    Ok(file_identity(dir)? == file_identity(&current)?)
}

mod image;
pub(in crate::platform) mod interpreter;

/// Bind the working directory by descriptor and every image in the interpreter chain
/// to bytes protected from replacement. The kernel never opens the source script or
/// its shebang pathname in the fork-to-exec interval.
pub(super) fn prepare(launch: Launch<'_>, kind: ImageKind) -> io::Result<Prepared> {
    let Launch {
        executable:
            Executable {
                path,
                mut file,
                digest,
            },
        cwd,
        directory,
        args,
        environment,
    } = launch;
    if !same_directory(&directory, cwd)? {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            "verified launch working directory changed before spawn",
        ));
    }
    let cwd_fd = directory.as_raw_fd();
    #[cfg(target_os = "linux")]
    let mut images = image::Images::new();
    #[cfg(not(target_os = "linux"))]
    let mut images = image::Images::new()?;
    let mut staged = images.stage(&mut file)?;
    super::verify_image(&mut staged.file, digest)?;
    let mut original = path;
    let mut args = args.to_vec();

    use interpreter::shebang;
    for depth in 0..=shebang::MAX_DEPTH {
        let Some(script) = shebang::read(&staged.file)? else {
            break;
        };
        if kind == ImageKind::Native {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "native launch does not accept scripts",
            ));
        }
        if depth == shebang::MAX_DEPTH {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "too many script interpreters",
            ));
        }
        let (canonical, interpreter_file) = interpreter::trusted(&script.path)?;
        let (interpreter, mut interpreter_file, options) = if script.uses_env(&canonical) {
            let search = environment
                .get(OsStr::new("PATH"))
                .filter(|value| std::env::split_paths(value).all(|path| path.is_absolute()))
                .map(|value| value.as_os_str());
            let (name, path) = script.env_target(cwd, search)?;
            let (_, file) = interpreter::trusted(&path)?;
            (name.into(), file, Vec::new())
        } else {
            (script.path, interpreter_file, script.options)
        };
        // Prepend the same arguments the kernel would inject for this interpreter.
        args.splice(
            ..0,
            options
                .into_iter()
                .chain([staged.path.clone().into_os_string()]),
        );
        images.retain_script(staged);
        staged = images.stage(&mut interpreter_file)?;
        original = interpreter;
    }

    #[cfg(target_os = "linux")]
    let loader = if let Some(loader) = interpreter::elf::loader(&staged.file)? {
        let (_, mut source) = interpreter::trusted(&loader.path)?;
        let image = images.stage(&mut source)?;
        if interpreter::elf::loader(&image.file)?.is_some() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "unsupported nested ELF loader",
            ));
        }
        let expected = super::digest(&mut loader.bound_image(&staged.file, &image.path)?)?;
        let mut rewritten =
            images.stage_from(&mut loader.bound_image(&staged.file, &image.path)?)?;
        super::verify_image(&mut rewritten.file, expected)?;
        staged = rewritten;
        Some(image)
    } else {
        None
    };
    #[cfg(target_os = "macos")]
    let loader = interpreter::macho::loader(&staged.file)?;

    let mut command = std::process::Command::new(&staged.path);
    command.arg0(original);
    command
        .args(args)
        .env_clear()
        .envs(environment.iter())
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let (lease, scripts) = images.finish();
    #[cfg(target_os = "linux")]
    let script_fds: Vec<_> = scripts
        .iter()
        .map(|script| script.file.as_raw_fd())
        .collect();
    let checked = scripts.iter().chain([&staged]);
    #[cfg(target_os = "linux")]
    let checked = checked.chain(loader.iter());
    let paths = checked
        .map(image::ImagePath::new)
        .collect::<io::Result<Vec<_>>>()?;
    let guards = (lease.clone(), directory, staged, scripts, loader);
    let mut command = Command::from(command);
    command.kill_on_drop(true);
    let command = ResolvedCommand::verified(command, move || {
        // Keep these descriptors (including the working directory) and any private
        // stage live even if a supervisor hands off or cancels the spawn future.
        let _guards = &guards;
        paths.iter().try_for_each(image::ImagePath::check)?;
        // SAFETY: fchdir and fcntl take live descriptors owned by the binding.
        unsafe {
            if libc::fchdir(cwd_fd) == -1 {
                return Err(io::Error::last_os_error());
            }
            #[cfg(target_os = "linux")]
            for &fd in &script_fds {
                if libc::fcntl(fd, libc::F_SETFD, 0) == -1 {
                    return Err(io::Error::last_os_error());
                }
            }
        }
        Ok(())
    });
    Ok(Prepared { command, lease })
}

#[cfg(not(target_os = "linux"))]
fn staging_parent() -> io::Result<std::path::PathBuf> {
    use std::os::unix::fs::MetadataExt;

    // A writable ancestor could let a different user replace a whole staging subtree.
    // Canonicalize first, then walk from the filesystem root without following links.
    let home = std::env::home_dir()
        .ok_or(io::ErrorKind::NotFound)?
        .canonicalize()?;
    let components = home.ancestors().collect::<Vec<_>>();
    let user = rustix::process::geteuid().as_raw();
    // No group/other write bit; the superuser (including system-owned roots) is trusted.
    const SHARED_WRITE: u32 = 0o022;
    const ROOT_USER: u32 = 0;
    for path in components.into_iter().rev() {
        let directory = open_verified_directory(path)?;
        let metadata = directory.metadata()?;
        if (metadata.uid() != user && (metadata.uid() != ROOT_USER || path == home))
            || metadata.mode() & SHARED_WRITE != 0
        {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "executable staging requires protected home directory ancestors",
            ));
        }
        #[cfg(target_os = "macos")]
        if !super::super::private::macos::has_no_grants(&directory)? {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "executable staging requires protected home directory ACLs",
            ));
        }
    }
    Ok(home)
}