0
votes

I wish to parse a PE file and read the Optional Headers from it, and some other data which enables me to know if it is a 32bit PE or a 64 bit. I know that imagehlp and dbghlp header files give me structures such as IMAGE_OPTIONAL_HEADER. But I am not sure how to parse my file to yield these. I can use the documentation and write my own parser using offsets, but if anyone knows the correct API to parse the PE?

My objective : 1) determine if the file is x64 or x86 executable. Probably in Header?? 2) Check for ASLR, DEP and SAFESEH. the first two I think will be in PE Optional Headers.

So is there any API to parse my PE and return me these structures?

2

2 Answers

2
votes

You should take a look at the Image Helper Library. There is a method MapAndLoad that will give you a pointer to various parts of the PE file (LOADED_IMAGE structure), i.e. IMAGE_NT_HEADERS, IMAGE_SECTION_HEADER. The IMAGE_NT_HEADERS structure contains a pointer to an IMAGE_OPTIONAL_HEADER structure.

The field DllCharacteristic contains various flags like IMAGE_DLLCHARACTERISTICS_NX_COMPAT or IMAGE_DLLCHARACTERISTICS_NO_SEH for example.

To use these API include Imagehlp.h and link to Imagehlp.lib.

0
votes

1) determine if the file is x64 or x86 executable.

Machine field from IMAGE_FILE_HEADER

2) Check for ASLR, DEP and SAFESEH

ASLR:

  • Check DllCharacteristics from IMAGE_OPTIONAL_HEADER
  • Bitwise AND above field with IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE: if not 0 then image support ASLR.

DEP:

  • Check DllCharacteristics from IMAGE_OPTIONAL_HEADER
  • Bitwise AND above field with IMAGE_DLLCHARACTERISTICS_NX_COMPAT: if not 0 then image support ASLR.

SAFESEH:

  • Note that SAFESEH is only available for 32-bit PE.
  • Go to DataDirectory field of IMAGE_OPTIONAL_HEADER (array of IMAGE_DATA_DIRECTORY)
  • Get RVA from IMAGE_OPTIONAL_HEADER.DataDirectory[IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].VirtualAddress
  • This leads to an IMAGE_LOAD_CONFIG_DIRECTORY structure.
  • If SEHandlerTable field is not 0, then the image supports SAFESEH.