hasherezade / pe-bear

Portable Executable reversing tool with a friendly GUI
https://hshrzd.wordpress.com/pe-bear/
GNU General Public License v2.0
2.77k stars 171 forks source link

Error in Checksum calculation #30

Closed hasherezade closed 1 year ago

hasherezade commented 1 year ago

reported by Matthew (x86matthew):

The issue relates to the checksum field within the NT Optional Header. I have recently been generating some custom binaries and noticed that PE-Bear was reporting the checksum being incorrect (highlighted in red). Microsoft's MapFileAndCheckSum function confirmed that my original checksum was correct, so I did some investigating.

My results showed that PE-Bear was validating the checksum incorrectly when the total file size was not a multiple of 2. I have uploaded a simple set of minimal PE files to reproduce the issue at the following URL:

http://www.x86matthew.com/other/PeBearChecksum.zip

Checksum_0_Byte_Overlay.exe -> Basic PE file with 1024 total bytes, PE-Bear validates checksum correctly (0xAB91)

Checksum_1_Byte_Overlay.exe -> Basic PE file with 1025 total bytes, PE-Bear says checksum is invalid despite being correct (correct checksum: 0xAC0A)

Checksum_2_Byte_Overlay.exe -> Basic PE file with 1026 total bytes, PE-Bear validates checksum correctly (0x240C)

I believe the problem originates within the following function:

https://github.com/hasherezade/bearparser/blob/c059bcb25c6e9137cd1a4f1a97ae53f1a0a250b8/parser/pe/PEFile.cpp#L50

The code appears to be dividing the file size by 2 and discarding the additional byte if it exists. Of course, PE file sizes are usually multiples of 2 already so this will rarely be an issue in the real world.

hasherezade commented 1 year ago

After the patch, the valid checksum is calculated:

checks2

checks1

The test build including the patch is available to download from AppVeyor build server