erocarrera / pefile

pefile is a Python module to read and work with PE (Portable Executable) files
MIT License
1.86k stars 519 forks source link

Invalid offset assignment at get_data function during PE loading #389

Open Casperinous opened 9 months ago

Casperinous commented 9 months ago

Hello, Some context: I am using malduck (which internally is using pefile, latest release available) to write an extractor for SystemBC (file https://www.virustotal.com/gui/file/21bafa3f55e54a069b3d52385cc67945d671f8587c92d51fd4eba8a7eb2d4485) The aforementioned file / memory dump, when loaded in pefile it get stuck in a the while loop located at function get_string_u_at_rva (at line 6360). While debugging it, I figured out that the issue resides in get_data function (at line 1188) and specifically on this check:

if self.PointerToRawData is not None and self.SizeOfRawData is not None:
    if end > self.PointerToRawData + self.SizeOfRawData:
        end = self.PointerToRawData + self.SizeOfRawData

The second if check results in true, which assigns in the end variable an integer smaller than the one in the offset variable, resulting in returning data with bigger length than the one requested (in this case, it was requested a data with length 2 but it is returning a buffer with length 5570 bytes )

return self.pe.__data__[offset:end]

If this is a valid bug, I can make a PR in which I would suggest to add an if check to be sure than end > start, else return an empty buffer, unless you have something else to propose.