From d8f0d377379225d838aaa865efa7dee00baf9a2e Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Mon, 19 Oct 2026 23:25:54 +1100 Subject: [PATCH 1/2] LR-META-EXIF: TIFF keeps shared child IFDs and multi-string ASCII values A child IFD referenced twice (two SubIFDs entries, an Exif pointer shared by two directories) was dropped as a loop. Cycles are now detected on the parent path only; a shared IFD is parsed once and copied, and every copy counts against max_ifds, so recursion and output stay bounded. ASCII fields keep every NUL-separated string (Value::as_strings); as_str still returns the first. Sources: own design (TIFF 6.0 spec, ASCII type and SubIFDs). (cherry picked from commit 6f24fcb6b9c394d31bb8246f2bca95a7c59f13e8) Co-Authored-By: Claude Opus 5.5 --- crates/tiff/src/lib.rs | 18 ++++-- crates/tiff/src/reader.rs | 130 +++++++++++++++++++++++++++++++++++--- 2 files changed, 134 insertions(+), 14 deletions(-) diff --git a/crates/tiff/src/lib.rs b/crates/tiff/src/lib.rs index 2072c4936e2..d7ffe21b3a1 100644 --- a/crates/tiff/src/lib.rs +++ b/crates/tiff/src/lib.rs @@ -174,7 +174,8 @@ impl FieldType { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Value { Byte(Vec), - /// ASCII text (bytes up to the first NUL, decoded lossily as UTF-8). + /// ASCII text decoded lossily as UTF-8, without the terminating NULs. A field holding several strings keeps + /// them NUL-separated ([`Value::as_strings`]). Ascii(String), Short(Vec), Long(Vec), @@ -307,11 +308,11 @@ impl Value { } } - /// Text for ASCII values (trimmed of trailing NULs / spaces); `Byte`/`Undefined` are decoded as UTF-8 (lossy) - /// up to the first NUL, which covers XMP packets and UCS-less Exif strings. + /// Text for ASCII values (the first string, trimmed of trailing spaces); `Byte`/`Undefined` are decoded as + /// UTF-8 (lossy) up to the first NUL, which covers XMP packets and UCS-less Exif strings. pub fn as_str(&self) -> Option { match self { - Value::Ascii(s) => Some(s.trim_end_matches([' ', '\0']).to_string()), + Value::Ascii(s) => Some(s.split('\0').next().unwrap_or_default().trim_end().to_string()), Value::Byte(b) | Value::Undefined(b) => { let end = b.iter().position(|&c| c == 0).unwrap_or(b.len()); Some(String::from_utf8_lossy(&b[..end]).trim_end().to_string()) @@ -320,6 +321,15 @@ impl Value { } } + /// Every NUL-separated string of an ASCII value, each trimmed of trailing spaces (empty ones dropped); other + /// types give what [`Self::as_str`] gives. + pub fn as_strings(&self) -> Vec { + match self { + Value::Ascii(s) => s.split('\0').map(|p| p.trim_end().to_string()).filter(|p| !p.is_empty()).collect(), + _ => self.as_str().into_iter().filter(|p| !p.is_empty()).collect(), + } + } + /// Raw bytes for `Byte` / `Undefined` / `SByte` / `Ascii`. pub fn as_bytes(&self) -> Option<&[u8]> { match self { diff --git a/crates/tiff/src/reader.rs b/crates/tiff/src/reader.rs index 70c66c5a742..3f44af7265d 100644 --- a/crates/tiff/src/reader.rs +++ b/crates/tiff/src/reader.rs @@ -1,7 +1,7 @@ //! Bounds-checked IFD parsing. use crate::{ByteOrder, Entry, FieldType, Ifd, Result, Tiff, TiffError, Value, tags}; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; /// Limits applied while parsing. The defaults are generous for real files and safe for hostile ones. #[derive(Clone, Debug)] @@ -177,7 +177,9 @@ pub(crate) fn parse(data: &[u8], opts: &ParseOptions) -> Result { let mut ctx = Ctx::new(data, order, big, opts); let mut ifds = Vec::new(); let mut off = first; - while off != 0 { + // the top-level chain stops at an IFD it already holds (a `next` pointer looping back) + let mut chain = HashSet::new(); + while off != 0 && chain.insert(off) { match ctx.ifd(off, 0, 0) { Ok((ifd, next)) => { ifds.push(ifd); @@ -210,15 +212,28 @@ struct Ctx<'a> { order: ByteOrder, big: bool, opts: &'a ParseOptions, - visited: HashSet, + /// Offsets of the IFDs being parsed (the current path from the root): a child pointing at one of them is a + /// cycle. + ancestors: Vec, + /// IFDs produced so far, counting every copy of a shared one (bounded by `max_ifds`). + visits: usize, + /// IFDs already parsed, by (offset, base): a second pointer to one (two `SubIFDs` entries, or an Exif pointer + /// shared by two directories) gets a copy instead of being dropped. + parsed: HashMap<(u64, u64), (Ifd, u64)>, budget: u64, entries_total: usize, } +/// The number of IFDs in `ifd`'s tree, itself included. +fn tree_size(ifd: &Ifd) -> usize { + let boxed = [&ifd.exif, &ifd.gps, &ifd.interop].into_iter().flatten().map(|b| tree_size(b)); + ifd.sub_ifds.iter().map(tree_size).chain(boxed).fold(1usize, usize::saturating_add) +} + impl<'a> Ctx<'a> { fn new(data: &'a [u8], order: ByteOrder, big: bool, opts: &'a ParseOptions) -> Self { let budget = opts.budget_for(data.len()); - Self { data, order, big, opts, visited: HashSet::new(), budget, entries_total: 0 } + Self { data, order, big, opts, ancestors: Vec::new(), visits: 0, parsed: HashMap::new(), budget, entries_total: 0 } } fn read_off(&self, pos: usize) -> Option { @@ -230,12 +245,30 @@ impl<'a> Ctx<'a> { if depth > self.opts.max_depth { return Err(TiffError::Limit("IFD nesting depth")); } - if self.visited.len() >= self.opts.max_ifds { - return Err(TiffError::Limit("IFD count")); - } - if !self.visited.insert(offset) { + if self.ancestors.contains(&offset) { return Err(TiffError::Invalid(format!("IFD loop at {offset}"))); } + if let Some((ifd, next)) = self.parsed.get(&(offset, base)) { + let visits = self.visits.saturating_add(tree_size(ifd)); + if visits > self.opts.max_ifds { + return Err(TiffError::Limit("IFD count")); + } + self.visits = visits; + return Ok((ifd.clone(), *next)); + } + if self.visits >= self.opts.max_ifds { + return Err(TiffError::Limit("IFD count")); + } + self.visits = self.visits.saturating_add(1); + self.ancestors.push(offset); + let r = self.parse_dir(offset, base, depth); + self.ancestors.pop(); + let (ifd, next) = r?; + self.parsed.insert((offset, base), (ifd.clone(), next)); + Ok((ifd, next)) + } + + fn parse_dir(&mut self, offset: u64, base: u64, depth: usize) -> Result<(Ifd, u64)> { let dir = directory_entries(self.data, offset, self.order, self.big, self.opts.max_entries)?; // Bound total entries across the whole parse so overlapping IFD tables (SubIFD pointers // shifted by one entry) cannot allocate millions of `Entry`s from a small input. @@ -314,8 +347,10 @@ pub fn decode(o: ByteOrder, typ: FieldType, b: &[u8]) -> Value { FieldType::Byte => Value::Byte(b.to_vec()), FieldType::Undefined => Value::Undefined(b.to_vec()), FieldType::Ascii => { - let end = b.iter().position(|&c| c == 0).unwrap_or(b.len()); - Value::Ascii(String::from_utf8_lossy(&b[..end]).into_owned()) + // every NUL-separated string is kept (TIFF 6.0 allows several in one field); only the + // terminating NULs go + let end = b.iter().rposition(|&c| c != 0).map_or(0, |i| i.saturating_add(1)); + Value::Ascii(String::from_utf8_lossy(b.get(..end).unwrap_or_default()).into_owned()) } FieldType::SByte => Value::SByte(b.iter().map(|&x| x as i8).collect()), FieldType::Short => Value::Short(b.as_chunks::<2>().0.iter().map(|c| o.u16(arr(c))).collect()), @@ -381,6 +416,81 @@ mod tests { d } + /// A classic little-endian TIFF: IFD0 at 8 with `SubIFDs` = [`a`, `b`] and Exif → `exif`; a one-entry IFD + /// (tag 0x0101 = its offset) at 38 and at 56; `IFD0`'s next pointer is `next`. + fn shared_children(a: u32, b: u32, exif: u32, next: u32) -> Vec { + let o = ByteOrder::Little; + let mut d = b"II*\0\x08\0\0\0".to_vec(); + o.put_u16(&mut d, 2); + // SubIFDs: two LONGs (8 bytes) stored out of line at 74 + o.put_u16(&mut d, 330); + o.put_u16(&mut d, 4); + d.extend(2u32.to_le_bytes()); + d.extend(74u32.to_le_bytes()); + o.put_u16(&mut d, 34665); + o.put_u16(&mut d, 4); + d.extend(1u32.to_le_bytes()); + d.extend(exif.to_le_bytes()); + d.extend(next.to_le_bytes()); + for at in [38u32, 56] { + d.resize(at as usize, 0); + o.put_u16(&mut d, 1); + o.put_u16(&mut d, 0x0101); + o.put_u16(&mut d, 4); + d.extend(1u32.to_le_bytes()); + d.extend(at.to_le_bytes()); + d.extend(0u32.to_le_bytes()); + } + d.resize(74, 0); + d.extend(a.to_le_bytes()); + d.extend(b.to_le_bytes()); + d + } + + #[test] + fn a_child_ifd_referenced_twice_is_kept_both_times() { + let t = Tiff::parse(&shared_children(38, 38, 38, 0)).unwrap(); + let ifd = &t.ifds[0]; + assert_eq!(ifd.sub_ifds.len(), 2, "the second SubIFDs pointer to the same IFD used to be dropped"); + assert!(ifd.sub_ifds.iter().all(|s| s.u64(0x0101) == Some(38))); + assert_eq!(ifd.exif.as_ref().and_then(|e| e.u64(0x0101)), Some(38)); + // distinct children still parse as before + let t = Tiff::parse(&shared_children(38, 56, 56, 0)).unwrap(); + let subs: Vec<_> = t.ifds[0].sub_ifds.iter().map(|s| s.u64(0x0101)).collect(); + assert_eq!(subs, vec![Some(38), Some(56)]); + // a chain IFD that is also a child is parsed in the chain too + let t = Tiff::parse(&shared_children(38, 56, 56, 56)).unwrap(); + assert_eq!(t.ifds.len(), 2); + assert_eq!(t.ifds[1].u64(0x0101), Some(56)); + } + + #[test] + fn a_child_pointing_at_its_parent_is_still_a_loop() { + let t = Tiff::parse(&shared_children(8, 38, 8, 8)).unwrap(); + assert_eq!(t.ifds.len(), 1); + assert_eq!(t.ifds[0].sub_ifds.len(), 1); + assert!(t.ifds[0].exif.is_none()); + } + + #[test] + fn shared_children_count_against_the_ifd_limit() { + let opts = ParseOptions { max_ifds: 2, ..Default::default() }; + let t = Tiff::parse_with(&shared_children(38, 38, 38, 0), &opts).unwrap(); + assert_eq!(t.ifds[0].sub_ifds.len(), 1); + assert!(t.ifds[0].exif.is_none()); + } + + #[test] + fn ascii_keeps_every_nul_separated_string() { + let v = decode(ByteOrder::Little, FieldType::Ascii, b"one\0two\0\0"); + assert_eq!(v, Value::Ascii("one\0two".into())); + assert_eq!(v.as_str().as_deref(), Some("one")); + assert_eq!(v.as_strings(), vec!["one".to_string(), "two".to_string()]); + assert_eq!(decode(ByteOrder::Little, FieldType::Ascii, b"\0\0"), Value::Ascii(String::new())); + assert!(decode(ByteOrder::Little, FieldType::Ascii, b"\0\0").as_strings().is_empty()); + assert_eq!(decode(ByteOrder::Little, FieldType::Ascii, b"abc").as_str().as_deref(), Some("abc")); + } + #[test] fn only_a_directory_read_whole_has_a_next_pointer() { // the comparison itself, on every target: a declared count past u32::MAX never matches a small read count From 92be6313f356275b7b442e1441ec397b28a77e5c Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Mon, 26 Oct 2026 11:40:18 +1100 Subject: [PATCH 2/2] LR-META-EXIF: shared IFD copies are charged entries and value bytes, keyed by depth Review follow-up. A copy of a shared IFD is now charged the IFDs, entries and value bytes its first parse used, so many pointers to one large IFD cannot clone past max_entries_total or the value budget. The cache is keyed by depth too, so a copy has the children a fresh parse at that depth would have. Value::as_bytes on ASCII gives the first string again, as byte readers (the SR2 private-field selection) expect. Sources: own design. Co-Authored-By: Claude Opus 5.5 --- crates/tiff/src/lib.rs | 4 +-- crates/tiff/src/reader.rs | 61 ++++++++++++++++++++++++++++++++------- 2 files changed, 52 insertions(+), 13 deletions(-) diff --git a/crates/tiff/src/lib.rs b/crates/tiff/src/lib.rs index d7ffe21b3a1..98c42ac021f 100644 --- a/crates/tiff/src/lib.rs +++ b/crates/tiff/src/lib.rs @@ -330,11 +330,11 @@ impl Value { } } - /// Raw bytes for `Byte` / `Undefined` / `SByte` / `Ascii`. + /// Raw bytes for `Byte` / `Undefined` / `SByte` / `Ascii` (an ASCII value's first string only). pub fn as_bytes(&self) -> Option<&[u8]> { match self { Value::Byte(b) | Value::Undefined(b) => Some(b), - Value::Ascii(s) => Some(s.as_bytes()), + Value::Ascii(s) => s.as_bytes().split(|&c| c == 0).next(), _ => None, } } diff --git a/crates/tiff/src/reader.rs b/crates/tiff/src/reader.rs index 3f44af7265d..f1c57ab718e 100644 --- a/crates/tiff/src/reader.rs +++ b/crates/tiff/src/reader.rs @@ -217,17 +217,28 @@ struct Ctx<'a> { ancestors: Vec, /// IFDs produced so far, counting every copy of a shared one (bounded by `max_ifds`). visits: usize, - /// IFDs already parsed, by (offset, base): a second pointer to one (two `SubIFDs` entries, or an Exif pointer - /// shared by two directories) gets a copy instead of being dropped. - parsed: HashMap<(u64, u64), (Ifd, u64)>, + /// IFDs already parsed, by (offset, base, depth): a second pointer to one (two `SubIFDs` entries, or an Exif + /// pointer shared by two directories) gets a copy instead of being dropped. Keyed by depth too, so a copy has + /// exactly the children a fresh parse at that depth would have; a copy is charged the IFDs, entries and value + /// bytes of the first parse, so copies stay inside every limit. + parsed: HashMap<(u64, u64, usize), Parsed>, budget: u64, entries_total: usize, } -/// The number of IFDs in `ifd`'s tree, itself included. -fn tree_size(ifd: &Ifd) -> usize { - let boxed = [&ifd.exif, &ifd.gps, &ifd.interop].into_iter().flatten().map(|b| tree_size(b)); - ifd.sub_ifds.iter().map(tree_size).chain(boxed).fold(1usize, usize::saturating_add) +/// What parsing one IFD and its children used up: a copy of it is charged the same. +#[derive(Clone, Copy)] +struct Cost { + ifds: usize, + entries: usize, + bytes: u64, +} + +/// An IFD parsed once, kept for later pointers to it. +struct Parsed { + ifd: Ifd, + next: u64, + cost: Cost, } impl<'a> Ctx<'a> { @@ -248,23 +259,40 @@ impl<'a> Ctx<'a> { if self.ancestors.contains(&offset) { return Err(TiffError::Invalid(format!("IFD loop at {offset}"))); } - if let Some((ifd, next)) = self.parsed.get(&(offset, base)) { - let visits = self.visits.saturating_add(tree_size(ifd)); + let key = (offset, base, depth); + if let Some(c) = self.parsed.get(&key) { + // a copy costs what the first parse did: its IFDs, entries and value bytes + let visits = self.visits.saturating_add(c.cost.ifds); if visits > self.opts.max_ifds { return Err(TiffError::Limit("IFD count")); } + let entries = self.entries_total.saturating_add(c.cost.entries); + if entries > self.opts.max_entries_total { + return Err(TiffError::Limit("entry count")); + } + if c.cost.bytes > self.budget { + return Err(TiffError::Limit("value bytes")); + } self.visits = visits; - return Ok((ifd.clone(), *next)); + self.entries_total = entries; + self.budget -= c.cost.bytes; + return Ok((c.ifd.clone(), c.next)); } if self.visits >= self.opts.max_ifds { return Err(TiffError::Limit("IFD count")); } + let (visits0, entries0, budget0) = (self.visits, self.entries_total, self.budget); self.visits = self.visits.saturating_add(1); self.ancestors.push(offset); let r = self.parse_dir(offset, base, depth); self.ancestors.pop(); let (ifd, next) = r?; - self.parsed.insert((offset, base), (ifd.clone(), next)); + let cost = Cost { + ifds: self.visits.saturating_sub(visits0), + entries: self.entries_total.saturating_sub(entries0), + bytes: budget0.saturating_sub(self.budget), + }; + self.parsed.insert(key, Parsed { ifd: ifd.clone(), next, cost }); Ok((ifd, next)) } @@ -480,12 +508,23 @@ mod tests { assert!(t.ifds[0].exif.is_none()); } + /// Hostile input: many pointers to one shared IFD must not clone past the entry limit (each child has one + /// entry, so three copies need three entries plus the root's two). + #[test] + fn shared_children_count_against_the_entry_limit() { + let opts = ParseOptions { max_entries_total: 4, ..Default::default() }; + let t = Tiff::parse_with(&shared_children(38, 38, 38, 0), &opts).unwrap(); + assert_eq!(t.ifds[0].sub_ifds.len(), 2); + assert!(t.ifds[0].exif.is_none(), "the third copy would pass the entry limit"); + } + #[test] fn ascii_keeps_every_nul_separated_string() { let v = decode(ByteOrder::Little, FieldType::Ascii, b"one\0two\0\0"); assert_eq!(v, Value::Ascii("one\0two".into())); assert_eq!(v.as_str().as_deref(), Some("one")); assert_eq!(v.as_strings(), vec!["one".to_string(), "two".to_string()]); + assert_eq!(v.as_bytes(), Some(&b"one"[..]), "byte readers see the first string, as before"); assert_eq!(decode(ByteOrder::Little, FieldType::Ascii, b"\0\0"), Value::Ascii(String::new())); assert!(decode(ByteOrder::Little, FieldType::Ascii, b"\0\0").as_strings().is_empty()); assert_eq!(decode(ByteOrder::Little, FieldType::Ascii, b"abc").as_str().as_deref(), Some("abc"));