Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Ignore EOCD signatures inside ZIP comments (#660)

Max Mittelstädte1d962163b29
diff --git a/crates/formats/src/zip.rs b/crates/formats/src/zip.rs
index 33670d08..b57500e3 100644
--- a/crates/formats/src/zip.rs
+++ b/crates/formats/src/zip.rs
@@ -222,12 +222,19 @@ fn find_eocd(data: &[u8]) -> Option<usize> {
let tail = data.get(from..)?;
// Search backwards so a stray signature in the comment can't shadow the real record.
let mut i = tail.len().checked_sub(22)?;
+ let mut found = None;
+ let mut last_signature = None;
loop {
if tail.get(i..i + 4) == Some(b"PK\x05\x06") {
- return Some(from + i);
+ last_signature.get_or_insert(from + i);
+ if let Some(comment_len) = tail.get(i + 20..i + 22).and_then(|bytes| <[u8; 2]>::try_from(bytes).ok()).map(u16::from_le_bytes)
+ && i + 22 + usize::from(comment_len) == tail.len()
+ {
+ found = Some(from + i);
+ }
}
if i == 0 {
- return None;
+ return found.or(last_signature);
}
i -= 1;
}
@@ -373,6 +380,25 @@ mod tests {
assert_eq!(parse(&zip, 10).unwrap().entries[0].name, "dir/file.txt");
}
+ #[test]
+ fn valid_entry_survives_eocd_signature_in_comment() {
+ let mut zip = build(&[("a.txt", b"hello")]);
+ let comment = b"PK\x05\x06\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
+ let eocd = zip.len() - 22;
+ zip[eocd + 20..eocd + 22].copy_from_slice(&(comment.len() as u16).to_le_bytes());
+ zip.extend_from_slice(comment);
+
+ assert_eq!(parse(&zip, 10).unwrap().entries.len(), 1);
+ }
+
+ #[test]
+ fn valid_entry_survives_bytes_after_eocd_comment() {
+ let mut zip = build(&[("a.txt", b"hello")]);
+ zip.extend_from_slice(b"tail");
+
+ assert_eq!(parse(&zip, 10).unwrap().entries.len(), 1);
+ }
+
#[test]
fn lists_and_reads_stored_entries() {
let z = build(&[("a.txt", b"hello"), ("dir/b.js", b"console.log(1)")]);