Budget every header-declared allocation
Browse files at this commit81c7624861fd2c96db08377aca645bb0cabbbbe7Parent: df0c158- fix
- budget every header-declared allocation
- bound LZW growth
5 changed files +418 -5
- crates/ec-h265-syntax/src/slice.rs +11 -0
- crates/ec-image/src/gif.rs +30 -3
- crates/ec-image/src/lib.rs +80 -1
- crates/ec-image/src/webp/mod.rs +8 -1
- crates/ec-image/tests/fuzz.rs +289 -0
crates/ec-h265-syntax/src/slice.rsmodified+11 -0
| @@ -430,6 +430,17 @@ impl SliceHeader { | |||
| 430 | if h.slice_type == SliceType::B { | 430 | if h.slice_type == SliceType::B { |
| 431 | h.num_ref_idx_l1_active_minus1 = r.read_ue()?; | 431 | h.num_ref_idx_l1_active_minus1 = r.read_ue()?; |
| 432 | } | 432 | } |
| 433 | + // 7.4.7.1: both fields are in range 0..=14. Past that is | ||
| 434 | + // a corrupt stream, not a bigger reference list -- and | ||
| 435 | + // pred_weight_table below sizes a Vec from this value, so | ||
| 436 | + // an unchecked ue(v) is a header-declared allocation an | ||
| 437 | + // attacker fully controls (up to 2^32 entries from a | ||
| 438 | + // handful of bits). | ||
| 439 | + if h.num_ref_idx_l0_active_minus1 > 14 || h.num_ref_idx_l1_active_minus1 > 14 { | ||
| 440 | + return Err(Error::corrupt( | ||
| 441 | + "HEVC slice header: num_ref_idx_lX_active_minus1 out of range", | ||
| 442 | + )); | ||
| 443 | + } | ||
| 433 | } | 444 | } |
| 434 | let num_pic_total_curr = h.short_term_ref_pic_set.num_used_by_curr + num_long_term; | 445 | let num_pic_total_curr = h.short_term_ref_pic_set.num_used_by_curr + num_long_term; |
| 435 | if pps.lists_modification_present && num_pic_total_curr > 1 { | 446 | if pps.lists_modification_present && num_pic_total_curr > 1 { |
crates/ec-image/src/gif.rsmodified+30 -3
| @@ -14,7 +14,7 @@ | |||
| 14 | //! so a decoder that waits one code longer reads small pictures correctly and | 14 | //! so a decoder that waits one code longer reads small pictures correctly and |
| 15 | //! large ones as noise. | 15 | //! large ones as noise. |
| 16 | 16 | ||
| 17 | -use crate::{AnimationFrame, Image, ImageFormat, Info, Limits, Metadata, Pixels}; | 17 | +use crate::{AllocBudget, AnimationFrame, Image, ImageFormat, Info, Limits, Metadata, Pixels}; |
| 18 | use ec_core::{Error, Result}; | 18 | use ec_core::{Error, Result}; |
| 19 | 19 | ||
| 20 | /// GIF interlace: `(start, step)` for each of the four passes. | 20 | /// GIF interlace: `(start, step)` for each of the four passes. |
| @@ -150,6 +150,13 @@ fn lzw_decode(min_code_size: u8, data: &[u8], expected: usize) -> Result<Vec<u8> | |||
| 150 | let mut pos = 0; | 150 | let mut pos = 0; |
| 151 | 151 | ||
| 152 | while let Some(code) = lzw.read_code(data, &mut pos) { | 152 | while let Some(code) = lzw.read_code(data, &mut pos) { |
| 153 | + if out.len() >= expected { | ||
| 154 | + // Output already satisfies the declared frame size; a bomb-style | ||
| 155 | + // stream can keep growing the dictionary and emitting further | ||
| 156 | + // codes after this point, so stop before decoding any more of | ||
| 157 | + // them rather than let `out` expand unbounded (LZW bomb). | ||
| 158 | + break; | ||
| 159 | + } | ||
| 153 | if code == lzw.clear_code { | 160 | if code == lzw.clear_code { |
| 154 | lzw.reset(); | 161 | lzw.reset(); |
| 155 | continue; | 162 | continue; |
| @@ -328,7 +335,13 @@ fn indices_to_rgba(indices: &[u8], palette: &[[u8; 3]], gce: Option<&Gce>) -> Re | |||
| 328 | /// Composite every raw frame onto a full-canvas buffer: blend the frame over | 335 | /// Composite every raw frame onto a full-canvas buffer: blend the frame over |
| 329 | /// the canvas, then apply its disposal method to the canvas the next frame | 336 | /// the canvas, then apply its disposal method to the canvas the next frame |
| 330 | /// starts from. | 337 | /// starts from. |
| 331 | -fn composite(frames: Vec<RawFrame>, canvas_w: u32, canvas_h: u32) -> Result<Vec<AnimationFrame>> { | 338 | +fn composite( |
| 339 | + frames: Vec<RawFrame>, | ||
| 340 | + canvas_w: u32, | ||
| 341 | + canvas_h: u32, | ||
| 342 | + limits: &Limits, | ||
| 343 | + budget: &mut AllocBudget, | ||
| 344 | +) -> Result<Vec<AnimationFrame>> { | ||
| 332 | let cw = canvas_w as usize; | 345 | let cw = canvas_w as usize; |
| 333 | let ch = canvas_h as usize; | 346 | let ch = canvas_h as usize; |
| 334 | let n = cw * ch; | 347 | let n = cw * ch; |
| @@ -337,6 +350,10 @@ fn composite(frames: Vec<RawFrame>, canvas_w: u32, canvas_h: u32) -> Result<Vec< | |||
| 337 | let mut result: Vec<(Vec<[u8; 4]>, u32)> = Vec::with_capacity(frames.len()); | 350 | let mut result: Vec<(Vec<[u8; 4]>, u32)> = Vec::with_capacity(frames.len()); |
| 338 | 351 | ||
| 339 | for frame in frames { | 352 | for frame in frames { |
| 353 | + // Every frame clones the whole canvas -- the real multiplier a | ||
| 354 | + // single buffer's own bound never catches -- so it is spent from the | ||
| 355 | + // decode-wide budget just like the frame's own indices were above. | ||
| 356 | + budget.spend(limits, "GIF composited canvas", n * 4)?; | ||
| 340 | let indices = if frame.interlaced { | 357 | let indices = if frame.interlaced { |
| 341 | deinterlace(&frame.indices, frame.width as usize, frame.height as usize) | 358 | deinterlace(&frame.indices, frame.width as usize, frame.height as usize) |
| 342 | } else { | 359 | } else { |
| @@ -482,6 +499,8 @@ pub fn decode_animation(data: &[u8], limits: Limits) -> Result<Vec<AnimationFram | |||
| 482 | // Block loop | 499 | // Block loop |
| 483 | let mut frames = Vec::new(); | 500 | let mut frames = Vec::new(); |
| 484 | let mut pending_gce: Option<Gce> = None; | 501 | let mut pending_gce: Option<Gce> = None; |
| 502 | + let mut budget = AllocBudget::default(); | ||
| 503 | + budget.spend(&limits, "GIF canvas", canvas_bytes)?; | ||
| 485 | 504 | ||
| 486 | loop { | 505 | loop { |
| 487 | let block = r.u8()?; | 506 | let block = r.u8()?; |
| @@ -497,6 +516,14 @@ pub fn decode_animation(data: &[u8], limits: Limits) -> Result<Vec<AnimationFram | |||
| 497 | if width == 0 || height == 0 { | 516 | if width == 0 || height == 0 { |
| 498 | return Err(Error::corrupt("GIF: zero-size frame")); | 517 | return Err(Error::corrupt("GIF: zero-size frame")); |
| 499 | } | 518 | } |
| 519 | + // A frame's own rectangle is a header field like any other -- | ||
| 520 | + // nothing says it has to fit inside the canvas the logical | ||
| 521 | + // screen descriptor already bounded, so it gets its own check | ||
| 522 | + // before it sizes the indices buffer below. | ||
| 523 | + limits.check(width, height)?; | ||
| 524 | + let indices_bytes = | ||
| 525 | + limits.check_bytes("GIF frame indices", (width as usize).checked_mul(height as usize))?; | ||
| 526 | + budget.spend(&limits, "GIF frame indices", indices_bytes)?; | ||
| 500 | 527 | ||
| 501 | let has_lct = fpacked & 0x80 != 0; | 528 | let has_lct = fpacked & 0x80 != 0; |
| 502 | let interlaced = fpacked & 0x40 != 0; | 529 | let interlaced = fpacked & 0x40 != 0; |
| @@ -567,5 +594,5 @@ pub fn decode_animation(data: &[u8], limits: Limits) -> Result<Vec<AnimationFram | |||
| 567 | return Err(Error::corrupt("GIF: no image data")); | 594 | return Err(Error::corrupt("GIF: no image data")); |
| 568 | } | 595 | } |
| 569 | 596 | ||
| 570 | - composite(frames, canvas_w, canvas_h) | 597 | + composite(frames, canvas_w, canvas_h, &limits, &mut budget) |
| 571 | } | 598 | } |
crates/ec-image/src/lib.rsmodified+80 -1
| @@ -120,13 +120,22 @@ pub struct Limits { | |||
| 120 | pub max_pixels: u64, | 120 | pub max_pixels: u64, |
| 121 | /// Largest single decompressed buffer accepted, in bytes. | 121 | /// Largest single decompressed buffer accepted, in bytes. |
| 122 | pub max_alloc: usize, | 122 | pub max_alloc: usize, |
| 123 | + /// Largest total bytes accepted across every frame of one decode call. | ||
| 124 | + /// | ||
| 125 | + /// A single frame can pass [`Limits::check_bytes`] on its own and still | ||
| 126 | + /// be a bomb once an animation's frame count multiplies it — GIF and | ||
| 127 | + /// WebP both composite onto a full canvas per frame, so a file with many | ||
| 128 | + /// small-looking frames can retain gigabytes nothing ever checked one | ||
| 129 | + /// buffer at a time. [`AllocBudget`] enforces this across a decode call. | ||
| 130 | + pub max_total_alloc: usize, | ||
| 123 | } | 131 | } |
| 124 | 132 | ||
| 125 | impl Default for Limits { | 133 | impl Default for Limits { |
| 126 | fn default() -> Self { | 134 | fn default() -> Self { |
| 127 | Limits { | 135 | Limits { |
| 128 | max_pixels: 1 << 28, | 136 | max_pixels: 1 << 28, |
| 129 | - max_alloc: 1 << 32, | 137 | + max_alloc: 1 << 30, |
| 138 | + max_total_alloc: 1 << 32, | ||
| 130 | } | 139 | } |
| 131 | } | 140 | } |
| 132 | } | 141 | } |
| @@ -146,6 +155,49 @@ impl Limits { | |||
| 146 | } | 155 | } |
| 147 | Ok(()) | 156 | Ok(()) |
| 148 | } | 157 | } |
| 158 | + | ||
| 159 | + /// Check a byte count computed from header-declared fields (a frame's | ||
| 160 | + /// `width * height * bpp`, a palette size, a chunk length) before it | ||
| 161 | + /// sizes a single allocation. `what` names the buffer for the error. | ||
| 162 | + pub fn check_bytes(&self, what: &str, bytes: Option<usize>) -> Result<usize> { | ||
| 163 | + let bytes = | ||
| 164 | + bytes.ok_or_else(|| Error::corrupt(format!("{what}: size overflows usize")))?; | ||
| 165 | + if bytes > self.max_alloc { | ||
| 166 | + return Err(Error::unsupported( | ||
| 167 | + what.to_string(), | ||
| 168 | + format!("{bytes} bytes past the {} allocation limit", self.max_alloc), | ||
| 169 | + )); | ||
| 170 | + } | ||
| 171 | + Ok(bytes) | ||
| 172 | + } | ||
| 173 | +} | ||
| 174 | + | ||
| 175 | +/// Accumulates bytes spent across every frame of one decode call and refuses | ||
| 176 | +/// once the running total crosses [`Limits::max_total_alloc`] — the guard | ||
| 177 | +/// for `frame_count x canvas`, which [`Limits::check_bytes`] alone never | ||
| 178 | +/// sees since it only ever looks at one buffer at a time. | ||
| 179 | +#[derive(Debug, Default)] | ||
| 180 | +pub struct AllocBudget(usize); | ||
| 181 | + | ||
| 182 | +impl AllocBudget { | ||
| 183 | + /// Spend `bytes` from the budget, refusing once the running total passes | ||
| 184 | + /// `limits.max_total_alloc`. | ||
| 185 | + pub fn spend(&mut self, limits: &Limits, what: &str, bytes: usize) -> Result<()> { | ||
| 186 | + self.0 = self | ||
| 187 | + .0 | ||
| 188 | + .checked_add(bytes) | ||
| 189 | + .ok_or_else(|| Error::corrupt(format!("{what}: total size overflows usize")))?; | ||
| 190 | + if self.0 > limits.max_total_alloc { | ||
| 191 | + return Err(Error::unsupported( | ||
| 192 | + what.to_string(), | ||
| 193 | + format!( | ||
| 194 | + "{} total decoded bytes past the {} limit", | ||
| 195 | + self.0, limits.max_total_alloc | ||
| 196 | + ), | ||
| 197 | + )); | ||
| 198 | + } | ||
| 199 | + Ok(()) | ||
| 200 | + } | ||
| 149 | } | 201 | } |
| 150 | 202 | ||
| 151 | /// What a file said about its own pixels, parsed but not applied. | 203 | /// What a file said about its own pixels, parsed but not applied. |
| @@ -478,4 +530,31 @@ mod tests { | |||
| 478 | assert!(limits.check(0, 10).is_err()); | 530 | assert!(limits.check(0, 10).is_err()); |
| 479 | assert!(limits.check(100_000, 100_000).is_err()); | 531 | assert!(limits.check(100_000, 100_000).is_err()); |
| 480 | } | 532 | } |
| 533 | + | ||
| 534 | + #[test] | ||
| 535 | + fn check_bytes_refuses_past_max_alloc_before_a_frame_size_carries_it() { | ||
| 536 | + let limits = Limits::default(); | ||
| 537 | + assert!(limits.check_bytes("test", Some(1024)).is_ok()); | ||
| 538 | + assert!(limits.check_bytes("test", Some(limits.max_alloc + 1)).is_err()); | ||
| 539 | + assert!(limits.check_bytes("test", None).is_err()); | ||
| 540 | + } | ||
| 541 | + | ||
| 542 | + #[test] | ||
| 543 | + fn alloc_budget_refuses_once_repeated_spends_cross_the_total() { | ||
| 544 | + // The class this guards: no single spend is ever over budget on its | ||
| 545 | + // own, but a canvas cloned once per animation frame is. | ||
| 546 | + let limits = Limits::default(); | ||
| 547 | + let mut budget = AllocBudget::default(); | ||
| 548 | + let per_frame = limits.max_total_alloc / 4; | ||
| 549 | + for i in 0..4 { | ||
| 550 | + assert!( | ||
| 551 | + budget.spend(&limits, "frame", per_frame).is_ok(), | ||
| 552 | + "frame {i} alone is within budget" | ||
| 553 | + ); | ||
| 554 | + } | ||
| 555 | + assert!( | ||
| 556 | + budget.spend(&limits, "frame", per_frame).is_err(), | ||
| 557 | + "a fifth frame the same size crosses the total" | ||
| 558 | + ); | ||
| 559 | + } | ||
| 481 | } | 560 | } |
crates/ec-image/src/webp/mod.rsmodified+8 -1
| @@ -245,8 +245,11 @@ pub fn decode_frames(data: &[u8], limits: Limits) -> Result<Vec<crate::Animation | |||
| 245 | // advice to a viewer about what to show behind the animation, not a colour | 245 | // advice to a viewer about what to show behind the animation, not a colour |
| 246 | // the frames are composited onto -- libwebp's own animation decoder | 246 | // the frames are composited onto -- libwebp's own animation decoder |
| 247 | // ignores it the same way. | 247 | // ignores it the same way. |
| 248 | - let mut canvas = vec![0u8; canvas_width as usize * canvas_height as usize * 4]; | 248 | + let canvas_bytes = canvas_width as usize * canvas_height as usize * 4; |
| 249 | + let mut canvas = vec![0u8; canvas_bytes]; | ||
| 249 | let mut dispose: Option<(u32, u32, u32, u32)> = None; | 250 | let mut dispose: Option<(u32, u32, u32, u32)> = None; |
| 251 | + let mut budget = crate::AllocBudget::default(); | ||
| 252 | + budget.spend(&limits, "WebP canvas", canvas_bytes)?; | ||
| 250 | 253 | ||
| 251 | for chunk in &chunks { | 254 | for chunk in &chunks { |
| 252 | if &chunk.tag != b"ANMF" { | 255 | if &chunk.tag != b"ANMF" { |
| @@ -267,6 +270,10 @@ pub fn decode_frames(data: &[u8], limits: Limits) -> Result<Vec<crate::Animation | |||
| 267 | "WebP: frame {width}x{height}+{x}+{y} runs off a {canvas_width}x{canvas_height} canvas" | 270 | "WebP: frame {width}x{height}+{x}+{y} runs off a {canvas_width}x{canvas_height} canvas" |
| 268 | ))); | 271 | ))); |
| 269 | } | 272 | } |
| 273 | + // Every ANMF frame clones the whole composited canvas below -- the | ||
| 274 | + // real multiplier a single buffer's own bound never catches -- so | ||
| 275 | + // it is spent from the decode-wide budget before that clone runs. | ||
| 276 | + budget.spend(&limits, "WebP composited canvas", canvas_bytes)?; | ||
| 270 | 277 | ||
| 271 | // The previous frame's disposal happens before this one is drawn, so a | 278 | // The previous frame's disposal happens before this one is drawn, so a |
| 272 | // caller that keeps every frame still sees each one whole. | 279 | // caller that keeps every frame still sees each one whole. |
crates/ec-image/tests/fuzz.rsmodified+289 -0
| @@ -257,6 +257,295 @@ fn a_header_asking_for_more_pixels_than_the_limit_is_refused() { | |||
| 257 | assert!(format!("{err}").contains("limit"), "{err}"); | 257 | assert!(format!("{err}").contains("limit"), "{err}"); |
| 258 | } | 258 | } |
| 259 | 259 | ||
| 260 | +/// LSB-first bit packer, matching how every decoder in this crate reads a | ||
| 261 | +/// GIF LZW or VP8L bitstream: used to hand-craft the smallest possible valid | ||
| 262 | +/// compressed payload for the budget tests below. | ||
| 263 | +struct BitWriter { | ||
| 264 | + buffer: u64, | ||
| 265 | + bits: u8, | ||
| 266 | + out: Vec<u8>, | ||
| 267 | +} | ||
| 268 | + | ||
| 269 | +impl BitWriter { | ||
| 270 | + fn new() -> Self { | ||
| 271 | + BitWriter { | ||
| 272 | + buffer: 0, | ||
| 273 | + bits: 0, | ||
| 274 | + out: Vec::new(), | ||
| 275 | + } | ||
| 276 | + } | ||
| 277 | + | ||
| 278 | + fn push(&mut self, value: u16, width: u8) { | ||
| 279 | + self.buffer |= u64::from(value) << self.bits; | ||
| 280 | + self.bits += width; | ||
| 281 | + while self.bits >= 8 { | ||
| 282 | + self.out.push((self.buffer & 0xff) as u8); | ||
| 283 | + self.buffer >>= 8; | ||
| 284 | + self.bits -= 8; | ||
| 285 | + } | ||
| 286 | + } | ||
| 287 | + | ||
| 288 | + fn finish(mut self) -> Vec<u8> { | ||
| 289 | + if self.bits > 0 { | ||
| 290 | + self.out.push((self.buffer & 0xff) as u8); | ||
| 291 | + } | ||
| 292 | + self.out | ||
| 293 | + } | ||
| 294 | +} | ||
| 295 | + | ||
| 296 | +/// A minimal GIF: no global colour table, one 0x2C image descriptor with a | ||
| 297 | +/// 2-colour local table and a one-pixel LZW stream (clear, colour 0, end), | ||
| 298 | +/// followed by the trailer. `canvas_w`/`canvas_h` size the logical screen; | ||
| 299 | +/// the frame itself is always 1x1 so its own indices buffer is trivial — | ||
| 300 | +/// what grows per frame is the *composited canvas* `composite` clones. | ||
| 301 | +fn one_pixel_gif(canvas_w: u16, canvas_h: u16, frames: usize) -> Vec<u8> { | ||
| 302 | + let mut w = BitWriter::new(); | ||
| 303 | + w.push(4, 3); // clear code (min_code_size 2 -> clear = 1<<2) | ||
| 304 | + w.push(0, 3); // colour index 0, literal | ||
| 305 | + w.push(5, 3); // end code | ||
| 306 | + let lzw = w.finish(); | ||
| 307 | + | ||
| 308 | + let mut data = Vec::new(); | ||
| 309 | + data.extend_from_slice(b"GIF87a"); | ||
| 310 | + data.extend_from_slice(&canvas_w.to_le_bytes()); | ||
| 311 | + data.extend_from_slice(&canvas_h.to_le_bytes()); | ||
| 312 | + data.push(0x00); // no global colour table | ||
| 313 | + data.push(0); | ||
| 314 | + data.push(0); | ||
| 315 | + for _ in 0..frames { | ||
| 316 | + data.push(0x2C); | ||
| 317 | + data.extend_from_slice(&0u16.to_le_bytes()); // left | ||
| 318 | + data.extend_from_slice(&0u16.to_le_bytes()); // top | ||
| 319 | + data.extend_from_slice(&1u16.to_le_bytes()); // width | ||
| 320 | + data.extend_from_slice(&1u16.to_le_bytes()); // height | ||
| 321 | + data.push(0x80); // has LCT, sorted=0, size field 0 -> 2 colours | ||
| 322 | + data.extend_from_slice(&[0, 0, 0, 255, 255, 255]); // 2-colour LCT | ||
| 323 | + data.push(2); // min code size | ||
| 324 | + data.push(lzw.len() as u8); | ||
| 325 | + data.extend_from_slice(&lzw); | ||
| 326 | + data.push(0); // sub-block terminator | ||
| 327 | + } | ||
| 328 | + data.push(0x3B); // trailer | ||
| 329 | + data | ||
| 330 | +} | ||
| 331 | + | ||
| 332 | +#[test] | ||
| 333 | +fn a_gif_frame_asking_for_more_pixels_than_the_limit_is_refused() { | ||
| 334 | + // A single 0x2C image descriptor declaring a 60000x60000 frame: the | ||
| 335 | + // frame's own rectangle is a header field like the canvas is, and must | ||
| 336 | + // be refused before it sizes the indices buffer below it. | ||
| 337 | + let mut data = Vec::new(); | ||
| 338 | + data.extend_from_slice(b"GIF87a"); | ||
| 339 | + data.extend_from_slice(&4u16.to_le_bytes()); | ||
| 340 | + data.extend_from_slice(&4u16.to_le_bytes()); | ||
| 341 | + data.push(0x00); | ||
| 342 | + data.push(0); | ||
| 343 | + data.push(0); | ||
| 344 | + data.push(0x2C); | ||
| 345 | + data.extend_from_slice(&0u16.to_le_bytes()); | ||
| 346 | + data.extend_from_slice(&0u16.to_le_bytes()); | ||
| 347 | + data.extend_from_slice(&60000u16.to_le_bytes()); | ||
| 348 | + data.extend_from_slice(&60000u16.to_le_bytes()); | ||
| 349 | + data.push(0x00); | ||
| 350 | + | ||
| 351 | + let start = std::time::Instant::now(); | ||
| 352 | + let err = ec_image::decode_animation(&data).expect_err("60000x60000 frame is past the limit"); | ||
| 353 | + assert!(start.elapsed().as_millis() < 100, "{:?}", start.elapsed()); | ||
| 354 | + assert!(format!("{err}").contains("limit"), "{err}"); | ||
| 355 | +} | ||
| 356 | + | ||
| 357 | +#[test] | ||
| 358 | +fn a_gif_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget() { | ||
| 359 | + // Each frame is 1x1 -- cheap to encode, cheap to check on its own -- but | ||
| 360 | + // `composite` clones the *whole* canvas onto the result once per frame. | ||
| 361 | + // A canvas near the single-buffer limit, repeated a few dozen times, | ||
| 362 | + // must be caught by the decode-wide budget even though no single frame | ||
| 363 | + // or single buffer ever looks large by itself. | ||
| 364 | + let data = one_pixel_gif(16000, 16000, 64); | ||
| 365 | + let start = std::time::Instant::now(); | ||
| 366 | + let err = ec_image::decode_animation(&data) | ||
| 367 | + .expect_err("64 clones of a near-limit canvas is past the total budget"); | ||
| 368 | + // A few real canvas clones run before the budget catches up (the budget | ||
| 369 | + // is spent per frame, so it can't refuse before at least one clone), so | ||
| 370 | + // this bounds "a handful of gigabyte copies", not "no allocation at all". | ||
| 371 | + assert!(start.elapsed().as_secs() < 5, "{:?}", start.elapsed()); | ||
| 372 | + assert!(format!("{err}").contains("limit"), "{err}"); | ||
| 373 | +} | ||
| 374 | + | ||
| 375 | +#[test] | ||
| 376 | +fn a_gif_with_a_few_tiny_frames_over_a_huge_canvas_still_decodes() { | ||
| 377 | + // The other side of the same budget: a handful of frames over a large | ||
| 378 | + // canvas is exactly what a real animation looks like, and must not be | ||
| 379 | + // refused just because the guard above exists. | ||
| 380 | + let data = one_pixel_gif(4000, 4000, 3); | ||
| 381 | + let frames = ec_image::decode_animation(&data).expect("well within every limit"); | ||
| 382 | + assert_eq!(frames.len(), 3); | ||
| 383 | +} | ||
| 384 | + | ||
| 385 | +/// A minimal RIFF WebP with an ANIM/VP8X header and `frames` ANMF chunks, | ||
| 386 | +/// each carrying a 1x1 VP8L payload (the smallest valid lossless image: a | ||
| 387 | +/// bitstream header plus one pixel, no transforms, no colour cache). | ||
| 388 | +fn one_pixel_animated_webp(canvas_w: u32, canvas_h: u32, frames: usize) -> Vec<u8> { | ||
| 389 | + // VP8L bitstream for a 1x1 image: signature 0x2f, 14-bit width-1=0, | ||
| 390 | + // 14-bit height-1=0, 1-bit alpha flag=0, 3-bit version=0, then the | ||
| 391 | + // image data: no colour cache, no meta prefix, one simple prefix code | ||
| 392 | + // per channel (colour index 0 for all four), then the single pixel. | ||
| 393 | + let mut w = BitWriter::new(); | ||
| 394 | + w.push(0, 14); // width - 1 | ||
| 395 | + w.push(0, 14); // height - 1 | ||
| 396 | + w.push(0, 1); // alpha_is_used | ||
| 397 | + w.push(0, 3); // version | ||
| 398 | + w.push(0, 1); // no transform | ||
| 399 | + w.push(0, 1); // no colour cache | ||
| 400 | + w.push(0, 1); // no meta prefix | ||
| 401 | + for _ in 0..5 { | ||
| 402 | + // green/red/blue/alpha/distance, in that order: a simple code, one | ||
| 403 | + // symbol, value 0. | ||
| 404 | + w.push(1, 1); // simple code | ||
| 405 | + w.push(0, 1); // one symbol | ||
| 406 | + w.push(0, 1); // symbol is not a literal byte read as 8 bits | ||
| 407 | + w.push(0, 1); // symbol0 = 0 | ||
| 408 | + } | ||
| 409 | + let vp8l_bits = w.finish(); | ||
| 410 | + let mut vp8l = vec![0x2f]; | ||
| 411 | + vp8l.extend_from_slice(&vp8l_bits); | ||
| 412 | + if vp8l.len() % 2 == 1 { | ||
| 413 | + vp8l.push(0); | ||
| 414 | + } | ||
| 415 | + | ||
| 416 | + fn chunk(tag: &[u8; 4], body: &[u8]) -> Vec<u8> { | ||
| 417 | + let mut c = Vec::new(); | ||
| 418 | + c.extend_from_slice(tag); | ||
| 419 | + c.extend_from_slice(&(body.len() as u32).to_le_bytes()); | ||
| 420 | + c.extend_from_slice(body); | ||
| 421 | + if body.len() % 2 == 1 { | ||
| 422 | + c.push(0); | ||
| 423 | + } | ||
| 424 | + c | ||
| 425 | + } | ||
| 426 | + | ||
| 427 | + let mut vp8x = vec![0x02, 0, 0, 0]; // flags: bit 0x02 is "has animation" | ||
| 428 | + let off24 = |v: u32| v.to_le_bytes()[..3].to_vec(); | ||
| 429 | + let dim24 = |v: u32| (v - 1).to_le_bytes()[..3].to_vec(); | ||
| 430 | + vp8x.extend_from_slice(&dim24(canvas_w)); | ||
| 431 | + vp8x.extend_from_slice(&dim24(canvas_h)); | ||
| 432 | + let mut anim = vec![0, 0, 0, 0, 0, 0]; // background colour | ||
| 433 | + anim.extend_from_slice(&0u16.to_le_bytes()); // loop count | ||
| 434 | + | ||
| 435 | + let mut anmf_body = Vec::new(); | ||
| 436 | + anmf_body.extend_from_slice(&off24(0)); // x offset (raw value, x = field*2) | ||
| 437 | + anmf_body.extend_from_slice(&off24(0)); // y offset | ||
| 438 | + anmf_body.extend_from_slice(&dim24(1)); // width - 1 | ||
| 439 | + anmf_body.extend_from_slice(&dim24(1)); // height - 1 | ||
| 440 | + anmf_body.extend_from_slice(&off24(1)); // duration | ||
| 441 | + anmf_body.push(0x00); // reserved/blend/dispose | ||
| 442 | + anmf_body.extend_from_slice(&chunk(b"VP8L", &vp8l)); | ||
| 443 | + | ||
| 444 | + let mut payload = Vec::new(); | ||
| 445 | + payload.extend_from_slice(&chunk(b"VP8X", &vp8x)); | ||
| 446 | + payload.extend_from_slice(&chunk(b"ANIM", &anim)); | ||
| 447 | + for _ in 0..frames { | ||
| 448 | + payload.extend_from_slice(&chunk(b"ANMF", &anmf_body)); | ||
| 449 | + } | ||
| 450 | + | ||
| 451 | + let mut data = Vec::new(); | ||
| 452 | + data.extend_from_slice(b"RIFF"); | ||
| 453 | + data.extend_from_slice(&(4 + payload.len() as u32).to_le_bytes()); | ||
| 454 | + data.extend_from_slice(b"WEBP"); | ||
| 455 | + data.extend_from_slice(&payload); | ||
| 456 | + data | ||
| 457 | +} | ||
| 458 | + | ||
| 459 | +#[test] | ||
| 460 | +fn a_webp_animation_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget() { | ||
| 461 | + // The WebP analogue of the GIF test above: `decode_frames` clones the | ||
| 462 | + // whole composited canvas into the result once per ANMF chunk. | ||
| 463 | + let data = one_pixel_animated_webp(16000, 16000, 64); | ||
| 464 | + let start = std::time::Instant::now(); | ||
| 465 | + let err = ec_image::decode_animation(&data) | ||
| 466 | + .expect_err("64 clones of a near-limit canvas is past the total budget"); | ||
| 467 | + assert!(start.elapsed().as_millis() < 2000, "{:?}", start.elapsed()); | ||
| 468 | + assert!(format!("{err}").contains("limit"), "{err}"); | ||
| 469 | +} | ||
| 470 | + | ||
| 471 | +/// Build an LZW-compressed data stream that keeps expanding after the | ||
| 472 | +/// dictionary itself has stopped growing: a run of `cScSc` codes (each equal | ||
| 473 | +/// to the not-yet-assigned `next_code`) fills the 4096-entry dictionary with | ||
| 474 | +/// entries of increasing length, then a run of plain references to the | ||
| 475 | +/// longest entry keeps emitting ~4 KB of output per 12-bit code with no | ||
| 476 | +/// further dictionary growth to bound it. This is the classic GIF LZW bomb: | ||
| 477 | +/// a stream well under 200 KB that decodes, uncapped, to hundreds of | ||
| 478 | +/// megabytes. | ||
| 479 | +fn lzw_bomb() -> Vec<u8> { | ||
| 480 | + let min_code_size = 2u8; | ||
| 481 | + let clear_code = 1u16 << min_code_size; // 4 | ||
| 482 | + let end_code = clear_code + 1; // 5 | ||
| 483 | + let mut next_code = clear_code + 2; // 6 | ||
| 484 | + let mut code_size = min_code_size + 1; // 3 | ||
| 485 | + | ||
| 486 | + let mut w = BitWriter::new(); | ||
| 487 | + w.push(clear_code, code_size); | ||
| 488 | + w.push(0, code_size); // first code after clear: a literal, no dictionary entry | ||
| 489 | + | ||
| 490 | + // Phase 1: cScSc every time -- fills the dictionary, entries growing | ||
| 491 | + // 2, 3, 4, ... bytes long (mirrors `Lzw::derive`'s widening rule exactly, | ||
| 492 | + // so the decoder reads this stream at the same code width we wrote it). | ||
| 493 | + while next_code < 4096 { | ||
| 494 | + w.push(next_code, code_size); | ||
| 495 | + if next_code >= (1u16 << code_size) - 1 && code_size < 12 { | ||
| 496 | + code_size += 1; | ||
| 497 | + } | ||
| 498 | + next_code += 1; | ||
| 499 | + } | ||
| 500 | + | ||
| 501 | + // Phase 2: dictionary is full (`derive` is now a no-op), so repeating the | ||
| 502 | + // longest entry's code keeps producing ~4 KB per code with nothing left | ||
| 503 | + // to cap it. | ||
| 504 | + let longest = next_code - 1; | ||
| 505 | + for _ in 0..100_000 { | ||
| 506 | + w.push(longest, code_size); | ||
| 507 | + } | ||
| 508 | + | ||
| 509 | + w.push(end_code, code_size); | ||
| 510 | + w.finish() | ||
| 511 | +} | ||
| 512 | + | ||
| 513 | +/// A GIF whose frame declares 4x4 (16 indices) but whose LZW stream, if | ||
| 514 | +/// decoded past that point, expands to hundreds of megabytes: guards the | ||
| 515 | +/// `lzw_decode` bound at gif.rs that stops the loop once `out` already holds | ||
| 516 | +/// `expected` bytes, rather than only checking after the loop. | ||
| 517 | +#[test] | ||
| 518 | +fn a_gif_lzw_bomb_does_not_expand_past_its_declared_frame() { | ||
| 519 | + let lzw = lzw_bomb(); | ||
| 520 | + eprintln!("gif-lzw-bomb: {} bytes of LZW data", lzw.len()); | ||
| 521 | + | ||
| 522 | + let mut data = Vec::new(); | ||
| 523 | + data.extend_from_slice(b"GIF87a"); | ||
| 524 | + data.extend_from_slice(&4u16.to_le_bytes()); | ||
| 525 | + data.extend_from_slice(&4u16.to_le_bytes()); | ||
| 526 | + data.push(0x00); // no global colour table | ||
| 527 | + data.push(0); | ||
| 528 | + data.push(0); | ||
| 529 | + data.push(0x2C); | ||
| 530 | + data.extend_from_slice(&0u16.to_le_bytes()); // left | ||
| 531 | + data.extend_from_slice(&0u16.to_le_bytes()); // top | ||
| 532 | + data.extend_from_slice(&4u16.to_le_bytes()); // width | ||
| 533 | + data.extend_from_slice(&4u16.to_le_bytes()); // height | ||
| 534 | + data.push(0x81); // has LCT, size field 1 -> 4 colours (indices 0..3) | ||
| 535 | + data.extend_from_slice(&[0, 0, 0, 64, 64, 64, 128, 128, 128, 255, 255, 255]); | ||
| 536 | + data.push(2); // min code size | ||
| 537 | + for chunk in lzw.chunks(255) { | ||
| 538 | + data.push(chunk.len() as u8); | ||
| 539 | + data.extend_from_slice(chunk); | ||
| 540 | + } | ||
| 541 | + data.push(0); // sub-block terminator | ||
| 542 | + data.push(0x3B); // trailer | ||
| 543 | + | ||
| 544 | + let start = std::time::Instant::now(); | ||
| 545 | + let _ = ec_image::decode(&data); | ||
| 546 | + assert!(start.elapsed().as_secs() < 1, "{:?}", start.elapsed()); | ||
| 547 | +} | ||
| 548 | + | ||
| 260 | fn crc32(data: &[u8]) -> u32 { | 549 | fn crc32(data: &[u8]) -> u32 { |
| 261 | let mut c = 0xffff_ffffu32; | 550 | let mut c = 0xffff_ffffu32; |
| 262 | for &b in data { | 551 | for &b in data { |