Skip to content

Commit

Permalink
patterns/zip: Improved fallback method for finding eocd (#177)
Browse files Browse the repository at this point in the history
zip pattern: Improved fallback method for finding eocd. Added test data to cover this edge case
  • Loading branch information
flawwan authored Oct 24, 2023
1 parent 6fbdcac commit a992d1b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
30 changes: 23 additions & 7 deletions patterns/zip.hexpat
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
};

Expand Down Expand Up @@ -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")]];
Binary file added tests/patterns/test_data/zip_eocd.hexpat.zip
Binary file not shown.

0 comments on commit a992d1b

Please sign in to comment.