-
Notifications
You must be signed in to change notification settings - Fork 1.2k
fix(detector): cap decompressed content-stream size #418
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
abimaelmartell
wants to merge
1
commit into
main
Choose a base branch
from
fix/detector-stream-inflate
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+268
−7
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,145 @@ | ||
| //! Bounded stream decompression for detector scans. | ||
| //! | ||
| //! `lopdf::Stream::decompressed_content` materializes the full decoded buffer | ||
| //! before any caller can apply a limit. A few megabytes of Flate-compressed | ||
| //! zeros can therefore expand to gigabytes. These helpers stop inflate once | ||
| //! the decoded budget is reached. | ||
|
|
||
| use flate2::read::{DeflateDecoder, ZlibDecoder}; | ||
| use lopdf::Stream; | ||
| use std::io::Read; | ||
|
|
||
| /// Maximum decoded bytes held for a single content stream during detection. | ||
| pub(crate) const MAX_DECOMPRESSED_STREAM_BYTES: usize = 32 * 1024 * 1024; | ||
|
|
||
| /// Decode `stream` for scanning, or return an empty buffer when the decoded | ||
| /// size would exceed `max_bytes`. | ||
| pub(crate) fn stream_content_for_scan(stream: &Stream) -> Vec<u8> { | ||
| match decompressed_content_bounded(stream, MAX_DECOMPRESSED_STREAM_BYTES) { | ||
| Some(data) => data, | ||
| None => Vec::new(), | ||
| } | ||
| } | ||
|
|
||
| /// Incremental decode with a hard output cap. `None` means the stream is | ||
| /// larger than `max_bytes` (or not safely decodable within that budget). | ||
| pub(crate) fn decompressed_content_bounded(stream: &Stream, max_bytes: usize) -> Option<Vec<u8>> { | ||
| let filters = match stream.filters() { | ||
| Ok(filters) => filters, | ||
| Err(_) => { | ||
| return take_if_within_budget(&stream.content, max_bytes); | ||
| } | ||
| }; | ||
|
|
||
| if filters.is_empty() { | ||
| return take_if_within_budget(&stream.content, max_bytes); | ||
| } | ||
|
|
||
| // Plain Flate is the highly compressible case. Detector scans only need | ||
| // the inflated operator bytes; skip PNG predictors here so inflate can | ||
| // stop at the budget instead of materializing the full buffer first. | ||
| if filters.len() == 1 && filters[0] == b"FlateDecode" { | ||
| return inflate_flate_bounded(&stream.content, max_bytes); | ||
| } | ||
|
|
||
| if stream.content.len() > max_bytes { | ||
| return None; | ||
| } | ||
| match stream.decompressed_content() { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P1: When a content stream uses a filter chain, this branch materializes the entire decoded buffer before checking its size. Decode every supported filter incrementally or reject the stream before this call, otherwise a small multi-filter stream bypasses the 32 MiB protection. Prompt for AI agents |
||
| Ok(data) if data.len() <= max_bytes => Some(data), | ||
| Ok(_) => None, | ||
| Err(_) => take_if_within_budget(&stream.content, max_bytes), | ||
| } | ||
| } | ||
|
|
||
| fn take_if_within_budget(bytes: &[u8], max_bytes: usize) -> Option<Vec<u8>> { | ||
| if bytes.len() > max_bytes { | ||
| None | ||
| } else { | ||
| Some(bytes.to_vec()) | ||
| } | ||
| } | ||
|
|
||
| fn inflate_flate_bounded(input: &[u8], max_bytes: usize) -> Option<Vec<u8>> { | ||
| if input.is_empty() { | ||
| return Some(Vec::new()); | ||
| } | ||
| match read_bounded(ZlibDecoder::new(input), max_bytes) { | ||
| Some(data) => Some(data), | ||
| None if input.len() > 2 => read_bounded(DeflateDecoder::new(&input[2..]), max_bytes), | ||
| None => None, | ||
| } | ||
| } | ||
|
|
||
| fn read_bounded<R: Read>(mut decoder: R, max_bytes: usize) -> Option<Vec<u8>> { | ||
| let mut output = Vec::new(); | ||
| let mut buf = [0u8; 16 * 1024]; | ||
| loop { | ||
| match decoder.read(&mut buf) { | ||
| Ok(0) => return Some(output), | ||
| Ok(n) => { | ||
| if output.len().saturating_add(n) > max_bytes { | ||
| return None; | ||
| } | ||
| output.extend_from_slice(&buf[..n]); | ||
| } | ||
| Err(_) => return None, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use flate2::write::ZlibEncoder; | ||
| use flate2::Compression; | ||
| use lopdf::dictionary; | ||
| use std::io::Write; | ||
|
|
||
| fn flate_stream(plain: &[u8]) -> Stream { | ||
| let mut encoder = ZlibEncoder::new(Vec::new(), Compression::best()); | ||
| encoder.write_all(plain).unwrap(); | ||
| let compressed = encoder.finish().unwrap(); | ||
| Stream::new(dictionary! { "Filter" => "FlateDecode" }, compressed) | ||
| } | ||
|
|
||
| #[test] | ||
| fn small_flate_stream_round_trips() { | ||
| let plain = b"BT /F1 12 Tf (Hello world) Tj ET"; | ||
| let stream = flate_stream(plain); | ||
| assert_eq!( | ||
| decompressed_content_bounded(&stream, MAX_DECOMPRESSED_STREAM_BYTES).as_deref(), | ||
| Some(plain.as_slice()) | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn highly_compressible_flate_stops_at_budget() { | ||
| let plain = vec![0u8; 256 * 1024]; | ||
| let stream = flate_stream(&plain); | ||
| assert!( | ||
| stream.content.len() < 8 * 1024, | ||
| "fixture must stay compact on disk, got {} compressed bytes", | ||
| stream.content.len() | ||
| ); | ||
| assert!(decompressed_content_bounded(&stream, 16 * 1024).is_none()); | ||
| assert_eq!( | ||
| decompressed_content_bounded(&stream, 256 * 1024).as_deref(), | ||
| Some(plain.as_slice()) | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn uncompressed_over_budget_is_skipped() { | ||
| let stream = Stream::new(dictionary! {}, vec![b'x'; 64]); | ||
| assert!(decompressed_content_bounded(&stream, 32).is_none()); | ||
| assert_eq!(decompressed_content_bounded(&stream, 64).unwrap().len(), 64); | ||
| } | ||
|
|
||
| #[test] | ||
| fn scan_helper_returns_empty_when_capped() { | ||
| let stream = flate_stream(&vec![0u8; 64 * 1024]); | ||
| // Production cap is far above 64 KiB, so this still decodes. | ||
| assert_eq!(stream_content_for_scan(&stream).len(), 64 * 1024); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P2: When a Flate content stream has PNG predictor parameters, this branch scans predictor-encoded bytes instead of applying predictor reversal. Apply predictor decoding incrementally or route predictor streams through a correctly bounded decoder, or text pages using them can be misclassified.
Prompt for AI agents