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
//! Landlock: a thread that gives up access to files, to ports and to other
//! processes, without any privilege.
//!
//! A *ruleset* names the kinds of access it is about (it *handles* them),
//! and holds rules that each allow some of them somewhere: under a
//! directory, on a port. A thread that restricts itself with a ruleset is
//! from then on refused every access the ruleset handles and no rule
//! allows. What the ruleset does not handle is as it was: a ruleset that
//! handles writing alone leaves reading to the permissions of files.
//!
//! ```no_run
//! # #[cfg(any(target_os = "linux", target_os = "fullrust"))] {
//! use oscall::fs::{self, OpenOptions};
//! use oscall::process::linux::{self, landlock};
//! use oscall::process::linux::landlock::{AccessFs, AccessNet, RestrictFlags, Scope};
//!
//! // Nothing is written from here on, except under `/tmp`.
//! let abi = landlock::abi_version()?;
//! let writing = AccessFs::WRITING & AccessFs::for_abi(abi);
//! let ruleset = landlock::create_ruleset(writing, AccessNet::empty(), Scope::empty())?;
//! let tmp = fs::open("/tmp", &OpenOptions::new().read(true).directory(true))?;
//! landlock::add_path_rule(&ruleset, &tmp, writing)?;
//! linux::set_no_new_privileges()?;
//! landlock::restrict_self(&ruleset, RestrictFlags::empty())?;
//! # }
//! # Ok::<(), oscall::Error>(())
//! ```
//!
//! # What a restriction is attached to
//!
//! As a [`seccomp`](super::seccomp) filter: to the calling **thread**, and
//! the threads and processes it creates afterwards, for good, across
//! `execve`. Restricting again adds a layer: an access is allowed when
//! every layer allows it (16 layers at most, `E2BIG` beyond). And like a
//! filter it wants a thread that may not gain privileges
//! ([`set_no_new_privileges`](super::set_no_new_privileges)), or
//! `CAP_SYS_ADMIN`. [`ConfineExt::landlock`](super::ConfineExt::landlock)
//! restricts a child alone, before its program starts.
//!
//! Files that are open stay open, with what they could do: a restriction
//! is about what is opened from then on. (Truncating and the `ioctl`s of
//! devices, which are done on open files, are decided when the file is
//! opened.)
//!
//! A thread that may not open files for writing may not open the null
//! device either: spawning a child with
//! [`Stdio::Null`](crate::process::Stdio::Null) then fails, unless a rule
//! allows `/dev/null`.
//!
//! # Versions
//!
//! Landlock grew, and says how far by a number: [`abi_version`]. A kernel
//! refuses ([`InvalidInput`](crate::ErrorKind::InvalidInput)) a ruleset
//! that handles a kind of access it does not know, since it could not
//! enforce it; [`AccessFs::for_abi`], [`AccessNet::for_abi`] and
//! [`Scope::for_abi`] are what a version knows, to mask a ruleset with.
//! What an older kernel cannot restrict is then not restricted: a program
//! decides whether that is good enough for it.
//!
//! | Version | Linux | What it added |
//! |---|---|---|
//! | 1 | 5.13 | files and directories: [`AccessFs::EXECUTE`] to [`AccessFs::MAKE_SYM`] |
//! | 2 | 5.19 | [`AccessFs::REFER`] |
//! | 3 | 6.2 | [`AccessFs::TRUNCATE`] |
//! | 4 | 6.7 | TCP ports: [`AccessNet`] |
//! | 5 | 6.10 | [`AccessFs::IOCTL_DEV`] |
//! | 6 | 6.12 | [`Scope`] |
//! | 7 | 6.15 | [`RestrictFlags`] |
//!
//! # What is needed of the system
//!
//! A kernel built with Landlock (`CONFIG_SECURITY_LANDLOCK`) and started
//! with it among its security modules (`/sys/kernel/security/lsm` lists
//! them): [`abi_version`] fails with
//! [`Unsupported`](crate::ErrorKind::Unsupported) otherwise, as it does
//! under an emulator that lacks the calls (qemu-user).

use crate::{AsHandle, OwnedHandle, Result, sys};

crate::macros::flags! {
    /// Kinds of access to files and directories: `LANDLOCK_ACCESS_FS_*`.
    ///
    /// In a rule for a directory, a right about files is for the files
    /// under it at any depth, and a right about a directory for it and
    /// those under it. A rule for a file that is not a directory can only
    /// hold the rights about files ([`AccessFs::FILE`]).
    pub struct AccessFs: u64 {
        /// Running a file as a program.
        const EXECUTE = 1;
        /// Opening a file for writing.
        const WRITE_FILE = 1 << 1;
        /// Opening a file for reading.
        const READ_FILE = 1 << 2;
        /// Listing a directory.
        const READ_DIR = 1 << 3;
        /// Removing an empty directory, or renaming one.
        const REMOVE_DIR = 1 << 4;
        /// Removing a file, or renaming one.
        const REMOVE_FILE = 1 << 5;
        /// Creating, renaming or linking a character device.
        const MAKE_CHAR = 1 << 6;
        /// Creating or renaming a directory.
        const MAKE_DIR = 1 << 7;
        /// Creating, renaming or linking a regular file.
        const MAKE_REG = 1 << 8;
        /// Creating, renaming or linking a Unix-domain socket.
        const MAKE_SOCK = 1 << 9;
        /// Creating, renaming or linking a FIFO.
        const MAKE_FIFO = 1 << 10;
        /// Creating, renaming or linking a block device.
        const MAKE_BLOCK = 1 << 11;
        /// Creating, renaming or linking a symbolic link.
        const MAKE_SYM = 1 << 12;
        /// Linking or renaming a file into another directory (version 2).
        /// A ruleset that does not handle it refuses it all the same:
        /// this is the one right that is denied unless handled *and*
        /// allowed.
        const REFER = 1 << 13;
        /// Truncating a file: `truncate`, `ftruncate`, and opening with
        /// truncation (version 3).
        const TRUNCATE = 1 << 14;
        /// The `ioctl`s of a character or block device, save those every
        /// file takes (version 5).
        const IOCTL_DEV = 1 << 15;
    }
}

impl AccessFs {
    /// The rights that a rule for a file may hold: those that are not
    /// about a directory.
    pub const FILE: Self = Self(
        Self::EXECUTE.0
            | Self::WRITE_FILE.0
            | Self::READ_FILE.0
            | Self::TRUNCATE.0
            | Self::IOCTL_DEV.0,
    );

    /// Everything that reads: files, directories, and running programs.
    pub const READING: Self = Self(Self::EXECUTE.0 | Self::READ_FILE.0 | Self::READ_DIR.0);

    /// Everything that changes what a filesystem holds: every right but
    /// those of [`READING`](Self::READING) and
    /// [`IOCTL_DEV`](Self::IOCTL_DEV).
    pub const WRITING: Self = Self(0x7fff & !Self::READING.0);

    /// The rights that version `abi` of Landlock knows
    /// ([`abi_version`]): empty for 0, all of them for a version newer
    /// than this list.
    pub const fn for_abi(abi: u32) -> Self {
        Self(match abi {
            0 => 0,
            1 => 0x1fff,
            2 => 0x3fff,
            3 | 4 => 0x7fff,
            _ => 0xffff,
        })
    }
}

crate::macros::flags! {
    /// Kinds of access to the network: `LANDLOCK_ACCESS_NET_*` (version
    /// 4). They are about TCP ports, of IPv4 and IPv6 alike; nothing else
    /// of the network is restricted.
    pub struct AccessNet: u64 {
        /// Binding a TCP socket to a port.
        const BIND_TCP = 1;
        /// Connecting a TCP socket to a port.
        const CONNECT_TCP = 1 << 1;
    }
}

impl AccessNet {
    /// The rights that version `abi` of Landlock knows.
    pub const fn for_abi(abi: u32) -> Self {
        Self(if abi >= 4 { 3 } else { 0 })
    }
}

crate::macros::flags! {
    /// What a restricted thread may no longer do to processes that are
    /// not restricted as it is: `LANDLOCK_SCOPE_*` (version 6). No rule
    /// allows any of it back.
    pub struct Scope: u64 {
        /// Connecting to an abstract Unix-domain socket that a process
        /// outside the restriction created.
        const ABSTRACT_UNIX_SOCKET = 1;
        /// Sending a signal to a process outside the restriction.
        const SIGNAL = 1 << 1;
    }
}

impl Scope {
    /// The scopes that version `abi` of Landlock knows.
    pub const fn for_abi(abi: u32) -> Self {
        Self(if abi >= 6 { 3 } else { 0 })
    }
}

crate::macros::flags! {
    /// What is logged of a restriction: the flags of [`restrict_self`]
    /// (version 7). A denied access is written to the audit log of the
    /// system, by default until the thread runs another program.
    pub struct RestrictFlags: u32 {
        /// Nothing is logged of what the thread is denied before it runs
        /// another program (`LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF`).
        const LOG_SAME_EXEC_OFF = 1;
        /// What is denied goes on being logged after the thread has run
        /// another program (`LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON`).
        const LOG_NEW_EXEC_ON = 1 << 1;
        /// Nothing is logged of what restrictions added later, on top of
        /// this one, deny (`LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF`).
        const LOG_SUBDOMAINS_OFF = 1 << 2;
    }
}

/// The version of Landlock the running kernel has, 1 or more:
/// `landlock_create_ruleset` with `LANDLOCK_CREATE_RULESET_VERSION`. See
/// the [module documentation](self#versions).
///
/// # Errors
///
/// [`Unsupported`](crate::ErrorKind::Unsupported) for a kernel without
/// Landlock (`ENOSYS`), one that has it switched off (`EOPNOTSUPP`), and
/// an emulator that lacks the call.
pub fn abi_version() -> Result<u32> {
    sys::process::landlock::abi_version()
}

/// The fixes the running kernel has for mistakes found in Landlock, one
/// bit each: `landlock_create_ruleset` with
/// `LANDLOCK_CREATE_RULESET_ERRATA` (Linux 6.15, and the older kernels
/// the fixes were brought to). The kernel's documentation lists them.
///
/// # Errors
///
/// As [`abi_version`]; [`InvalidInput`](crate::ErrorKind::InvalidInput)
/// on a kernel that does not answer the question.
pub fn errata() -> Result<u32> {
    sys::process::landlock::errata()
}

/// Creates a ruleset that handles these kinds of access, with no rule
/// yet: `landlock_create_ruleset` (Linux 5.13). Restricting a thread with
/// it as it is denies all of them, everywhere.
///
/// The handle is close-on-exec, and is what [`add_path_rule`],
/// [`add_port_rule`], [`restrict_self`] and
/// [`ConfineExt::landlock`](super::ConfineExt::landlock) take. It can be
/// kept, and used for several threads or children.
///
/// # Errors
///
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) for a right the
/// kernel does not know (mask with [`AccessFs::for_abi`] and its kin);
/// `ENOMSG` for a ruleset that handles nothing; `E2BIG` for network
/// rights or scopes on a kernel older than they are;
/// [`Unsupported`](crate::ErrorKind::Unsupported) as for
/// [`abi_version`].
pub fn create_ruleset(fs: AccessFs, net: AccessNet, scopes: Scope) -> Result<OwnedHandle> {
    sys::process::landlock::create_ruleset(fs, net, scopes)
}

/// Adds to `ruleset` a rule that allows the access `allowed` to the file
/// `parent` is open on, and, when it is a directory, to everything under
/// it: `landlock_add_rule` with `LANDLOCK_RULE_PATH_BENEATH`.
///
/// `parent` is any handle of the file or directory, whatever it was
/// opened for (`O_PATH` is enough). The rule is about that file, wherever
/// it is later moved or mounted, not about its name.
///
/// # Errors
///
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) for rights the
/// ruleset does not handle, and for rights about directories on a file
/// that is not one; `ENOMSG` for no right at all;
/// [`BadHandle`](crate::ErrorKind::BadHandle) for a handle that is not
/// open, or a `ruleset` that is not one (`EBADFD`).
pub fn add_path_rule<R, P>(ruleset: &R, parent: &P, allowed: AccessFs) -> Result<()>
where
    R: AsHandle + ?Sized,
    P: AsHandle + ?Sized,
{
    sys::process::landlock::add_path_rule(ruleset.as_handle(), parent.as_handle(), allowed)
}

/// Adds to `ruleset` a rule that allows the access `allowed` to the TCP
/// port `port`: `landlock_add_rule` with `LANDLOCK_RULE_NET_PORT`
/// (version 4). The port is the number as programs write it, not in
/// network byte order.
///
/// Binding to port 0 asks the system for any free port of its dynamic
/// range: a rule for port 0 allows that, and so every port of that range.
///
/// # Errors
///
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) for rights the
/// ruleset does not handle, and on a kernel older than the rule.
pub fn add_port_rule<R: AsHandle + ?Sized>(
    ruleset: &R,
    port: u16,
    allowed: AccessNet,
) -> Result<()> {
    sys::process::landlock::add_port_rule(ruleset.as_handle(), port, allowed)
}

/// Restricts the calling **thread** with `ruleset`, for good:
/// `landlock_restrict_self`. See the
/// [module documentation](self#what-a-restriction-is-attached-to) for
/// what that means, and for what the caller must have done first.
///
/// The ruleset is copied: rules added to it later are for the threads
/// restricted later.
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) without
/// [`set_no_new_privileges`](super::set_no_new_privileges) nor
/// `CAP_SYS_ADMIN`; `E2BIG` for a seventeenth layer;
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) for flags the kernel
/// does not know.
pub fn restrict_self<R: AsHandle + ?Sized>(ruleset: &R, flags: RestrictFlags) -> Result<()> {
    sys::process::landlock::restrict_self(ruleset.as_handle(), flags)
}