1use 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
14const PRIVATE_MODE: u32 = 0o600;
16
17const GROUP_OTHER_BITS: u32 = 0o077;
20
21#[derive(Debug, thiserror::Error)]
25#[non_exhaustive]
26pub enum PrivateFileError {
27 #[error("file already exists and will not be overwritten")]
29 AlreadyExists,
30 #[error("file is a symbolic link")]
32 Symlink,
33 #[error("file is not a regular file")]
35 NotRegularFile,
36 #[error("file mode {mode:04o} is wider than 0600")]
38 TooPermissive {
39 mode: u32,
41 },
42 #[error("file is larger than {limit} bytes")]
44 TooLarge {
45 limit: usize,
47 },
48 #[error("file is owned by uid {uid}, not by the user running stratum")]
52 WrongOwner {
53 uid: u32,
55 },
56 #[error("{0}")]
58 Io(#[source] io::Error),
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub(crate) enum ModePolicy {
64 OwnerOnly,
66 Any,
68}
69
70pub(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
121pub(crate) fn create(path: &Path, contents: &[u8]) -> Result<(), PrivateFileError> {
135 create_with(path, |file| file.write_all(contents))
136}
137
138fn create_with(
141 path: &Path,
142 write: impl FnOnce(&mut File) -> io::Result<()>,
143) -> Result<(), PrivateFileError> {
144 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 let _removed = fs::remove_file(&temp);
172 return Err(err);
173 }
174 sync_parent(path);
175 Ok(())
176}
177
178fn 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
196pub(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
219fn link_new(temp: &Path, target: &Path) -> io::Result<()> {
222 fs::hard_link(temp, target)?;
223 let _removed = fs::remove_file(temp);
225 Ok(())
226}
227
228pub(crate) fn remove(path: &Path) -> Result<(), PrivateFileError> {
230 fs::remove_file(path).map_err(PrivateFileError::Io)?;
231 sync_parent(path);
232 Ok(())
233}
234
235fn 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 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 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}