Skip to main content

stratum_node_cli/
private_file.rs

1//! Exclusive creation and checked reading of files that hold secrets.
2
3use std::fs::{self, File, OpenOptions};
4use std::io::{self, Read as _, Write as _};
5use std::os::unix::fs::{MetadataExt as _, OpenOptionsExt as _};
6use std::path::Path;
7
8use rustix::fs::{Mode, OFlags};
9use rustix::io::Errno;
10use rustix::process::geteuid;
11use zeroize::Zeroizing;
12
13/// The permission bits a private file is created with.
14const PRIVATE_MODE: u32 = 0o600;
15
16/// Permission bits that must be clear on a private file: any access by the
17/// group or by others.
18const GROUP_OTHER_BITS: u32 = 0o077;
19
20/// Why a private file could not be created or read.
21///
22/// No variant carries any part of the file's contents.
23#[derive(Debug, thiserror::Error)]
24#[non_exhaustive]
25pub enum PrivateFileError {
26    /// The file exists and is never overwritten.
27    #[error("file already exists and will not be overwritten")]
28    AlreadyExists,
29    /// The path is a symbolic link, which is refused for secret files.
30    #[error("file is a symbolic link")]
31    Symlink,
32    /// The path is not a regular file.
33    #[error("file is not a regular file")]
34    NotRegularFile,
35    /// The file grants access to its group or to others.
36    #[error("file mode {mode:04o} is wider than 0600")]
37    TooPermissive {
38        /// The file's permission bits.
39        mode: u32,
40    },
41    /// The file is larger than its format allows.
42    #[error("file is larger than {limit} bytes")]
43    TooLarge {
44        /// The largest accepted size in bytes.
45        limit: usize,
46    },
47    /// The file belongs to another user. Checked only for files that must
48    /// be the operator's own, such as the key file, and not when running as
49    /// root.
50    #[error("file is owned by uid {uid}, not by the user running stratum")]
51    WrongOwner {
52        /// The file's owner.
53        uid: u32,
54    },
55    /// An operating-system error.
56    #[error("{0}")]
57    Io(#[source] io::Error),
58}
59
60/// Policy for the permission bits of a file being read.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub(crate) enum ModePolicy {
63    /// Refuse a file that grants any access to group or others.
64    OwnerOnly,
65    /// Accept any mode (the file belongs to someone else, such as the node).
66    Any,
67}
68
69/// Reads a regular file of at most `limit` bytes into zeroising memory.
70///
71/// The file is opened once, with `O_NOFOLLOW` (a symbolic link in the
72/// last component is refused by the kernel), `O_NONBLOCK` (opening a FIFO
73/// or device returns at once instead of waiting for a writer) and
74/// `O_CLOEXEC`. Its type, mode and owner are then checked on the open
75/// descriptor, so nothing can be swapped in between a check and the open.
76/// Under [`ModePolicy::OwnerOnly`] a mode wider than `0600`, or an owner
77/// other than the effective user, is refused. The owner is not compared when
78/// running as root (`sudo -E stratum setup` with the operator's own key
79/// file): root can read the file anyway, and the trust boundary does not
80/// defend against root.
81pub(crate) fn read(
82    path: &Path,
83    limit: usize,
84    policy: ModePolicy,
85) -> Result<Zeroizing<Vec<u8>>, PrivateFileError> {
86    let flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC;
87    let fd = rustix::fs::open(path, flags, Mode::empty()).map_err(|errno| {
88        if errno == Errno::LOOP {
89            PrivateFileError::Symlink
90        } else {
91            PrivateFileError::Io(io::Error::from(errno))
92        }
93    })?;
94    let file = File::from(fd);
95    let opened = file.metadata().map_err(PrivateFileError::Io)?;
96    if !opened.is_file() {
97        return Err(PrivateFileError::NotRegularFile);
98    }
99    if policy == ModePolicy::OwnerOnly {
100        let mode = opened.mode() & 0o7777;
101        if mode & GROUP_OTHER_BITS != 0 {
102            return Err(PrivateFileError::TooPermissive { mode });
103        }
104        let euid = geteuid();
105        if !euid.is_root() && opened.uid() != euid.as_raw() {
106            return Err(PrivateFileError::WrongOwner { uid: opened.uid() });
107        }
108    }
109    let cap = u64::try_from(limit).map_or(u64::MAX, |n| n.saturating_add(1));
110    let mut contents = Zeroizing::new(Vec::with_capacity(limit.saturating_add(1)));
111    file.take(cap)
112        .read_to_end(&mut contents)
113        .map_err(PrivateFileError::Io)?;
114    if contents.len() > limit {
115        return Err(PrivateFileError::TooLarge { limit });
116    }
117    Ok(contents)
118}
119
120/// Creates `path` exclusively with mode `0600`, writes `contents` and syncs
121/// the file and its directory.
122///
123/// The mode is set at creation, so the file is never readable by others,
124/// and an existing file or symbolic link at `path` is never followed or
125/// overwritten. A partly written file is removed.
126pub(crate) fn create(path: &Path, contents: &[u8]) -> Result<(), PrivateFileError> {
127    let mut file = OpenOptions::new()
128        .write(true)
129        .create_new(true)
130        .mode(PRIVATE_MODE)
131        .open(path)
132        .map_err(|err| {
133            if err.kind() == io::ErrorKind::AlreadyExists {
134                PrivateFileError::AlreadyExists
135            } else {
136                PrivateFileError::Io(err)
137            }
138        })?;
139    let written = file
140        .write_all(contents)
141        .and_then(|()| file.sync_all())
142        .map_err(PrivateFileError::Io);
143    if let Err(err) = written {
144        drop(file);
145        // Best effort: the error being returned is the one that matters.
146        let _removed = fs::remove_file(path);
147        return Err(err);
148    }
149    sync_parent(path);
150    Ok(())
151}
152
153/// Removes a file and syncs its directory.
154pub(crate) fn remove(path: &Path) -> Result<(), PrivateFileError> {
155    fs::remove_file(path).map_err(PrivateFileError::Io)?;
156    sync_parent(path);
157    Ok(())
158}
159
160/// Syncs the directory holding `path` so a creation or removal is durable.
161///
162/// Best effort: some filesystems refuse to sync a directory, and the file
163/// itself has already been synced.
164fn sync_parent(path: &Path) {
165    let parent = match path.parent() {
166        Some(dir) if !dir.as_os_str().is_empty() => dir,
167        _ => Path::new("."),
168    };
169    if let Ok(dir) = File::open(parent) {
170        let _synced = dir.sync_all();
171    }
172}