Windows PE executable file CRC calculation issue
Let me explain what I'm trying to accomplish. I want to know from inside my Windows executable file if it was tampered with after i开发者_运维知识库t was built. For that I decided to calculate the CRC value on its own file from within and compare it with a predefined value. But what I'm encountering is that once the executable is built the CRC remains the same, but only until I re-build it again (without any changes done to the source code). That's when the CRC changes. What is the magic here? Does the compiler add some arbitrary bytes to the exe file?
PS. I'm using Microsoft Visual Studio C++ 2008 and run my tests on Windows 7 Ultimate.
It could be some timestamp or version number automatically embedded by the compiler/linker...
To account for that I suggest something different (based on the fact that these are native EXE/DLLs):
Just postprocess the generated file - don't assume anything about CRC32 of the resulting file before it is generated...
Windows has a really "nice" feature when loading an EXE/DLL: it just ignores anything at the end of the file that doesn't belong there.
You can use this to your advantage: append a block of bytes (for example 256 bytes) to the file. This block can contain whatever you like (hash of your file, length of your file etc.) and can be even encrypted... when you want to check you calculate the information needed (like your CRC...) and compare it to that block of your file...
To make it harder you can include different hashes and choose randomly which one you check... you can even sprinkle some random bytes into that block... Also put in a check that makes sure there is only one such block present... so you can abort or whatever you want if there is no such block, more than one such block or your check and the saved information from that block does not match.
Have you considered using a digital signature? The signature can be applied after compilation, and allows you to verify that the EXE has not been edited. This a perfect case for one.
You can use "SignTool.EXE" to sign your EXE.
To verify you can use the code found at:
Verify whether an executable is signed or not (signtool used to sign that exe)
I believe you would have to purchase a Code Signing Certificate (if you want it fully validated). I think GoDaddy provides the least expensive ones (right now). I have also heard that if you have an open source project, you may be able to obtain a free signing Cert. from some authorities.
精彩评论