artifactize-foundation 0.27.1

Native file, path and executable primitives for Artifactize.
Documentation
//! Resolve interpreter names only through directories other OS users cannot replace.

use std::{
    collections::VecDeque,
    ffi::OsString,
    fs::{self, File},
    io,
    os::unix::fs::MetadataExt,
    path::{Component, Path, PathBuf},
};

pub(super) mod shebang;

/// Matches Linux's cap for symlink resolution (and bounds a cycle on other Unix hosts).
const MAX_LINKS: usize = 40;

pub(super) fn trusted(path: &Path) -> io::Result<(PathBuf, File)> {
    if !path.is_absolute() {
        return Err(unprotected());
    }
    let root = Path::new("/");
    #[cfg(target_os = "linux")]
    let kernel = open_without_magic_links(path)?;
    check(&super::open_verified_directory(root)?)?;
    let mut prefix = root.to_owned();
    let mut pending = components(path);
    let mut links = 0;
    while let Some(component) = pending.pop_front() {
        match component.as_encoded_bytes() {
            b"/" => {
                prefix = root.to_owned();
            }
            b".." => {
                prefix.pop();
            }
            _ => {
                let next = prefix.join(&component);
                // Every directory in prefix is already protected; only its trusted
                // owner (this user or the system) can replace this path component.
                let entry = fs::symlink_metadata(&next)?;
                if entry.is_symlink() {
                    if !trusted_owner(entry.uid()) {
                        return Err(unprotected());
                    }
                    links += 1;
                    if links > MAX_LINKS {
                        return Err(unprotected());
                    }
                    for component in components(&fs::read_link(next)?).into_iter().rev() {
                        pending.push_front(component);
                    }
                } else if pending.is_empty() {
                    let file = super::open_executable(&next)?;
                    check(&file)?;
                    #[cfg(target_os = "linux")]
                    if !super::same_file(&kernel, &next)? {
                        return Err(unprotected());
                    }
                    // Use the caller's spelling for this final check so component
                    // normalization cannot accidentally accept a non-file path.
                    #[cfg(target_os = "macos")]
                    if !super::same_file(&file, &fs::canonicalize(path)?)? {
                        return Err(unprotected());
                    }
                    const EXECUTE_BITS: u32 = 0o111;
                    if file.metadata()?.mode() & EXECUTE_BITS == 0 {
                        return Err(unprotected());
                    }
                    return Ok((next, file));
                } else {
                    check(&super::open_verified_directory(&next)?)?;
                    prefix = next;
                }
            }
        }
    }
    Err(unprotected())
}

fn components(path: &Path) -> VecDeque<OsString> {
    path.components()
        .filter(|component| *component != Component::CurDir)
        .map(|component| component.as_os_str().to_owned())
        .collect()
}

pub(super) fn check(file: &File) -> io::Result<()> {
    #[cfg(target_os = "linux")]
    {
        let filesystem = rustix::fs::fstatfs(file)?.f_type;
        // A user-supplied FUSE server can forge owner/mode for its inodes.
        if filesystem == libc::FUSE_SUPER_MAGIC as rustix::fs::FsWord
            || filesystem == rustix::fs::PROC_SUPER_MAGIC
        {
            return Err(unprotected());
        }
    }
    let metadata = file.metadata()?;
    // Only the current UID and the system are trusted to change the image or its name.
    // Linux POSIX ACLs include their effective group mask in the mode.
    const SHARED_WRITE: u32 = 0o022;
    if !trusted_owner(metadata.uid()) || metadata.mode() & SHARED_WRITE != 0 {
        return Err(unprotected());
    }
    #[cfg(target_os = "macos")]
    if is_descriptor_filesystem(file)? || !crate::platform::private::macos::has_no_grants(file)? {
        return Err(unprotected());
    }
    Ok(())
}

fn trusted_owner(uid: u32) -> bool {
    // A system administrator is not an unprivileged peer.
    const ROOT_USER: u32 = 0;
    uid == ROOT_USER || uid == rustix::process::geteuid().as_raw()
}

#[cfg(target_os = "macos")]
fn is_descriptor_filesystem(file: &File) -> io::Result<bool> {
    use std::{ffi::CStr, mem::MaybeUninit, os::fd::AsRawFd};
    let mut info = MaybeUninit::<libc::statfs>::uninit();
    // SAFETY: the descriptor remains open, fstatfs gets a full output buffer,
    // and the successful result contains a NUL-terminated filesystem type.
    unsafe {
        if libc::fstatfs(file.as_raw_fd(), info.as_mut_ptr()) != 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(matches!(
            CStr::from_ptr(info.assume_init().f_fstypename.as_ptr()).to_bytes(),
            b"devfs" | b"fdesc"
        ))
    }
}

fn unprotected() -> io::Error {
    io::Error::new(
        io::ErrorKind::PermissionDenied,
        "executable and its path must be protected from other users",
    )
}

#[cfg(target_os = "linux")]
fn open_without_magic_links(path: &Path) -> io::Result<File> {
    use rustix::fs::{CWD, Mode, OFlags, ResolveFlags, openat2};
    // Native lookup with the original spelling also rejects cwd-/process-dependent
    // procfs links, including ones reached by a conventional symlink or a bind mount.
    let fd = openat2(
        CWD,
        path,
        OFlags::PATH | OFlags::CLOEXEC,
        Mode::empty(),
        ResolveFlags::NO_MAGICLINKS,
    )?;
    Ok(fd.into())
}

#[cfg(target_os = "linux")]
pub(super) mod elf;
#[cfg(target_os = "macos")]
pub(super) mod macho;