From cad2ed461009a94accf05f1b963f5c689a085f55 Mon Sep 17 00:00:00 2001 From: "Claude Opus 5.5" Date: Thu, 8 Oct 2026 14:52:43 -0400 Subject: [PATCH] PNM: the file, not the header, bounds what a decode reserves (#1110) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ASCII PGM/PPM reserved a u32 (four bytes) per declared sample before reading any, against a Limits budget of one or two bytes per sample, so a 19-byte header could ask for 12 GiB. With Limits::none() a 2³¹ × 2³¹ header panics with "capacity overflow"; PBM reserved 2⁶² bytes before finding the raster missing and aborted. ASCII reservations are now capped by what the remaining bytes can hold (a PBM digit is at least a byte, a PGM/PPM sample at least a digit and a separator), and binary PBM checks the raster length before reserving. Limits::none() documents that it is still bounded by usize overflow checks, but the decoder multiplied w × h × channels, n × 2 (16-bit samples) and the PFM raster length unchecked. A new sample_count checks the product, and the length checks use checked_mul. Tests: a header alone reserves nothing (P1-P4), u32::MAX sizes are errors (P3, P5, P6, PF, P7), and ASCII files with no slack (PBM digits without separators, no trailing whitespace) still decode. The first two failed before the fix: an abort on the 2⁶² reservation, "capacity overflow" for the P2/P3 headers, and "attempt to multiply with overflow". --- crates/codecs/src/codecs/pnm.rs | 34 ++++++++++++++++++++++--------- crates/codecs/tests/limits.rs | 36 +++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 10 deletions(-) diff --git a/crates/codecs/src/codecs/pnm.rs b/crates/codecs/src/codecs/pnm.rs index b4f4957447..61840aeecf 100644 --- a/crates/codecs/src/codecs/pnm.rs +++ b/crates/codecs/src/codecs/pnm.rs @@ -93,6 +93,15 @@ fn from_values(w: u32, h: u32, layout: ChannelLayout, maxval: u32, values: Vec Result { + (w as usize) + .checked_mul(h as usize) + .and_then(|p| p.checked_mul(channels)) + .ok_or_else(|| CodecError::LimitExceeded(format!("{w}x{h}x{channels} samples do not fit in memory"))) +} + fn read_binary(data: &[u8], n: usize, maxval: u32) -> Result, CodecError> { if maxval < 256 { if data.len() < n { @@ -100,10 +109,10 @@ fn read_binary(data: &[u8], n: usize, maxval: u32) -> Result, CodecErro } Ok(data[..n].iter().map(|&v| v as u32).collect()) } else { - if data.len() < n * 2 { + let Some(len) = n.checked_mul(2).filter(|&len| data.len() >= len) else { return Err(err("truncated raster")); - } - Ok(data[..n * 2].as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]]) as u32).collect()) + }; + Ok(data[..len].as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]]) as u32).collect()) } } @@ -117,15 +126,16 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result b'1' | b'4' => { let (w, h) = (r.uint()?, r.uint()?); limits.check(w, h, ChannelLayout::Gray, SampleType::U8)?; - let n = w as usize * h as usize; - let mut px = Vec::with_capacity(n); + let n = sample_count(w, h, 1)?; + let mut px; if kind == b'4' { r.single_ws()?; let row = (w as usize).div_ceil(8); let data = r.rest(); - if data.len() < row * h as usize { + if row.checked_mul(h as usize).is_none_or(|len| data.len() < len) { return Err(err("truncated raster")); } + px = Vec::with_capacity(n); for y in 0..h as usize { for x in 0..w as usize { let bit = (data[y * row + x / 8] >> (7 - x % 8)) & 1; @@ -133,6 +143,8 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result } } } else { + // Each ASCII pixel takes at least a byte, so the file bounds the reservation (#1110). + px = Vec::with_capacity(n.min(r.rest().len())); while px.len() < n { r.skip_ws_and_comments(); match r.b.get(r.pos) { @@ -150,12 +162,14 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result let (w, h, maxval) = (r.uint()?, r.uint()?, r.uint()?); let layout = if matches!(kind, b'2' | b'5') { ChannelLayout::Gray } else { ChannelLayout::Rgb }; limits.check(w, h, layout, sample_for_maxval(maxval)?)?; - let n = w as usize * h as usize * layout.channels(); + let n = sample_count(w, h, layout.channels())?; let values = if matches!(kind, b'5' | b'6') { r.single_ws()?; read_binary(r.rest(), n, maxval)? } else { - let mut v = Vec::with_capacity(n); + // Each ASCII sample is a digit and a separator (the last may lack one), so the + // file, not the header, bounds the reservation (#1110). + let mut v = Vec::with_capacity(n.min(r.rest().len() / 2 + 1)); for _ in 0..n { v.push(r.uint()?); } @@ -177,7 +191,7 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result let nc = layout.channels(); let row = w as usize * nc; let data = r.rest(); - if data.len() < row * h as usize * 4 { + if sample_count(w, h, nc)?.checked_mul(4).is_none_or(|len| data.len() < len) { return Err(err("truncated raster")); } let le = scale < 0.0; @@ -235,7 +249,7 @@ fn decode_pam(r: &mut Reader<'_>, limits: &Limits) -> Result } }; limits.check(w, h, layout, sample_for_maxval(maxval)?)?; - let n = w as usize * h as usize * layout.channels(); + let n = sample_count(w, h, layout.channels())?; let values = read_binary(r.rest(), n, maxval)?; from_values(w, h, layout, maxval, values) } diff --git a/crates/codecs/tests/limits.rs b/crates/codecs/tests/limits.rs index 17f9ebcc29..e808a9cae7 100644 --- a/crates/codecs/tests/limits.rs +++ b/crates/codecs/tests/limits.rs @@ -100,6 +100,42 @@ fn pnm_bomb_header_rejected() { assert!(is_limit(decode(b"PF\n100000 100000\n-1.0\n"))); } +#[test] +fn pnm_header_alone_reserves_nothing_without_limits() { + // #1110: ASCII PGM/PPM reserved four bytes per declared sample before reading any. A + // 2³¹ × 2³¹ header asked for more than isize::MAX ("capacity overflow"), and PBM reserved + // 2⁶² bytes before finding the raster missing (an abort). + let none = opts(Limits::none()); + let side = 1u32 << 31; + for f in [format!("P1\n{side} {side}\n"), format!("P2\n{side} {side}\n255\n"), format!("P3\n{side} {side}\n255\n"), format!("P4\n{side} {side}\n")] { + assert!(decode_with(f.as_bytes(), &none).is_err(), "{f:?}"); + } +} + +#[test] +fn pnm_header_sizes_that_overflow_usize_are_errors_without_limits() { + let m = u32::MAX; + let none = opts(Limits::none()); + for f in [ + format!("P3\n{m} {m}\n255\n"), + format!("P6\n{m} {m}\n255\n"), + format!("P5\n{m} {m}\n65535\n"), + format!("PF\n{m} {m}\n-1.0\n"), + format!("P7\nWIDTH {m}\nHEIGHT {m}\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n"), + ] { + assert!(decode_with(f.as_bytes(), &none).is_err(), "{f:?}"); + } +} + +#[test] +fn ascii_pnm_with_the_tightest_layout_still_decodes() { + // The capacity bound for #1110 must not cut off files with no slack: PBM digits need no + // separator, and the last ASCII sample needs no trailing whitespace. + assert_eq!(decode(b"P1\n3 1\n010").unwrap().data(), &[255, 0, 255]); + assert_eq!(decode(b"P2\n3 1\n255\n1 2 3").unwrap().data(), &[1, 2, 3]); + assert_eq!(decode(b"P3\n1 1\n255\n9 8 7").unwrap().data(), &[9, 8, 7]); +} + #[test] fn jpeg_bomb_header_rejected() { // SOI + SOF0 claiming 65535x65535x3 with no scan data.