From 5e5c0cf874939864c62c962bc6b2feabadd8d0e3 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 4 Nov 2026 03:28:45 +0000 Subject: [PATCH] dng: reject zero or over-16-bit sample depths before unpacking (#4192) unpack accepted a bit depth of 0: the input requirement became zero bytes, so one source byte produced a header-sized buffer of zero samples. Depths outside 1..=16 (the u16 output range) are now rejected up front. --- crates/raw/src/dng_lines.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/crates/raw/src/dng_lines.rs b/crates/raw/src/dng_lines.rs index b69ba967e..d6bfd6b6a 100644 --- a/crates/raw/src/dng_lines.rs +++ b/crates/raw/src/dng_lines.rs @@ -171,6 +171,10 @@ fn chunks<'a>(t: &Tiff<'a>, ifd: &Ifd, l: &RawLayout) -> Result>> /// words in the file's byte order, other depths packed most significant bit first with each row /// starting on a byte boundary (TIFF 6.0 ยง7, DNG BitsPerSample). pub fn unpack(bytes: &[u8], w: usize, h: usize, spp: usize, bits: u32, big_endian: bool) -> Result> { + // zero-bit samples need no input, so a header could ask for any number of them + if !(1..=16).contains(&bits) { + return Err(Error::Malformed("unsupported bits per sample")); + } let per_row = w * spp; let row_bytes = (per_row * bits as usize).div_ceil(8); let need = row_bytes.checked_mul(h).ok_or(Error::TooLarge)?; @@ -263,3 +267,16 @@ pub fn read(t: &Tiff, ifd: &Ifd) -> Result { } Ok(RawImage { width: l.width, height: l.height, samples_per_pixel: spp, bits: l.bits, data }) } + +#[cfg(test)] +mod unpack_tests { + use super::*; + + #[test] + fn zero_or_oversized_bit_depths_are_rejected_before_allocating() { + // zero-bit samples consume no input: one byte used to yield a whole picture of zeros + assert!(matches!(unpack(&[0], 1 << 20, 1 << 10, 1, 0, false), Err(Error::Malformed(_)))); + assert!(matches!(unpack(&[0; 64], 4, 1, 1, 17, false), Err(Error::Malformed(_)))); + assert_eq!(unpack(&[0x12, 0x34, 0x50], 2, 1, 1, 12, true).unwrap(), vec![0x123, 0x450]); + } +}