From 01a4aca8eb4a5473669d8489b7850145116ae7ea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 21:46:10 -0800 Subject: [PATCH] hayro-syntax: the CCITT and JPEG 2000 decoders apply the document's pixel limit `DecodeLimits::with_max_image_pixels` raised the interpreter's check, but the CCITT and JPEG 2000 filters kept a fixed cap of 2^28 pixels, so an image between the two limits passed the interpreter and then failed to decode. Both filters now take the document's `max_image_pixels`: CCITT for its size check and for the rows decoded when the height is unknown, JPEG 2000 for the codestream's dimensions. `ccitt_size_ok` keeps the 2^28 default. JBIG2 keeps its own 2^28 cap. --- vendor/README.craft-reader.md | 13 +++-- .../hayro-syntax/src/decode_limits_tests.rs | 24 +++++++++ vendor/hayro-syntax/src/filter/ccitt.rs | 24 ++++++--- vendor/hayro-syntax/src/filter/jpx.rs | 28 ++++++----- vendor/hayro-syntax/src/filter/mod.rs | 49 +++++++++++++------ vendor/hayro-syntax/src/object/stream.rs | 6 ++- 6 files changed, 104 insertions(+), 40 deletions(-) diff --git a/vendor/README.craft-reader.md b/vendor/README.craft-reader.md index 6487d1a59c..7ac1d6f3ce 100644 --- a/vendor/README.craft-reader.md +++ b/vendor/README.craft-reader.md @@ -109,7 +109,8 @@ the last filter of an image of known size may produce (1 GiB by default), and `with_max_image_pixels` sets the most pixels an image or mask may have for the interpreter to decode it (2^28 by default, at most 2^32), before and after its codec decodes it. With 64-bit pointers a caller may raise either one; elsewhere a raise is clamped to the default. -`image_size_ok` keeps the 2^28 default. An 8-bit `DeviceRGB` image with the default or inverted `/Decode` and no transfer function keeps its decoded samples as its +The CCITT and JPEG 2000 decoders hold an image to the document's pixel limit; JBIG2 keeps +its own 2^28. `image_size_ok` and `ccitt_size_ok` keep the 2^28 default. An 8-bit `DeviceRGB` image with the default or inverted `/Decode` and no transfer function keeps its decoded samples as its RGB data instead of copying them into a second buffer. Tests: `decode_limits_tests::image_limits_default_and_caller_figures` in hayro-syntax and `image_limits` in `crates/pdf/tests/interpretation.rs`. @@ -162,7 +163,8 @@ Hostile-input bounds (CodeRabbit findings): - A CID font's `/W2` run that starts past CID 65535 is skipped as in `/W`, instead of overflowing and discarding the whole table. - CCITT images: `ccitt_size_ok` (inherited PdfCraft ledger item 2) allows at most 2^20 - columns and 2^28 pixels (columns × rows) before the decoder allocates. A `/Columns` past + columns and 2^28 pixels (columns × rows) before the decoder allocates; the decoder applies + the document's pixel limit in place of 2^28. A `/Columns` past `u32::MAX` is refused rather than wrapped to a small width. `/Rows` follows PdfCraft (17) and (19): `/Rows 0` or a value below `/Height` decodes to the image height, and decoding still stops where the data ends. @@ -196,9 +198,10 @@ raster tests are adapted in `tests/upstream_raster.rs` and the text contracts in `tests/upstream_text.rs`. (P8)'s PdfCraft test needs a Japanese substitute font and is not ported. - A CCITT image with `/Rows 0` (unknown height) decodes at most the rows that fit the stream's - output limit (counted in 1-bit rows) and 2^28 pixels; a known height is clamped the same way. - Before, it decoded to the end of the data, and a bit of 2D code can repeat a whole row. -- A JPEG 2000 image over 2^28 pixels, or over its output limit (at least 64 MiB), by the + output limit (counted in 1-bit rows) and the document's pixel limit (2^28 by default); a + known height is clamped the same way. Before, it decoded to the end of the data, and a bit of + 2D code can repeat a whole row. +- A JPEG 2000 image over the document's pixel limit (2^28 by default), or over its output limit (at least 64 MiB), by the codestream's own dimensions is refused before decoding, and its buffer is reserved fallibly: the image dictionary's smaller size no longer stands in for the size the decoder allocates. diff --git a/vendor/hayro-syntax/src/decode_limits_tests.rs b/vendor/hayro-syntax/src/decode_limits_tests.rs index 5d2585c07d..1d9d3c118e 100644 --- a/vendor/hayro-syntax/src/decode_limits_tests.rs +++ b/vendor/hayro-syntax/src/decode_limits_tests.rs @@ -206,6 +206,30 @@ fn image_limits_default_and_caller_figures() { assert_eq!(crate::filter::decode_limit(&small, true, limits.with_max_decoded_image(100)), 100); } +/// A document's pixel limit reaches the CCITT decoder: an 8 × 4 Group 4 image decodes with the +/// default limit and with one of 32 pixels, and is refused with one of 31. +#[cfg(feature = "images")] +#[test] +fn a_documents_pixel_limit_reaches_the_ccitt_decoder() { + // One horizontal-mode row, three V0 rows, then EOFB: all black. + const ALL_BLACK_8X4: [u8; 6] = [0x26, 0xa2, 0xfe, 0x00, 0x20, 0x02]; + let (mut out, mut offsets) = base(); + let mut image = format!("<< /Length {} /Filter /CCITTFaxDecode /DecodeParms << /K -1 /Columns 8 >> >>\nstream\n", ALL_BLACK_8X4.len()).into_bytes(); + image.extend_from_slice(&ALL_BLACK_8X4); + image.extend_from_slice(b"\nendstream"); + object(&mut out, &mut offsets, 4, &image); + table(&mut out, &offsets, ""); + let params = ImageDecodeParams { width: 8, height: 4, ..Default::default() }; + let decoded = |limits: DecodeLimits| { + let pdf = Pdf::new_with_limits(out.clone(), limits).unwrap(); + let stream = pdf.xref().get::>(ObjectIdentifier::new(4, 0)).unwrap(); + stream.decoded_image(¶ms).map(|r| r.data.len()).ok() + }; + assert_eq!(decoded(DecodeLimits::default()), Some(32)); + assert_eq!(decoded(DecodeLimits::default().with_max_image_pixels(32)), Some(32)); + assert_eq!(decoded(DecodeLimits::default().with_max_image_pixels(31)), None); +} + #[test] fn object_stream_limit_applies_after_successful_root_xref() { let (bytes, _, _) = object_stream_pdf(false); diff --git a/vendor/hayro-syntax/src/filter/ccitt.rs b/vendor/hayro-syntax/src/filter/ccitt.rs index a7921a5de1..881ebc9eab 100644 --- a/vendor/hayro-syntax/src/filter/ccitt.rs +++ b/vendor/hayro-syntax/src/filter/ccitt.rs @@ -8,12 +8,14 @@ use alloc::vec::Vec; use core::iter; use hayro_ccitt::{DecodeSettings, Decoder, DecoderContext, EncodingMode}; -/// PdfCraft patch: `limit` is the most bytes the filter may produce (see `decode_limit`). +/// PdfCraft patch: `limit` is the most bytes the filter may produce (see `decode_limit`), and +/// `max_pixels` the most pixels (columns × rows) the image may decode to. pub(crate) fn decode( data: &[u8], params: &Dict<'_>, image_params: &ImageDecodeParams, limit: usize, + max_pixels: u64, ) -> Option> { let k = params.get::(K).unwrap_or(0); @@ -28,7 +30,7 @@ pub(crate) fn decode( .map_or(image_params.height, |rows| rows.max(image_params.height)); let end_of_block = params.get::(END_OF_BLOCK).unwrap_or(true); // A `/Columns` past `u32::MAX` is refused: truncated, it would wrap to a small width that - // passes `ccitt_size_ok` and decode the image at the wrong width. + // passes `ccitt_size_within` and decode the image at the wrong width. let columns = match params.get::(COLUMNS) { Some(columns) => u32::try_from(columns).ok()?, None => 1728, @@ -51,15 +53,15 @@ pub(crate) fn decode( }; // PdfCraft patch: refuse absurd sizes before the decoder allocates for them. - if !super::ccitt_size_ok(settings.columns, settings.rows) { + if !super::ccitt_size_within(settings.columns, settings.rows, max_pixels) { return None; } // PdfCraft patch: the decoder stops after `rows` rows; with `/Rows 0` (unknown) it ran to the // end of the data, and a bit of 2D code can repeat a whole row, so a small stream produced - // gigabytes. Decode at most the rows that fit the output limit and the pixel cap. The limit + // gigabytes. Decode at most the rows that fit the output limit and the pixel limit. The limit // counts the stream's own 1-bit rows (`decode_limit`), whatever depth the rows are widened to. let mut settings = settings; - let fit = super::ccitt_max_rows(settings.columns, settings.columns.div_ceil(8), limit); + let fit = super::ccitt_max_rows(settings.columns, settings.columns.div_ceil(8), limit, max_pixels); settings.rows = if settings.rows == 0 { fit } else { settings.rows.min(fit) }; if settings.rows == 0 { return None; @@ -193,9 +195,19 @@ mod tests { #[test] fn columns_past_u32_max_are_refused_not_wrapped() { let params = ImageDecodeParams { width: 8, height: 4, ..Default::default() }; - let decoded = |dict: &[u8]| decode(&ALL_BLACK_8X4, &Dict::from_bytes(dict).unwrap(), ¶ms, 1 << 20); + let decoded = |dict: &[u8]| decode(&ALL_BLACK_8X4, &Dict::from_bytes(dict).unwrap(), ¶ms, 1 << 20, 1 << 28); assert!(decoded(b"<< /K -1 /Columns 8 >>").is_some()); // 2^32 + 8 would wrap to 8 columns. assert!(decoded(b"<< /K -1 /Columns 4294967304 >>").is_none()); } + + /// The image's 32 pixels are decoded with a pixel limit of 32 and refused with one of 31. + #[test] + fn the_pixel_limit_given_is_the_one_applied() { + let params = ImageDecodeParams { width: 8, height: 4, ..Default::default() }; + let dict = Dict::from_bytes(b"<< /K -1 /Columns 8 >>").unwrap(); + let decoded = |max_pixels| decode(&ALL_BLACK_8X4, &dict, ¶ms, 1 << 20, max_pixels); + assert_eq!(decoded(32).map(|r| r.data.len()), Some(32)); + assert!(decoded(31).is_none()); + } } diff --git a/vendor/hayro-syntax/src/filter/jpx.rs b/vendor/hayro-syntax/src/filter/jpx.rs index b2092eb35a..26358150a7 100644 --- a/vendor/hayro-syntax/src/filter/jpx.rs +++ b/vendor/hayro-syntax/src/filter/jpx.rs @@ -16,15 +16,13 @@ impl ImageColorSpace { } } -/// PdfCraft patch: the most pixels a JPEG 2000 image may decode to, as for JBIG2. -const MAX_PIXELS: u64 = 1 << 28; - /// PdfCraft patch: the least output `limit` a JPEG 2000 image is held to: the limit comes from the /// image dictionary's size, which a decoder may round differently from the codestream's. const MIN_LIMIT: usize = 64 << 20; -/// PdfCraft patch: `limit` is the most bytes the filter may produce (see `decode_limit`). -pub(crate) fn decode(data: &[u8], params: &ImageDecodeParams, limit: usize) -> Option> { +/// PdfCraft patch: `limit` is the most bytes the filter may produce (see `decode_limit`), and +/// `max_pixels` the most pixels the codestream may decode to. +pub(crate) fn decode(data: &[u8], params: &ImageDecodeParams, limit: usize, max_pixels: u64) -> Option> { use crate::object::stream::ImageColorSpace; let settings = DecodeSettings { @@ -82,9 +80,9 @@ pub(crate) fn decode(data: &[u8], params: &ImageDecodeParams, limit: usize) -> O }; let has_alpha = image.has_alpha(); // PdfCraft patch: the decoder sizes its output from the codestream's own dimensions, not the - // image dictionary's, and allocates it infallibly. Refuse more than `MAX_PIXELS` pixels or + // image dictionary's, and allocates it infallibly. Refuse more than `max_pixels` pixels or // more than `limit` bytes before decoding, and reserve the buffer fallibly. - if u64::from(width) * u64::from(height) > MAX_PIXELS { + if u64::from(width) * u64::from(height) > max_pixels { return None; } let channels = usize::from(cs.num_components()) + usize::from(has_alpha); @@ -454,7 +452,7 @@ mod tests { height: 2, ..ImageDecodeParams::default() }; - let result = decode(PALETTE_JP2, ¶ms, usize::MAX).unwrap(); + let result = decode(PALETTE_JP2, ¶ms, usize::MAX, 1 << 28).unwrap(); let image = result.image_data.unwrap(); assert!(matches!(image.color_space, Some(ImageColorSpace::Rgb))); let red = [255, 0, 0]; @@ -474,10 +472,18 @@ mod tests { height: 2, ..ImageDecodeParams::default() }; - let result = decode(PALETTE_JP2, ¶ms, usize::MAX).unwrap(); + let result = decode(PALETTE_JP2, ¶ms, usize::MAX, 1 << 28).unwrap(); assert_eq!(&*result.data, &[0, 1, 0, 1, 1, 0, 1, 0][..]); } + /// The codestream's 8 pixels are decoded with a pixel limit of 8 and refused with one of 7. + #[test] + fn the_pixel_limit_given_is_the_one_applied() { + let params = ImageDecodeParams { is_indexed: true, num_components: Some(1), width: 4, height: 2, ..ImageDecodeParams::default() }; + assert_eq!(decode(PALETTE_JP2, ¶ms, usize::MAX, 8).map(|r| r.data.len()), Some(8)); + assert!(decode(PALETTE_JP2, ¶ms, usize::MAX, 7).is_none()); + } + /// A 1x1, 1-bit codestream (one empty packet, so its sample is the midpoint 1) as a JP2 file /// whose header holds `extra` boxes after `ihdr` and `colr`. fn one_bit_jp2(extra: &[u8]) -> Vec { @@ -516,7 +522,7 @@ mod tests { ..ImageDecodeParams::default() }; let bpc = |data: &[u8]| { - decode(data, ¶ms, usize::MAX) + decode(data, ¶ms, usize::MAX, 1 << 28) .and_then(|r| r.image_data) .map(|d| d.bits_per_component) }; @@ -538,7 +544,7 @@ mod tests { bpc: Some(1), ..params.clone() }; - let palette_bpc = decode(&one_bit_jp2(&palette), &one_bit, usize::MAX) + let palette_bpc = decode(&one_bit_jp2(&palette), &one_bit, usize::MAX, 1 << 28) .and_then(|r| r.image_data) .map(|d| d.bits_per_component); assert_eq!(palette_bpc, Some(8), "/BitsPerComponent 1 with a palette"); diff --git a/vendor/hayro-syntax/src/filter/mod.rs b/vendor/hayro-syntax/src/filter/mod.rs index c52f5d2ab4..b1a3ed0d68 100644 --- a/vendor/hayro-syntax/src/filter/mod.rs +++ b/vendor/hayro-syntax/src/filter/mod.rs @@ -86,13 +86,16 @@ impl Filter { } } - /// PdfCraft patch: `limit` is the most bytes the filter may produce (see `decode_limit`). + /// PdfCraft patch: `limit` is the most bytes the filter may produce (see `decode_limit`), and + /// `max_pixels` the most pixels a CCITT or JPEG 2000 image may decode to (the document's + /// [`DecodeLimits::max_image_pixels`](crate::DecodeLimits::max_image_pixels)). pub(crate) fn apply( &self, data: &[u8], params: &Dict<'_>, #[cfg_attr(not(feature = "images"), allow(unused))] image_params: &ImageDecodeParams, limit: usize, + #[cfg_attr(not(feature = "images"), allow(unused))] max_pixels: u64, control: Option<&crate::cancel::Control>, ) -> Result, DecodeFailure> { crate::cancel::check(control).ok_or(DecodeFailure::StreamDecode)?; @@ -115,11 +118,11 @@ impl Filter { #[cfg(feature = "images")] Self::DctDecode => dct::decode(data, params, image_params).ok_or(DecodeFailure::ImageDecode), #[cfg(feature = "images")] - Self::CcittFaxDecode => ccitt::decode(data, params, image_params, limit).ok_or(DecodeFailure::ImageDecode), + Self::CcittFaxDecode => ccitt::decode(data, params, image_params, limit, max_pixels).ok_or(DecodeFailure::ImageDecode), #[cfg(feature = "images")] Self::Jbig2Decode => jbig2::decode(data, params, image_params, limit).ok_or(DecodeFailure::ImageDecode), #[cfg(feature = "images")] - Self::JpxDecode => jpx::decode(data, image_params, limit).ok_or(DecodeFailure::ImageDecode), + Self::JpxDecode => jpx::decode(data, image_params, limit, max_pixels).ok_or(DecodeFailure::ImageDecode), #[cfg(not(feature = "images"))] Self::DctDecode | Self::CcittFaxDecode | Self::Jbig2Decode | Self::JpxDecode => { warn!("image decoding is not supported (enable the `images` feature)"); @@ -175,34 +178,48 @@ pub(crate) fn decode_limit(params: &ImageDecodeParams, last: bool, limits: crate /// PdfCraft patch: whether a CCITT image of `columns` × `rows` may be decoded. The decoder sizes /// its line buffers from `/Columns`, which a fuzzed file set to 4294967295 (a 4 GiB allocation); -/// real fax lines are a few thousand pixels wide. +/// real fax lines are a few thousand pixels wide. At most [`MAX_IMAGE_PIXELS`] pixels, the +/// default of [`DecodeLimits::max_image_pixels`](crate::DecodeLimits::max_image_pixels). pub fn ccitt_size_ok(columns: u32, rows: u32) -> bool { - const MAX_COLUMNS: u32 = 1 << 20; - columns > 0 && columns <= MAX_COLUMNS && u64::from(columns) * u64::from(rows.max(1)) <= MAX_CCITT_PIXELS + ccitt_size_within(columns, rows, MAX_IMAGE_PIXELS) } -/// PdfCraft patch: the most pixels a CCITT image may decode to. -const MAX_CCITT_PIXELS: u64 = 1 << 28; +/// PdfCraft patch: [`ccitt_size_ok`] with at most `max_pixels` pixels (columns × rows). +pub(crate) fn ccitt_size_within(columns: u32, rows: u32, max_pixels: u64) -> bool { + const MAX_COLUMNS: u32 = 1 << 20; + columns > 0 && columns <= MAX_COLUMNS && u64::from(columns) * u64::from(rows.max(1)) <= max_pixels +} /// PdfCraft patch: the most rows of `columns` pixels, `row_bytes` bytes each once decoded, that fit -/// both `limit` bytes and the pixel cap; at least one when one row fits. +/// both `limit` bytes and `max_pixels` pixels; at least one when one row fits. #[cfg(feature = "images")] -pub(crate) fn ccitt_max_rows(columns: u32, row_bytes: u32, limit: usize) -> u32 { - let by_pixels = MAX_CCITT_PIXELS / u64::from(columns.max(1)); +pub(crate) fn ccitt_max_rows(columns: u32, row_bytes: u32, limit: usize, max_pixels: u64) -> u32 { + let by_pixels = max_pixels / u64::from(columns.max(1)); let by_bytes = u64::try_from(limit).unwrap_or(u64::MAX) / u64::from(row_bytes.max(1)); u32::try_from(by_pixels.min(by_bytes)).unwrap_or(u32::MAX) } #[cfg(all(test, feature = "images"))] mod ccitt_tests { - use super::ccitt_max_rows; + use super::{MAX_IMAGE_PIXELS, ccitt_max_rows, ccitt_size_ok, ccitt_size_within}; /// PdfCraft patch: an image of unknown height decodes at most the rows that fit both the output - /// limit (in 1-bit rows) and the 2^28-pixel cap. + /// limit (in 1-bit rows) and the pixel limit. #[test] fn unknown_ccitt_rows_fit_the_limit_and_the_pixel_cap() { - assert_eq!(ccitt_max_rows(1728, 216, 216 * 100), 100); - assert_eq!(ccitt_max_rows(1 << 20, 1 << 17, usize::MAX), 1 << 8); - assert_eq!(ccitt_max_rows(1728, 216, 100), 0); + assert_eq!(ccitt_max_rows(1728, 216, 216 * 100, MAX_IMAGE_PIXELS), 100); + assert_eq!(ccitt_max_rows(1 << 20, 1 << 17, usize::MAX, MAX_IMAGE_PIXELS), 1 << 8); + assert_eq!(ccitt_max_rows(1728, 216, 100, MAX_IMAGE_PIXELS), 0); + assert_eq!(ccitt_max_rows(1 << 20, 1 << 17, usize::MAX, 1 << 30), 1 << 10); + } + + /// A 32768 × 16384 image (2^29 pixels) is past the default limit and within a limit of 2^30. + #[test] + fn ccitt_size_follows_the_pixel_limit() { + assert!(!ccitt_size_ok(32_768, 16_384)); + assert!(!ccitt_size_within(32_768, 16_384, MAX_IMAGE_PIXELS)); + assert!(ccitt_size_within(32_768, 16_384, 1 << 30)); + assert!(ccitt_size_ok(16_384, 16_384)); + assert!(!ccitt_size_within(16_384, 16_384, (1 << 28) - 1)); } } diff --git a/vendor/hayro-syntax/src/object/stream.rs b/vendor/hayro-syntax/src/object/stream.rs index 339cf779e3..65da9f9b9b 100644 --- a/vendor/hayro-syntax/src/object/stream.rs +++ b/vendor/hayro-syntax/src/object/stream.rs @@ -249,8 +249,10 @@ impl<'a> Stream<'a> { .enumerate() { // PdfCraft patch: see `filter::decode_limit`. - let limit = crate::filter::decode_limit(image_params, i + 1 == count, self.dict.ctx().decode_limits()).min(max); - let new = filter.apply(current.as_ref().map(|c| c.data.as_ref()).unwrap_or(&data), params, image_params, limit, self.dict.ctx().control())?; + let limits = self.dict.ctx().decode_limits(); + let limit = crate::filter::decode_limit(image_params, i + 1 == count, limits).min(max); + let input = current.as_ref().map(|c| c.data.as_ref()).unwrap_or(&data); + let new = filter.apply(input, params, image_params, limit, limits.max_image_pixels(), self.dict.ctx().control())?; current = Some(new); }