artifactize-foundation 0.27.2

Native file, path and executable primitives for Artifactize.
Documentation
//! Staged Unix executable images.
use std::{
    fs::File,
    io::{self, Seek, SeekFrom},
    path::PathBuf,
};

#[cfg(target_os = "linux")]
use std::path::Path;

use super::super::Lease;

pub(super) struct Image {
    pub file: File,
    pub path: PathBuf,
}

pub(super) struct Images {
    scripts: Vec<Image>,
    #[cfg(not(target_os = "linux"))]
    directory: crate::platform::private::PrivateTempDir,
    #[cfg(not(target_os = "linux"))]
    count: usize,
}

impl Images {
    #[cfg(target_os = "linux")]
    pub fn new() -> Self {
        Self {
            scripts: Vec::new(),
        }
    }

    #[cfg(not(target_os = "linux"))]
    pub fn new() -> io::Result<Self> {
        let directory =
            super::private_tempdir_in("artifactize-verified-", &super::staging_parent()?)?;
        Ok(Self {
            scripts: Vec::new(),
            directory,
            count: 0,
        })
    }

    #[cfg(target_os = "linux")]
    pub fn stage(&mut self, source: &mut File) -> io::Result<Image> {
        source.seek(SeekFrom::Start(0))?;
        self.stage_from(source)
    }

    #[cfg(target_os = "linux")]
    pub fn stage_from(&self, source: &mut impl io::Read) -> io::Result<Image> {
        use rustix::fs::{MemfdFlags, memfd_create};
        use std::os::fd::AsRawFd;

        let mut file = File::from(memfd_create(
            c"artifactize-verified",
            MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING,
        )?);
        io::copy(source, &mut file)?;
        seal(&file)?;
        let path = PathBuf::from(format!("/proc/self/fd/{}", file.as_raw_fd()));
        check_proc_path(&file, &path)?;
        Ok(Image { file, path })
    }

    #[cfg(not(target_os = "linux"))]
    pub fn stage(&mut self, source: &mut File) -> io::Result<Image> {
        use std::os::unix::fs::PermissionsExt;
        // Remove owner-write permission before opening the image for exec.
        const OWNER_READ_EXECUTE: u32 = 0o500;
        let path = self.directory.path().join(format!("image-{}", self.count));
        self.count += 1;
        let mut target = super::create_private_file(&path)?;
        source.seek(SeekFrom::Start(0))?;
        io::copy(source, &mut target)?;
        target.set_permissions(std::fs::Permissions::from_mode(OWNER_READ_EXECUTE))?;
        drop(target);
        Ok(Image {
            file: super::open_executable(&path)?,
            path,
        })
    }

    pub fn retain_script(&mut self, script: Image) {
        self.scripts.push(script);
    }

    pub fn finish(self) -> (Lease, Vec<Image>) {
        #[cfg(target_os = "linux")]
        return (Lease::default(), self.scripts);
        #[cfg(not(target_os = "linux"))]
        (Lease::staged(self.directory), self.scripts)
    }
}

#[cfg(target_os = "linux")]
pub(super) fn seal(file: &File) -> io::Result<()> {
    use rustix::fs::{SealFlags, fcntl_add_seals};
    fcntl_add_seals(
        file,
        SealFlags::WRITE | SealFlags::SHRINK | SealFlags::GROW | SealFlags::SEAL,
    )?;
    Ok(())
}

#[cfg(target_os = "linux")]
fn check_proc_path(file: &File, path: &Path) -> io::Result<()> {
    use rustix::fs::{PROC_SUPER_MAGIC, fstatfs};
    // In a chroot /proc need not be procfs. Reject a fake descriptor directory
    // even if it currently leads to equivalent bytes. Unprivileged users cannot
    // replace a root-owned procfs mount or redirect its per-process magic links.
    super::interpreter::check(&super::open_verified_directory(Path::new("/"))?)?;
    let proc = super::open_verified_directory(Path::new("/proc"))?;
    let fds = super::open_verified_directory(Path::new("/proc/self/fd"))?;
    let resolved = File::open(path)?;
    if fstatfs(&proc)?.f_type == PROC_SUPER_MAGIC
        && fstatfs(&fds)?.f_type == PROC_SUPER_MAGIC
        && super::file_identity(file)? == super::file_identity(&resolved)?
    {
        Ok(())
    } else {
        Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            "verified launch requires native descriptor paths",
        ))
    }
}

pub(super) struct ImagePath {
    path: std::ffi::CString,
    expected: rustix::fs::Stat,
}

impl ImagePath {
    pub fn new(image: &Image) -> io::Result<Self> {
        use std::os::unix::ffi::OsStrExt;
        Ok(Self {
            path: std::ffi::CString::new(image.path.as_os_str().as_bytes())?,
            expected: rustix::fs::fstat(&image.file)?,
        })
    }

    /// Recheck the exact name in the child after admission, using only native syscalls.
    /// The verified file is a sealed descriptor on Linux and a private pathname on macOS.
    pub fn check(&self) -> io::Result<()> {
        use rustix::fs::{AtFlags, CWD, statat};

        #[cfg(target_os = "linux")]
        let flags = AtFlags::empty(); // Resolve the native descriptor link.
        #[cfg(target_os = "macos")]
        let flags = AtFlags::SYMLINK_NOFOLLOW;
        let expected = &self.expected;
        let actual = statat(CWD, self.path.as_c_str(), flags)?;
        if expected.st_dev == actual.st_dev
            && expected.st_ino == actual.st_ino
            && expected.st_size == actual.st_size
            && expected.st_mtime == actual.st_mtime
            && expected.st_mtime_nsec == actual.st_mtime_nsec
            && expected.st_ctime == actual.st_ctime
            && expected.st_ctime_nsec == actual.st_ctime_nsec
        {
            Ok(())
        } else {
            Err(io::Error::from_raw_os_error(libc::EACCES))
        }
    }
}