From a992d1ba92f7ea9c87cf296e122e0ef7f1aad5b0 Mon Sep 17 00:00:00 2001 From: Hugo Date: Tue, 24 Oct 2023 07:35:02 +0200 Subject: [PATCH] patterns/zip: Improved fallback method for finding eocd (#177) zip pattern: Improved fallback method for finding eocd. Added test data to cover this edge case --- patterns/zip.hexpat | 30 ++++++++++++++----- tests/patterns/test_data/zip_eocd.hexpat.zip | Bin 0 -> 274 bytes 2 files changed, 23 insertions(+), 7 deletions(-) create mode 100644 tests/patterns/test_data/zip_eocd.hexpat.zip diff --git a/patterns/zip.hexpat b/patterns/zip.hexpat index c2dd8bf..0a4e836 100644 --- a/patterns/zip.hexpat +++ b/patterns/zip.hexpat @@ -25,12 +25,28 @@ fn find_eocd() { return std::mem::size()-22; } else { // If it's not there, then there's probably a zip comment; - // search the last 64KB of the file for the signature. - // This is not entirely reliable, since the signature could - // randomly appear in compressed data before the actual EOCD, - // but it should be good enough... - u128 last64k = std::math::max(0, std::mem::size()-65536-22); - return std::mem::find_sequence_in_range(0, last64k, std::mem::size(), 0x50,0x4B,0x05,0x06); + // search the last 64KB of the file for the signature. + u128 offset_search_from = std::math::max(0, std::mem::size()-65536-22); + u128 prev_address; + while(1){ + u128 current_address = std::mem::find_sequence_in_range(0, offset_search_from, std::mem::size(), 0x50,0x4B,0x05,0x06); + + //Reached EOF and did not find valid eocd. + if (current_address == 340282366920938463463374607431768211455){ + std::error("Could not find EOCD."); + } + + //Potential eocd found. Create a eocd struct + EndOfCentralDirectory EOCD @ current_address; + + //If central directory file header is valid, then we know the eocd offset is valid. + if (std::mem::read_unsigned(EOCD.CDOffset, 4, std::mem::Endian::Little) == 0x2014B50){ + return current_address; + } + + offset_search_from = current_address + 1; + prev_address = current_address; + } } }; @@ -112,4 +128,4 @@ struct CentralDirectoryFileHeader { char comment[fileCommentLength]; }; -CentralDirectoryFileHeader centralDirHeaders[fileInfo.CDRCount] @ (fileInfo.CDOffset) [[name("Files")]]; +CentralDirectoryFileHeader centralDirHeaders[fileInfo.CDRCount] @ (fileInfo.CDOffset) [[name("Files")]]; \ No newline at end of file diff --git a/tests/patterns/test_data/zip_eocd.hexpat.zip b/tests/patterns/test_data/zip_eocd.hexpat.zip new file mode 100644 index 0000000000000000000000000000000000000000..836556a2b7b657c001e05d23e92f3402719cec6a GIT binary patch literal 274 zcmWIWW@h1H0D)&rVc{`(_n4f4Y!K!J;*8XsobvploD{v1iV{Zz2=HcQbHV~Z;?6h# zNG`yek;$F`mwhS>>_9si7!<%Hn(bUrVMYcChN%-C>*TWBVyung(*x0`8x5yq0cq#_ e+}zZ>5|B+GBN%}&4M^t!u?E8`ya1#Jq5uGqwMypz literal 0 HcmV?d00001