forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

untrusted_header.rs247 lines, 10.1 KiBHistoryRawDownload
1//! What a container header claims is untrusted input, and the numbers it
2//! claims them with reach every raster this engine sizes.
3//!
4//! An mp4 `pasp` box is eight bytes: two 32-bit big-endian integers, the ratio
5//! one coded pixel is drawn at. Nothing in the file makes them sane. Four
6//! chosen bytes are enough to make the probe report a zero width, or a width
7//! that wrapped a `u32` on its way down from the multiply -- and both of those
8//! go straight into the `resize` that sizes the decode worker's stretched
9//! planes, before a single pixel is drawn.
10//!
11//! This test byte-patches a copy of the baseline fixture and opens it through
12//! the ordinary door: the patched files live in a temp directory and are made
13//! here, so no hostile bytes are committed to the repository.
14//!
15//! ```text
16//! cargo test -p engine --test untrusted_header -- --test-threads=1
17//! ```
18
19use std::path::{Path, PathBuf};
20
21use engine::demux::Demuxer;
22
23fn asset(name: &str) -> PathBuf {
24 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
25 .join("../../assets")
26 .join(name)
27}
28
29/// A temp directory that cleans itself up, so a failing test does not leave a
30/// hostile mp4 lying around for the next one to trip over.
31struct Scratch(PathBuf);
32
33impl Scratch {
34 fn new(tag: &str) -> Self {
35 let dir = std::env::temp_dir().join(format!("edith-untrusted-header-{tag}"));
36 let _ = std::fs::remove_dir_all(&dir);
37 std::fs::create_dir_all(&dir).expect("a temp directory for the patched fixture");
38 Self(dir)
39 }
40
41 fn path(&self, name: &str) -> PathBuf {
42 self.0.join(name)
43 }
44}
45
46impl Drop for Scratch {
47 fn drop(&mut self) {
48 let _ = std::fs::remove_dir_all(&self.0);
49 }
50}
51
52/// A copy of `source` with the eight bytes of its `pasp` payload replaced.
53///
54/// Returns the byte offset the payload was written at, so the test can name
55/// the exact bytes it changed rather than asserting about a file whose
56/// provenance is a fixture somebody might regenerate.
57fn patch_pasp(source: &Path, into: &Path, h: u32, v: u32) -> usize {
58 let bytes = std::fs::read(source).expect("read the source fixture");
59 let at = bytes
60 .windows(4)
61 .position(|window| window == b"pasp")
62 .expect("the fixture carries a pasp box")
63 + 4; // the type is four bytes; the payload follows it
64 let mut patched = bytes.clone();
65 patched[at..at + 4].copy_from_slice(&h.to_be_bytes());
66 patched[at + 4..at + 8].copy_from_slice(&v.to_be_bytes());
67 std::fs::write(into, patched).expect("write the patched fixture");
68 at
69}
70
71/// The claims an mp4 can make about its pixels that are not a picture: a zero
72/// half, which divides to nothing, and a huge half, whose multiply wraps a
73/// `u32` on the way down.
74#[test]
75fn a_pasp_box_cannot_declare_a_zero_or_wrapped_display_width() {
76 // Read the untouched fixture first: the patches below are asserted
77 // against *its* numbers, so a regenerated fixture that stops carrying a
78 // `pasp` box fails here loudly instead of silently passing.
79 let (baseline, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open the baseline");
80 let coded = (baseline.coded_width, baseline.coded_height);
81 assert_eq!(
82 (baseline.width, baseline.height),
83 coded,
84 "the baseline fixture is square, so its display pair is its coded pair -- which is \
85 what the patched files are asserted against"
86 );
87 assert!(
88 baseline.pixel_aspect.is_square(),
89 "the baseline fixture states 1:1, which is square"
90 );
91
92 let scratch = Scratch::new("pasp");
93 for (tag, h, v) in [
94 ("zero_h", 0u32, 1u32),
95 ("zero_v", 1, 0),
96 ("both_zero", 0, 0),
97 // 1920 * 0x00FF_FFFF = 32_212_252_800, which narrowed to a u32 is
98 // 2_147_481_728: a width that looks plausible in a log and cannot be
99 // allocated on any machine this runs on.
100 ("wrap_h", 0x00FF_FFFF, 1),
101 // 1:0x00FF_FFFF is the other end: a two-column strip of a picture.
102 ("wrap_v", 1, 0x00FF_FFFF),
103 ] {
104 let name = format!("pasp_{tag}.mp4");
105 let into = scratch.path(&name);
106 let at = patch_pasp(&asset("test_baseline.mp4"), &into, h, v);
107 assert_eq!(
108 std::fs::read(&into).unwrap()[at..at + 8],
109 [h.to_be_bytes(), v.to_be_bytes()].concat(),
110 "{tag}: the patch landed where it was aimed"
111 );
112
113 // The ordinary door: open the file the way a library open does.
114 let (meta, _) = Demuxer::open(&into)
115 .unwrap_or_else(|why| panic!("{tag} (pasp {h}:{v} at byte {at}): open failed: {why}"));
116
117 // A header that claims an unusable ratio is read as the picture it
118 // really is: the coded one, square, drawn one to one.
119 assert_eq!(
120 (meta.width, meta.height),
121 (baseline.width, baseline.height),
122 "{tag} (pasp {h}:{v}): an unusable ratio must read as square, not as a \
123 zero-column or wrapped raster"
124 );
125 assert!(
126 meta.pixel_aspect.is_square(),
127 "{tag} (pasp {h}:{v}): the reported aspect must be one this engine can draw"
128 );
129 assert!(
130 meta.width > 0 && meta.height > 0,
131 "{tag} (pasp {h}:{v}): a zero dimension here is what sizes an allocation to nothing"
132 );
133 }
134}
135
136/// The half that matters is not the probe: it is the worker that sizes its
137/// stretched planes from the same number. A decode that used to abort on a
138/// capacity overflow here now returns the coded picture.
139#[test]
140fn a_hostile_pasp_decodes_the_coded_picture_instead_of_aborting() {
141 let scratch = Scratch::new("decode");
142 let into = scratch.path("pasp_wrap.mp4");
143 patch_pasp(&asset("test_baseline.mp4"), &into, 0x00FF_FFFF, 1);
144
145 let (baseline, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open the baseline");
146 let coded = (baseline.width, baseline.height);
147 let (meta, _) = Demuxer::open(&into).expect("a hostile header is still an openable file");
148 let (_, frames, _) =
149 engine::DecodeSession::open_at(&into, 0).expect("a hostile header does not stop the decoder");
150 let frame = frames
151 .recv()
152 .expect("the first frame arrives rather than the worker aborting on its allocation");
153 assert_eq!(
154 frame.width,
155 meta.width,
156 "the decoded frame is drawn at the width the probe reported"
157 );
158 assert_eq!(
159 (frame.width, frame.height),
160 coded,
161 "the coded picture, drawn square: a wrapped claim resizes nothing"
162 );
163}
164/// The same bound, on the other door. An mp4 states its picture in a visual
165/// sample entry's two `u16` fields -- a smaller claim than Matroska's EBML
166/// integer, but still eight times past the 8K ceiling, and it reaches the same
167/// `decode.rs` allocation.
168#[test]
169fn a_mp4_may_not_state_a_picture_past_the_resolution_bound() {
170 let scratch = Scratch::new("mp4dims");
171 let into = scratch.path("mp4_huge_dims.mp4");
172 patch_sample_entry_size(&asset("test_baseline.mp4"), &into, 65535, 65535);
173
174 let Err(why) = Demuxer::open(&into) else {
175 panic!("a 65535x65535 mp4 is refused by name, never opened");
176 };
177 let said = why.to_string();
178 assert!(
179 said.contains("65535") && said.contains(&engine::MAX_RESOLUTION.to_string()),
180 "the refusal names the size claimed and the maximum: {said}"
181 );
182 assert!(
183 engine::demux::UnsupportedDisplaySize::is_it(&why),
184 "and it is the named refusal a caller can match on, not a string"
185 );
186}
187
188/// A copy of `source` with the width and height of its first visual sample
189/// entry set to `w`/`h` (ISO/IEC 14496-12 §12.1.3: two 16-bit fields, 24
190/// bytes into the entry, after the 6 reserved bytes, the 2-byte data
191/// reference index and the 16 bytes of pre-defined and reserved fields).
192fn patch_sample_entry_size(source: &Path, into: &Path, w: u16, h: u16) {
193 let mut bytes = std::fs::read(source).expect("read the source fixture");
194 let stsd = find(&bytes, b"stsd").expect("the fixture has a sample description");
195 // 'stsd' + version/flags + entry_count, then the first entry.
196 let entry = stsd + 12;
197 assert_eq!(&bytes[entry + 4..entry + 8], b"avc1", "the first entry is the video one");
198 bytes[entry + 32..entry + 34].copy_from_slice(&w.to_be_bytes());
199 bytes[entry + 34..entry + 36].copy_from_slice(&h.to_be_bytes());
200 std::fs::write(into, bytes).expect("write the patched fixture");
201}
202
203fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
204 haystack
205 .windows(needle.len())
206 .position(|window| window == needle)
207}
208
209/// The boundary of the bound, stated as a test rather than left as a surprise:
210/// 7680 -- 8K UHD -- opens, and 8192 -- 8K DCI, a real ProRes 4444 XQ master
211/// width -- is refused by name.
212///
213/// The refusal of a DCI-width master is a behaviour change this lane
214/// introduced: before it, the bound was asked only of a keystroke and a
215/// `.edith` line, never of a file's own header, so a container could state any
216/// size at all. `MAX_RESOLUTION` stays 7680 rather than being raised to 8192,
217/// because it gates those two doors at 7680 too and widening the ceiling on
218/// every path to accommodate a container is a wider decision than a header fix
219/// should make.
220#[test]
221fn the_resolution_bound_admits_uhd_and_refuses_dci_width_by_name() {
222 let scratch = Scratch::new("dci");
223 let coded_height = 720u16;
224
225 let uhd = scratch.path("uhd_7680.mp4");
226 patch_sample_entry_size(&asset("test_baseline.mp4"), &uhd, 7680, coded_height);
227 let (meta, _) = Demuxer::open(&uhd).expect("8K UHD is inside the bound and opens");
228 assert_eq!(
229 (meta.coded_width, meta.coded_height),
230 (7680, u32::from(coded_height)),
231 "an 8K UHD header is read as stated"
232 );
233
234 let dci = scratch.path("dci_8192.mp4");
235 patch_sample_entry_size(&asset("test_baseline.mp4"), &dci, 8192, coded_height);
236 let Err(why) = Demuxer::open(&dci) else {
237 panic!("an 8192-wide DCI master is refused by name, never opened");
238 };
239 assert!(
240 engine::demux::UnsupportedDisplaySize::is_it(&why),
241 "the refusal is the named one a caller can match: {why}"
242 );
243 assert!(
244 why.to_string().contains("8192"),
245 "and it names the width claimed: {why}"
246 );
247}