diff --git a/crates/ec-h265-syntax/src/slice.rs b/crates/ec-h265-syntax/src/slice.rs index e483291b..d0d5a6f3 100644 --- a/crates/ec-h265-syntax/src/slice.rs +++ b/crates/ec-h265-syntax/src/slice.rs @@ -430,6 +430,17 @@ impl SliceHeader { if h.slice_type == SliceType::B { h.num_ref_idx_l1_active_minus1 = r.read_ue()?; } + // 7.4.7.1: both fields are in range 0..=14. Past that is + // a corrupt stream, not a bigger reference list -- and + // pred_weight_table below sizes a Vec from this value, so + // an unchecked ue(v) is a header-declared allocation an + // attacker fully controls (up to 2^32 entries from a + // handful of bits). + if h.num_ref_idx_l0_active_minus1 > 14 || h.num_ref_idx_l1_active_minus1 > 14 { + return Err(Error::corrupt( + "HEVC slice header: num_ref_idx_lX_active_minus1 out of range", + )); + } } let num_pic_total_curr = h.short_term_ref_pic_set.num_used_by_curr + num_long_term; if pps.lists_modification_present && num_pic_total_curr > 1 { diff --git a/crates/ec-image/src/gif.rs b/crates/ec-image/src/gif.rs index ce421755..b0427a00 100644 --- a/crates/ec-image/src/gif.rs +++ b/crates/ec-image/src/gif.rs @@ -14,7 +14,7 @@ //! so a decoder that waits one code longer reads small pictures correctly and //! large ones as noise. -use crate::{AnimationFrame, Image, ImageFormat, Info, Limits, Metadata, Pixels}; +use crate::{AllocBudget, AnimationFrame, Image, ImageFormat, Info, Limits, Metadata, Pixels}; use ec_core::{Error, Result}; /// 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 let mut pos = 0; while let Some(code) = lzw.read_code(data, &mut pos) { + if out.len() >= expected { + // Output already satisfies the declared frame size; a bomb-style + // stream can keep growing the dictionary and emitting further + // codes after this point, so stop before decoding any more of + // them rather than let `out` expand unbounded (LZW bomb). + break; + } if code == lzw.clear_code { lzw.reset(); continue; @@ -328,7 +335,13 @@ fn indices_to_rgba(indices: &[u8], palette: &[[u8; 3]], gce: Option<&Gce>) -> Re /// Composite every raw frame onto a full-canvas buffer: blend the frame over /// the canvas, then apply its disposal method to the canvas the next frame /// starts from. -fn composite(frames: Vec, canvas_w: u32, canvas_h: u32) -> Result> { +fn composite( + frames: Vec, + canvas_w: u32, + canvas_h: u32, + limits: &Limits, + budget: &mut AllocBudget, +) -> Result> { let cw = canvas_w as usize; let ch = canvas_h as usize; let n = cw * ch; @@ -337,6 +350,10 @@ fn composite(frames: Vec, canvas_w: u32, canvas_h: u32) -> Result, u32)> = Vec::with_capacity(frames.len()); for frame in frames { + // Every frame clones the whole canvas -- the real multiplier a + // single buffer's own bound never catches -- so it is spent from the + // decode-wide budget just like the frame's own indices were above. + budget.spend(limits, "GIF composited canvas", n * 4)?; let indices = if frame.interlaced { deinterlace(&frame.indices, frame.width as usize, frame.height as usize) } else { @@ -482,6 +499,8 @@ pub fn decode_animation(data: &[u8], limits: Limits) -> Result = None; + let mut budget = AllocBudget::default(); + budget.spend(&limits, "GIF canvas", canvas_bytes)?; loop { let block = r.u8()?; @@ -497,6 +516,14 @@ pub fn decode_animation(data: &[u8], limits: Limits) -> Result Result Self { Limits { max_pixels: 1 << 28, - max_alloc: 1 << 32, + max_alloc: 1 << 30, + max_total_alloc: 1 << 32, } } } @@ -146,6 +155,49 @@ impl Limits { } Ok(()) } + + /// Check a byte count computed from header-declared fields (a frame's + /// `width * height * bpp`, a palette size, a chunk length) before it + /// sizes a single allocation. `what` names the buffer for the error. + pub fn check_bytes(&self, what: &str, bytes: Option) -> Result { + let bytes = + bytes.ok_or_else(|| Error::corrupt(format!("{what}: size overflows usize")))?; + if bytes > self.max_alloc { + return Err(Error::unsupported( + what.to_string(), + format!("{bytes} bytes past the {} allocation limit", self.max_alloc), + )); + } + Ok(bytes) + } +} + +/// Accumulates bytes spent across every frame of one decode call and refuses +/// once the running total crosses [`Limits::max_total_alloc`] — the guard +/// for `frame_count x canvas`, which [`Limits::check_bytes`] alone never +/// sees since it only ever looks at one buffer at a time. +#[derive(Debug, Default)] +pub struct AllocBudget(usize); + +impl AllocBudget { + /// Spend `bytes` from the budget, refusing once the running total passes + /// `limits.max_total_alloc`. + pub fn spend(&mut self, limits: &Limits, what: &str, bytes: usize) -> Result<()> { + self.0 = self + .0 + .checked_add(bytes) + .ok_or_else(|| Error::corrupt(format!("{what}: total size overflows usize")))?; + if self.0 > limits.max_total_alloc { + return Err(Error::unsupported( + what.to_string(), + format!( + "{} total decoded bytes past the {} limit", + self.0, limits.max_total_alloc + ), + )); + } + Ok(()) + } } /// What a file said about its own pixels, parsed but not applied. @@ -478,4 +530,31 @@ mod tests { assert!(limits.check(0, 10).is_err()); assert!(limits.check(100_000, 100_000).is_err()); } + + #[test] + fn check_bytes_refuses_past_max_alloc_before_a_frame_size_carries_it() { + let limits = Limits::default(); + assert!(limits.check_bytes("test", Some(1024)).is_ok()); + assert!(limits.check_bytes("test", Some(limits.max_alloc + 1)).is_err()); + assert!(limits.check_bytes("test", None).is_err()); + } + + #[test] + fn alloc_budget_refuses_once_repeated_spends_cross_the_total() { + // The class this guards: no single spend is ever over budget on its + // own, but a canvas cloned once per animation frame is. + let limits = Limits::default(); + let mut budget = AllocBudget::default(); + let per_frame = limits.max_total_alloc / 4; + for i in 0..4 { + assert!( + budget.spend(&limits, "frame", per_frame).is_ok(), + "frame {i} alone is within budget" + ); + } + assert!( + budget.spend(&limits, "frame", per_frame).is_err(), + "a fifth frame the same size crosses the total" + ); + } } diff --git a/crates/ec-image/src/webp/mod.rs b/crates/ec-image/src/webp/mod.rs index c5db77e6..d673d27a 100644 --- a/crates/ec-image/src/webp/mod.rs +++ b/crates/ec-image/src/webp/mod.rs @@ -245,8 +245,11 @@ pub fn decode_frames(data: &[u8], limits: Limits) -> Result = None; + let mut budget = crate::AllocBudget::default(); + budget.spend(&limits, "WebP canvas", canvas_bytes)?; for chunk in &chunks { if &chunk.tag != b"ANMF" { @@ -267,6 +270,10 @@ pub fn decode_frames(data: &[u8], limits: Limits) -> Result, +} + +impl BitWriter { + fn new() -> Self { + BitWriter { + buffer: 0, + bits: 0, + out: Vec::new(), + } + } + + fn push(&mut self, value: u16, width: u8) { + self.buffer |= u64::from(value) << self.bits; + self.bits += width; + while self.bits >= 8 { + self.out.push((self.buffer & 0xff) as u8); + self.buffer >>= 8; + self.bits -= 8; + } + } + + fn finish(mut self) -> Vec { + if self.bits > 0 { + self.out.push((self.buffer & 0xff) as u8); + } + self.out + } +} + +/// A minimal GIF: no global colour table, one 0x2C image descriptor with a +/// 2-colour local table and a one-pixel LZW stream (clear, colour 0, end), +/// followed by the trailer. `canvas_w`/`canvas_h` size the logical screen; +/// the frame itself is always 1x1 so its own indices buffer is trivial — +/// what grows per frame is the *composited canvas* `composite` clones. +fn one_pixel_gif(canvas_w: u16, canvas_h: u16, frames: usize) -> Vec { + let mut w = BitWriter::new(); + w.push(4, 3); // clear code (min_code_size 2 -> clear = 1<<2) + w.push(0, 3); // colour index 0, literal + w.push(5, 3); // end code + let lzw = w.finish(); + + let mut data = Vec::new(); + data.extend_from_slice(b"GIF87a"); + data.extend_from_slice(&canvas_w.to_le_bytes()); + data.extend_from_slice(&canvas_h.to_le_bytes()); + data.push(0x00); // no global colour table + data.push(0); + data.push(0); + for _ in 0..frames { + data.push(0x2C); + data.extend_from_slice(&0u16.to_le_bytes()); // left + data.extend_from_slice(&0u16.to_le_bytes()); // top + data.extend_from_slice(&1u16.to_le_bytes()); // width + data.extend_from_slice(&1u16.to_le_bytes()); // height + data.push(0x80); // has LCT, sorted=0, size field 0 -> 2 colours + data.extend_from_slice(&[0, 0, 0, 255, 255, 255]); // 2-colour LCT + data.push(2); // min code size + data.push(lzw.len() as u8); + data.extend_from_slice(&lzw); + data.push(0); // sub-block terminator + } + data.push(0x3B); // trailer + data +} + +#[test] +fn a_gif_frame_asking_for_more_pixels_than_the_limit_is_refused() { + // A single 0x2C image descriptor declaring a 60000x60000 frame: the + // frame's own rectangle is a header field like the canvas is, and must + // be refused before it sizes the indices buffer below it. + let mut data = Vec::new(); + data.extend_from_slice(b"GIF87a"); + data.extend_from_slice(&4u16.to_le_bytes()); + data.extend_from_slice(&4u16.to_le_bytes()); + data.push(0x00); + data.push(0); + data.push(0); + data.push(0x2C); + data.extend_from_slice(&0u16.to_le_bytes()); + data.extend_from_slice(&0u16.to_le_bytes()); + data.extend_from_slice(&60000u16.to_le_bytes()); + data.extend_from_slice(&60000u16.to_le_bytes()); + data.push(0x00); + + let start = std::time::Instant::now(); + let err = ec_image::decode_animation(&data).expect_err("60000x60000 frame is past the limit"); + assert!(start.elapsed().as_millis() < 100, "{:?}", start.elapsed()); + assert!(format!("{err}").contains("limit"), "{err}"); +} + +#[test] +fn a_gif_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget() { + // Each frame is 1x1 -- cheap to encode, cheap to check on its own -- but + // `composite` clones the *whole* canvas onto the result once per frame. + // A canvas near the single-buffer limit, repeated a few dozen times, + // must be caught by the decode-wide budget even though no single frame + // or single buffer ever looks large by itself. + let data = one_pixel_gif(16000, 16000, 64); + let start = std::time::Instant::now(); + let err = ec_image::decode_animation(&data) + .expect_err("64 clones of a near-limit canvas is past the total budget"); + // A few real canvas clones run before the budget catches up (the budget + // is spent per frame, so it can't refuse before at least one clone), so + // this bounds "a handful of gigabyte copies", not "no allocation at all". + assert!(start.elapsed().as_secs() < 5, "{:?}", start.elapsed()); + assert!(format!("{err}").contains("limit"), "{err}"); +} + +#[test] +fn a_gif_with_a_few_tiny_frames_over_a_huge_canvas_still_decodes() { + // The other side of the same budget: a handful of frames over a large + // canvas is exactly what a real animation looks like, and must not be + // refused just because the guard above exists. + let data = one_pixel_gif(4000, 4000, 3); + let frames = ec_image::decode_animation(&data).expect("well within every limit"); + assert_eq!(frames.len(), 3); +} + +/// A minimal RIFF WebP with an ANIM/VP8X header and `frames` ANMF chunks, +/// each carrying a 1x1 VP8L payload (the smallest valid lossless image: a +/// bitstream header plus one pixel, no transforms, no colour cache). +fn one_pixel_animated_webp(canvas_w: u32, canvas_h: u32, frames: usize) -> Vec { + // VP8L bitstream for a 1x1 image: signature 0x2f, 14-bit width-1=0, + // 14-bit height-1=0, 1-bit alpha flag=0, 3-bit version=0, then the + // image data: no colour cache, no meta prefix, one simple prefix code + // per channel (colour index 0 for all four), then the single pixel. + let mut w = BitWriter::new(); + w.push(0, 14); // width - 1 + w.push(0, 14); // height - 1 + w.push(0, 1); // alpha_is_used + w.push(0, 3); // version + w.push(0, 1); // no transform + w.push(0, 1); // no colour cache + w.push(0, 1); // no meta prefix + for _ in 0..5 { + // green/red/blue/alpha/distance, in that order: a simple code, one + // symbol, value 0. + w.push(1, 1); // simple code + w.push(0, 1); // one symbol + w.push(0, 1); // symbol is not a literal byte read as 8 bits + w.push(0, 1); // symbol0 = 0 + } + let vp8l_bits = w.finish(); + let mut vp8l = vec![0x2f]; + vp8l.extend_from_slice(&vp8l_bits); + if vp8l.len() % 2 == 1 { + vp8l.push(0); + } + + fn chunk(tag: &[u8; 4], body: &[u8]) -> Vec { + let mut c = Vec::new(); + c.extend_from_slice(tag); + c.extend_from_slice(&(body.len() as u32).to_le_bytes()); + c.extend_from_slice(body); + if body.len() % 2 == 1 { + c.push(0); + } + c + } + + let mut vp8x = vec![0x02, 0, 0, 0]; // flags: bit 0x02 is "has animation" + let off24 = |v: u32| v.to_le_bytes()[..3].to_vec(); + let dim24 = |v: u32| (v - 1).to_le_bytes()[..3].to_vec(); + vp8x.extend_from_slice(&dim24(canvas_w)); + vp8x.extend_from_slice(&dim24(canvas_h)); + let mut anim = vec![0, 0, 0, 0, 0, 0]; // background colour + anim.extend_from_slice(&0u16.to_le_bytes()); // loop count + + let mut anmf_body = Vec::new(); + anmf_body.extend_from_slice(&off24(0)); // x offset (raw value, x = field*2) + anmf_body.extend_from_slice(&off24(0)); // y offset + anmf_body.extend_from_slice(&dim24(1)); // width - 1 + anmf_body.extend_from_slice(&dim24(1)); // height - 1 + anmf_body.extend_from_slice(&off24(1)); // duration + anmf_body.push(0x00); // reserved/blend/dispose + anmf_body.extend_from_slice(&chunk(b"VP8L", &vp8l)); + + let mut payload = Vec::new(); + payload.extend_from_slice(&chunk(b"VP8X", &vp8x)); + payload.extend_from_slice(&chunk(b"ANIM", &anim)); + for _ in 0..frames { + payload.extend_from_slice(&chunk(b"ANMF", &anmf_body)); + } + + let mut data = Vec::new(); + data.extend_from_slice(b"RIFF"); + data.extend_from_slice(&(4 + payload.len() as u32).to_le_bytes()); + data.extend_from_slice(b"WEBP"); + data.extend_from_slice(&payload); + data +} + +#[test] +fn a_webp_animation_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget() { + // The WebP analogue of the GIF test above: `decode_frames` clones the + // whole composited canvas into the result once per ANMF chunk. + let data = one_pixel_animated_webp(16000, 16000, 64); + let start = std::time::Instant::now(); + let err = ec_image::decode_animation(&data) + .expect_err("64 clones of a near-limit canvas is past the total budget"); + assert!(start.elapsed().as_millis() < 2000, "{:?}", start.elapsed()); + assert!(format!("{err}").contains("limit"), "{err}"); +} + +/// Build an LZW-compressed data stream that keeps expanding after the +/// dictionary itself has stopped growing: a run of `cScSc` codes (each equal +/// to the not-yet-assigned `next_code`) fills the 4096-entry dictionary with +/// entries of increasing length, then a run of plain references to the +/// longest entry keeps emitting ~4 KB of output per 12-bit code with no +/// further dictionary growth to bound it. This is the classic GIF LZW bomb: +/// a stream well under 200 KB that decodes, uncapped, to hundreds of +/// megabytes. +fn lzw_bomb() -> Vec { + let min_code_size = 2u8; + let clear_code = 1u16 << min_code_size; // 4 + let end_code = clear_code + 1; // 5 + let mut next_code = clear_code + 2; // 6 + let mut code_size = min_code_size + 1; // 3 + + let mut w = BitWriter::new(); + w.push(clear_code, code_size); + w.push(0, code_size); // first code after clear: a literal, no dictionary entry + + // Phase 1: cScSc every time -- fills the dictionary, entries growing + // 2, 3, 4, ... bytes long (mirrors `Lzw::derive`'s widening rule exactly, + // so the decoder reads this stream at the same code width we wrote it). + while next_code < 4096 { + w.push(next_code, code_size); + if next_code >= (1u16 << code_size) - 1 && code_size < 12 { + code_size += 1; + } + next_code += 1; + } + + // Phase 2: dictionary is full (`derive` is now a no-op), so repeating the + // longest entry's code keeps producing ~4 KB per code with nothing left + // to cap it. + let longest = next_code - 1; + for _ in 0..100_000 { + w.push(longest, code_size); + } + + w.push(end_code, code_size); + w.finish() +} + +/// A GIF whose frame declares 4x4 (16 indices) but whose LZW stream, if +/// decoded past that point, expands to hundreds of megabytes: guards the +/// `lzw_decode` bound at gif.rs that stops the loop once `out` already holds +/// `expected` bytes, rather than only checking after the loop. +#[test] +fn a_gif_lzw_bomb_does_not_expand_past_its_declared_frame() { + let lzw = lzw_bomb(); + eprintln!("gif-lzw-bomb: {} bytes of LZW data", lzw.len()); + + let mut data = Vec::new(); + data.extend_from_slice(b"GIF87a"); + data.extend_from_slice(&4u16.to_le_bytes()); + data.extend_from_slice(&4u16.to_le_bytes()); + data.push(0x00); // no global colour table + data.push(0); + data.push(0); + data.push(0x2C); + data.extend_from_slice(&0u16.to_le_bytes()); // left + data.extend_from_slice(&0u16.to_le_bytes()); // top + data.extend_from_slice(&4u16.to_le_bytes()); // width + data.extend_from_slice(&4u16.to_le_bytes()); // height + data.push(0x81); // has LCT, size field 1 -> 4 colours (indices 0..3) + data.extend_from_slice(&[0, 0, 0, 64, 64, 64, 128, 128, 128, 255, 255, 255]); + data.push(2); // min code size + for chunk in lzw.chunks(255) { + data.push(chunk.len() as u8); + data.extend_from_slice(chunk); + } + data.push(0); // sub-block terminator + data.push(0x3B); // trailer + + let start = std::time::Instant::now(); + let _ = ec_image::decode(&data); + assert!(start.elapsed().as_secs() < 1, "{:?}", start.elapsed()); +} + fn crc32(data: &[u8]) -> u32 { let mut c = 0xffff_ffffu32; for &b in data {