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
//! File capabilities: what a program gains from its file when it is run,
//! kept in the `security.capability` extended attribute.

use super::CapabilitySet;
use crate::{AsHandle, AsPath, ErrorKind, Result, sys};

/// The name of the extended attribute.
const NAME: &[u8] = b"security.capability";

// `include/uapi/linux/capability.h`. Every field is a little-endian
// number of 32 bits, on every architecture.
const VFS_CAP_REVISION_MASK: u32 = 0xff00_0000;
const VFS_CAP_FLAGS_EFFECTIVE: u32 = 1;
const VFS_CAP_REVISION_1: u32 = 0x0100_0000;
const VFS_CAP_REVISION_2: u32 = 0x0200_0000;
const VFS_CAP_REVISION_3: u32 = 0x0300_0000;

/// `struct vfs_cap_data` as revision 1 had it: the flags and one pair of
/// sets of 32 bits.
const SIZE_1: usize = 12;
/// `struct vfs_cap_data`: the flags and two pairs.
const SIZE_2: usize = 20;
/// `struct vfs_ns_cap_data`: the same, and the user that is root of the
/// user namespace the capabilities are for.
const SIZE_3: usize = 24;

/// `struct vfs_ns_cap_data`, the largest of the three.
#[repr(C)]
#[allow(dead_code)]
struct VfsNsCapData {
    magic_etc: u32,
    /// Permitted and inheritable: the low halves, then the high ones.
    data: [[u32; 2]; 2],
    rootid: u32,
}

const _: () = assert!(size_of::<VfsNsCapData>() == SIZE_3);

/// The capabilities of a program file: the value of its
/// `security.capability` extended attribute, which the kernel reads when
/// the file is run.
///
/// With `P` and `I` the sets of the file, and `P'` those of the process
/// after `execve`:
///
/// - `P'(permitted) = (P(inheritable) & I) | (P & bounding set) |
///   P'(ambient)`: the file's permitted set is given outright, within the
///   bounding set, and its inheritable set lets through what the process
///   already holds as inheritable;
/// - `P'(effective)` is `P'(permitted)` if [`effective`](Self::effective)
///   is set, and the ambient set otherwise: a program that does not know
///   about capabilities needs the bit, one that raises them itself does
///   not.
///
/// If the bit is set and the process cannot get all of the file's
/// permitted set (the bounding set lacks one), `execve` fails with
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied). None of this
/// applies on a filesystem mounted `nosuid`, nor to a process that set
/// [`set_no_new_privileges`](super::set_no_new_privileges): the file is
/// then run as if it had no capabilities. The kernel removes the attribute
/// when the file is written to or changes owner.
///
/// # The root identifier
///
/// A value written in a user namespace other than the initial one is for
/// that namespace only: the kernel records the user that is root there
/// ([`root_id`](Self::root_id), revision 3 of the format), and the
/// capabilities are granted to processes of that namespace and of those
/// below it, and to no other. The kernel converts as it goes:
///
/// - who writes from within a user namespace writes no identifier, and
///   the kernel adds the one of the root of the writer's namespace;
/// - who reads from within the namespace the value is for sees no
///   identifier; who reads from above sees it, as the user is called in
///   the reader's namespace;
/// - a process with `CAP_SETFCAP` in the initial namespace may write any
///   identifier, to prepare the files of a container whose root that user
///   will be.
///
/// The fields are public and the structure may grow: build one with
/// [`new`](Self::new).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct FileCapabilities {
    /// The capabilities the program gets, within the bounding set of the
    /// process that runs it.
    pub permitted: CapabilitySet,
    /// The capabilities the program keeps of the inheritable set of the
    /// process that runs it.
    pub inheritable: CapabilitySet,
    /// Whether the program starts with its permitted capabilities in
    /// effect (`VFS_CAP_FLAGS_EFFECTIVE`).
    pub effective: bool,
    /// The user that is root of the user namespace the capabilities are
    /// for, as the caller's namespace calls it; `None` when they are for
    /// the namespace of the caller, or for every namespace.
    pub root_id: Option<u32>,
}

impl FileCapabilities {
    /// The longest value [`to_bytes`](Self::to_bytes) writes.
    pub const MAX_LEN: usize = SIZE_3;

    /// Capabilities with no root identifier.
    pub const fn new(
        permitted: CapabilitySet,
        inheritable: CapabilitySet,
        effective: bool,
    ) -> Self {
        Self {
            permitted,
            inheritable,
            effective,
            root_id: None,
        }
    }

    /// The same for the user namespace whose root is the user `root_id`.
    pub const fn with_root_id(mut self, root_id: u32) -> Self {
        self.root_id = Some(root_id);
        self
    }

    /// Reads the value of a `security.capability` attribute: revisions 1
    /// (sets of 32 bits), 2 and 3 (with a root identifier) of
    /// `struct vfs_cap_data`.
    ///
    /// # Errors
    ///
    /// [`InvalidInput`](crate::ErrorKind::InvalidInput) for a revision
    /// that is none of the three, and for a length that is not the one of
    /// its revision.
    pub fn from_bytes(value: &[u8]) -> Result<Self> {
        let word = |index: usize| {
            let bytes = value.get(4 * index..4 * index + 4)?;
            Some(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
        };
        let invalid = || crate::Error::from(ErrorKind::InvalidInput);
        let magic = word(0).ok_or_else(invalid)?;
        let (len, halves) = match magic & VFS_CAP_REVISION_MASK {
            VFS_CAP_REVISION_1 => (SIZE_1, 1),
            VFS_CAP_REVISION_2 => (SIZE_2, 2),
            VFS_CAP_REVISION_3 => (SIZE_3, 2),
            _ => return Err(invalid()),
        };
        if value.len() != len {
            return Err(invalid());
        }
        let mut sets = [0u64; 2];
        for half in 0..halves {
            for (set, bits) in sets.iter_mut().enumerate() {
                let part = word(1 + 2 * half + set).ok_or_else(invalid)?;
                *bits |= u64::from(part) << (32 * half);
            }
        }
        Ok(Self {
            permitted: CapabilitySet::from_bits(sets[0]),
            inheritable: CapabilitySet::from_bits(sets[1]),
            effective: magic & VFS_CAP_FLAGS_EFFECTIVE != 0,
            root_id: if len == SIZE_3 { word(5) } else { None },
        })
    }

    /// Writes the value of the attribute into `buf`, and returns it:
    /// revision 3 (24 bytes) with a root identifier, revision 2 (20
    /// bytes) without.
    pub fn to_bytes<'b>(&self, buf: &'b mut [u8; Self::MAX_LEN]) -> &'b [u8] {
        let (revision, len) = match self.root_id {
            Some(_) => (VFS_CAP_REVISION_3, SIZE_3),
            None => (VFS_CAP_REVISION_2, SIZE_2),
        };
        let (permitted, inheritable) = (self.permitted.bits(), self.inheritable.bits());
        let words = [
            revision
                | if self.effective {
                    VFS_CAP_FLAGS_EFFECTIVE
                } else {
                    0
                },
            permitted as u32,
            inheritable as u32,
            (permitted >> 32) as u32,
            (inheritable >> 32) as u32,
            self.root_id.unwrap_or(0),
        ];
        for (bytes, word) in buf.as_chunks_mut::<4>().0.iter_mut().zip(words) {
            *bytes = word.to_le_bytes();
        }
        &buf[..len]
    }
}

/// What a read of the attribute returned.
fn parse(value: &[u8; 64], len: Option<usize>) -> Result<Option<FileCapabilities>> {
    match len {
        None => Ok(None),
        Some(len) => {
            let value = value.get(..len).ok_or(ErrorKind::InvalidInput)?;
            FileCapabilities::from_bytes(value).map(Some)
        }
    }
}

/// The capabilities of the program file `path`, following symbolic links;
/// `None` if it has none. Reads the `security.capability` extended
/// attribute ([`fs::unix::get_xattr`](crate::fs::unix::get_xattr)).
///
/// # Errors
///
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) for a value that is
/// not one the kernel writes; [`Unsupported`](crate::ErrorKind::Unsupported)
/// on a filesystem without such attributes.
pub fn file_capabilities<P: AsPath + ?Sized>(path: &P) -> Result<Option<FileCapabilities>> {
    let mut value = [0u8; 64];
    let len = sys::fs::xattr::get(path.as_path_bytes(), NAME, &mut value, true)?;
    parse(&value, len)
}

/// As [`file_capabilities`], for an open file.
pub fn handle_file_capabilities(handle: impl AsHandle) -> Result<Option<FileCapabilities>> {
    let mut value = [0u8; 64];
    let len = sys::fs::xattr::fget(handle.as_handle(), NAME, &mut value)?;
    parse(&value, len)
}

/// Sets the capabilities of the program file `path`, following symbolic
/// links: writes its `security.capability` extended attribute.
///
/// See [`FileCapabilities`] for what the kernel makes of the root
/// identifier, and for when the capabilities are ignored. The kernel
/// stores the attribute on what it is given (a directory takes one,
/// measured on xfs), and only ever reads it from a file it runs.
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) without
/// `CAP_SETFCAP`: in the user namespace of the filesystem to write a root
/// identifier, and otherwise in a user namespace that maps the owner and
/// the group of the file;
/// [`Unsupported`](crate::ErrorKind::Unsupported) on a filesystem without
/// such attributes.
pub fn set_file_capabilities<P: AsPath + ?Sized>(
    path: &P,
    capabilities: &FileCapabilities,
) -> Result<()> {
    let mut buf = [0u8; FileCapabilities::MAX_LEN];
    let value = capabilities.to_bytes(&mut buf);
    let mode = crate::fs::unix::XattrMode::Any;
    sys::fs::xattr::set(path.as_path_bytes(), NAME, value, mode, true)
}

/// As [`set_file_capabilities`], for an open file.
pub fn set_handle_file_capabilities(
    handle: impl AsHandle,
    capabilities: &FileCapabilities,
) -> Result<()> {
    let mut buf = [0u8; FileCapabilities::MAX_LEN];
    let value = capabilities.to_bytes(&mut buf);
    let mode = crate::fs::unix::XattrMode::Any;
    sys::fs::xattr::fset(handle.as_handle(), NAME, value, mode)
}

/// Removes the capabilities of the program file `path`, following symbolic
/// links. Returns whether it had any.
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) without
/// `CAP_SETFCAP`, as for [`set_file_capabilities`]: also when the file has
/// none, the kernel asking before it looks.
pub fn remove_file_capabilities<P: AsPath + ?Sized>(path: &P) -> Result<bool> {
    removed(sys::fs::xattr::remove(path.as_path_bytes(), NAME, true))
}

/// As [`remove_file_capabilities`], for an open file.
pub fn remove_handle_file_capabilities(handle: impl AsHandle) -> Result<bool> {
    removed(sys::fs::xattr::fremove(handle.as_handle(), NAME))
}

/// Whether there was an attribute to remove.
fn removed(result: Result<()>) -> Result<bool> {
    match result {
        Ok(()) => Ok(true),
        Err(error) if error.raw_os_error() == sys::errno::ENODATA => Ok(false),
        Err(error) => Err(error),
    }
}