Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

security: harden developer tools, scripts, and testkit against hostile input (#3078)

Dylan M. Taylor057f460085c6
diff --git a/Cargo.lock b/Cargo.lock
index 9ce535a44..09b966946 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2292,6 +2292,7 @@ version = "0.12.0"
dependencies = [
"chrono",
"png",
+ "tempfile",
]
[[package]]
diff --git a/crates/av1/tools/extract_tables.py b/crates/av1/tools/extract_tables.py
index a037a3765..b4df9155b 100644
--- a/crates/av1/tools/extract_tables.py
+++ b/crates/av1/tools/extract_tables.py
@@ -14,6 +14,8 @@ Only the specification text is read:
Each table is emitted as a nested Rust array whose shape is checked against the declared
dimensions; the element type is the narrowest of u8/i8/u16/i16/i32 that holds every value.
"""
+import ast
+import operator
import os
import re
import sys
@@ -43,7 +45,30 @@ def ev(expr):
e = expr.strip().replace("\\", "")
e = re.sub(r"\b([A-Z][A-Z0-9_]*)\b", lambda m: str(consts[m.group(1)]) if m.group(1) in consts else m.group(1), e)
e = e.replace("/", "//")
- return int(eval(e, {"__builtins__": {}}, {}))
+ binary = {
+ ast.Add: operator.add,
+ ast.Sub: operator.sub,
+ ast.Mult: operator.mul,
+ ast.FloorDiv: operator.floordiv,
+ ast.Mod: operator.mod,
+ ast.LShift: operator.lshift,
+ ast.RShift: operator.rshift,
+ ast.BitOr: operator.or_,
+ ast.BitAnd: operator.and_,
+ ast.BitXor: operator.xor,
+ }
+ unary = {ast.UAdd: operator.pos, ast.USub: operator.neg, ast.Invert: operator.invert}
+
+ def calculate(node):
+ if isinstance(node, ast.Constant) and isinstance(node.value, int):
+ return node.value
+ if isinstance(node, ast.BinOp) and type(node.op) in binary:
+ return binary[type(node.op)](calculate(node.left), calculate(node.right))
+ if isinstance(node, ast.UnaryOp) and type(node.op) in unary:
+ return unary[type(node.op)](calculate(node.operand))
+ raise ValueError("unsupported specification expression")
+
+ return int(calculate(ast.parse(e, mode="eval").body))
# --- constants: symbol table (section 3) ---
diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml
index 3e3f1f1ff..f4da4a400 100644
--- a/crates/testkit/Cargo.toml
+++ b/crates/testkit/Cargo.toml
@@ -15,3 +15,7 @@ workspace = true
[dependencies]
png = "0.18"
chrono = { workspace = true }
+
+[dev-dependencies]
+tempfile = "3.27"
+
diff --git a/crates/testkit/src/fixtures.rs b/crates/testkit/src/fixtures.rs
index 62e9a1449..22e3c7a88 100644
--- a/crates/testkit/src/fixtures.rs
+++ b/crates/testkit/src/fixtures.rs
@@ -122,8 +122,8 @@ mod tests {
#[test]
fn generate_is_cached_and_atomic() {
- let dir = std::env::temp_dir().join(format!("filmcraft-testkit-gen-{}", std::process::id()));
- let out = dir.join("f.bin");
+ let dir = tempfile::tempdir().unwrap();
+ let out = dir.path().join("f.bin");
let _ = std::fs::remove_file(&out);
assert!(generate(&out, |_| false).is_none());
assert!(!out.exists());
diff --git a/crates/testkit/src/golden.rs b/crates/testkit/src/golden.rs
index 6d52c14d5..03655f483 100644
--- a/crates/testkit/src/golden.rs
+++ b/crates/testkit/src/golden.rs
@@ -348,8 +348,8 @@ mod tests {
if blessing() {
return;
}
- let dir = std::env::temp_dir().join(format!("filmcraft-testkit-golden-{}", std::process::id()));
- let path = dir.join("ramp.png");
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("ramp.png");
let img = ramp(32, 16, 255);
write_png(&path, &img).unwrap();
assert!(check_golden(&path, &img, Tolerance::EXACT, "t", "unit test").is_ok());
@@ -360,7 +360,7 @@ mod tests {
far.px.iter_mut().step_by(4).for_each(|v| *v = 255 - *v);
let e = check_golden(&path, &far, Tolerance::RENDER, "t", "unit test").unwrap_err();
assert!(e.contains("PSNR"), "{e}");
- assert!(check_golden(&dir.join("missing.png"), &img, Tolerance::RENDER, "t", "unit test").unwrap_err().contains("FILMCRAFT_BLESS"));
+ assert!(check_golden(&dir.path().join("missing.png"), &img, Tolerance::RENDER, "t", "unit test").unwrap_err().contains("FILMCRAFT_BLESS"));
}
#[test]
diff --git a/crates/testkit/src/oracle.rs b/crates/testkit/src/oracle.rs
index 50a1ce22c..ba8981084 100644
--- a/crates/testkit/src/oracle.rs
+++ b/crates/testkit/src/oracle.rs
@@ -202,10 +202,8 @@ mod tests {
}
use std::ffi::OsString;
- fn tmpdir(tag: &str) -> PathBuf {
- let d = std::env::temp_dir().join(format!("filmcraft-testkit-{tag}-{}", std::process::id()));
- std::fs::create_dir_all(&d).unwrap();
- d
+ fn tmpdir(_tag: &str) -> PathBuf {
+ tempfile::tempdir().unwrap().keep()
}
#[test]
diff --git a/packaging/macos/import-cert.sh b/packaging/macos/import-cert.sh
index 2acf4bf3d..4fa50e08f 100755
--- a/packaging/macos/import-cert.sh
+++ b/packaging/macos/import-cert.sh
@@ -19,7 +19,7 @@ fi
TMP="${RUNNER_TEMP:-${TMPDIR:-/tmp}}"
KEYCHAIN="$TMP/filmcraft-signing.keychain-db"
-CERT="$TMP/filmcraft-signing.p12"
+CERT="$(mktemp "$TMP/filmcraft-signing.XXXXXX.p12")"
KC_PASS="${KEYCHAIN_PASSWORD:-$(openssl rand -hex 24)}"
trap 'rm -f "$CERT"' EXIT
diff --git a/xtask/src/main.rs b/xtask/src/main.rs
index e3f883e0f..98902837a 100644
--- a/xtask/src/main.rs
+++ b/xtask/src/main.rs
@@ -375,9 +375,8 @@ fn serve_dir(dir: &std::path::Path, port: u16) -> Result<(), String> {
break;
}
}
- let path = line.split_whitespace().nth(1).unwrap_or("/").split(['?', '#']).next().unwrap_or("/").to_string();
- let rel = if path == "/" { "index.html".to_string() } else { path.trim_start_matches('/').replace("..", "") };
- let file = dir.join(&rel);
+ let path = line.split_whitespace().nth(1).unwrap_or("/").split(['?', '#']).next().unwrap_or("/");
+ let file = served_path(&dir, path);
let (status, body) = match std::fs::read(&file) {
Ok(b) => ("200 OK", b),
Err(_) => ("404 Not Found", b"not found".to_vec()),
@@ -403,6 +402,39 @@ fn serve_dir(dir: &std::path::Path, port: u16) -> Result<(), String> {
Ok(())
}
+fn served_path(root: &std::path::Path, request_path: &str) -> std::path::PathBuf {
+ use std::path::Component;
+ if request_path == "/" {
+ return root.join("index.html");
+ }
+ let repeated_root = request_path.starts_with("//");
+ let raw = request_path.strip_prefix('/').unwrap_or(request_path);
+ let relative = std::path::Path::new(raw);
+ let windows_prefix = raw.contains('\\') || raw.split('/').next().is_some_and(|part| part.ends_with(':'));
+ if !repeated_root && !windows_prefix && relative.components().all(|part| matches!(part, Component::Normal(_))) {
+ root.join(relative)
+ } else {
+ // A path that cannot name a child of the document root deliberately misses.
+ root.join(".invalid-request-path")
+ }
+}
+
+#[cfg(test)]
+mod serve_tests {
+ use super::served_path;
+ use std::path::Path;
+
+ #[test]
+ fn preview_paths_cannot_escape_the_document_root() {
+ let root = Path::new("/dist");
+ assert_eq!(served_path(root, "/"), root.join("index.html"));
+ assert_eq!(served_path(root, "/assets/app.js"), root.join("assets/app.js"));
+ for hostile in ["/../etc/passwd", "//etc/passwd", "/a/../../etc/passwd", r"C:\\Windows\\win.ini"] {
+ assert_eq!(served_path(root, hostile), root.join(".invalid-request-path"));
+ }
+ }
+}
+
/// (crate, test target, test) whose ignored test builds that crate's fixture matrix.
const FIXTURE_GENERATORS: &[(&str, &str, &str)] = &[
("h264", "it", "conformance::generate_fixtures"),
diff --git a/xtask/src/parity.rs b/xtask/src/parity.rs
index 774a0a76a..0b6f81b19 100644
--- a/xtask/src/parity.rs
+++ b/xtask/src/parity.rs
@@ -38,6 +38,8 @@ use serde_json::Value;
const MAX_DEPTH: usize = 16;
/// Most menu items accepted from a reference file.
const MAX_ITEMS: usize = 20_000;
+/// Most UTF-8 bytes retained in one expanded leaf path.
+const MAX_PATH_BYTES: usize = 4 * 1024;
/// Keys holding a node's label, and its children.
const LABEL_KEYS: [&str; 3] = ["name", "title", "label"];
const CHILD_KEYS: [&str; 6] = ["children", "items", "submenu", "menu", "menuItems", "menu_items"];
@@ -303,6 +305,10 @@ fn push_leaf(prefix: &[String], label: &str, min: usize, out: &mut Vec<Vec<Strin
if out.len() >= MAX_ITEMS {
return Err(format!("reference has more than {MAX_ITEMS} items"));
}
+ let bytes = prefix.iter().try_fold(label.trim().len(), |n, part| n.checked_add(part.len())).ok_or("reference path is too large")?;
+ if bytes > MAX_PATH_BYTES {
+ return Err(format!("reference path has more than {MAX_PATH_BYTES} bytes"));
+ }
let mut path = prefix.to_vec();
path.push(label.trim().to_string());
if path.len() >= min.max(1) {
@@ -622,6 +628,8 @@ mod tests {
assert!(reference_paths(&json!(many), area).unwrap_err().contains("more than"));
let bare: Vec<String> = (0..MAX_ITEMS + 1).map(|i| format!("Effect {i}")).collect();
assert!(area == Area::Menus || reference_paths(&json!(bare), area).unwrap_err().contains("more than"));
+ let long = format!("File > {}", "x".repeat(MAX_PATH_BYTES));
+ assert!(reference_paths(&json!([long]), area).unwrap_err().contains("bytes"));
}
// odd values are skipped, not trusted
assert_eq!(reference_paths(&json!([1, null, true, {"name": 5}, ["File"]]), Area::Menus).unwrap(), Vec::<Vec<String>>::new());