mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-29 17:43:57 +01:00
fix(engine): size-check library image import; exclusive unguessable temp files (#125)
This commit is contained in:
1 parent
20a45a47f6
commit
cd5bdf95f7
6 files changed
+85
-8
No files matched your search
@@ -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
|
||||
|
||||
@@ -264,7 +264,7 @@ fn export_png(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -108,6 +108,9 @@ pub(crate) fn import_to_library(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
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<u64> {
|
||||
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<TempTrack> {
|
||||
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)
|
||||
|
||||
@@ -55,9 +55,13 @@ pub fn load(path: &std::path::Path) -> Result<Document, EngineError> {
|
||||
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(())
|
||||
}
|
||||
|
||||
|
||||
@@ -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<u64> {
|
||||
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<Writer> {
|
||||
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"));
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
Reference in new issue
Block a user