From 55b1d36d2a68b1d25a706049642835da8f326dfb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 26 Aug 2026 19:57:26 +0300 Subject: [PATCH] fix(image): close a TIFF LZW dictionary-corruption cycle that grew unbounded A code strictly greater than the dictionary's next slot was accepted into the KwKwK branch and stored as `previous`; a later entry then chained through that out-of-range value, breaking the prefix-chain invariant and letting the decode walk cycle, growing `stack` to gigabytes on a fuzzed 8950-byte fixture. Require code == next for KwKwK; anything else is corrupt input, not a decodable stream. --- crates/ec-image/src/tiff.rs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/ec-image/src/tiff.rs b/crates/ec-image/src/tiff.rs index d08329b8..b1a75f60 100644 --- a/crates/ec-image/src/tiff.rs +++ b/crates/ec-image/src/tiff.rs @@ -402,9 +402,17 @@ fn lzw(input: &[u8], hint: usize) -> Result> { } stack.push(walk as u8); *stack.last().unwrap() - } else if let Some(previous) = previous { - // The KwKwK case: the code being emitted is the one this step is - // about to define. + } else if code as usize == next { + // The KwKwK case: the code being emitted is exactly the one this + // step is about to define. A code greater than `next` is not a + // KwKwK case at all -- it names a dictionary entry that does not + // exist yet -- and accepting it here would let `previous` (set + // below to this out-of-range `code`) get written into a future + // `prefix` slot, breaking the invariant that every prefix chain + // strictly decreases and turning the walk above into a cycle + // that grows `stack` without bound. + let previous = previous + .ok_or_else(|| Error::corrupt("TIFF: an LZW stream opening with a new code"))?; let mut walk = previous; while walk >= 258 { stack.push(suffix[walk as usize]); @@ -415,7 +423,9 @@ fn lzw(input: &[u8], hint: usize) -> Result> { stack.insert(0, first); first } else { - return Err(Error::corrupt("TIFF: an LZW stream opening with a new code")); + // code as usize > next: a reference to a dictionary entry that + // does not exist yet, neither an ordinary code nor a valid KwKwK. + return Err(Error::corrupt("TIFF: an LZW code past the dictionary")); }; out.extend(stack.iter().rev()); if let Some(previous) = previous {