Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

M11: the optimizer decodes an image no further than its samples can need

Grzegorz Martens88c089bd2931
diff --git a/crates/optimize/src/images.rs b/crates/optimize/src/images.rs
index 59b3b6417..6eb0ddaa7 100644
--- a/crates/optimize/src/images.rs
+++ b/crates/optimize/src/images.rs
@@ -261,7 +261,8 @@ fn count_decoded(_n: u64) {
/// 8-bit samples of an image (`n` components), decoded, with `/DecodeParms` given by reference
/// too ([`Document::with_direct_parms`]): read without them, a predictor's tag bytes would shift
/// every row, and the image would be written back wrong. `None` for a JPEG whose colour transform
-/// readers may disagree about ([`ycc_encoded`]).
+/// readers may disagree about ([`ycc_encoded`]), and for data that decodes past what the samples
+/// can need ([`allowance`]).
pub(crate) fn pixels(doc: &Document, s: &Stream, n: usize) -> Option<Vec<u8>> {
let (w, h) = (u32::try_from(s.dict.int(b"Width")?).ok()?, u32::try_from(s.dict.int(b"Height")?).ok()?);
if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS {
@@ -277,11 +278,18 @@ pub(crate) fn pixels(doc: &Document, s: &Stream, n: usize) -> Option<Vec<u8>> {
count_decoded(u64::from(w) * u64::from(h));
(v.len() == bytes).then_some(v)
} else {
- let v = doc.with_direct_parms(s).decoded().ok()?;
+ let v = doc.with_direct_parms(s).decoded_within(allowance(bytes, h)?).ok()?;
Some(v.get(..bytes)?.to_vec())
}
}
+/// How far an image of `bytes` samples in `rows` rows is decoded: a filter stage may produce up
+/// to twice them (ASCIIHex text under Flate) plus a PNG predictor's byte a row. More can only be a
+/// decompression bomb, and the image is left alone.
+fn allowance(bytes: usize, rows: u32) -> Option<usize> {
+ bytes.checked_add(usize::try_from(rows).ok()?)?.checked_mul(2)?.checked_add(4096)
+}
+
/// Whether the samples of a three-component JPEG are YCbCr, to be converted to RGB (ISO 32000-2
/// §7.4.8). An Adobe APP14 marker's transform flag says so, overriding the filter's
/// /ColorTransform; without a marker /ColorTransform does, 1 (YCbCr) by default.
@@ -575,8 +583,10 @@ fn mono(doc: &Document, s: &Stream, compression: MonoCompression) -> Option<Stre
if w == 0 || h == 0 || w > pdfcraft_filters::MAX_G4_COLUMNS || u64::from(w) * u64::from(h) > MAX_PIXELS {
return None;
}
- // Through its parameters given by reference too, as `pixels` reads.
- let g4 = pdfcraft_filters::encode_g4(&doc.with_direct_parms(s).decoded().ok()?, w, h).ok()?;
+ // Through its parameters given by reference too, as `pixels` reads, and no further than its
+ // rows can need.
+ let bytes = usize::try_from(w).ok()?.div_ceil(8).checked_mul(usize::try_from(h).ok()?)?;
+ let g4 = pdfcraft_filters::encode_g4(&doc.with_direct_parms(s).decoded_within(allowance(bytes, h)?).ok()?, w, h).ok()?;
let mut new = d.clone();
for k in [&b"Filter"[..], b"DecodeParms", b"Length", b"DL"] {
new.remove(k);
diff --git a/crates/optimize/tests/optimize.rs b/crates/optimize/tests/optimize.rs
index 0336d73e9..62e3b5a15 100644
--- a/crates/optimize/tests/optimize.rs
+++ b/crates/optimize/tests/optimize.rs
@@ -474,6 +474,34 @@ fn images_whose_decode_parms_are_references_come_out_as_with_them_direct() {
assert_eq!(build("numbers"), direct, "the numbers inside by reference");
}
+/// An image whose data decodes far past what its samples can need (a decompression bomb) is left
+/// alone rather than decoded up to the 1 GiB limit: a 1-bit one that would become Group 4, and an
+/// eight-bit one that would be resampled, each with a megabyte of zeros after its samples.
+#[test]
+fn images_whose_data_decodes_far_past_their_samples_are_left_alone() {
+ let (w, h) = (1200u32, 480u32);
+ let text = bilevel(w, h, false);
+ let shades: Vec<u8> = (0..w * h).map(|i| ((i % w) * 255 / w) as u8 ^ ((i / w) as u8 & 0x0F)).collect();
+ for padding in [0, 1 << 20] {
+ let mut doc = Document::new_empty();
+ let padded = |data: &[u8]| data.iter().copied().chain(std::iter::repeat_n(0, padding)).collect::<Vec<u8>>();
+ let grey = |bits: i64| [("BitsPerComponent", bits.into()), ("ColorSpace", Object::name("DeviceGray"))];
+ let one_bit = mono_image(&mut doc, w, h, &padded(&text), None, &grey(1));
+ let eight_bit = mono_image(&mut doc, w, h, &padded(&shades), None, &grey(8));
+ // 300 × 120 pt is 288 ppi; 144 × 57.6 pt is 600 ppi.
+ page(&mut doc, &[("A", one_bit), ("B", eight_bit)], "q 300 0 0 120 20 600 cm /A Do Q q 144 0 0 57.6 20 400 cm /B Do Q");
+ let before = [one_bit, eight_bit].map(|r| stream(&doc, r).raw);
+ let r = optimize(&mut doc, &Settings::default()).unwrap();
+ let after = [one_bit, eight_bit].map(|r| stream(&doc, r).raw);
+ if padding == 0 {
+ assert_eq!((r.images_resampled, r.images_recompressed), (1, 1), "{r:?}");
+ } else {
+ assert_eq!((r.images_resampled, r.images_recompressed), (0, 0), "{r:?}");
+ assert_eq!(after, before);
+ }
+ }
+}
+
#[test]
fn settings_choose_what_happens() {
let mut doc = Document::new_empty();