Skip to content

Commit ff6eb65

Browse files
authored
Merge pull request #609 from emmertex/upr/never-crash-r3
Never crash: upstream #3002/#3007/#3008/#3011 remainders
2 parents be53dd1 + 411a089 commit ff6eb65

5 files changed

Lines changed: 95 additions & 19 deletions

File tree

‎crates/codecs/tests/it/fuzz.rs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,22 @@ fn thumbnail_respects_configured_source_pixel_limit() {
291291
assert_eq!(decode_thumbnail_with(&bytes, &opts).unwrap().image.width, 1);
292292
}
293293

294+
/// A header claiming zero width or height is an error, never a decoded image with no pixels
295+
/// (downstream filters index into it).
296+
#[test]
297+
fn zero_size_headers_are_refused() {
298+
let jpeg = seeds()[0].clone();
299+
let sof = jpeg.windows(2).position(|m| m == [0xFF, 0xC0]).unwrap();
300+
for at in [sof + 5, sof + 7] {
301+
let mut j = jpeg.clone();
302+
j[at..at + 2].copy_from_slice(&[0, 0]);
303+
assert!(decode_unguarded(&j, Format::Jpeg, &small_opts()).is_err());
304+
}
305+
let mut png = seeds()[1].clone();
306+
png[16..20].copy_from_slice(&[0; 4]);
307+
assert!(decode_unguarded(&png, Format::Png, &small_opts()).is_err());
308+
}
309+
294310
fn seeds() -> &'static Vec<Vec<u8>> {
295311
static S: OnceLock<Vec<Vec<u8>>> = OnceLock::new();
296312
S.get_or_init(|| {

‎crates/meta/src/xmp.rs‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -264,8 +264,17 @@ pub(crate) fn unescape_attr(s: &str) -> String {
264264
while let Some(i) = rest.find('&') {
265265
out.push_str(&rest[..i]);
266266
rest = &rest[i..];
267-
// the longest reference is `&#x10FFFF;`: search a short window, not the rest of the value per `&`
268-
let end = rest.as_bytes().iter().take(12).position(|&b| b == b';');
267+
// the longest reference is `&#x10FFFF;` plus leading zeros: skip the zeros (each byte once, since a
268+
// miss resumes after the `&`), then search a short window, not the rest of the value per `&`
269+
let b = rest.as_bytes();
270+
let digits = match (b.get(1), b.get(2)) {
271+
(Some(b'#'), Some(b'x' | b'X')) => 3,
272+
(Some(b'#'), _) => 2,
273+
_ => 1,
274+
};
275+
let zeros = b.iter().skip(digits).take_while(|&&c| c == b'0').count();
276+
let skip = digits.saturating_add(zeros.saturating_sub(1));
277+
let end = b.iter().skip(skip).take(12).position(|&c| c == b';').map(|j| j.saturating_add(skip));
269278
match end.and_then(|j| entity(&rest[1..j]).map(|c| (c, j))) {
270279
Some((c, j)) => {
271280
out.push(c);
@@ -998,6 +1007,10 @@ mod tests {
9981007
assert_eq!(unescape_attr(&many), many);
9991008
// multi-byte text around a reference is never cut inside a character
10001009
assert_eq!(unescape_attr("é&amp;日&é;"), "é&日&é;");
1010+
// leading zeros are valid in numeric references, however many there are
1011+
assert_eq!(unescape_attr("&#00000000000000000065;&#x000000000000000042;"), "AB");
1012+
let zeros = format!("&#{};", "0".repeat(1 << 20));
1013+
assert_eq!(unescape_attr(&zeros), zeros);
10011014
}
10021015

10031016
fn full() -> Metadata {

‎crates/raster/src/lib.rs‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,9 @@ impl std::fmt::Display for AllocError {
6565

6666
impl std::error::Error for AllocError {}
6767

68-
/// The largest single image buffer [`Image::try_new`] allocates (64 GiB).
69-
pub const MAX_IMAGE_BYTES: usize = 64 << 30;
68+
/// The largest single image buffer [`Image::try_new`] allocates (64 GiB, or `isize::MAX` bytes on
69+
/// 32-bit targets such as wasm32, where 64 GiB doesn't fit in `usize`).
70+
pub const MAX_IMAGE_BYTES: usize = if usize::BITS >= 64 { 1 << 36 } else { isize::MAX as usize };
7071

7172
/// A vector of `n` copies of `v`, or an error when it can't be had (overflow, past [`MAX_IMAGE_BYTES`],
7273
/// allocator failure) instead of an abort. `width`/`height` only label the error.
@@ -225,7 +226,7 @@ impl<T: Copy + Default> Image<T> {
225226
} else {
226227
for (x, (o, s)) in row.iter_mut().zip(a).enumerate() {
227228
let t = if x < other.width && y < other.height {
228-
other.data.get(y * other.width + x).copied().unwrap_or_default()
229+
y.checked_mul(other.width).and_then(|i| i.checked_add(x)).and_then(|i| other.data.get(i)).copied().unwrap_or_default()
229230
} else {
230231
U::default()
231232
};
@@ -406,6 +407,12 @@ mod tests {
406407
assert_eq!((c.width, c.height), (4, 3));
407408
assert_eq!(c.get(1, 1), 3.0);
408409
assert_eq!(c.get(3, 2), 1.0);
410+
// a hostile `other` whose width times row overflows reads defaults instead of panicking
411+
let wide = Plane { width: usize::MAX, height: 3, data: vec![5.0; 2] };
412+
let narrow = Plane::filled(1, 3, 1.0);
413+
let d = narrow.zip_map(&wide, |x, y| x + y);
414+
assert_eq!(d.get(0, 0), 6.0);
415+
assert_eq!(d.get(0, 2), 1.0);
409416
let same = a.zip_map(&a, |x, y| x + y);
410417
assert!(same.data.iter().all(|&v| v == 2.0));
411418
}

‎crates/raw/src/vendor/cr2.rs‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -260,13 +260,15 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
260260
let widths: Vec<usize> = match &slices {
261261
Some(s) => {
262262
let n = s[0].min(64) as usize;
263-
let mut v = vec![s[1] as usize; n];
264-
v.push(s[2] as usize);
263+
// `as usize` would truncate a 64-bit width on 32-bit targets (wasm32, x86) and hide the overflow
264+
let width = |w: u64| usize::try_from(w).map_err(|_| RawError::Corrupt("CR2 slice widths overflow".into()));
265+
let mut v = vec![width(s[1])?; n];
266+
v.push(width(s[2])?);
265267
v
266268
}
267269
None => {
268270
let w = (fw as u64).checked_mul(nc as u64).ok_or_else(|| RawError::Corrupt("bad CR2 frame size".into()))?;
269-
vec![w as usize]
271+
vec![usize::try_from(w).map_err(|_| RawError::Corrupt("bad CR2 frame size".into()))?]
270272
}
271273
};
272274
// slice widths come from the file: a sum that overflows is a corrupt file, not a wrapped width

‎crates/tiff/src/reader.rs‎

Lines changed: 49 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -217,17 +217,28 @@ struct Ctx<'a> {
217217
ancestors: Vec<u64>,
218218
/// IFDs produced so far, counting every copy of a shared one (bounded by `max_ifds`).
219219
visits: usize,
220-
/// IFDs already parsed, by (offset, base): a second pointer to one (two `SubIFDs` entries, or an Exif pointer
221-
/// shared by two directories) gets a copy instead of being dropped.
222-
parsed: HashMap<(u64, u64), (Ifd, u64)>,
220+
/// IFDs already parsed, by (offset, base, depth): a second pointer to one (two `SubIFDs` entries, or an Exif
221+
/// pointer shared by two directories) gets a copy instead of being dropped. Keyed by depth too, so a copy has
222+
/// exactly the children a fresh parse at that depth would have; a copy is charged the IFDs, entries and value
223+
/// bytes of the first parse, so copies stay inside every limit.
224+
parsed: HashMap<(u64, u64, usize), Parsed>,
223225
budget: u64,
224226
entries_total: usize,
225227
}
226228

227-
/// The number of IFDs in `ifd`'s tree, itself included.
228-
fn tree_size(ifd: &Ifd) -> usize {
229-
let boxed = [&ifd.exif, &ifd.gps, &ifd.interop].into_iter().flatten().map(|b| tree_size(b));
230-
ifd.sub_ifds.iter().map(tree_size).chain(boxed).fold(1usize, usize::saturating_add)
229+
/// What parsing one IFD and its children used up: a copy of it is charged the same.
230+
#[derive(Clone, Copy)]
231+
struct Cost {
232+
ifds: usize,
233+
entries: usize,
234+
bytes: u64,
235+
}
236+
237+
/// An IFD parsed once, kept for later pointers to it.
238+
struct Parsed {
239+
ifd: Ifd,
240+
next: u64,
241+
cost: Cost,
231242
}
232243

233244
impl<'a> Ctx<'a> {
@@ -248,23 +259,40 @@ impl<'a> Ctx<'a> {
248259
if self.ancestors.contains(&offset) {
249260
return Err(TiffError::Invalid(format!("IFD loop at {offset}")));
250261
}
251-
if let Some((ifd, next)) = self.parsed.get(&(offset, base)) {
252-
let visits = self.visits.saturating_add(tree_size(ifd));
262+
let key = (offset, base, depth);
263+
if let Some(c) = self.parsed.get(&key) {
264+
// a copy costs what the first parse did: its IFDs, entries and value bytes
265+
let visits = self.visits.saturating_add(c.cost.ifds);
253266
if visits > self.opts.max_ifds {
254267
return Err(TiffError::Limit("IFD count"));
255268
}
269+
let entries = self.entries_total.saturating_add(c.cost.entries);
270+
if entries > self.opts.max_entries_total {
271+
return Err(TiffError::Limit("entry count"));
272+
}
273+
if c.cost.bytes > self.budget {
274+
return Err(TiffError::Limit("value bytes"));
275+
}
256276
self.visits = visits;
257-
return Ok((ifd.clone(), *next));
277+
self.entries_total = entries;
278+
self.budget = self.budget.saturating_sub(c.cost.bytes);
279+
return Ok((c.ifd.clone(), c.next));
258280
}
259281
if self.visits >= self.opts.max_ifds {
260282
return Err(TiffError::Limit("IFD count"));
261283
}
284+
let (visits0, entries0, budget0) = (self.visits, self.entries_total, self.budget);
262285
self.visits = self.visits.saturating_add(1);
263286
self.ancestors.push(offset);
264287
let r = self.parse_dir(offset, base, depth);
265288
self.ancestors.pop();
266289
let (ifd, next) = r?;
267-
self.parsed.insert((offset, base), (ifd.clone(), next));
290+
let cost = Cost {
291+
ifds: self.visits.saturating_sub(visits0),
292+
entries: self.entries_total.saturating_sub(entries0),
293+
bytes: budget0.saturating_sub(self.budget),
294+
};
295+
self.parsed.insert(key, Parsed { ifd: ifd.clone(), next, cost });
268296
Ok((ifd, next))
269297
}
270298

@@ -480,6 +508,16 @@ mod tests {
480508
assert!(t.ifds[0].exif.is_none());
481509
}
482510

511+
/// Hostile input: many pointers to one shared IFD must not clone past the entry limit (each child has one
512+
/// entry, so three copies need three entries plus the root's two).
513+
#[test]
514+
fn shared_children_count_against_the_entry_limit() {
515+
let opts = ParseOptions { max_entries_total: 4, ..Default::default() };
516+
let t = Tiff::parse_with(&shared_children(38, 38, 38, 0), &opts).unwrap();
517+
assert_eq!(t.ifds[0].sub_ifds.len(), 2);
518+
assert!(t.ifds[0].exif.is_none(), "the third copy would pass the entry limit");
519+
}
520+
483521
#[test]
484522
fn ascii_keeps_every_nul_separated_string() {
485523
let v = decode(ByteOrder::Little, FieldType::Ascii, b"one\0two\0\0");

0 commit comments

Comments
 (0)