From cd5bdf95f79c1ac91e08922a4268dc9aa1fd3634 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 08:13:42 -0500 Subject: [PATCH] fix(engine): size-check library image import; exclusive unguessable temp files (#125) --- CHANGELOG.md | 1 + crates/engine/src/cmds_file.rs | 2 +- crates/engine/src/cmds_sound.rs | 10 ++++---- crates/engine/src/format.rs | 10 +++++--- crates/engine/src/vfs.rs | 37 ++++++++++++++++++++++++++++++ crates/engine/tests/read_bounds.rs | 33 ++++++++++++++++++++++++++ 6 files changed, 85 insertions(+), 8 deletions(-) create mode 100644 crates/engine/tests/read_bounds.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 54c0f18d..c24cdf20 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +* **Security: safer reads and temp files.** Import to Library checks an image's size (256 MiB) before reading it, and saves, audio exports and the video soundtrack write their temporary files under unguessable names, created exclusively. * **Saved commands (command macros)** (ADR 0097, M6). * In the **History** panel, **Ctrl+click** steps (Shift+click a range) and choose **Save As Command…**: the steps come back at the end of the **Commands** menu, to run on whatever is diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index 0f4375dd..d00a2540 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -264,7 +264,7 @@ fn export_png(s: &mut Session, p: &Value) -> Result { } /// Largest file Import to Stage reads. -const MAX_IMPORT_BYTES: u64 = 256 * 1024 * 1024; +pub(crate) const MAX_IMPORT_BYTES: u64 = 256 * 1024 * 1024; /// Import to Stage: the drawing's shapes and text become editable elements on a new layer /// named after the file, in a keyframe at the playhead, selected, as one undo step. A drawing diff --git a/crates/engine/src/cmds_sound.rs b/crates/engine/src/cmds_sound.rs index abef14ef..e055f1fa 100644 --- a/crates/engine/src/cmds_sound.rs +++ b/crates/engine/src/cmds_sound.rs @@ -108,6 +108,9 @@ pub(crate) fn import_to_library(s: &mut Session, p: &Value) -> Result { } let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); if matches!(ext.as_deref(), Some("png" | "jpg" | "jpeg")) { + if crate::vfs::len(&path)? > crate::cmds_file::MAX_IMPORT_BYTES { + return Err(EngineError::Format(format!("{} is too large to import", path.display()))); + } let bytes = crate::vfs::read(&path)?; let id = anicraft_doc::BitmapId(s.doc.alloc_id()); let bitmap = anicraft_doc::Bitmap::from_image(id, file_name(&path, "image"), bytes).map_err(|e| EngineError::Format(format!("{}: {e}", path.display())))?; @@ -357,9 +360,9 @@ pub(crate) fn write_mix(path: &Path, voices: &[Voice], rate: u32, from: u64, to: use std::io::Write; let frames = to.saturating_sub(from); let header = wav::header(rate, 2, bits, frames).ok_or_else(|| EngineError::Param("that much audio does not fit in a WAV file (4 GB); lower 'rate' or the frame range".into()))?; - let tmp = path.with_extension("wav.tmp"); + let tmp = path.with_extension(format!("{}.wav.tmp", crate::vfs::random_suffix())); let result = (|| -> Result { - let mut f = crate::vfs::Writer::create(&tmp)?; + let mut f = crate::vfs::Writer::create_new(&tmp)?; f.write_all(&header)?; const BLOCK: u64 = 65_536; let mut buf = vec![0f32; BLOCK as usize * 2]; @@ -420,8 +423,7 @@ impl Drop for TempTrack { /// The soundtrack of movie frames `first..=last` as a 48 kHz 16-bit WAV in the temp folder. pub(crate) fn temp_track(s: &Session, first: u32, last: u32) -> Result { const RATE: u32 = 48_000; - let nanos = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); - let track = TempTrack(std::env::temp_dir().join(format!("anicraft-track-{}-{nanos}.wav", std::process::id()))); + let track = TempTrack(std::env::temp_dir().join(format!("anicraft-track-{}-{}.wav", std::process::id(), crate::vfs::random_suffix()))); let (voices, a, b) = soundtrack(s, first, last, RATE); write_mix(&track.0, &voices, RATE, a, b, wav::Bits::Int16)?; Ok(track) diff --git a/crates/engine/src/format.rs b/crates/engine/src/format.rs index debe4557..5cd9b074 100644 --- a/crates/engine/src/format.rs +++ b/crates/engine/src/format.rs @@ -55,9 +55,13 @@ pub fn load(path: &std::path::Path) -> Result { pub fn save(doc: &Document, path: &std::path::Path) -> Result<(), EngineError> { let json = to_json(doc)?; // Write next to the target, then rename: a crash mid-write never corrupts the old file. - let tmp = path.with_extension("anicraft.tmp"); - crate::vfs::write(&tmp, json)?; - crate::vfs::rename(&tmp, path)?; + // The temp name is unguessable and created exclusively, so a planted file or symlink can't redirect the write. + let tmp = path.with_extension(format!("anicraft.{}.tmp", crate::vfs::random_suffix())); + crate::vfs::write_new(&tmp, json)?; + if let Err(e) = crate::vfs::rename(&tmp, path) { + let _ = crate::vfs::remove_file(&tmp); + return Err(e.into()); + } Ok(()) } diff --git a/crates/engine/src/vfs.rs b/crates/engine/src/vfs.rs index f4f25f88..dd759767 100644 --- a/crates/engine/src/vfs.rs +++ b/crates/engine/src/vfs.rs @@ -208,6 +208,22 @@ pub fn write(path: &Path, data: impl AsRef<[u8]>) -> io::Result<()> { } } +/// Like [`write`], but the file must not exist yet (`O_EXCL`: a planted file or symlink makes it +/// fail instead of being written through). For temporary files. +pub fn write_new(path: &Path, data: impl AsRef<[u8]>) -> io::Result<()> { + match mem(|m| m.write(path, data.as_ref().to_vec())) { + Some(r) => r, + None => std::fs::OpenOptions::new().write(true).create_new(true).open(path).and_then(|mut f| io::Write::write_all(&mut f, data.as_ref())), + } +} + +/// 16 hex digits an outsider can't guess (the standard library's randomly seeded hasher), for +/// temporary file names. +pub fn random_suffix() -> String { + use std::hash::{BuildHasher, Hasher}; + format!("{:016x}", std::collections::hash_map::RandomState::new().build_hasher().finish()) +} + /// The file's size in bytes (`std::fs::metadata(path)?.len()`). pub fn len(path: &Path) -> io::Result { mem(|m| m.len(path)).unwrap_or_else(|| std::fs::metadata(path).map(|m| m.len())) @@ -265,6 +281,14 @@ impl Writer { Ok(Writer::Disk(io::BufWriter::new(std::fs::File::create(path)?))) } + /// Like [`Writer::create`], but the file must not exist yet. + pub fn create_new(path: &Path) -> io::Result { + if in_memory() { + return Writer::create(path); + } + Ok(Writer::Disk(io::BufWriter::new(std::fs::OpenOptions::new().write(true).create_new(true).open(path)?))) + } + pub fn finish(self) -> io::Result<()> { match self { Writer::Disk(mut f) => io::Write::flush(&mut f), @@ -299,6 +323,19 @@ impl io::Write for Writer { mod tests { use super::*; + #[test] + fn temp_files_are_created_exclusively() { + let dir = std::env::temp_dir().join(format!("anicraft-vfs-{}-{}", std::process::id(), random_suffix())); + std::fs::create_dir_all(&dir).unwrap(); + let f = dir.join("t.tmp"); + write_new(&f, b"a").unwrap(); + assert_eq!(write_new(&f, b"b").unwrap_err().kind(), io::ErrorKind::AlreadyExists); + assert_eq!(Writer::create_new(&f).err().map(|e| e.kind()), Some(io::ErrorKind::AlreadyExists)); + assert_eq!(std::fs::read(&f).unwrap(), b"a"); + assert_ne!(random_suffix(), random_suffix()); + std::fs::remove_dir_all(&dir).ok(); + } + #[test] fn paths_have_one_spelling_and_stay_inside() { assert_eq!(key(Path::new("/a/./b/../c.txt")).unwrap(), PathBuf::from("a").join("c.txt")); diff --git a/crates/engine/tests/read_bounds.rs b/crates/engine/tests/read_bounds.rs new file mode 100644 index 00000000..514054a0 --- /dev/null +++ b/crates/engine/tests/read_bounds.rs @@ -0,0 +1,33 @@ +//! Files commands read are size-checked before they are read, and saves leave no predictable temp file. +#![cfg(not(target_arch = "wasm32"))] + +use anicraft_engine::Session; +use serde_json::json; + +#[test] +fn import_to_library_checks_an_image_size_before_reading() { + let dir = std::env::temp_dir().join(format!("anicraft-readbounds-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let big = dir.join("big.png"); + // A sparse file: the size is claimed without being stored (or read, if the check works). + std::fs::File::create(&big).unwrap().set_len(256 * 1024 * 1024 + 1).unwrap(); + let mut s = Session::default(); + let e = s.execute("file.import_to_library", &json!({"path": big})).unwrap_err().to_string(); + assert!(e.contains("too large"), "{e}"); + std::fs::remove_dir_all(&dir).ok(); +} + +#[test] +fn save_does_not_write_through_a_planted_predictable_temp_path() { + let dir = std::env::temp_dir().join(format!("anicraft-savetmp-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let target = dir.join("a.anicraft"); + let victim = dir.join("victim.txt"); + std::fs::write(&victim, "keep").unwrap(); + #[cfg(unix)] + std::os::unix::fs::symlink(&victim, dir.join("a.anicraft.tmp")).unwrap(); + anicraft_engine::format::save(&Session::default().doc, &target).unwrap(); + assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep"); + assert!(target.is_file()); + std::fs::remove_dir_all(&dir).ok(); +}