Skip to main content

stratum_node_cli/
private_file.rs

1//! Exclusive creation and checked reading of files that hold secrets.
2
3use std::ffi::OsString;
4use std::fs::{self, File, OpenOptions};
5use std::io::{self, Read as _, Write as _};
6use std::os::unix::fs::{MetadataExt as _, OpenOptionsExt as _};
7use std::path::{Path, PathBuf};
8
9use rustix::fs::{Mode, OFlags};
10use rustix::io::Errno;
11use rustix::process::geteuid;
12use zeroize::Zeroizing;
13
14/// The permission bits a private file is created with.
15const PRIVATE_MODE: u32 = 0o600;
16
17/// Permission bits that must be clear on a private file: any access by the
18/// group or by others.
19const GROUP_OTHER_BITS: u32 = 0o077;
20
21/// Why a private file could not be created or read.
22///
23/// No variant carries any part of the file's contents.
24#[derive(Debug, thiserror::Error)]
25#[non_exhaustive]
26pub enum PrivateFileError {
27    /// The file exists and is never overwritten.
28    #[error("file already exists and will not be overwritten")]
29    AlreadyExists,
30    /// The path is a symbolic link, which is refused for secret files.
31    #[error("file is a symbolic link")]
32    Symlink,
33    /// The path is not a regular file.
34    #[error("file is not a regular file")]
35    NotRegularFile,
36    /// The file grants access to its group or to others.
37    #[error("file mode {mode:04o} is wider than 0600")]
38    TooPermissive {
39        /// The file's permission bits.
40        mode: u32,
41    },
42    /// The file is larger than its format allows.
43    #[error("file is larger than {limit} bytes")]
44    TooLarge {
45        /// The largest accepted size in bytes.
46        limit: usize,
47    },
48    /// The file belongs to another user. Checked only for files that must
49    /// be the operator's own, such as the key file, and not when running as
50    /// root.
51    #[error("file is owned by uid {uid}, not by the user running stratum")]
52    WrongOwner {
53        /// The file's owner.
54        uid: u32,
55    },
56    /// An operating-system error.
57    #[error("{0}")]
58    Io(#[source] io::Error),
59}
60
61/// Policy for the permission bits of a file being read.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub(crate) enum ModePolicy {
64    /// Refuse a file that grants any access to group or others.
65    OwnerOnly,
66    /// Accept any mode (the file belongs to someone else, such as the node).
67    Any,
68}
69
70/// Reads a regular file of at most `limit` bytes into zeroising memory.
71///
72/// The file is opened once, with `O_NOFOLLOW` (a symbolic link in the
73/// last component is refused by the kernel), `O_NONBLOCK` (opening a FIFO
74/// or device returns at once instead of waiting for a writer) and
75/// `O_CLOEXEC`. Its type, mode and owner are then checked on the open
76/// descriptor, so nothing can be swapped in between a check and the open.
77/// Under [`ModePolicy::OwnerOnly`] a mode wider than `0600`, or an owner
78/// other than the effective user, is refused. The owner is not compared when
79/// running as root (`sudo -E stratum setup` with the operator's own key
80/// file): root can read the file anyway, and the trust boundary does not
81/// defend against root.
82pub(crate) fn read(
83    path: &Path,
84    limit: usize,
85    policy: ModePolicy,
86) -> Result<Zeroizing<Vec<u8>>, PrivateFileError> {
87    let flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC;
88    let fd = rustix::fs::open(path, flags, Mode::empty()).map_err(|errno| {
89        if errno == Errno::LOOP {
90            PrivateFileError::Symlink
91        } else {
92            PrivateFileError::Io(io::Error::from(errno))
93        }
94    })?;
95    let file = File::from(fd);
96    let opened = file.metadata().map_err(PrivateFileError::Io)?;
97    if !opened.is_file() {
98        return Err(PrivateFileError::NotRegularFile);
99    }
100    if policy == ModePolicy::OwnerOnly {
101        let mode = opened.mode() & 0o7777;
102        if mode & GROUP_OTHER_BITS != 0 {
103            return Err(PrivateFileError::TooPermissive { mode });
104        }
105        let euid = geteuid();
106        if !euid.is_root() && opened.uid() != euid.as_raw() {
107            return Err(PrivateFileError::WrongOwner { uid: opened.uid() });
108        }
109    }
110    let cap = u64::try_from(limit).map_or(u64::MAX, |n| n.saturating_add(1));
111    let mut contents = Zeroizing::new(Vec::with_capacity(limit.saturating_add(1)));
112    file.take(cap)
113        .read_to_end(&mut contents)
114        .map_err(PrivateFileError::Io)?;
115    if contents.len() > limit {
116        return Err(PrivateFileError::TooLarge { limit });
117    }
118    Ok(contents)
119}
120
121/// Creates `path` exclusively with mode `0600`, writes `contents` and syncs
122/// the file and its directory.
123///
124/// The contents are written to a new temporary file in the same directory
125/// (`.<name>.tmp-<random>`, created exclusively with mode `0600`), synced,
126/// and only then moved to `path` with [`place_new`], which never replaces
127/// anything already there. So the file is never readable by others, an
128/// existing file or symbolic link at `path` is never followed or
129/// overwritten (including one that appears while the contents are being
130/// written), and a process killed part-way never leaves a partial file
131/// under the final name: at worst it leaves the hidden temporary file,
132/// which no later run reads or collides with. On any error the temporary
133/// file is removed.
134pub(crate) fn create(path: &Path, contents: &[u8]) -> Result<(), PrivateFileError> {
135    create_with(path, |file| file.write_all(contents))
136}
137
138/// As [`create`], with `write` filling the file; the seam the tests use to
139/// stop a write part-way.
140fn create_with(
141    path: &Path,
142    write: impl FnOnce(&mut File) -> io::Result<()>,
143) -> Result<(), PrivateFileError> {
144    // Refuse early, so a secret is not written to disk only to be discarded.
145    // The exclusive placement below is what guarantees it.
146    if fs::symlink_metadata(path).is_ok() {
147        return Err(PrivateFileError::AlreadyExists);
148    }
149    let temp = temporary_name(path)?;
150    let mut file = OpenOptions::new()
151        .write(true)
152        .create_new(true)
153        .mode(PRIVATE_MODE)
154        .open(&temp)
155        .map_err(PrivateFileError::Io)?;
156    let written = write(&mut file)
157        .and_then(|()| file.sync_all())
158        .map_err(PrivateFileError::Io);
159    drop(file);
160    let placed = written.and_then(|()| {
161        place_new(&temp, path).map_err(|err| {
162            if err.kind() == io::ErrorKind::AlreadyExists {
163                PrivateFileError::AlreadyExists
164            } else {
165                PrivateFileError::Io(err)
166            }
167        })
168    });
169    if let Err(err) = placed {
170        // Best effort: the error being returned is the one that matters.
171        let _removed = fs::remove_file(&temp);
172        return Err(err);
173    }
174    sync_parent(path);
175    Ok(())
176}
177
178/// A fresh hidden name beside `path`: `.<name>.tmp-<12 hex digits>`.
179fn temporary_name(path: &Path) -> Result<PathBuf, PrivateFileError> {
180    let name = path.file_name().ok_or_else(|| {
181        PrivateFileError::Io(io::Error::new(
182            io::ErrorKind::InvalidInput,
183            "the path does not name a file",
184        ))
185    })?;
186    let mut tag = [0u8; 6];
187    getrandom::fill(&mut tag).map_err(|_| {
188        PrivateFileError::Io(io::Error::other("the system random source is unavailable"))
189    })?;
190    let mut temp = OsString::from(".");
191    temp.push(name);
192    temp.push(format!(".tmp-{}", hex::encode(tag)));
193    Ok(path.with_file_name(temp))
194}
195
196/// Moves the file at `temp` to `target` only if nothing exists at `target`;
197/// an existing file, directory or symbolic link there is never replaced and
198/// gives [`io::ErrorKind::AlreadyExists`].
199///
200/// On Linux this is one `renameat2(RENAME_NOREPLACE)`. Where the kernel or
201/// filesystem lacks that flag (and on other systems) it is a hard link to
202/// `target`, which fails the same way when `target` exists, followed by
203/// removing `temp`. Either way there is no window in which a file at
204/// `target` could be overwritten. Both names must be in the same
205/// filesystem.
206pub(crate) fn place_new(temp: &Path, target: &Path) -> io::Result<()> {
207    #[cfg(any(target_os = "linux", target_os = "android"))]
208    {
209        use rustix::fs::{renameat_with, RenameFlags, CWD};
210        match renameat_with(CWD, temp, CWD, target, RenameFlags::NOREPLACE) {
211            Ok(()) => return Ok(()),
212            Err(errno) if [Errno::INVAL, Errno::NOSYS, Errno::OPNOTSUPP].contains(&errno) => {}
213            Err(errno) => return Err(io::Error::from(errno)),
214        }
215    }
216    link_new(temp, target)
217}
218
219/// The portable half of [`place_new`]: a hard link, which never replaces
220/// an existing `target`, then removing `temp`.
221fn link_new(temp: &Path, target: &Path) -> io::Result<()> {
222    fs::hard_link(temp, target)?;
223    // Best effort: the file is in place under `target` already.
224    let _removed = fs::remove_file(temp);
225    Ok(())
226}
227
228/// Removes a file and syncs its directory.
229pub(crate) fn remove(path: &Path) -> Result<(), PrivateFileError> {
230    fs::remove_file(path).map_err(PrivateFileError::Io)?;
231    sync_parent(path);
232    Ok(())
233}
234
235/// Syncs the directory holding `path` so a creation or removal is durable.
236///
237/// Best effort: some filesystems refuse to sync a directory, and the file
238/// itself has already been synced.
239fn sync_parent(path: &Path) {
240    let parent = match path.parent() {
241        Some(dir) if !dir.as_os_str().is_empty() => dir,
242        _ => Path::new("."),
243    };
244    if let Ok(dir) = File::open(parent) {
245        let _synced = dir.sync_all();
246    }
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252    use std::panic::{self, AssertUnwindSafe};
253
254    /// The names in `dir`, sorted.
255    fn names(dir: &Path) -> Vec<String> {
256        let mut names: Vec<String> = fs::read_dir(dir)
257            .expect("read dir")
258            .map(|entry| {
259                entry
260                    .expect("entry")
261                    .file_name()
262                    .to_string_lossy()
263                    .into_owned()
264            })
265            .collect();
266        names.sort();
267        names
268    }
269
270    #[test]
271    fn a_complete_file_is_private_and_nothing_else_is_left() {
272        let dir = tempfile::tempdir().expect("tempdir");
273        let path = dir.path().join("key.nsec");
274        create(&path, b"secret\n").expect("create");
275        assert_eq!(fs::read(&path).expect("read"), b"secret\n", "contents");
276        let mode = fs::metadata(&path).expect("metadata").mode() & 0o7777;
277        assert_eq!(mode, PRIVATE_MODE, "mode");
278        assert_eq!(names(dir.path()), ["key.nsec"], "no temporary file is left");
279        assert!(
280            matches!(
281                create(&path, b"other"),
282                Err(PrivateFileError::AlreadyExists)
283            ),
284            "an existing file is refused"
285        );
286        assert_eq!(fs::read(&path).expect("read"), b"secret\n", "and kept");
287    }
288
289    #[test]
290    fn a_write_stopped_part_way_leaves_nothing_under_the_final_name() {
291        let dir = tempfile::tempdir().expect("tempdir");
292        let path = dir.path().join("key.nsec");
293        // A panic part-way stands in for a kill: no error path runs.
294        let stopped = panic::catch_unwind(AssertUnwindSafe(|| {
295            create_with(&path, |file| {
296                file.write_all(b"nsec1part")?;
297                panic!("killed mid-write");
298            })
299        }));
300        assert!(stopped.is_err(), "the write was stopped");
301        assert!(
302            fs::symlink_metadata(&path).is_err(),
303            "no partial file under the final name: {:?}",
304            names(dir.path())
305        );
306        create(&path, b"secret\n").expect("the next create succeeds");
307    }
308
309    #[test]
310    fn a_file_appearing_during_the_write_is_kept() {
311        let dir = tempfile::tempdir().expect("tempdir");
312        let path = dir.path().join("key.nsec");
313        let result = create_with(&path, |file| {
314            fs::write(&path, b"theirs")?;
315            file.write_all(b"ours")
316        });
317        assert!(
318            matches!(result, Err(PrivateFileError::AlreadyExists)),
319            "{result:?}"
320        );
321        assert_eq!(fs::read(&path).expect("read"), b"theirs", "never replaced");
322        assert_eq!(
323            names(dir.path()),
324            ["key.nsec"],
325            "the temporary file is removed"
326        );
327    }
328
329    #[test]
330    fn both_placements_refuse_an_existing_target() {
331        let dir = tempfile::tempdir().expect("tempdir");
332        let target = dir.path().join("final");
333        for place in [place_new, link_new] {
334            let temp = dir.path().join("temp");
335            fs::write(&temp, b"ours").expect("temp");
336            fs::write(&target, b"theirs").expect("theirs");
337            let err = place(&temp, &target).expect_err("refused");
338            assert_eq!(err.kind(), io::ErrorKind::AlreadyExists, "{err}");
339            assert_eq!(fs::read(&target).expect("target"), b"theirs", "kept");
340            fs::remove_file(&target).expect("clear");
341            place(&temp, &target).expect("placed");
342            assert_eq!(fs::read(&target).expect("target"), b"ours", "placed");
343            assert!(fs::metadata(&temp).is_err(), "the temporary name is gone");
344            fs::remove_file(&target).expect("clear");
345        }
346    }
347}