Introduction

Portable Executables (PE) is the file format for executables on Windows.

Eg- .exe, .dll, .sys & .scr (screen saver file).

PE Structure

Every header shown in the following figure is defined as a data structure that holds information about the PE File.

PE_Structure.png

DOS Header (IMAGE_DOS_HEADER)

The first header of a PE File is always prefixed with 2 byes - 0x4D & 0x5A, commonly referred to as MZ. These bytes represent the DOS header signature, which is used to confirm that the file parsed or inspected is a valid PE File.

typedef struct _IMAGE_DOS_HEADER {      // DOS .EXE header
    WORD   e_magic;                     // Magic number
    WORD   e_cblp;                      // Bytes on last page of file
    WORD   e_cp;                        // Pages in file
    WORD   e_crlc;                      // Relocations
    WORD   e_cparhdr;                   // Size of header in paragraphs
    WORD   e_minalloc;                  // Minimum extra paragraphs needed
    WORD   e_maxalloc;                  // Maximum extra paragraphs needed
    WORD   e_ss;                        // Initial (relative) SS value
    WORD   e_sp;                        // Initial SP value
    WORD   e_csum;                      // Checksum
    WORD   e_ip;                        // Initial IP value
    WORD   e_cs;                        // Initial (relative) CS value
    WORD   e_lfarlc;                    // File address of relocation table
    WORD   e_ovno;                      // Overlay number
    WORD   e_res[4];                    // Reserved words
    WORD   e_oemid;                     // OEM identifier (for e_oeminfo)
    WORD   e_oeminfo;                   // OEM information; e_oemid specific
    WORD   e_res2[10];                  // Reserved words
    LONG   e_lfanew;                    // Offset to the NT header
  } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;

Important Ones -

  1. e_magic → 2 bytes fixed value - 0x5A4D or MZ.
  2. e_lfanew → 4 byte holds offset to start of NT_Header. Always at a fixec offset 0x3C.

DOS Stub

"This program cannot be run in DOS mode"

NT Header (IMAGE_NT_HEADER)

NT Header incorporates 2 other image headers: FileHeader & OptionalHeader, which includes a large amount of information about the PE File.

Similar to the DOS Header the NT Header also contains a signature member that is used to verify it. The signature element is equal to “PE” string 0x50 & 0x45 bytes.

As the signature member is DWORD, it will be represented as 0x50450000.

// 32-bit Version
typedef struct _IMAGE_NT_HEADERS {
  DWORD                   Signature;
  IMAGE_FILE_HEADER       FileHeader;
  IMAGE_OPTIONAL_HEADER32 OptionalHeader;
} IMAGE_NT_HEADERS32, *PIMAGE_NT_HEADERS32;