cloudfox-coreshift-core 2.33.0

Low-level Linux and Android systems primitives for CoreShift (CloudFox)
Documentation
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/

//! Low-level process management primitives.
//!
//! Safe wrappers around `fork`, `setsid`, `setpgid`, `dup2`, `prctl`,
//! and fd-range close — building blocks for double-fork supervisor patterns.

use crate::CoreError;
use crate::error::syscall_ret;

/// Result of a [`fork`] call.
pub enum ForkResult {
    /// Returned in the parent with the child's PID.
    Parent(i32),
    /// Returned in the child (PID = 0).
    Child,
}

/// Fork the current process.
///
/// # Safety
/// After `fork`, only async-signal-safe operations are safe in the child
/// before `exec`. Rust's allocator is not async-signal-safe; use this only
/// in the narrow pattern of fork → exec or fork → immediate `_exit`.
pub unsafe fn fork() -> Result<ForkResult, CoreError> {
    let pid = unsafe { libc::fork() };
    if pid < 0 {
        return Err(CoreError::sys(
            std::io::Error::last_os_error().raw_os_error().unwrap_or(-1),
            "fork",
        ));
    }
    if pid == 0 {
        Ok(ForkResult::Child)
    } else {
        Ok(ForkResult::Parent(pid))
    }
}

/// Create a new session and set the calling process as leader.
pub fn setsid() -> Result<(), CoreError> {
    let ret = unsafe { libc::setsid() };
    if ret < 0 {
        return Err(CoreError::sys(
            std::io::Error::last_os_error().raw_os_error().unwrap_or(-1),
            "setsid",
        ));
    }
    Ok(())
}

/// Set the process group ID of `pid` to `pgid` (use 0 for self).
pub fn setpgid(pid: i32, pgid: i32) -> Result<(), CoreError> {
    syscall_ret(unsafe { libc::setpgid(pid, pgid) }, "setpgid")
}

/// Redirect stdin, stdout, and stderr to `/dev/null`.
///
/// # Safety
/// Uses `dup2` on file descriptors 0/1/2.
pub unsafe fn redirect_stdio_to_devnull() -> Result<(), CoreError> {
    let fd = unsafe { libc::open(c"/dev/null".as_ptr(), libc::O_RDWR) };
    if fd < 0 {
        return Err(CoreError::sys(
            std::io::Error::last_os_error().raw_os_error().unwrap_or(-1),
            "open:/dev/null",
        ));
    }
    unsafe {
        libc::dup2(fd, 0);
        libc::dup2(fd, 1);
        libc::dup2(fd, 2);
        if fd > 2 {
            libc::close(fd);
        }
    }
    Ok(())
}

/// Set the signal sent to this process when its **parent thread** dies
/// (`PR_SET_PDEATHSIG`).
///
/// Precision: the signal is delivered when the parent *thread that created
/// this task* exits (`forget_original_parent` runs on every thread's
/// `do_exit`), not when the parent process dies — in a thread-pool caller a
/// worker-thread exit kills its children while the process lives. The signal
/// is retained across exec except under `bprm->secureexec`. For spawn
/// wiring (which is opt-in and leader-only) see
/// [`SpawnOptionsBuilder::pdeath_signal`](crate::spawn::SpawnOptionsBuilder::pdeath_signal).
pub fn set_pdeathsig(sig: i32) -> Result<(), CoreError> {
    syscall_ret(
        unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, sig as libc::c_ulong, 0, 0, 0) },
        "prctl:PR_SET_PDEATHSIG",
    )
}

/// Set the process's `PR_SET_DUMPABLE` flag.
///
/// `dumpable = false` is daemon self-hardening (A17-02): the process cannot
/// produce core dumps and its `/proc/self` memory is not readable by children
/// via `process_vm_readv`/`pidfd_getfd`. Used together with
/// [`set_ptracer`] to make a privileged daemon resistant to child tracing.
/// The flag is inherited by `fork` children, which is fine for the exec jobs
/// (they drop privileges under `setresuid` anyway).
///
/// ### Errors
/// - `EINVAL`: unsupported `PR_SET_DUMPABLE` value (only 0/1 are valid).
pub fn set_dumpable(dumpable: bool) -> Result<(), CoreError> {
    syscall_ret(
        unsafe { libc::prctl(libc::PR_SET_DUMPABLE, dumpable as libc::c_ulong, 0, 0, 0) },
        "prctl:PR_SET_DUMPABLE",
    )
}

/// Restrict which processes may ptrace this one (`PR_SET_PTRACER`).
///
/// `pid = 0` denies all tracing — the strongest setting and the one the
/// daemon uses (A17-02). This is an additional per-process restriction that
/// works even where YAMA is not compiled (`CONFIG_SECURITY_YAMA` unset): a
/// child cannot `ptrace`/`pidfd_getfd`/`process_vm_readv` the daemon.
///
/// **Platform caveat (verified on the audit target, an Android 5.10 kernel):
/// `PR_SET_PTRACER` is implemented under `CONFIG_CHECKPOINT_RESTORE`, which
/// Android kernels build without — the prctl then returns `EINVAL` for every
/// argument.** Callers must treat `EINVAL` as "unsupported, proceed with
/// `PR_SET_DUMPABLE=0` + self-seccomp as the actual protection" and only fail
/// hard on unexpected errors. See the daemon's hub hook for the tolerant
/// wrapper.
///
/// ### Errors
/// - `EINVAL`: unsupported on this kernel (no `CONFIG_CHECKPOINT_RESTORE`).
pub fn set_ptracer(pid: i32) -> Result<(), CoreError> {
    syscall_ret(
        unsafe { libc::prctl(libc::PR_SET_PTRACER, pid as libc::c_ulong, 0, 0, 0) },
        "prctl:PR_SET_PTRACER",
    )
}

/// Set this thread's name (`PR_SET_NAME`, the `comm` field visible in
/// `/proc/<pid>/task/<tid>/comm`, capped at 15 bytes + NUL).
///
/// Threads created by `std::thread` inherit the process comm unless named, so a
/// daemon that spawns several worker threads ends up with indistinguishable
/// names. Naming each thread makes `/proc`/`ps`/strace output actionable
/// (e.g. `coreshift_fg` vs `coreshift_fps`).
///
/// ### Errors
/// - `EINVAL`/`EFAULT`: unsupported name (truncated at 15 bytes, never a
///   failure — this is best-effort diagnostics).
pub fn set_thread_name(name: &str) -> Result<(), CoreError> {
    let mut buf = [0u8; 16];
    let bytes = name.as_bytes();
    let n = bytes.len().min(15);
    buf[..n].copy_from_slice(&bytes[..n]);
    syscall_ret(
        unsafe { libc::prctl(libc::PR_SET_NAME, buf.as_ptr() as libc::c_ulong, 0, 0, 0) },
        "prctl:PR_SET_NAME",
    )
}

/// Duplicate `src_fd` onto `dst_fd` and close `src_fd`.
///
/// Equivalent to `dup2(src_fd, dst_fd); close(src_fd)`.
///
/// # Safety
/// Manipulates raw file descriptors.
pub unsafe fn redirect_fd_to(src_fd: i32, dst_fd: i32) {
    unsafe {
        libc::dup2(src_fd, dst_fd);
        // CORE-M8: when src == dst, `dup2` is a no-op and `close(src_fd)`
        // would close the very fd meant to be kept.
        if src_fd != dst_fd {
            libc::close(src_fd);
        }
    }
}

pub fn getuid() -> u32 {
    unsafe { libc::getuid() }
}
pub fn getgid() -> u32 {
    unsafe { libc::getgid() }
}

/// Drop process privileges to the given UID (`setresuid`).
///
/// Sets real, effective, and saved UID to `uid`.
pub fn setuid(uid: u32) -> Result<(), CoreError> {
    syscall_ret(unsafe { libc::setresuid(uid, uid, uid) }, "setresuid")
}

/// Drop process privileges to the given GID (`setresgid`).
///
/// Sets real, effective, and saved GID to `gid`.
pub fn setgid(gid: u32) -> Result<(), CoreError> {
    syscall_ret(unsafe { libc::setresgid(gid, gid, gid) }, "setresgid")
}

/// Close all file descriptors >= `start`.
///
/// Enumerates `/proc/self/fd` to avoid EBADF on sparse fd tables.
/// Falls back to a blind 3..1024 scan if `/proc/self/fd` is unreadable.
pub fn close_fds_from(start: i32) {
    // Open the dir handle ourselves so we own its fd: `std::fs::read_dir` hides
    // it, and its dirfd is listed in `/proc/self/fd`, so a naive snapshot that
    // includes it would close it mid-iteration and again on drop
    // (double-close → in a multithreaded daemon the fd can be reused and an
    // unrelated socket/log fd gets closed, finding 12).
    let dir = unsafe { libc::opendir(c"/proc/self/fd".as_ptr()) };
    if dir.is_null() {
        for fd in start..1024 {
            unsafe { libc::close(fd) };
        }
        return;
    }
    let dir_fd = unsafe { libc::dirfd(dir) };
    let mut fds = Vec::new();
    loop {
        // readdir is not thread-safe against a concurrent close of the fd it is
        // reading, but this runs in a forked single-threaded child; the fd
        // snapshot is taken before any close happens below.
        let ent = unsafe { libc::readdir(dir) };
        if ent.is_null() {
            break;
        }
        let name = unsafe { (*ent).d_name.as_ptr() };
        let name = unsafe { std::ffi::CStr::from_ptr(name) };
        let Ok(name) = name.to_str() else { continue };
        if let Ok(fd) = name.parse::<i32>()
            && fd >= start
            && fd != dir_fd
        {
            fds.push(fd);
        }
    }
    // Close the dir handle first so its fd is never in the close set, then
    // close the snapshot.
    unsafe { libc::closedir(dir) };
    for fd in fds {
        unsafe { libc::close(fd) };
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn set_dumpable_round_trips() {
        // The flag is process-wide and inherits across fork, so save/restore
        // around the test to keep the suite's own behaviour stable.
        let saved = unsafe { libc::prctl(libc::PR_GET_DUMPABLE, 0, 0, 0, 0) };
        set_dumpable(false).unwrap();
        assert_eq!(unsafe { libc::prctl(libc::PR_GET_DUMPABLE, 0, 0, 0, 0) }, 0);
        set_dumpable(true).unwrap();
        assert_eq!(unsafe { libc::prctl(libc::PR_GET_DUMPABLE, 0, 0, 0, 0) }, 1);
        if saved >= 0 {
            unsafe { libc::prctl(libc::PR_SET_DUMPABLE, saved as libc::c_ulong, 0, 0, 0) };
        }
    }

    #[test]
    fn set_ptracer_is_ok_or_unsupported() {
        // PR_SET_PTRACER(0) denies all tracing. On kernels built without
        // CONFIG_CHECKPOINT_RESTORE (notably Android, where the audit target
        // kernel is 5.10) the prctl is unimplemented and fails EINVAL for every
        // argument. The daemon's contract is therefore: Ok on kernels that
        // support it, tolerated EINVAL on the rest — never a hard failure for
        // any other reason.
        match set_ptracer(0) {
            Ok(()) => {}
            Err(e) if e.raw_os_error() == Some(libc::EINVAL) => {}
            Err(e) => panic!("PR_SET_PTRACER(0) failed unexpectedly: {e}"),
        }
        // Restore the default where supported so the test runner itself is not
        // left locked down (PR_SET_PTRACER_ANY is 0xffff_ffff_ffff_ffff — not
        // reachable via a signed i32, hence the direct prctl).
        unsafe {
            libc::prctl(libc::PR_SET_PTRACER, libc::PR_SET_PTRACER_ANY, 0, 0, 0);
        };
    }
}