From 33ee2badf91aedd123dfdfa602461eda4e2e4937 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 30 Sep 2026 15:54:55 +0300 Subject: [PATCH] fix(demux): an untrusted pasp ratio cannot size a zero or wrapped raster The mp4 `pasp` box is eight bytes of header and both halves went into `PixelAspect { h, v }` unvalidated, while every other arm of that reader validated. Four consequences, all reachable at file open, before a pixel is drawn: - `is_square()` treated `h == 0, v == 5` as non-square, though its own comment claimed it covered "a degenerate one a crafted header claimed"; - `width_factor` divided by nothing, giving `h == 0` a factor of 0; - `width_factor` narrowed `coded * h` from a u64 to a u32, and 1920 * 0x00FF_FFFF wraps to 2_147_481_728; - both flowed into the `resize` that sizes the decode worker's stretched planes and into `meta.width`. `width_factor` is now total: it refuses anything `PixelAspect::stated` calls unusable (a zero half, or a reduced pair carrying a term past 1024 -- judged reduced, so ffmpeg's unreduced 17280/12960 spelling is judged by the picture it names), computes in a u64 that cannot overflow, and falls back to the coded width rather than narrowing to a zero or an oversized raster. The bound that keeps a header claim from sizing an unsatisfiable allocation is `MAX_DISPLAY_WIDTH`. `pasp_of` judges the read through the same `stated`, so the aspect this engine *reports* is one it can draw. Sane ratios are unchanged bit for bit: 4/3 over 1440x1080 is still 1920. Witnesses: - demux unit: six degenerate claims (both zero halves, both wrap directions) must all read as the coded width. RED: `h:0,v:1 -> 0`, `h:16777215,v:1 -> 2147481728`, `h:1,v:16777215 -> 0`. - end to end: a byte-patched copy of assets/test_baseline.mp4, its eight `pasp` payload bytes replaced, opened through the ordinary door. RED was a hard SIGABRT -- "memory allocation of 3092375531520 bytes failed" -- not an assertion failure, which is the whole severity of the defect. --- crates/engine/src/demux.rs | 178 ++++++++++++++++++++---- crates/engine/tests/untrusted_header.rs | 163 ++++++++++++++++++++++ 2 files changed, 312 insertions(+), 29 deletions(-) create mode 100644 crates/engine/tests/untrusted_header.rs diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 8fea412..8d7819b 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -372,12 +372,50 @@ impl PixelAspect { /// The square pixels everything before anamorphic sources was. pub const SQUARE: Self = Self { h: 1, v: 1 }; + /// The widest display raster this engine will stretch a coded frame into. + /// A container can claim any ratio at all, but no real one needs more + /// than a 16k canvas's worth of columns, and the bound is what keeps a + /// header claim from sizing an allocation no machine can satisfy. + const MAX_DISPLAY_WIDTH: u32 = 65_535; + + /// The largest term a *reduced* aspect ratio may keep. A real display + /// ratio is a small pair of integers however it was spelled -- 4:3, 16:9, + /// 8:5, 12:11 -- and ffmpeg's unreduced DAR spellings reduce to one. + /// A pair whose reduction still carries a term past this is not a ratio + /// at all but four chosen bytes, and it is refused as one. + const MAX_ASPECT_TERM: u32 = 1024; + + /// The ratio a container stated, or [`None`] when it stated one this + /// engine cannot draw. Both halves arrive from header bytes -- read + /// straight out of an mp4 `pasp` box, or computed from a Matroska + /// `Display*` pair beside the coded size -- so the test lives here, once, + /// rather than in each door that reads one. + /// + /// Unusable means: a zero half (nothing to divide by), or a *reduced* + /// pair carrying a term past [`Self::MAX_ASPECT_TERM`] (a pair of chosen + /// bytes rather than a ratio). Judged reduced, so an unreduced spelling of + /// a real one -- ffmpeg writes 17280/12960 for 16:9 -- is judged by the + /// picture it names and not by how many digits it took. + pub fn stated(h: u32, v: u32) -> Option { + if h == 0 || v == 0 { + return None; + } + let (mut a, mut b) = (h, v); + while b != 0 { + (a, b) = (b, a % b); + } + (h / a <= Self::MAX_ASPECT_TERM && v / a <= Self::MAX_ASPECT_TERM).then_some(Self { h, v }) + } + /// Whether the displayed picture is the coded one, drawn one to one. + /// + /// Both halves of the ratio are untrusted bytes -- four of them in an mp4 + /// `pasp` box, and a product of two header values on the Matroska door -- + /// so a half that is zero is a claim this engine cannot divide by, and it + /// means square rather than a division by zero: the file states nothing + /// usable, which is what every file that states no aspect at all states. pub fn is_square(self) -> bool { - // An unstated ratio (0) and a stated 1:1 are the same pixels, and a - // degenerate one a crafted header claimed is square rather than a - // division by zero. - self.v == 0 || self.h == self.v + self.h == 0 || self.v == 0 || self.h == self.v } /// How many coded columns one displayed column is worth: the factor the @@ -388,14 +426,33 @@ impl PixelAspect { /// cover -- the same rounding swscale applies, and the same one that keeps /// the stretch a whole-sample operation rather than a smear. pub fn width_factor(self, coded_width: u32) -> u32 { - if self.is_square() { + // The same judgement [`Self::stated`] makes at the read, repeated here + // because this is the one function every door reaches: a ratio built + // rather than read still has to survive the multiply that follows. + if Self::stated(self.h, self.v).is_none() { return coded_width; } // (coded * h / v), rounded up to even: 1440 at 4:3 gives 1920 exactly, // and a ratio that does not divide evenly is widened to the nearest // even column count rather than shown cropped or squeezed. + // + // Every step is checked, because the whole point of this arithmetic is + // that it sizes an allocation from bytes a file chose. `coded * h` is + // at most 2^64-ish and cannot overflow a u64, but the quotient is + // then *narrowed* to a u32 and can wrap -- 1920 * 0x00FF_FFFF narrows + // to 2_147_481_728 -- and a narrowed zero becomes a zero-column + // raster. A display that does not fit [`Self::MAX_DISPLAY_WIDTH`] is + // drawn at the coded size instead: the picture is shown slightly + // wrong, which is what every unrenderable header deserves, rather than + // aborting the decode worker on a capacity overflow before a pixel is + // drawn. let wide = u64::from(coded_width) * u64::from(self.h); - (((wide + u64::from(self.v) - 1) / u64::from(self.v)) as u32 | 1) & !1 + let scaled = (wide + u64::from(self.v) - 1) / u64::from(self.v); + let rounded = scaled.next_multiple_of(2); + if rounded == 0 || rounded > u64::from(Self::MAX_DISPLAY_WIDTH) { + return coded_width; + } + rounded as u32 } } @@ -2911,14 +2968,21 @@ fn rotation_of_roll(degrees: f64) -> crate::Result { /// /// The units decide what the pair *is*: 3 spells a display aspect ratio (16 and /// 9 over 1440x1080 is what ffmpeg writes for a `setsar=4/3` source, measured), -/// 4 spells the sample aspect ratio itself, and 0/absent spells pixels -- where -/// a pair beside the coded one at all means a crop, not an aspect. 1 and 2 -/// (centimetres, inches) are physical sizes a picture this engine shows cannot -/// mean anything by, and read as square rather than guessed. Every unstated or -/// unusable shape is [`PixelAspect::SQUARE`], which is also the answer the spec's -/// own default gives: DisplayWidth and DisplayHeight "SHOULD be set to the -/// PixelWidth and PixelHeight" when they mean the same thing, so a file that -/// means square most often says nothing at all. +/// 4 spells the sample aspect ratio itself, and **0 spells pixels** -- which is +/// the ordinary case and the one a `Display*` pair is *for*: the spec has the +/// pair in pixels, so `1920`x`1080` beside a `1440`x`1080` coded track is +/// exactly the 4/3 stretch, stated the way this door below reads it. An absent +/// pair is the file saying nothing, which is also square; a pair that *is* +/// present and equal to the coded one is square by arithmetic, not by +/// assumption. +/// +/// 1 and 2 (centimetres, inches) are physical sizes a picture this engine +/// shows on a screen cannot mean anything by, and read as square rather than +/// guessed. Every unstated or unusable shape is [`PixelAspect::SQUARE`], which +/// is also the answer the spec's own default gives: DisplayWidth and +/// DisplayHeight "SHOULD be set to the PixelWidth and PixelHeight" when they +/// mean the same thing, so a file that means square most often says nothing +/// at all. fn pixel_aspect_of( display_width: u64, display_height: u64, @@ -2931,22 +2995,30 @@ fn pixel_aspect_of( if display_width == 0 || display_height == 0 || coded_width == 0 || coded_height == 0 { return PixelAspect::SQUARE; } + // A stated pair, whichever unit spells it, is a claim about a real + // picture and is judged by [`PixelAspect::stated`] like every other + // header read: a ratio that reduces to nothing usable is square, and the + // caller learns that by being handed it rather than by a zero-width + // raster later on. + let stated = |h: u64, v: u64| { + PixelAspect::stated(h.min(u64::from(u32::MAX)) as u32, v.min(u64::from(u32::MAX)) as u32) + .unwrap_or(PixelAspect::SQUARE) + }; match display_unit { // 4: the pair *is* the sample aspect ratio. - 4 => PixelAspect { - h: display_width.min(u32::MAX as u64) as u32, - v: display_height.min(u32::MAX as u64) as u32, - }, - // 3: the pair is the display aspect ratio -- display_w / display_h -- - // which the SAR is that against the coded one: sar = dar * h / w. - // 16/9 over 1440x1080 lands on 4/3. - 3 => PixelAspect { - h: ((display_width * u64::from(coded_height)) - .min(u32::MAX as u64 * u64::from(coded_width))) as u32, - v: ((display_height * u64::from(coded_width)) - .min(u32::MAX as u64 * u64::from(coded_height))) as u32, - }, - // Pixels (0) or a physical unit this engine cannot interpret: square. + 4 => stated(display_width, display_height), + // 3: the pair is a display *aspect ratio*, and 0: the pair is a + // display *pixel size*. Both reduce to the same SAR -- the ratio + // against the coded one -- and that they do is the point: 16/9 over + // 1440x1080 and 1920x1080 over 1440x1080 are the same claim about the + // same picture, and both land on 4/3. `saturating_mul` because the + // pair is untrusted and a product past a u64 is a claim with no + // picture behind it. + 0 | 3 => stated( + display_width.saturating_mul(u64::from(coded_height)), + display_height.saturating_mul(u64::from(coded_width)), + ), + // A physical unit this engine cannot interpret: square. _ => PixelAspect::SQUARE, } } @@ -4173,7 +4245,11 @@ fn pasp_of(path: &Path, track_id: u32) -> PixelAspect { ) else { return PixelAspect::SQUARE; }; - PixelAspect { h, v } + // Eight bytes a file chose, read into a ratio that sizes every raster + // downstream, so they are judged by [`PixelAspect::stated`] here: the + // aspect this engine *reports* is one it can draw, not merely one it + // survived. + PixelAspect::stated(h, v).unwrap_or(PixelAspect::SQUARE) } /// The `clli` and `mdcv` boxes of `track_id`'s sample entry: what an mp4 says @@ -5613,6 +5689,50 @@ mod tests { assert_eq!(first_frame_sample(entries, Some(0)), 1, "zero is no trim"); } + /// Four bytes of an mp4 `pasp` box are four bytes of untrusted input, and + /// every one of them reaches the width an allocation is sized from. A + /// header that claims `h == 0`, or one whose ratio widens the coded width + /// past the whole `u32` range, must read as the picture it really is -- + /// square, drawn at the coded size -- rather than as a zero-column or a + /// wrapped raster the decode worker tries to allocate. + #[test] + fn an_untrusted_pixel_aspect_cannot_size_a_zero_or_wrapped_raster() { + // Collected, not asserted one at a time: a witness that stops at the + // first degenerate hides whether the other classes are caught too. + let wrong: Vec = [ + PixelAspect { h: 0, v: 1 }, + PixelAspect { h: 1, v: 0 }, + PixelAspect { h: 0, v: 0 }, + // 1920 * 0x00FF_FFFF is 32_212_252_800: it wraps a u32 to + // 2_147_483_648, which is a plausible-looking "width" and an + // impossible one to allocate. + PixelAspect { h: 0x00FF_FFFF, v: 1 }, + PixelAspect { h: 0xFFFF_FFFF, v: 0xFFFF_FFFF - 1 }, + // A ratio that is not a raster anybody has: 1:0x00FF_FFFF. + PixelAspect { h: 1, v: 0x00FF_FFFF }, + ] + .into_iter() + .filter_map(|hostile| { + let factor = hostile.width_factor(1920); + (factor != 1920).then(|| { + format!("{hostile:?} -> {factor} (a zero column or an oversized raster)") + }) + }) + .collect(); + assert!( + wrong.is_empty(), + "a degenerate pixel aspect must read as square:\n{}", + wrong.join("\n") + ); + // The sane ratios still stretch, bit for bit as they always did: the + // hardening refuses the untrusted, it does not round the ordinary. + assert_eq!(PixelAspect { h: 4, v: 3 }.width_factor(1440), 1920); + assert_eq!(PixelAspect { h: 1, v: 1 }.width_factor(1920), 1920); + assert_eq!(PixelAspect::SQUARE.width_factor(1920), 1920); + // An unreduced spelling of the same 4:3 lands on the same picture. + assert_eq!(PixelAspect { h: 16, v: 12 }.width_factor(1440), 1920); + } + #[test] fn rejects_misparse() { assert!(append_annex_b(&[0, 0, 0, 9, 0x65], 4, &mut Vec::new()).is_err()); diff --git a/crates/engine/tests/untrusted_header.rs b/crates/engine/tests/untrusted_header.rs new file mode 100644 index 0000000..c24c407 --- /dev/null +++ b/crates/engine/tests/untrusted_header.rs @@ -0,0 +1,163 @@ +//! What a container header claims is untrusted input, and the numbers it +//! claims them with reach every raster this engine sizes. +//! +//! An mp4 `pasp` box is eight bytes: two 32-bit big-endian integers, the ratio +//! one coded pixel is drawn at. Nothing in the file makes them sane. Four +//! chosen bytes are enough to make the probe report a zero width, or a width +//! that wrapped a `u32` on its way down from the multiply -- and both of those +//! go straight into the `resize` that sizes the decode worker's stretched +//! planes, before a single pixel is drawn. +//! +//! This test byte-patches a copy of the baseline fixture and opens it through +//! the ordinary door: the patched files live in a temp directory and are made +//! here, so no hostile bytes are committed to the repository. +//! +//! ```text +//! cargo test -p engine --test untrusted_header -- --test-threads=1 +//! ``` + +use std::path::{Path, PathBuf}; + +use engine::demux::Demuxer; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// A temp directory that cleans itself up, so a failing test does not leave a +/// hostile mp4 lying around for the next one to trip over. +struct Scratch(PathBuf); + +impl Scratch { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("edith-untrusted-header-{tag}")); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("a temp directory for the patched fixture"); + Self(dir) + } + + fn path(&self, name: &str) -> PathBuf { + self.0.join(name) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A copy of `source` with the eight bytes of its `pasp` payload replaced. +/// +/// Returns the byte offset the payload was written at, so the test can name +/// the exact bytes it changed rather than asserting about a file whose +/// provenance is a fixture somebody might regenerate. +fn patch_pasp(source: &Path, into: &Path, h: u32, v: u32) -> usize { + let bytes = std::fs::read(source).expect("read the source fixture"); + let at = bytes + .windows(4) + .position(|window| window == b"pasp") + .expect("the fixture carries a pasp box") + + 4; // the type is four bytes; the payload follows it + let mut patched = bytes.clone(); + patched[at..at + 4].copy_from_slice(&h.to_be_bytes()); + patched[at + 4..at + 8].copy_from_slice(&v.to_be_bytes()); + std::fs::write(into, patched).expect("write the patched fixture"); + at +} + +/// The claims an mp4 can make about its pixels that are not a picture: a zero +/// half, which divides to nothing, and a huge half, whose multiply wraps a +/// `u32` on the way down. +#[test] +fn a_pasp_box_cannot_declare_a_zero_or_wrapped_display_width() { + // Read the untouched fixture first: the patches below are asserted + // against *its* numbers, so a regenerated fixture that stops carrying a + // `pasp` box fails here loudly instead of silently passing. + let (baseline, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open the baseline"); + let coded = (baseline.coded_width, baseline.coded_height); + assert_eq!( + (baseline.width, baseline.height), + coded, + "the baseline fixture is square, so its display pair is its coded pair -- which is \ + what the patched files are asserted against" + ); + assert!( + baseline.pixel_aspect.is_square(), + "the baseline fixture states 1:1, which is square" + ); + + let scratch = Scratch::new("pasp"); + for (tag, h, v) in [ + ("zero_h", 0u32, 1u32), + ("zero_v", 1, 0), + ("both_zero", 0, 0), + // 1920 * 0x00FF_FFFF = 32_212_252_800, which narrowed to a u32 is + // 2_147_481_728: a width that looks plausible in a log and cannot be + // allocated on any machine this runs on. + ("wrap_h", 0x00FF_FFFF, 1), + // 1:0x00FF_FFFF is the other end: a two-column strip of a picture. + ("wrap_v", 1, 0x00FF_FFFF), + ] { + let name = format!("pasp_{tag}.mp4"); + let into = scratch.path(&name); + let at = patch_pasp(&asset("test_baseline.mp4"), &into, h, v); + assert_eq!( + std::fs::read(&into).unwrap()[at..at + 8], + [h.to_be_bytes(), v.to_be_bytes()].concat(), + "{tag}: the patch landed where it was aimed" + ); + + // The ordinary door: open the file the way a library open does. + let (meta, _) = Demuxer::open(&into) + .unwrap_or_else(|why| panic!("{tag} (pasp {h}:{v} at byte {at}): open failed: {why}")); + + // A header that claims an unusable ratio is read as the picture it + // really is: the coded one, square, drawn one to one. + assert_eq!( + (meta.width, meta.height), + (baseline.width, baseline.height), + "{tag} (pasp {h}:{v}): an unusable ratio must read as square, not as a \ + zero-column or wrapped raster" + ); + assert!( + meta.pixel_aspect.is_square(), + "{tag} (pasp {h}:{v}): the reported aspect must be one this engine can draw" + ); + assert!( + meta.width > 0 && meta.height > 0, + "{tag} (pasp {h}:{v}): a zero dimension here is what sizes an allocation to nothing" + ); + } +} + +/// The half that matters is not the probe: it is the worker that sizes its +/// stretched planes from the same number. A decode that used to abort on a +/// capacity overflow here now returns the coded picture. +#[test] +fn a_hostile_pasp_decodes_the_coded_picture_instead_of_aborting() { + let scratch = Scratch::new("decode"); + let into = scratch.path("pasp_wrap.mp4"); + patch_pasp(&asset("test_baseline.mp4"), &into, 0x00FF_FFFF, 1); + + let (baseline, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open the baseline"); + let coded = (baseline.width, baseline.height); + let (meta, _) = Demuxer::open(&into).expect("a hostile header is still an openable file"); + let (_, frames, _) = + engine::DecodeSession::open_at(&into, 0).expect("a hostile header does not stop the decoder"); + let frame = frames + .recv() + .expect("the first frame arrives rather than the worker aborting on its allocation"); + assert_eq!( + frame.width, + meta.width, + "the decoded frame is drawn at the width the probe reported" + ); + assert_eq!( + (frame.width, frame.height), + coded, + "the coded picture, drawn square: a wrapped claim resizes nothing" + ); +} \ No newline at end of file