Close a TIFF LZW dictionary-corruption cycle that grew unbounded
Browse files at this commit55b1d36d2a68b1d25a706049642835da8f326dfbParent: fd823fc- fix
- close a TIFF LZW dictionary-corruption cycle that grew unbounded
1 changed file +14 -4
- crates/ec-image/src/tiff.rs +14 -4
crates/ec-image/src/tiff.rsmodified+14 -4
| @@ -402,9 +402,17 @@ fn lzw(input: &[u8], hint: usize) -> Result<Vec<u8>> { | |||
| 402 | } | 402 | } |
| 403 | stack.push(walk as u8); | 403 | stack.push(walk as u8); |
| 404 | *stack.last().unwrap() | 404 | *stack.last().unwrap() |
| 405 | - } else if let Some(previous) = previous { | 405 | + } else if code as usize == next { |
| 406 | - // The KwKwK case: the code being emitted is the one this step is | 406 | + // The KwKwK case: the code being emitted is exactly the one this |
| 407 | - // about to define. | 407 | + // step is about to define. A code greater than `next` is not a |
| 408 | + // KwKwK case at all -- it names a dictionary entry that does not | ||
| 409 | + // exist yet -- and accepting it here would let `previous` (set | ||
| 410 | + // below to this out-of-range `code`) get written into a future | ||
| 411 | + // `prefix` slot, breaking the invariant that every prefix chain | ||
| 412 | + // strictly decreases and turning the walk above into a cycle | ||
| 413 | + // that grows `stack` without bound. | ||
| 414 | + let previous = previous | ||
| 415 | + .ok_or_else(|| Error::corrupt("TIFF: an LZW stream opening with a new code"))?; | ||
| 408 | let mut walk = previous; | 416 | let mut walk = previous; |
| 409 | while walk >= 258 { | 417 | while walk >= 258 { |
| 410 | stack.push(suffix[walk as usize]); | 418 | stack.push(suffix[walk as usize]); |
| @@ -415,7 +423,9 @@ fn lzw(input: &[u8], hint: usize) -> Result<Vec<u8>> { | |||
| 415 | stack.insert(0, first); | 423 | stack.insert(0, first); |
| 416 | first | 424 | first |
| 417 | } else { | 425 | } else { |
| 418 | - return Err(Error::corrupt("TIFF: an LZW stream opening with a new code")); | 426 | + // code as usize > next: a reference to a dictionary entry that |
| 427 | + // does not exist yet, neither an ordinary code nor a valid KwKwK. | ||
| 428 | + return Err(Error::corrupt("TIFF: an LZW code past the dictionary")); | ||
| 419 | }; | 429 | }; |
| 420 | out.extend(stack.iter().rev()); | 430 | out.extend(stack.iter().rev()); |
| 421 | if let Some(previous) = previous { | 431 | if let Some(previous) = previous { |