Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

security: harden native temporary and recovery files

Dylan M. Taylor76f0e08df7a7
diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs
index 635bf924a..e6510bb6a 100644
--- a/crates/format/src/atomic.rs
+++ b/crates/format/src/atomic.rs
@@ -37,6 +37,9 @@ pub mod meta;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
+
+#[cfg(unix)]
+use std::os::unix::fs::OpenOptionsExt;
use std::sync::atomic::{AtomicU64, Ordering};
/// The file-system steps [`atomic_write_with`] performs. [`RealFs`] is the real thing; tests
@@ -86,7 +89,11 @@ impl AtomicFs for RealFs {
self.write_new_progress(tmp, bytes, &|_| {})
}
fn write_new_progress(&self, tmp: &Path, bytes: &[u8], progress: &dyn Fn(f32)) -> io::Result<()> {
- let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(tmp)?;
+ let mut f = std::fs::OpenOptions::new();
+ f.write(true).create_new(true);
+ #[cfg(unix)]
+ f.mode(0o600);
+ let mut f = f.open(tmp)?;
let mut written = 0usize;
for chunk in bytes.chunks(WRITE_CHUNK) {
f.write_all(chunk)?;
diff --git a/crates/format/src/autosave.rs b/crates/format/src/autosave.rs
index fa3c9a408..1c3bec026 100644
--- a/crates/format/src/autosave.rs
+++ b/crates/format/src/autosave.rs
@@ -189,7 +189,9 @@ pub fn list_recovery(recovery_dir: &Path) -> Vec<RecoveryEntry> {
};
for e in rd.flatten() {
let p = e.path();
- if p.extension().is_some_and(|x| x == "json")
+ if e.file_type().is_ok_and(|ft| ft.is_file())
+ && p.extension().is_some_and(|x| x == "json")
+ && e.metadata().is_ok_and(|m| m.len() <= (1 << 20))
&& let Ok(bytes) = std::fs::read(&p)
&& let Ok(info) = serde_json::from_slice::<RecoveryInfo>(&bytes)
&& sanitize(&info.key) == info.key
@@ -402,6 +404,9 @@ fn untouched_for(path: &Path, min_age: std::time::Duration, missing_ok: bool) ->
}
fn remove_entry(dir: &Path, key: &str) -> Result<()> {
+ if sanitize(key) != key {
+ return Err(FormatError::corrupt("recovery entry key contains path components"));
+ }
let bundle = dir.join(format!("{key}.pcraft"));
if bundle.exists() {
std::fs::remove_dir_all(bundle)?;
diff --git a/crates/format/src/read.rs b/crates/format/src/read.rs
index 4ebfcbbfa..8ad0dccca 100644
--- a/crates/format/src/read.rs
+++ b/crates/format/src/read.rs
@@ -24,7 +24,11 @@ pub fn read_file(path: &Path) -> io::Result<Vec<u8>> {
/// [`read_file`] with a chosen read size (tests use small ones to exercise the loop).
pub fn read_file_with(path: &Path, chunk: usize) -> io::Result<Vec<u8>> {
let mut f = std::fs::File::open(path)?;
- let len = f.metadata().map(|m| m.len()).unwrap_or(0);
+ let metadata = f.metadata()?;
+ if !metadata.is_file() {
+ return Err(io::Error::new(io::ErrorKind::InvalidInput, "path is not a regular file"));
+ }
+ let len = metadata.len();
read_all_with(&mut f, len, chunk)
}