Codecs: cap what tiff_exif::read copies from overlapping EXIF values (#5982)

An entry's value only has to lie inside the file, so many Exif entries can
point at the same bytes: a 62 KB TIFF with 1,000 such entries made the reader
copy 50 MB (and the block writer copy it again), on every TIFF import and on
export of a document carrying an EXIF block.

read() now has a copy budget shared by IFD0's descriptive tags and the GPS and
Exif directories: at most 4 MiB, and never more than the stream's own length,
since the values of a well-formed stream are distinct bytes of it. An entry
that does not fit is left out and later, smaller ones are still kept; the
small directories are read first so a huge maker note cannot crowd out the
GPS position. Maker notes of 200 KB and 1 MB round-trip as before.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Rj8vs4QyUES3uwgX6SuGGh
This commit is contained in:
Brian TorresandClaude Sonnet 5.5 committed 2026-10-15 01:01:37 -07:00
1 parent df055f3dcb
commit 827e4e7094
2 files changed
+130 -10

No files matched your search

+36 -10
View File
@@ -6,7 +6,9 @@
//! the same reader ([`super::tiff_ifd::File`]): reading a TIFF builds a block from the file's own
//! directories, writing one copies the block's directories into the file. Values are copied as
//! bytes (re-ordered when the byte orders differ), so tags PhotoCraft doesn't know survive.
//! Classic TIFF only on the reading side: an EXIF block has 4-byte offsets.
//! Classic TIFF only on the reading side: an EXIF block has 4-byte offsets. What is copied is
//! bounded by the stream's own size and a fixed cap, because entries of a hostile file can
//! overlap (see [`read`]).
use tiff::encoder::{DirectoryEncoder, TiffEncoder, TiffKind};
use tiff::tags::{Tag, Type};
@@ -27,6 +29,11 @@ const TAG_INTEROP_IFD: u16 = 40965;
const IFD0_TAGS: [u16; 7] = [270, 271, 272, 305, 306, 315, 33432];
/// At most this many entries are copied from one directory.
const MAX_FIELDS: usize = 1024;
/// At most this many value bytes are copied from one stream, over all its directories. Real EXIF
/// is far smaller (the largest Nikon maker note seen is under 1 MB); the cap leaves room for
/// that and for a few such notes. A stream never yields more than its own length either (see
/// [`read`]).
const MAX_COPIED_BYTES: usize = 4 * 1024 * 1024;
/// One entry with its value bytes in the byte order of the stream it came from.
#[derive(Clone, Debug, PartialEq)]
@@ -53,13 +60,22 @@ impl ExifDirs {
}
}
fn fields(f: &File<'_>, ifd: &Ifd, keep: impl Fn(u16) -> bool) -> Vec<Field> {
ifd.entries
.iter()
.filter(|e| keep(e.tag) && !matches!(e.tag, TAG_EXIF_IFD | TAG_GPS_IFD | TAG_INTEROP_IFD))
.filter_map(|e| Some(Field { tag: e.tag, ty: e.ty, count: u32::try_from(e.count).ok()?, value: f.data(e)?.to_vec() }))
.take(MAX_FIELDS)
.collect()
/// The entries of `ifd` that `keep` accepts, with their values copied. An entry's value only has
/// to lie inside the file, so entries may overlap: `budget` is the number of value bytes that may
/// still be copied (shared by all the directories of one stream), and an entry whose value does
/// not fit in what is left is skipped, so later, smaller entries can still be kept.
fn fields(f: &File<'_>, ifd: &Ifd, budget: &mut usize, keep: impl Fn(u16) -> bool) -> Vec<Field> {
let mut out = Vec::new();
for e in ifd.entries.iter().filter(|e| keep(e.tag) && !matches!(e.tag, TAG_EXIF_IFD | TAG_GPS_IFD | TAG_INTEROP_IFD)) {
if out.len() >= MAX_FIELDS {
break;
}
let (Ok(count), Some(value)) = (u32::try_from(e.count), f.data(e)) else { continue };
let Some(left) = budget.checked_sub(value.len()) else { continue };
*budget = left;
out.push(Field { tag: e.tag, ty: e.ty, count, value: value.to_vec() });
}
out
}
fn sub(f: &File<'_>, ifd: &Ifd, tag: u16) -> Option<Ifd> {
@@ -69,14 +85,24 @@ fn sub(f: &File<'_>, ifd: &Ifd, tag: u16) -> Option<Ifd> {
/// The EXIF parts of the classic TIFF stream `b` (a TIFF file, or an EXIF block without its
/// `Exif\0\0` prefix): IFD0's descriptive tags and the Exif and GPS directories.
///
/// The values copied add up to at most [`MAX_COPIED_BYTES`] and to at most `b.len()`: the values
/// of a well-formed stream are distinct bytes of it, while a hostile one can have many entries
/// point at the same bytes and so ask for far more than its size. Entries that do not fit in what
/// is left are left out (the small descriptive directories come first, so a huge maker note
/// cannot crowd out the GPS position).
pub(crate) fn read(b: &[u8]) -> Option<ExifDirs> {
let f = File::parse(b)?;
if f.big {
return None;
}
let ifd0 = f.ifd(f.first_ifd)?;
let dir = |tag: u16| sub(&f, &ifd0, tag).map(|d| fields(&f, &d, |_| true)).unwrap_or_default();
Some(ExifDirs { le: f.le, ifd0: fields(&f, &ifd0, |t| IFD0_TAGS.contains(&t)), exif: dir(TAG_EXIF_IFD), gps: dir(TAG_GPS_IFD) })
let mut budget = MAX_COPIED_BYTES.min(b.len());
let ifd0_fields = fields(&f, &ifd0, &mut budget, |t| IFD0_TAGS.contains(&t));
let mut dir = |tag: u16| sub(&f, &ifd0, tag).map(|d| fields(&f, &d, &mut budget, |_| true)).unwrap_or_default();
let gps = dir(TAG_GPS_IFD);
let exif = dir(TAG_EXIF_IFD);
Some(ExifDirs { le: f.le, ifd0: ifd0_fields, exif, gps })
}
/// Bytes per element whose order a byte-order change reverses: a RATIONAL is two LONGs.
+94
View File
@@ -166,3 +166,97 @@ fn no_exif_is_written_without_embed_metadata() {
let tiff = encode(&img, Format::Tiff, &EncodeOptions { embed_metadata: false, ..Default::default() }).unwrap();
assert_eq!(decode(&tiff).unwrap().meta.exif, None);
}
// ---------------------------------------------------------------------------
// Bounded copying: an entry's value only has to lie inside the file, so a hostile file can have
// many entries point at the same bytes.
// ---------------------------------------------------------------------------
/// A valid 1x1 gray TIFF whose Exif directory has `entries` UNDEFINED entries of `count` bytes
/// that all point at the same `count` bytes: the file is about `count` bytes long and asks to
/// copy `entries * count`.
fn overlapping_tiff(entries: usize, count: u32) -> Vec<u8> {
let entry = |tag: u16, ty: u16, count: u32, value: u32| {
[tag.to_le_bytes().to_vec(), ty.to_le_bytes().to_vec(), count.to_le_bytes().to_vec(), value.to_le_bytes().to_vec()].concat()
};
let at_exif = 8 + 2 + 12 * 10 + 4;
let data_at = at_exif + 2 + 12 * entries + 4;
let mut out = b"II".to_vec();
out.extend(42u16.to_le_bytes());
out.extend(8u32.to_le_bytes());
out.extend(10u16.to_le_bytes());
for (tag, ty, value) in
[(256, 3, 1), (257, 3, 1), (258, 3, 8), (259, 3, 1), (262, 3, 1), (273, 4, 0), (277, 3, 1), (278, 3, 1), (279, 4, 1), (34665, 4, at_exif as u32)]
{
out.extend(entry(tag, ty, 1, value));
}
out.extend(0u32.to_le_bytes());
out.extend((entries as u16).to_le_bytes());
for i in 0..entries {
out.extend(entry(i as u16 + 1, 7, count, data_at as u32));
}
out.extend(0u32.to_le_bytes());
out.extend(vec![0x5A; count as usize]);
out
}
#[test]
fn overlapping_field_values_are_bounded() {
// About 62 KB on disk; copied entry by entry it would be 1,000 x 50,000 bytes.
let tiff = overlapping_tiff(1000, 50_000);
assert!(tiff.len() < 64 * 1024);
let img = decode(&tiff).expect("the image itself is fine");
assert_eq!(img.dimensions(), (1, 1));
let exif = img.meta.exif.expect("the first entries are kept");
assert!(exif.len() <= 2 * tiff.len(), "{} bytes of EXIF from a {} byte file", exif.len(), tiff.len());
}
#[test]
fn overlapping_field_values_in_an_exif_block_are_bounded_on_export() {
// The same block as an image's EXIF: the writer reads it with the same code.
let block = overlapping_tiff(1000, 50_000);
let mut img = Image::from_raw(2, 2, ChannelLayout::Gray, SampleType::U8, vec![0; 4]).unwrap();
img.meta.exif = Some(block.clone());
let tiff = encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap();
assert!(tiff.len() <= 2 * block.len(), "a {} byte block wrote a {} byte file", block.len(), tiff.len());
}
/// An EXIF block with a maker note of `len` bytes, an exposure time and a GPS latitude reference.
fn block_with_maker_note(le: bool, len: usize) -> Vec<u8> {
let b = Block { le };
b.build(
vec![(271, 2, 4, b"Cam\0".to_vec())],
vec![(33434, 5, 1, b.rational(1, 125)), (37500, 7, len as u32, (0..len).map(|i| (i * 7) as u8).collect())],
vec![(1, 2, 2, b"N\0".to_vec())],
)
}
#[test]
fn large_maker_notes_still_survive() {
// Nikon maker notes run from 100 KB to nearly 1 MB.
for len in [200 * 1024, 1000 * 1024] {
let block = block_with_maker_note(true, len);
let mut img = Image::from_raw(4, 3, ChannelLayout::Rgb, SampleType::U8, vec![90; 36]).unwrap();
img.meta.exif = Some(block.clone());
let tiff = encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap();
let back = decode(&tiff).unwrap().meta.exif.expect("EXIF read back");
let (ble, _, bexif, bgps) = dirs(&back);
let (ole, _, oexif, ogps) = dirs(&block);
assert_eq!(normalized(&bexif, ble), normalized(&oexif, ole), "{len} byte maker note");
assert_eq!(normalized(&bgps, ble), normalized(&ogps, ole));
}
}
#[test]
fn a_field_beyond_the_cap_is_dropped_and_the_rest_kept() {
let block = block_with_maker_note(false, 6 * 1024 * 1024);
let mut img = Image::from_raw(2, 2, ChannelLayout::Gray, SampleType::U8, vec![0; 4]).unwrap();
img.meta.exif = Some(block);
let tiff = encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap();
assert!(tiff.len() < 1024 * 1024, "{} bytes", tiff.len());
let back = decode(&tiff).unwrap().meta.exif.expect("EXIF read back");
let (_, ifd0, exif, gps) = dirs(&back);
assert_eq!(exif.iter().map(|e| e.0).collect::<Vec<_>>(), [33434], "the exposure time stays, the 6 MiB maker note goes");
assert_eq!(gps.iter().map(|e| e.0).collect::<Vec<_>>(), [1]);
assert_eq!(ifd0.iter().map(|e| e.0).collect::<Vec<_>>(), [271]);
}