From d6ae2e9e7e7717a58dad8b160d19e81945d26486 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 14:34:39 -0500 Subject: [PATCH] security(engine): read user-named files through the opened regular file under a byte cap (#3703) * security(engine): read user-named files through the opened regular file under a byte cap * address review: compare the probe error with the std::fs::read error * address review: open files for reading without waiting for a FIFO writer --- crates/engine/src/cmd/manage.rs | 7 +- crates/engine/src/cmd/print.rs | 2 +- crates/engine/src/display.rs | 6 +- crates/engine/src/export/watermark.rs | 5 +- crates/engine/src/files/fs.rs | 10 +-- crates/engine/src/files/tests.rs | 8 +- crates/engine/src/lib.rs | 1 + crates/engine/src/read_file.rs | 108 ++++++++++++++++++++++++++ crates/engine/src/slide_template.rs | 4 +- 9 files changed, 134 insertions(+), 17 deletions(-) create mode 100644 crates/engine/src/read_file.rs diff --git a/crates/engine/src/cmd/manage.rs b/crates/engine/src/cmd/manage.rs index 9b1f7e9f74..6e4cdfb105 100644 --- a/crates/engine/src/cmd/manage.rs +++ b/crates/engine/src/cmd/manage.rs @@ -64,6 +64,9 @@ fn set_names_ops(s: &crate::Session, names: &[String; 5]) -> Vec { .collect() } +/// Most bytes of a track log file. +const MAX_GPX_BYTES: u64 = 256 << 20; + /// Geotag photos from a GPX track log by capture time (Lightroom Classic's Map ▸ Tracklog ▸ /// Auto-Tag Photos). GPX times are UTC; capture times are the camera's local clock, so a photo's /// recorded zone (Exif `OffsetTimeOriginal`) or the `offset` parameter converts them. @@ -72,7 +75,9 @@ fn auto_tag_tracklog(s: &mut crate::Session, p: &Value) -> Result { const C: &str = "photo.autoTagTracklog"; let text = match (str_param(p, "gpx"), str_param(p, "path")) { (Some(t), _) => t.to_string(), - (None, Some(path)) => std::fs::read_to_string(path).map_err(|e| bad(C, format!("can't read {path}: {e}")))?, + (None, Some(path)) => crate::read_file::read_regular(path, MAX_GPX_BYTES) + .map(|b| String::from_utf8_lossy(&b).into_owned()) + .map_err(|e| bad(C, format!("can't read {path}: {e}")))?, (None, None) => return Err(bad(C, "missing `path` (a .gpx file) or `gpx` (its text)")), }; let log = parse_gpx(&text).map_err(|e| bad(C, e.to_string()))?; diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 1390ca1677..51f094866e 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -363,7 +363,7 @@ fn template_import(s: &mut Session, p: &Value) -> Result { if meta.len() > MAX_FILE { return Err(bad(ID, format!("{}: {} bytes is too large for a print template (at most {} KB)", path.display(), meta.len(), MAX_FILE / 1024))); } - let bytes = std::fs::read(path).map_err(|e| bad(ID, format!("{}: {e}", path.display())))?; + let bytes = crate::read_file::read_regular(path, MAX_FILE).map_err(|e| bad(ID, format!("{}: {e}", path.display())))?; let mut t = PrintTemplate::from_file(&bytes).map_err(|e| bad(ID, format!("{}: {e}", path.display())))?; if s.print_templates.len() >= MAX_TEMPLATES { return Err(bad(ID, format!("at most {MAX_TEMPLATES} templates; delete one first"))); diff --git a/crates/engine/src/display.rs b/crates/engine/src/display.rs index 34840e46d3..d9fa767207 100644 --- a/crates/engine/src/display.rs +++ b/crates/engine/src/display.rs @@ -29,11 +29,7 @@ impl Display { /// Load the ICC profile at `path`. pub fn load(path: &str) -> Result { let path = path.trim(); - let meta = std::fs::metadata(path).map_err(|e| format!("{path}: {e}"))?; - if meta.len() > MAX_PROFILE_BYTES as u64 { - return Err(format!("{path}: too large for an ICC profile")); - } - let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?; + let bytes = crate::read_file::read_regular(path, MAX_PROFILE_BYTES as u64).map_err(|e| format!("{path}: {e} (an ICC profile)"))?; Display::from_bytes(path, &bytes) } diff --git a/crates/engine/src/export/watermark.rs b/crates/engine/src/export/watermark.rs index c074808eae..ad19093313 100644 --- a/crates/engine/src/export/watermark.rs +++ b/crates/engine/src/export/watermark.rs @@ -236,11 +236,14 @@ pub(crate) fn watermark_logo(path: &str) -> Option> { Some(img) } +/// Most bytes of a watermark or layout graphic file. +const MAX_GRAPHIC_BYTES: u64 = 256 << 20; + /// A graphic file (a PNG with transparency, typically) as 8-bit sRGB with its alpha: the /// watermark logo, the loupe's layout image. Applies EXIF orientation before either consumer sizes it. /// The error says why it couldn't be read or decoded. pub fn read_graphic(path: &str) -> Result { - let bytes = std::fs::read(path).map_err(|e| format!("can't read {path}: {e}"))?; + let bytes = crate::read_file::read_regular(path, MAX_GRAPHIC_BYTES).map_err(|e| format!("can't read {path}: {e}"))?; let decoded = lightcraft_codecs::decode(&bytes, Default::default()).map_err(|e| format!("can't decode {path}: {e}"))?; Ok(decoded.to_srgb8().into_oriented(lightcraft_geom::Orientation::from_exif(decoded.orientation))) } diff --git a/crates/engine/src/files/fs.rs b/crates/engine/src/files/fs.rs index e839873cf0..bb25aff888 100644 --- a/crates/engine/src/files/fs.rs +++ b/crates/engine/src/files/fs.rs @@ -66,7 +66,7 @@ pub fn fs_pair_loader() -> PairLoader { let weight = len * if max_edge <= crate::media::SourceLevel::Thumb.max_edge() { 4 } else { 10 }; let gate = crate::memory::work_gate(); let _permit = if crate::memory::is_background() { gate.acquire(weight) } else { gate.acquire_urgent(weight) }; - let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?; + let bytes = crate::read_file::read_regular(path, crate::read_file::MAX_MEDIA_BYTES).map_err(|e| format!("{path}: {e}"))?; let r = load_vec_pair(bytes, max_edge, spec, with); crate::memory::release(); r @@ -84,15 +84,13 @@ pub fn fs_hooks() -> (FileLoader, FileProbe) { let loader: FileLoader = Arc::new(|path: &str, max_edge: usize, with: RawDecode<'_>| fs_load(path, max_edge, |bytes| load_vec(bytes, max_edge, with))); let probe: FileProbe = Arc::new(|path: &str| { - use std::io::Read; // one open, then everything from the open file: its size and modification time are not // round trips of their own (on a network share each of them is one) - let mut file = std::fs::File::open(path).map_err(|e| format!("{path}: {e}"))?; + let file = crate::read_file::open_for_read(path).map_err(|e| format!("{path}: {e}"))?; let meta = file.metadata().ok(); let len = meta.as_ref().map_or(0, |m| usize::try_from(m.len()).unwrap_or(usize::MAX)); let _permit = crate::memory::work_gate().acquire(len); - let mut bytes = Vec::new(); - file.read_to_end(&mut bytes).map_err(|e| format!("{path}: {e}"))?; + let bytes = crate::read_file::read_open(file, crate::read_file::MAX_MEDIA_BYTES).map_err(|e| format!("{path}: {e}"))?; let mut info = probe_bytes(path, &bytes)?; info.file_modified = meta.as_ref().and_then(modified_iso); Ok(info) @@ -111,7 +109,7 @@ fn fs_load(path: &str, max_edge: usize, load: impl FnOnce(Vec) -> Result< let weight = len.saturating_mul(if max_edge <= crate::media::SourceLevel::Thumb.max_edge() { 3 } else { 6 }); let gate = crate::memory::work_gate(); let _permit = if crate::memory::is_background() { gate.acquire(weight) } else { gate.acquire_urgent(weight) }; - let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?; + let bytes = crate::read_file::read_regular(path, crate::read_file::MAX_MEDIA_BYTES).map_err(|e| format!("{path}: {e}"))?; let r = load(bytes); // the file, the samples and the intermediate images are gone: give their pages back crate::memory::release(); diff --git a/crates/engine/src/files/tests.rs b/crates/engine/src/files/tests.rs index 599d173f7d..9700adce65 100644 --- a/crates/engine/src/files/tests.rs +++ b/crates/engine/src/files/tests.rs @@ -492,8 +492,14 @@ fn a_probe_of_a_file_that_cannot_be_read_names_the_path_and_the_cause() { for path in [dir.join("no-such-file.jpg"), dir.clone()] { let path = path.to_string_lossy().to_string(); let e = probe(&path).unwrap_err(); - assert_eq!(e, format!("{path}: {}", std::fs::read(&path).unwrap_err())); + // a folder is refused as "not a regular file" before any read, so only the path and a cause are pinned + assert!(e.starts_with(&format!("{path}: ")), "{e}"); } + // the system's own words for it, whatever the platform says + let missing = dir.join("no-such-file.jpg"); + let want = std::fs::read(&missing).unwrap_err().to_string(); + let got = probe(&missing.to_string_lossy()).unwrap_err(); + assert_eq!(got.strip_prefix(&format!("{}: ", missing.to_string_lossy())), Some(want.as_str())); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a733d90e08..dd67b755f9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -73,6 +73,7 @@ pub mod print_color; pub mod print_pdf; pub mod profile_refs; pub mod proof; +pub(crate) mod read_file; pub mod rename; pub mod segment; pub mod sidecar; diff --git a/crates/engine/src/read_file.rs b/crates/engine/src/read_file.rs new file mode 100644 index 0000000000..2dfb20f2b5 --- /dev/null +++ b/crates/engine/src/read_file.rs @@ -0,0 +1,108 @@ +//! Reads of files named by a user, a sidecar or a library: the OPENED file must be a regular file within a byte +//! cap, and no more than the cap is ever read. (A size taken from the pathname, then a second open and a read to EOF, +//! lets a link, a FIFO, a device or a file that grows in between turn into an unbounded read.) + +use std::io::{self, Read}; +use std::path::Path; + +/// Most bytes of a photo, video or other media file read into memory. +pub(crate) const MAX_MEDIA_BYTES: u64 = 8 << 30; + +/// `O_NONBLOCK` of the platforms that have a FIFO to wait on (std has no name for it, and libc is a +/// dev-dependency only); 0 elsewhere, where a FIFO open still waits for a writer. +#[cfg(unix)] +const O_NONBLOCK: i32 = if cfg!(all( + any(target_os = "linux", target_os = "android"), + not(any( + target_arch = "mips", + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6", + target_arch = "sparc", + target_arch = "sparc64" + )) +)) { + 0x800 +} else if cfg!(any( + target_os = "macos", + target_os = "ios", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + target_os = "dragonfly" +)) { + 0x4 +} else { + 0 +}; + +/// Opens `path` for reading without waiting for a FIFO's writer (a FIFO is refused by [`read_open`], not waited on). A +/// regular file is unaffected by the flag. +pub(crate) fn open_for_read(path: impl AsRef) -> io::Result { + let mut options = std::fs::OpenOptions::new(); + options.read(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, O_NONBLOCK); + options.open(path) +} + +/// The whole of the regular file at `path`, at most `max` bytes. +pub(crate) fn read_regular(path: impl AsRef, max: u64) -> io::Result> { + read_open(open_for_read(path)?, max) +} + +/// The whole of an already opened regular file, at most `max` bytes. +pub(crate) fn read_open(file: std::fs::File, max: u64) -> io::Result> { + let meta = file.metadata()?; + if !meta.is_file() { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "not a regular file")); + } + if meta.len() > max { + return Err(io::Error::new(io::ErrorKind::InvalidData, format!("{} bytes is more than the {max} allowed", meta.len()))); + } + let mut bytes = Vec::with_capacity(usize::try_from(meta.len()).unwrap_or(0)); + file.take(max.saturating_add(1)).read_to_end(&mut bytes)?; + if bytes.len() as u64 > max { + return Err(io::Error::new(io::ErrorKind::InvalidData, format!("more than the {max} bytes allowed"))); + } + Ok(bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_regular_file_within_the_cap_is_read_and_others_are_refused() { + let dir = std::env::temp_dir().join(format!("read-file-{}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let f = dir.join("a"); + std::fs::write(&f, b"abcd").unwrap(); + assert_eq!(read_regular(&f, 4).unwrap(), b"abcd"); + assert!(read_regular(&f, 3).is_err()); + assert!(read_regular(&dir, 100).is_err()); + #[cfg(unix)] + { + std::os::unix::fs::symlink("/dev/zero", dir.join("z")).unwrap(); + assert!(read_regular(dir.join("z"), 1 << 20).is_err()); + } + std::fs::remove_dir_all(&dir).unwrap(); + } + + /// A FIFO with no writer is refused, not waited on forever in `open`. + #[cfg(target_os = "linux")] + #[test] + fn a_fifo_without_a_writer_is_refused_without_blocking() { + let dir = std::env::temp_dir().join(format!("read-file-fifo-{}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let fifo = dir.join("pipe"); + // (no unsafe code in this crate: the coreutils tool makes the FIFO) + if !std::process::Command::new("mkfifo").arg(&fifo).status().is_ok_and(|s| s.success()) { + eprintln!("skipped: no mkfifo"); + return; + } + let err = read_regular(&fifo, 1 << 20).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{err}"); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/engine/src/slide_template.rs b/crates/engine/src/slide_template.rs index bf56a65694..0ff0c09878 100644 --- a/crates/engine/src/slide_template.rs +++ b/crates/engine/src/slide_template.rs @@ -389,7 +389,7 @@ fn read_user(file: &str, path: &Path) -> Result { if meta.len() > MAX_FILE { return Err(format!("{} bytes is too large for a slideshow template (at most {} KB)", meta.len(), MAX_FILE / 1024)); } - let bytes = std::fs::read(path).map_err(|e| e.to_string())?; + let bytes = crate::read_file::read_regular(path, MAX_FILE).map_err(|e| e.to_string())?; let p = parse(&bytes)?; Ok(Template { id: format!("{USER}{stem}"), @@ -411,7 +411,7 @@ pub fn read_file(path: &Path) -> Result { if meta.len() > MAX_FILE { return Err(format!("{}: {} bytes is too large for a slideshow template (at most {} KB)", path.display(), meta.len(), MAX_FILE / 1024)); } - let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?; + let bytes = crate::read_file::read_regular(path, MAX_FILE).map_err(|e| format!("{}: {e}", path.display()))?; let mut p = parse(&bytes).map_err(|e| format!("{}: {e}", path.display()))?; if p.name.is_none() { let stem = path.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();