diff --git a/crates/raw/src/dngwrite.rs b/crates/raw/src/dngwrite.rs index 8dd31410ca..169cae25c5 100644 --- a/crates/raw/src/dngwrite.rs +++ b/crates/raw/src/dngwrite.rs @@ -464,5 +464,8 @@ mod tests { assert_eq!(hostile, write_dng(&raw, &opts(2048)).expect("the cap itself writes"), "u32::MAX is clamped to the cap"); assert_ne!(hostile, write_dng(&raw, &opts(256)).expect("a normal tile writes"), "the clamp is not a no-op"); assert_eq!(crate::probe(&hostile), Some(RawFormat::Dng), "the clamped output is still a DNG"); + // the writer's own padded tile (2048 × 2048 around an 8 × 8 image) reads back + let back = crate::decode(&hostile).expect("a tile this writer pads to decodes"); + assert_eq!((back.width, back.height), (w, h)); } } diff --git a/crates/raw/src/preview.rs b/crates/raw/src/preview.rs index 90cabf8629..9bd28aa172 100644 --- a/crates/raw/src/preview.rs +++ b/crates/raw/src/preview.rs @@ -68,11 +68,17 @@ fn nikon_color_space(bytes: &[u8], tiff: &Tiff, exif: &Ifd, make: &str) -> Optio /// The first frame (SOF) marker of a JPEG and its position, from the marker segments before the first scan. fn first_frame(b: &[u8]) -> Option<(u8, usize)> { + first_frame_within(b, &mut { usize::MAX }) +} + +/// [`first_frame`] charging `work` one per step (a segment, or a fill byte); `None` too when it runs out. +fn first_frame_within(b: &[u8], work: &mut usize) -> Option<(u8, usize)> { if b.len() < 4 || !b.starts_with(&[0xff, 0xd8]) { return None; } let mut i = 2usize; while i.checked_add(4)? <= b.len() { + *work = work.checked_sub(1)?; if *b.get(i)? != 0xff { return None; } @@ -259,6 +265,7 @@ fn preview_covering(bytes: &[u8], min_edge: Option) -> Option> { } } } + bound_candidates(&mut found, bytes.len()); let largest = found.iter().copied().filter(|s| is_dct_jpeg(s) || is_jxl(s)).max_by_key(|s| s.len()); let best = min_edge .zip(largest) @@ -273,6 +280,25 @@ fn preview_covering(bytes: &[u8], min_edge: Option) -> Option> { best } +/// Drops candidate ranges that repeat an earlier one, that are not a displayable JPEG or JPEG XL, and valid ones +/// past a shared budget of [`scan_budget`] bytes: a range is charged only once it validates, so invalid ranges +/// covering most of the file cannot use up the budget before a valid preview. The header walks that validate +/// (or reject) the ranges share a second budget of the same size, charged for every walk, so many ranges +/// that start a JPEG header and run through fill bytes cannot each cost a walk of their length. +fn bound_candidates(found: &mut Vec<&[u8]>, file_len: usize) { + let mut seen = std::collections::HashSet::new(); + let mut left = scan_budget(file_len); + let mut work = scan_budget(file_len); + found.retain(|s| { + let mut dct = || first_frame_within(s, &mut work).is_some_and(|(m, _)| matches!(m, 0xc0..=0xc2)); + if !seen.insert((s.as_ptr() as usize, s.len())) || !(dct() || is_jxl(s)) || s.len() > left { + return false; + } + left -= s.len(); + true + }); +} + /// The end of the DCT JPEG whose SOI is at `soi` (exclusive index after its EOI) and its component count, /// walking the marker segments and the entropy-coded data. `None` when it is not a complete, displayable /// (baseline or progressive) JPEG, so a stray `D8 FF` in other data is rejected. `*reach` is left at @@ -413,3 +439,52 @@ fn trim_eoi(s: &[u8]) -> &[u8] { #[cfg(test)] mod tests; + +#[cfg(test)] +mod bound_tests { + #[test] + fn repeated_and_over_budget_candidates_are_dropped() { + let mut data = vec![0u8; 4 << 20]; + // a valid JPEG header every 16 bytes, so each range below validates + for i in 0..64 { + data[i * 16..i * 16 + 15].copy_from_slice(&[0xff, 0xd8, 0xff, 0xc0, 0, 11, 8, 0, 8, 0, 8, 1, 1, 0x11, 0]); + } + let mut found: Vec<&[u8]> = vec![&data[..], &data[..], &data[..]]; + super::bound_candidates(&mut found, data.len()); + assert_eq!(found.len(), 1); + // overlapping but unequal ranges stop at the shared budget (8 x the file, at least 1 MiB) + let mut found: Vec<&[u8]> = (0..64).map(|i| &data[i * 16..]).collect(); + super::bound_candidates(&mut found, data.len()); + assert!(found.len() <= 8 && found.iter().map(|s| s.len()).sum::() <= 8 * data.len()); + } + + #[test] + fn invalid_ranges_do_not_use_up_the_budget_before_a_valid_preview() { + let mut data = vec![0u8; 2 << 20]; + let jpeg = [0xff, 0xd8, 0xff, 0xc0, 0, 11, 8, 0, 8, 0, 8, 1, 1, 0x11, 0]; + data[1 << 20..(1 << 20) + jpeg.len()].copy_from_slice(&jpeg); + // 40 distinct invalid ranges of nearly the whole file (far past the 8 x budget), then the valid one + let mut found: Vec<&[u8]> = (0..40).map(|i| &data[i..1 << 20]).collect(); + found.push(&data[1 << 20..]); + super::bound_candidates(&mut found, data.len()); + assert_eq!(found.len(), 1); + assert!(found[0].starts_with(&[0xff, 0xd8])); + } + + #[test] + fn header_walks_of_many_fill_byte_ranges_share_a_budget() { + // a JPEG header followed by 100 000 fill bytes and no frame: each walk would run to the end + let mut data = vec![0xffu8; 100_100]; + data[..2].copy_from_slice(&[0xff, 0xd8]); + let valid = [0xff, 0xd8, 0xff, 0xc0, 0, 11, 8, 0, 8, 0, 8, 1, 1, 0x11, 0]; + // 50 distinct such ranges (5 M steps against the 1 MiB budget), then a valid header + let mut found: Vec<&[u8]> = (0..50).map(|i| &data[..100_000 + i]).collect(); + found.push(&valid); + super::bound_candidates(&mut found, data.len()); + assert!(found.is_empty(), "the walks stop at the shared budget, so the later header is not reached"); + // the same header with no hostile ranges before it is kept + let mut found: Vec<&[u8]> = vec![&valid]; + super::bound_candidates(&mut found, data.len()); + assert_eq!(found.len(), 1); + } +} diff --git a/crates/raw/src/tiffraw.rs b/crates/raw/src/tiffraw.rs index cf679546fa..fa4e4a6150 100644 --- a/crates/raw/src/tiffraw.rs +++ b/crates/raw/src/tiffraw.rs @@ -269,7 +269,13 @@ fn decode_chunk( #[cfg(feature = "dng")] comp::LOSSY_JPEG => { // lossy DNG: each chunk is a baseline (DCT) JPEG of 8-bit samples - let (px, jw, jh, jc) = lossy_jpeg(src, cpp, limits.max_lossy_tile_samples)?; + // a JPEG decoded for a tile may hold no more samples than the tile (a real one is exactly the tile): + // many small tiles pointing at one big JPEG would otherwise each decode all of it + // (the JPEG codes whole MCUs, at most 32 × 32 pixels each, so its size is the tile's rounded up to them) + let mcu = |v: usize| v.div_ceil(32).saturating_mul(32); + let tile_budget = + mcu(cw).saturating_mul(mcu(ch)).saturating_mul(if cpp == 1 { 1 } else { 3 }).clamp(1, limits.max_lossy_tile_samples.max(1)); + let (px, jw, jh, jc) = lossy_jpeg(src, cpp, tile_budget)?; // An edge tile's JPEG may be smaller than the nominal tile, but it has to cover the part of the tile // inside the image: one that doesn't would leave a black region in a picture reported as decoded // (PhotoCraft's and FilmCraft's readers refuse a JPEG smaller than its tile; this keeps the edge case). @@ -300,6 +306,16 @@ fn decode_chunk( // Deflate compresses at most about 1:1032, so a source this far under half of its // nominal length cannot reconstruct the chunk: refused before the nominal buffer is // inflated and predicted, which padding-only work would make gigabytes. + // Nor may the nominal chunk be mostly padding outside the image (a tile far larger than the picture): + // its allocation and predictor pass would be spent on samples nobody reads. + if n > vw + .saturating_mul(vh) + .saturating_mul(cpp) + .saturating_mul(MAX_PADDING_FACTOR) + .saturating_add(MAX_WRITER_TILE_SAMPLES.saturating_mul(cpp)) + { + return Err(RawError::Limit("deflated chunk is mostly padding outside the image")); + } if (src.len() as u64).saturating_mul(2048) < inflate_len { return Err(RawError::Corrupt(format!("a deflated chunk of {inflate_len} bytes is packed into only {} bytes", src.len()))); } @@ -344,6 +360,15 @@ fn jxl_chunk_check(src: &[u8], cw: usize, ch: usize, vw: usize, vh: usize, cpp: jxl_chunk(src, cw, ch, vw, vh, cpp, bits, float).map(|_| ()) } +/// How many times its in-image samples a deflated chunk's nominal size may reach (plus a writer tile of slack): +/// edge tiles of real files are mostly inside the image. +#[cfg(feature = "dng")] +const MAX_PADDING_FACTOR: usize = 32; +/// Samples per plane of the largest Deflate tile the DNG writer pads to (2048 × 2048, `dngwrite::MAX_DEFLATE_TILE`), +/// which a small image's one tile is nearly all padding of: such files still decode. +#[cfg(feature = "dng")] +const MAX_WRITER_TILE_SAMPLES: usize = 2048 * 2048; + #[cfg(feature = "dng")] /// Decode one baseline JPEG chunk to 8-bit samples: (samples, width, height, channels). pub(crate) fn lossy_jpeg(src: &[u8], cpp: usize, max_samples: usize) -> Result<(Vec, usize, usize, usize)> { @@ -535,6 +560,65 @@ mod lossy_tests { assert!((px(10, 5)[1] as i32 - 150).abs() <= 6, "green ramp: {:?}", px(10, 5)); } + /// A small tile may not decode a JPEG much larger than itself (a table of tiny tiles all pointing at one big + /// JPEG would decode it once per tile); a JPEG that fills the tile's whole 32 × 32 MCU block still decodes. + #[test] + fn a_lossy_tile_may_not_decode_a_much_larger_jpeg() { + let encode = |w: usize, h: usize| { + let mut out = Vec::new(); + jpeg_encoder::Encoder::new(&mut out, 90).encode(&vec![128u8; w * h * 3], w as u16, h as u16, jpeg_encoder::ColorType::Rgb).unwrap(); + out + }; + let image = |jpeg: &[u8]| { + let mut file = vec![0u8; 8]; + file.extend_from_slice(jpeg); + let info = ImageInfo { + width: 4, + height: 4, + bits_per_sample: vec![8, 8, 8], + samples_per_pixel: 3, + compression: comp::LOSSY_JPEG, + photometric: 34892, + planar: 1, + predictor: 1, + sample_format: 1, + new_subfile_type: 0, + layout: Layout::Tiles { tile_width: 16, tile_height: 16 }, + offsets: vec![8], + byte_counts: vec![jpeg.len() as u64], + }; + read_image(&file, &info, ByteOrder::Little, Packing::Msb, &Limits::default()) + }; + assert!(image(&encode(32, 32)).is_ok()); + assert!(matches!(image(&encode(256, 256)), Err(RawError::Corrupt(_)))); + } + + /// A Deflate tile that is nearly all padding outside the image (a 4096 × 4096 tile holding one column of a + /// 4097-wide picture) is refused before its nominal buffer is inflated; the writer's largest padded tile + /// (2048 × 2048) is within the slack (`dngwrite`'s clamp test). + #[test] + fn a_deflate_tile_that_is_mostly_padding_is_refused() { + let file = vec![0u8; 8 + 8192]; + let info = ImageInfo { + width: 4097, + height: 4096, + bits_per_sample: vec![8], + samples_per_pixel: 1, + compression: comp::ADOBE_DEFLATE, + photometric: 32803, + planar: 1, + predictor: 1, + sample_format: 1, + new_subfile_type: 0, + layout: Layout::Tiles { tile_width: 4096, tile_height: 4096 }, + offsets: vec![8, 8], + byte_counts: vec![8192, 8192], + }; + let chunks = info.chunks(file.len() as u64); + let edge = decode_chunk(&file, &info, &chunks[1], ByteOrder::Little, Packing::Msb, 1, 8, false, &Limits::default()); + assert!(matches!(edge, Err(RawError::Limit(_))), "{:?}", edge.err()); + } + fn strip_info(compression: u16, offsets: Vec, byte_counts: Vec) -> ImageInfo { ImageInfo { width: 4,