oscall 0.1.0

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! What a child sets about itself before it runs its program, besides its
//! descriptors, its session and its directory: the file creation mask, the
//! resource limits, the identity and the parent death signal.
//!
//! The parent prepares a [`Setup`]; the child, which shares its memory and
//! may only make system calls, applies it.

use alloc::vec::Vec;

use super::{raw_limit, resource_number};
use crate::process::Command;
use crate::sys::syscall;
use crate::{ErrorKind, Result};

/// `PR_SET_PDEATHSIG` (`include/uapi/linux/prctl.h`).
const PR_SET_PDEATHSIG: usize = 1;

/// The highest signal number (`_NSIG`).
const SIGNALS: i32 = 64;

/// A resource and its `struct rlimit64`.
pub(super) type RawLimit = (usize, [u64; 2]);

/// What the child applies. The pointers are to memory of the parent, which
/// outlives the child's use of it.
pub(super) struct Setup {
    umask: Option<u32>,
    limits: *const RawLimit,
    limits_len: usize,
    /// The supplementary groups (`gid_t`, 32 bits) and their number.
    groups: Option<(*const u32, usize)>,
    gid: Option<u32>,
    uid: Option<u32>,
    /// The signal to receive when the parent is gone, and the parent.
    death_signal: Option<(usize, usize)>,
}

impl Setup {
    /// Checks and converts what `command` asks for. `limits` holds the
    /// converted limits, and must outlive the result.
    pub(super) fn new(command: &Command<'_>, limits: &mut Vec<RawLimit>) -> Result<Self> {
        let setup = &command.setup;
        if setup.umask.is_some_and(|mask| mask & !0o777 != 0) {
            return Err(ErrorKind::InvalidInput.into());
        }
        limits
            .try_reserve_exact(setup.limits.len())
            .map_err(|_| ErrorKind::OutOfMemory)?;
        for &(resource, limit) in setup.limits {
            limits.push((resource_number(resource), raw_limit(limit)?));
        }
        let death_signal = match command.linux.parent_death_signal {
            None => None,
            Some(signal) if (1..=SIGNALS).contains(&signal) => {
                // SAFETY: no argument, and the call cannot fail.
                let parent = unsafe { syscall!(GETPID) }?;
                Some((signal as usize, parent))
            }
            Some(_) => return Err(ErrorKind::InvalidInput.into()),
        };
        Ok(Self {
            umask: setup.umask,
            limits: limits.as_ptr(),
            limits_len: limits.len(),
            groups: setup.groups.map(|groups| (groups.as_ptr(), groups.len())),
            gid: setup.gid,
            uid: setup.uid,
            death_signal,
        })
    }

    /// Whether the child changes its user or its group. When either
    /// changes, the kernel marks the *memory* of the process as that of a
    /// process which changed identity (`commit_creds` sets the "dumpable"
    /// flag of the `mm` to `fs.suid_dumpable`, 0 by default): no core
    /// dump, no debugger, `/proc/<pid>` owned by root. A child that shares
    /// the caller's memory would leave that on the caller, for good
    /// (measured: `PR_GET_DUMPABLE` went from 1 to 0 in the parent). Such
    /// a child must have its own copy of the memory.
    pub(super) fn changes_identity(&self) -> bool {
        self.uid.is_some() || self.gid.is_some()
    }

    /// Applies the setup to the calling process, with system calls only.
    ///
    /// The calls that change the identity are the kernel's, which change
    /// the calling thread alone (a libc tells every thread): the child has
    /// one thread. On x86 and arm the calls without a suffix take 16-bit
    /// identifiers, and the `32` ones are those to use.
    ///
    /// # Safety
    ///
    /// The process must be a child that is about to call `execve`, with
    /// every signal blocked, and the memory the setup was made from must
    /// still be there.
    pub(super) unsafe fn apply(&self) -> Result<()> {
        // SAFETY: the pointers and lengths are those of live slices; the
        // calls change the calling process alone.
        unsafe {
            if let Some(mask) = self.umask {
                syscall!(UMASK, mask)?;
            }

            // Before the identity changes: raising a hard limit needs the
            // privilege the child may be about to give up.
            let mut i = 0;
            while i < self.limits_len {
                let (resource, limit) = &*self.limits.add(i);
                syscall!(PRLIMIT64, 0, *resource, limit.as_ptr(), 0)?;
                i += 1;
            }

            // The groups first, then the group, then the user: each needs
            // the privilege that changing the user gives up.
            if let Some((groups, len)) = self.groups {
                #[cfg(any(target_arch = "x86", target_arch = "arm"))]
                syscall!(SETGROUPS32, len, groups)?;
                #[cfg(not(any(target_arch = "x86", target_arch = "arm")))]
                syscall!(SETGROUPS, len, groups)?;
            }
            if let Some(gid) = self.gid {
                #[cfg(any(target_arch = "x86", target_arch = "arm"))]
                syscall!(SETGID32, gid)?;
                #[cfg(not(any(target_arch = "x86", target_arch = "arm")))]
                syscall!(SETGID, gid)?;
            }
            if let Some(uid) = self.uid {
                #[cfg(any(target_arch = "x86", target_arch = "arm"))]
                syscall!(SETUID32, uid)?;
                #[cfg(not(any(target_arch = "x86", target_arch = "arm")))]
                syscall!(SETUID, uid)?;
            }

            // After the identity: the kernel clears the setting whenever
            // the effective user or group changes.
            if let Some((signal, parent)) = self.death_signal {
                syscall!(PRCTL, PR_SET_PDEATHSIG, signal, 0, 0, 0)?;
                // The signal is for a parent that goes away from now on.
                // One that went before (the calling thread waits for this
                // child, but the process can be killed) left the child to
                // another parent: the signal is due. It is blocked, like
                // every signal here, and is delivered when the mask is
                // emptied, just before the program starts. A parent of 0
                // is one in another process namespace: nothing can be
                // told.
                let now = syscall!(GETPPID)?;
                if now != parent && now != 0 {
                    let own = syscall!(GETPID)?;
                    syscall!(KILL, own, signal)?;
                }
            }
        }
        Ok(())
    }
}