use std::ffi::OsString;
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, PathBuf};
use rustix::fs::{Mode, OFlags};
use rustix::io::Errno;
use rustix::process::geteuid;
use zeroize::Zeroizing;
const PRIVATE_MODE: u32 = 0o600;
const GROUP_OTHER_BITS: u32 = 0o077;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum PrivateFileError {
#[error("file already exists and will not be overwritten")]
AlreadyExists,
#[error("file is a symbolic link")]
Symlink,
#[error("file is not a regular file")]
NotRegularFile,
#[error("file mode {mode:04o} is wider than 0600")]
TooPermissive {
mode: u32,
},
#[error("file is larger than {limit} bytes")]
TooLarge {
limit: usize,
},
#[error("file is owned by uid {uid}, not by the user running stratum")]
WrongOwner {
uid: u32,
},
#[error("{0}")]
Io(#[source] io::Error),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ModePolicy {
OwnerOnly,
Any,
}
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)
}
pub(crate) fn create(path: &Path, contents: &[u8]) -> Result<(), PrivateFileError> {
create_with(path, |file| file.write_all(contents))
}
fn create_with(
path: &Path,
write: impl FnOnce(&mut File) -> io::Result<()>,
) -> Result<(), PrivateFileError> {
if fs::symlink_metadata(path).is_ok() {
return Err(PrivateFileError::AlreadyExists);
}
let temp = temporary_name(path)?;
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(PRIVATE_MODE)
.open(&temp)
.map_err(PrivateFileError::Io)?;
let written = write(&mut file)
.and_then(|()| file.sync_all())
.map_err(PrivateFileError::Io);
drop(file);
let placed = written.and_then(|()| {
place_new(&temp, path).map_err(|err| {
if err.kind() == io::ErrorKind::AlreadyExists {
PrivateFileError::AlreadyExists
} else {
PrivateFileError::Io(err)
}
})
});
if let Err(err) = placed {
let _removed = fs::remove_file(&temp);
return Err(err);
}
sync_parent(path);
Ok(())
}
fn temporary_name(path: &Path) -> Result<PathBuf, PrivateFileError> {
let name = path.file_name().ok_or_else(|| {
PrivateFileError::Io(io::Error::new(
io::ErrorKind::InvalidInput,
"the path does not name a file",
))
})?;
let mut tag = [0u8; 6];
getrandom::fill(&mut tag).map_err(|_| {
PrivateFileError::Io(io::Error::other("the system random source is unavailable"))
})?;
let mut temp = OsString::from(".");
temp.push(name);
temp.push(format!(".tmp-{}", hex::encode(tag)));
Ok(path.with_file_name(temp))
}
pub(crate) fn place_new(temp: &Path, target: &Path) -> io::Result<()> {
#[cfg(any(target_os = "linux", target_os = "android"))]
{
use rustix::fs::{renameat_with, RenameFlags, CWD};
match renameat_with(CWD, temp, CWD, target, RenameFlags::NOREPLACE) {
Ok(()) => return Ok(()),
Err(errno) if [Errno::INVAL, Errno::NOSYS, Errno::OPNOTSUPP].contains(&errno) => {}
Err(errno) => return Err(io::Error::from(errno)),
}
}
link_new(temp, target)
}
fn link_new(temp: &Path, target: &Path) -> io::Result<()> {
fs::hard_link(temp, target)?;
let _removed = fs::remove_file(temp);
Ok(())
}
pub(crate) fn remove(path: &Path) -> Result<(), PrivateFileError> {
fs::remove_file(path).map_err(PrivateFileError::Io)?;
sync_parent(path);
Ok(())
}
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();
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::panic::{self, AssertUnwindSafe};
fn names(dir: &Path) -> Vec<String> {
let mut names: Vec<String> = fs::read_dir(dir)
.expect("read dir")
.map(|entry| {
entry
.expect("entry")
.file_name()
.to_string_lossy()
.into_owned()
})
.collect();
names.sort();
names
}
#[test]
fn a_complete_file_is_private_and_nothing_else_is_left() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("key.nsec");
create(&path, b"secret\n").expect("create");
assert_eq!(fs::read(&path).expect("read"), b"secret\n", "contents");
let mode = fs::metadata(&path).expect("metadata").mode() & 0o7777;
assert_eq!(mode, PRIVATE_MODE, "mode");
assert_eq!(names(dir.path()), ["key.nsec"], "no temporary file is left");
assert!(
matches!(
create(&path, b"other"),
Err(PrivateFileError::AlreadyExists)
),
"an existing file is refused"
);
assert_eq!(fs::read(&path).expect("read"), b"secret\n", "and kept");
}
#[test]
fn a_write_stopped_part_way_leaves_nothing_under_the_final_name() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("key.nsec");
let stopped = panic::catch_unwind(AssertUnwindSafe(|| {
create_with(&path, |file| {
file.write_all(b"nsec1part")?;
panic!("killed mid-write");
})
}));
assert!(stopped.is_err(), "the write was stopped");
assert!(
fs::symlink_metadata(&path).is_err(),
"no partial file under the final name: {:?}",
names(dir.path())
);
create(&path, b"secret\n").expect("the next create succeeds");
}
#[test]
fn a_file_appearing_during_the_write_is_kept() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("key.nsec");
let result = create_with(&path, |file| {
fs::write(&path, b"theirs")?;
file.write_all(b"ours")
});
assert!(
matches!(result, Err(PrivateFileError::AlreadyExists)),
"{result:?}"
);
assert_eq!(fs::read(&path).expect("read"), b"theirs", "never replaced");
assert_eq!(
names(dir.path()),
["key.nsec"],
"the temporary file is removed"
);
}
#[test]
fn both_placements_refuse_an_existing_target() {
let dir = tempfile::tempdir().expect("tempdir");
let target = dir.path().join("final");
for place in [place_new, link_new] {
let temp = dir.path().join("temp");
fs::write(&temp, b"ours").expect("temp");
fs::write(&target, b"theirs").expect("theirs");
let err = place(&temp, &target).expect_err("refused");
assert_eq!(err.kind(), io::ErrorKind::AlreadyExists, "{err}");
assert_eq!(fs::read(&target).expect("target"), b"theirs", "kept");
fs::remove_file(&target).expect("clear");
place(&temp, &target).expect("placed");
assert_eq!(fs::read(&target).expect("target"), b"ours", "placed");
assert!(fs::metadata(&temp).is_err(), "the temporary name is gone");
fs::remove_file(&target).expect("clear");
}
}
}