stratum-node-cli 0.1.0-alpha.1

The `stratum` operator client for Stratum pod nodes: operator key files, bootstrap claim, signed config apply, audit checkpoint and backup over the loopback API
Documentation
//! Exclusive creation and checked reading of files that hold secrets.

use std::fs::{self, File, OpenOptions};
use std::io::{self, Read as _, Write as _};
use std::os::unix::fs::{MetadataExt as _, OpenOptionsExt as _};
use std::path::Path;

use rustix::fs::{Mode, OFlags};
use rustix::io::Errno;
use rustix::process::geteuid;
use zeroize::Zeroizing;

/// The permission bits a private file is created with.
const PRIVATE_MODE: u32 = 0o600;

/// Permission bits that must be clear on a private file: any access by the
/// group or by others.
const GROUP_OTHER_BITS: u32 = 0o077;

/// Why a private file could not be created or read.
///
/// No variant carries any part of the file's contents.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum PrivateFileError {
    /// The file exists and is never overwritten.
    #[error("file already exists and will not be overwritten")]
    AlreadyExists,
    /// The path is a symbolic link, which is refused for secret files.
    #[error("file is a symbolic link")]
    Symlink,
    /// The path is not a regular file.
    #[error("file is not a regular file")]
    NotRegularFile,
    /// The file grants access to its group or to others.
    #[error("file mode {mode:04o} is wider than 0600")]
    TooPermissive {
        /// The file's permission bits.
        mode: u32,
    },
    /// The file is larger than its format allows.
    #[error("file is larger than {limit} bytes")]
    TooLarge {
        /// The largest accepted size in bytes.
        limit: usize,
    },
    /// The file belongs to another user. Checked only for files that must
    /// be the operator's own, such as the key file, and not when running as
    /// root.
    #[error("file is owned by uid {uid}, not by the user running stratum")]
    WrongOwner {
        /// The file's owner.
        uid: u32,
    },
    /// An operating-system error.
    #[error("{0}")]
    Io(#[source] io::Error),
}

/// Policy for the permission bits of a file being read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ModePolicy {
    /// Refuse a file that grants any access to group or others.
    OwnerOnly,
    /// Accept any mode (the file belongs to someone else, such as the node).
    Any,
}

/// Reads a regular file of at most `limit` bytes into zeroising memory.
///
/// The file is opened once, with `O_NOFOLLOW` (a symbolic link in the
/// last component is refused by the kernel), `O_NONBLOCK` (opening a FIFO
/// or device returns at once instead of waiting for a writer) and
/// `O_CLOEXEC`. Its type, mode and owner are then checked on the open
/// descriptor, so nothing can be swapped in between a check and the open.
/// Under [`ModePolicy::OwnerOnly`] a mode wider than `0600`, or an owner
/// other than the effective user, is refused. The owner is not compared when
/// running as root (`sudo -E stratum setup` with the operator's own key
/// file): root can read the file anyway, and the trust boundary does not
/// defend against root.
pub(crate) fn read(
    path: &Path,
    limit: usize,
    policy: ModePolicy,
) -> Result<Zeroizing<Vec<u8>>, PrivateFileError> {
    let flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC;
    let fd = rustix::fs::open(path, flags, Mode::empty()).map_err(|errno| {
        if errno == Errno::LOOP {
            PrivateFileError::Symlink
        } else {
            PrivateFileError::Io(io::Error::from(errno))
        }
    })?;
    let file = File::from(fd);
    let opened = file.metadata().map_err(PrivateFileError::Io)?;
    if !opened.is_file() {
        return Err(PrivateFileError::NotRegularFile);
    }
    if policy == ModePolicy::OwnerOnly {
        let mode = opened.mode() & 0o7777;
        if mode & GROUP_OTHER_BITS != 0 {
            return Err(PrivateFileError::TooPermissive { mode });
        }
        let euid = geteuid();
        if !euid.is_root() && opened.uid() != euid.as_raw() {
            return Err(PrivateFileError::WrongOwner { uid: opened.uid() });
        }
    }
    let cap = u64::try_from(limit).map_or(u64::MAX, |n| n.saturating_add(1));
    let mut contents = Zeroizing::new(Vec::with_capacity(limit.saturating_add(1)));
    file.take(cap)
        .read_to_end(&mut contents)
        .map_err(PrivateFileError::Io)?;
    if contents.len() > limit {
        return Err(PrivateFileError::TooLarge { limit });
    }
    Ok(contents)
}

/// Creates `path` exclusively with mode `0600`, writes `contents` and syncs
/// the file and its directory.
///
/// The mode is set at creation, so the file is never readable by others,
/// and an existing file or symbolic link at `path` is never followed or
/// overwritten. A partly written file is removed.
pub(crate) fn create(path: &Path, contents: &[u8]) -> Result<(), PrivateFileError> {
    let mut file = OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(PRIVATE_MODE)
        .open(path)
        .map_err(|err| {
            if err.kind() == io::ErrorKind::AlreadyExists {
                PrivateFileError::AlreadyExists
            } else {
                PrivateFileError::Io(err)
            }
        })?;
    let written = file
        .write_all(contents)
        .and_then(|()| file.sync_all())
        .map_err(PrivateFileError::Io);
    if let Err(err) = written {
        drop(file);
        // Best effort: the error being returned is the one that matters.
        let _removed = fs::remove_file(path);
        return Err(err);
    }
    sync_parent(path);
    Ok(())
}

/// Removes a file and syncs its directory.
pub(crate) fn remove(path: &Path) -> Result<(), PrivateFileError> {
    fs::remove_file(path).map_err(PrivateFileError::Io)?;
    sync_parent(path);
    Ok(())
}

/// Syncs the directory holding `path` so a creation or removal is durable.
///
/// Best effort: some filesystems refuse to sync a directory, and the file
/// itself has already been synced.
fn sync_parent(path: &Path) {
    let parent = match path.parent() {
        Some(dir) if !dir.as_os_str().is_empty() => dir,
        _ => Path::new("."),
    };
    if let Ok(dir) = File::open(parent) {
        let _synced = dir.sync_all();
    }
}