views:

54

answers:

3

Hello,

i need to validate whether given binary is a PE file or not. e.g if I rename jS/HTML or .class files to .exe or .dll , it won't be PE files still then. Parsing PE these files would give me info about this problem. What field indicates that given binary is a valid PE file or not..?

Note : I have checked about "e_magic" field of FileHeader. It always gets populated in case of wrong PE files(i.e js/html/java/class files renamed to .dll/Exe) and does'nt says anything at all about validity of PE.

Regards Usman

+4  A: 

If such a field existed, it'd be too easy to create an invalid exe and mark it as valid on purpose.

You verify that a file is a PE file by reading the PE header and checking values for all fields (the values should belong to valid ranges, should not point outside the file etc).

GSerg
+1 There are plenty of RVA (relative virtual address) fields to check; these should all point inside the appropriate kind of section in the PE. Once you've done that, however, you still don't know if the binary is malicious.
Tim Robinson
I don't think he said anything about malicious. He just doesn't want to have someone who is using a file which is obviously not PE as a PE file.
Billy ONeal
The meaning of 'using' is important here. If the user trusts this binary, and they're going to run it right after this check, then the Windows PE loader will make the necessary validation. If the purpose of this check is to work out whether the binary is trusted then there's a lot of work to do.
Tim Robinson
+1  A: 

One way is the usage of GetBinaryType function (see http://msdn.microsoft.com/en-us/library/aa364819.aspx) or the usage of SHGetFileInfo with SHGFI_EXETYPE.

Oleg
A: 

Check the Portable Executable/Common Object File Format Specification. There are three magic values for you to check:

  • The MZ header's magic number at the beginning of the file
  • The PE header's magic number "PE\0\0" at the start of the PE header
  • Version identifier for the optional header, IIRC, it's 0x10b for PE files, and 0x20b for PE+ (x64) files.

Beyond that, you'd have to parse the entire file and look at every processor instruction to ensure it's valid, etc. Several of the files use the COFF spec internally, and you might not have an easy way to distinguish that. PE's format itself was designed with multiple machines, and many different forms of compiled code can be contained while keeping the file valid.

Billy ONeal
Thanks Billy ONeal for answering.I think just to consider PE header's PE00 byte for making up the decision about PE file validity is enough. I think MZ headers byte just tels you that file is not able to run on DOS mode and Windows required for this that's it. Is'nt?
Usman