oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! `process::linux::seccomp`: installing a system call filter.
//!
//! The constants are those of `include/uapi/linux/seccomp.h`, `audit.h`
//! and `elf-em.h`.

use core::sync::atomic::{AtomicU8, Ordering};

use crate::process::linux::seccomp::{
    AddHandleFlags, FilterFlags, Instruction, ListenerFlags, Mode, Notification, NotificationSizes,
    Response, SyscallData,
};
use crate::sys::{errno, syscall};
use crate::{BorrowedHandle, ErrorKind, OwnedHandle, Result};

const SECCOMP_SET_MODE_STRICT: usize = 0;
const SECCOMP_SET_MODE_FILTER: usize = 1;
const SECCOMP_GET_NOTIF_SIZES: usize = 3;

const SECCOMP_FILTER_FLAG_TSYNC: usize = 1;
const SECCOMP_FILTER_FLAG_LOG: usize = 1 << 1;
const SECCOMP_FILTER_FLAG_SPEC_ALLOW: usize = 1 << 2;
pub(crate) const SECCOMP_FILTER_FLAG_NEW_LISTENER: usize = 1 << 3;
/// With `TSYNC`, a thread that cannot take the filter makes the call fail
/// with `ESRCH` instead of returning its identifier, which could not be
/// told from the descriptor of a listener.
const SECCOMP_FILTER_FLAG_TSYNC_ESRCH: usize = 1 << 4;
const SECCOMP_FILTER_FLAG_WAIT_KILLABLE_RECV: usize = 1 << 5;

pub(crate) const SECCOMP_USER_NOTIF_FLAG_CONTINUE: u32 = 1;
const SECCOMP_USER_NOTIF_FD_SYNC_WAKE_UP: usize = 1;
const SECCOMP_ADDFD_FLAG_SETFD: u32 = 1;
const SECCOMP_ADDFD_FLAG_SEND: u32 = 1 << 1;
/// The same on every architecture.
const O_CLOEXEC: u32 = 0o2000000;

// The requests of a listener: `_IOWR('!', 0, struct seccomp_notif)` and
// its kin. The six architectures supported encode a request the same way
// (`include/uapi/asm-generic/ioctl.h`): the direction in the two top
// bits, the size of the argument in the fourteen below, then the type and
// the number.
const IOC_WRITE: u32 = 1 << 30;
const IOC_READ: u32 = 2 << 30;
const fn request(direction: u32, number: u32, size: usize) -> u32 {
    direction | (size as u32) << 16 | (b'!' as u32) << 8 | number
}
const SECCOMP_IOCTL_NOTIF_RECV: u32 = request(IOC_READ | IOC_WRITE, 0, size_of::<Notification>());
const SECCOMP_IOCTL_NOTIF_SEND: u32 = request(IOC_READ | IOC_WRITE, 1, size_of::<Response>());
const SECCOMP_IOCTL_NOTIF_ID_VALID: u32 = request(IOC_WRITE, 2, size_of::<u64>());
const SECCOMP_IOCTL_NOTIF_ADDFD: u32 = request(IOC_WRITE, 3, size_of::<AddFd>());
const SECCOMP_IOCTL_NOTIF_SET_FLAGS: u32 = request(IOC_WRITE, 4, size_of::<u64>());

/// `struct seccomp_notif_addfd`.
#[repr(C)]
struct AddFd {
    id: u64,
    flags: u32,
    srcfd: u32,
    newfd: u32,
    newfd_flags: u32,
}

// The layouts of `include/uapi/linux/seccomp.h`. Their 64-bit members are
// all at multiples of eight: the alignment of `u64`, which is four on
// 32-bit x86, changes nothing.
const _: () = assert!(
    size_of::<SyscallData>() == 64
        && size_of::<Notification>() == 80
        && core::mem::offset_of!(Notification, data) == 16
        && core::mem::offset_of!(SyscallData, args) == 16
        && size_of::<Response>() == 24
        && size_of::<AddFd>() == 24
        && SECCOMP_IOCTL_NOTIF_RECV == 0xc050_2100
        && SECCOMP_IOCTL_NOTIF_SEND == 0xc018_2101
        && SECCOMP_IOCTL_NOTIF_ID_VALID == 0x4008_2102
        && SECCOMP_IOCTL_NOTIF_ADDFD == 0x4018_2103
        && SECCOMP_IOCTL_NOTIF_SET_FLAGS == 0x4008_2104
);

const PR_GET_SECCOMP: usize = 21;

/// `BPF_MAXINSNS`.
const MAX_INSTRUCTIONS: usize = 4096;

// `AUDIT_ARCH_*`: the ELF machine number, with a bit for 64 bits and a
// bit for little-endian.
const AUDIT_ARCH_64BIT: u32 = 0x8000_0000;
const AUDIT_ARCH_LE: u32 = 0x4000_0000;
pub(crate) const AUDIT_ARCH_X86: u32 = 3 | AUDIT_ARCH_LE;
pub(crate) const AUDIT_ARCH_ARM: u32 = 40 | AUDIT_ARCH_LE;
pub(crate) const AUDIT_ARCH_X86_64: u32 = 62 | AUDIT_ARCH_64BIT | AUDIT_ARCH_LE;
pub(crate) const AUDIT_ARCH_AARCH64: u32 = 183 | AUDIT_ARCH_64BIT | AUDIT_ARCH_LE;
pub(crate) const AUDIT_ARCH_RISCV32: u32 = 243 | AUDIT_ARCH_LE;
pub(crate) const AUDIT_ARCH_RISCV64: u32 = 243 | AUDIT_ARCH_64BIT | AUDIT_ARCH_LE;

/// The one of the target.
#[cfg(target_arch = "x86_64")]
pub(crate) const AUDIT_ARCH: u32 = AUDIT_ARCH_X86_64;
#[cfg(target_arch = "x86")]
pub(crate) const AUDIT_ARCH: u32 = AUDIT_ARCH_X86;
#[cfg(target_arch = "aarch64")]
pub(crate) const AUDIT_ARCH: u32 = AUDIT_ARCH_AARCH64;
#[cfg(target_arch = "arm")]
pub(crate) const AUDIT_ARCH: u32 = AUDIT_ARCH_ARM;
#[cfg(target_arch = "riscv64")]
pub(crate) const AUDIT_ARCH: u32 = AUDIT_ARCH_RISCV64;
#[cfg(target_arch = "riscv32")]
pub(crate) const AUDIT_ARCH: u32 = AUDIT_ARCH_RISCV32;

/// `struct sock_fprog`: the number of instructions, then a pointer to
/// them, aligned as a pointer is.
#[repr(C)]
pub(crate) struct Program {
    len: u16,
    filter: *const Instruction,
}

const _: () = assert!(
    size_of::<Instruction>() == 8
        && align_of::<Instruction>() == 4
        && size_of::<Program>() == 2 * size_of::<usize>()
);

impl Program {
    /// The program the kernel is given for `program`, which it borrows:
    /// the result must not outlive it.
    pub(crate) fn new(program: &[Instruction]) -> Result<Self> {
        // The kernel refuses both with this error.
        if program.is_empty() || program.len() > MAX_INSTRUCTIONS {
            return Err(ErrorKind::InvalidInput.into());
        }
        Ok(Self {
            len: program.len() as u16,
            filter: program.as_ptr(),
        })
    }

    /// `seccomp(SECCOMP_SET_MODE_FILTER)`. Only a system call.
    ///
    /// # Safety
    ///
    /// The instructions the program was made from must still be there.
    pub(crate) unsafe fn install(&self, flags: usize) -> Result<()> {
        // SAFETY: the kernel reads the structure and the instructions it
        // points to, which the caller keeps.
        unsafe { syscall!(SECCOMP, SECCOMP_SET_MODE_FILTER, flags, &raw const *self) }.map(drop)
    }

    /// The same with `SECCOMP_FILTER_FLAG_NEW_LISTENER`: the number of
    /// the descriptor of the listener. Only a system call.
    ///
    /// # Safety
    ///
    /// As [`install`](Self::install).
    pub(crate) unsafe fn install_listener(&self, flags: usize) -> Result<i32> {
        let flags = listener_flags(flags);
        // SAFETY: as for `install`.
        unsafe { syscall!(SECCOMP, SECCOMP_SET_MODE_FILTER, flags, &raw const *self) }
            .map(|fd| fd as i32)
    }
}

/// The flags of an installation that returns a listener.
const fn listener_flags(flags: usize) -> usize {
    let flags = flags | SECCOMP_FILTER_FLAG_NEW_LISTENER;
    // The kernel wants the two together, for the reason given above.
    if flags & SECCOMP_FILTER_FLAG_TSYNC != 0 {
        flags | SECCOMP_FILTER_FLAG_TSYNC_ESRCH
    } else {
        flags
    }
}

/// The `SECCOMP_FILTER_FLAG_*` of `flags`.
pub(crate) fn filter_flags(flags: FilterFlags) -> usize {
    let table = [
        (FilterFlags::ALL_THREADS, SECCOMP_FILTER_FLAG_TSYNC),
        (FilterFlags::LOG, SECCOMP_FILTER_FLAG_LOG),
        (
            FilterFlags::ALLOW_SPECULATION,
            SECCOMP_FILTER_FLAG_SPEC_ALLOW,
        ),
        (
            FilterFlags::WAIT_KILLABLE,
            SECCOMP_FILTER_FLAG_WAIT_KILLABLE_RECV,
        ),
    ];
    let mut raw = 0;
    for (flag, value) in table {
        if flags.contains(flag) {
            raw |= value;
        }
    }
    raw
}

pub(crate) fn install(program: &[Instruction], flags: FilterFlags) -> Result<()> {
    let program = Program::new(program)?;
    // SAFETY: the instructions are borrowed for the call.
    unsafe { program.install(filter_flags(flags)) }
}

pub(crate) fn install_listener(program: &[Instruction], flags: FilterFlags) -> Result<OwnedHandle> {
    let program = Program::new(program)?;
    // SAFETY: the instructions are borrowed for the call.
    let fd = unsafe { program.install_listener(filter_flags(flags)) }?;
    // SAFETY: the descriptor was just created (close-on-exec, as
    // listeners always are).
    Ok(unsafe { OwnedHandle::from_raw(fd) })
}

pub(crate) fn notification_sizes() -> Result<NotificationSizes> {
    // `struct seccomp_notif_sizes`.
    let mut sizes = [0u16; 3];
    // SAFETY: the kernel writes three numbers of 16 bits.
    unsafe { syscall!(SECCOMP, SECCOMP_GET_NOTIF_SIZES, 0, &raw mut sizes) }?;
    Ok(NotificationSizes {
        notification: sizes[0],
        response: sizes[1],
        data: sizes[2],
    })
}

/// Whether the kernel's notification fits the structure it is received
/// in: 0 while unknown, 1 if it does, 2 if not. A fact about the running
/// kernel, which cannot change.
static NOTIFICATION_FITS: AtomicU8 = AtomicU8::new(0);

/// Fails if the kernel would write more than a [`Notification`] holds.
fn check_notification_size() -> Result<()> {
    let known = match NOTIFICATION_FITS.load(Ordering::Relaxed) {
        0 => {
            let fits = usize::from(notification_sizes()?.notification) <= size_of::<Notification>();
            let known = if fits { 1 } else { 2 };
            NOTIFICATION_FITS.store(known, Ordering::Relaxed);
            known
        }
        known => known,
    };
    if known == 1 {
        Ok(())
    } else {
        Err(ErrorKind::Unsupported.into())
    }
}

/// `ioctl` on a listener, with a pointer.
///
/// # Safety
///
/// `arg` must point to what the request reads and writes.
unsafe fn listener_ioctl<T>(
    listener: BorrowedHandle<'_>,
    request: u32,
    arg: *mut T,
) -> Result<usize> {
    // SAFETY: the caller's contract.
    unsafe { syscall!(IOCTL, listener.as_raw(), request, arg) }
}

pub(crate) fn receive(listener: BorrowedHandle<'_>) -> Result<Notification> {
    check_notification_size()?;
    // The kernel refuses a structure that is not all zeroes.
    let mut notification = Notification::default();
    // SAFETY: the kernel writes one `struct seccomp_notif`, which was
    // checked to be no larger than this one.
    unsafe { listener_ioctl(listener, SECCOMP_IOCTL_NOTIF_RECV, &raw mut notification) }?;
    Ok(notification)
}

pub(crate) fn respond(listener: BorrowedHandle<'_>, response: &Response) -> Result<()> {
    let mut response = *response;
    // SAFETY: the kernel reads one `struct seccomp_notif_resp`.
    unsafe { listener_ioctl(listener, SECCOMP_IOCTL_NOTIF_SEND, &raw mut response) }.map(drop)
}

pub(crate) fn is_valid(listener: BorrowedHandle<'_>, id: u64) -> Result<bool> {
    let mut id = id;
    // SAFETY: the kernel reads one number of 64 bits.
    match unsafe { listener_ioctl(listener, SECCOMP_IOCTL_NOTIF_ID_VALID, &raw mut id) } {
        Ok(_) => Ok(true),
        Err(error) if error.raw_os_error() == errno::ENOENT => Ok(false),
        Err(error) => Err(error),
    }
}

pub(crate) fn add_handle(
    listener: BorrowedHandle<'_>,
    id: u64,
    handle: BorrowedHandle<'_>,
    at: Option<u32>,
    flags: AddHandleFlags,
) -> Result<u32> {
    let mut raw = 0;
    if at.is_some() {
        raw |= SECCOMP_ADDFD_FLAG_SETFD;
    }
    if flags.contains(AddHandleFlags::RESPOND) {
        raw |= SECCOMP_ADDFD_FLAG_SEND;
    }
    let mut add = AddFd {
        id,
        flags: raw,
        // A descriptor that is none is refused here, as the kernel would
        // of the number it becomes in an unsigned field.
        srcfd: u32::try_from(handle.as_raw()).map_err(|_| ErrorKind::BadHandle)?,
        newfd: at.unwrap_or(0),
        newfd_flags: if flags.contains(AddHandleFlags::CLOSE_ON_EXEC) {
            O_CLOEXEC
        } else {
            0
        },
    };
    // SAFETY: the kernel reads one `struct seccomp_notif_addfd`.
    unsafe { listener_ioctl(listener, SECCOMP_IOCTL_NOTIF_ADDFD, &raw mut add) }.map(|fd| fd as u32)
}

pub(crate) fn set_listener_flags(listener: BorrowedHandle<'_>, flags: ListenerFlags) -> Result<()> {
    let mut raw: usize = 0;
    if flags.contains(ListenerFlags::SYNC_WAKE_UP) {
        raw |= SECCOMP_USER_NOTIF_FD_SYNC_WAKE_UP;
    }
    // The request says it takes a pointer to a number of 64 bits; the
    // kernel takes the argument for the flags themselves.
    // SAFETY: no memory is involved.
    unsafe { syscall!(IOCTL, listener.as_raw(), SECCOMP_IOCTL_NOTIF_SET_FLAGS, raw) }.map(drop)
}

pub(crate) fn set_strict() -> Result<()> {
    // SAFETY: no memory is involved.
    unsafe { syscall!(SECCOMP, SECCOMP_SET_MODE_STRICT, 0, 0) }.map(drop)
}

pub(crate) fn mode() -> Result<Mode> {
    // SAFETY: no memory is involved.
    match unsafe { syscall!(PRCTL, PR_GET_SECCOMP, 0, 0, 0, 0) }? {
        0 => Ok(Mode::Disabled),
        1 => Ok(Mode::Strict),
        2 => Ok(Mode::Filter),
        _ => Err(ErrorKind::Other.into()),
    }
}