diff --git a/crates/xfl/src/lib.rs b/crates/xfl/src/lib.rs
index fbcb3ecc2..7283b56a0 100644
--- a/crates/xfl/src/lib.rs
+++ b/crates/xfl/src/lib.rs
@@ -318,6 +318,19 @@ fn find_end(data: &[u8]) -> Result<(u64, u64, u64, usize), ZipError> {
let Some((_, shift)) = locate_directory(data, count.into(), size.into(), offset.into(), candidate)
.filter(|&(dir, _)| directory_is_exact(data, dir, size.into(), count.into(), &mut directory_jumps))
else {
+ // An overstated size is safe to ignore only when the recorded entries fill
+ // the byte range from the declared offset to this single-disk end record.
+ // The classic entry count is below MAX_ENTRIES, so the walk checks every entry.
+ if count != 0
+ && u32_at(data, candidate + 4) == Some(0)
+ && u16_at(data, candidate + 8) == Some(count)
+ && let Ok(start) = usize::try_from(offset)
+ && let Some(measured) = candidate.checked_sub(start).and_then(|n| u32::try_from(n).ok())
+ && measured < size
+ && directory_is_exact(data, start, measured.into(), count.into(), &mut directory_jumps)
+ {
+ return Ok((count.into(), measured.into(), offset.into(), candidate));
+ }
continue;
};
if count == 0 && shift > 0 {
diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs
index 5ae0713ba..5611a92ca 100644
--- a/crates/xfl/src/tests.rs
+++ b/crates/xfl/src/tests.rs
@@ -108,6 +108,23 @@ fn damaged_archives_are_errors() {
assert!(Archive::open(&z).is_err());
}
+#[test]
+fn reads_a_directory_with_an_overstated_size() {
+ let mut z = zip(&[("DOMDocument.xml", b"", true), ("LIBRARY/ball.xml", b"", false)]);
+ let end = z.len() - 22;
+ let size = u32_at(&z, end + 12).unwrap();
+ z[end + 12..end + 16].copy_from_slice(&(size + 13).to_le_bytes());
+
+ let archive = Archive::open(&z).unwrap();
+ assert_eq!(archive.counts().0, 2);
+ assert_eq!(archive.read("DOMDocument.xml").unwrap().unwrap(), b"");
+ assert_eq!(archive.read("LIBRARY/ball.xml").unwrap().unwrap(), b"");
+
+ // Keep the overstated end record but remove the last byte of the final entry's name.
+ z.remove(end - 1);
+ assert_eq!(Archive::open(&z).err(), Some(ZipError::Damaged("the central directory is outside the archive")));
+}
+
#[test]
fn a_truncated_central_directory_is_damaged() {
let z = zip(&[("DOMDocument.xml", b"", true), ("b.xml", b"", true), ("c.xml", b"", false)]);