aslr

How to enable ASLR in a Windows PE binary?


How do i enable Address Space Layout Randomization of an executable?

Note: i am not using Visual Studio, or any compiler that provides a /dynamicbase compiler option.

For the purposes of this discussion, assume i am adding functionality to a compiler to enable ASLR.

Other PE Flags

There are other Windows executable image options that i already know how to set. For example, then IMAGE_FILE_NET_RUN_FROM_SWAP flag. You set the PE option in the PE binary header:

LOADED_IMAGE li;
MapAndLoad(fileName), null, li, false, false)

LI.FileHeader.FileHeader.Characteristics |= IMAGE_FILE_NET_RUN_FROM_SWAP;

UnMapAndLoad(li)

How does one enable Address Space Layout Randomization? Is it a PE flags? Is it an Assembly Manifest entry?

Bonus

How do i opt an executable into NX (No Execute)?


Solution

  • The solution is that the option is embedded in the PE binary header. But rather than

    loadedImage.FileHeader.FileHeader.Characteristics
    

    it's in:

    loadedImage.FileHeader.OptionalHeader.DllCharacteristics
    

    Where you set the flag:

    IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE = 0x0040; //The DLL can be relocated at load time.
    

    For a helper function pseudo-code of:

    void SetPEOptFlags(String filename, UInt32 flags)
    {
       // Any code is released into the public domain. No attribution required.
       LOADED_IMAGE li;
       MapAndLoad(filename, null, li, false, false);
      
       li.FileHeader.OptionalHeader.DllCharacteristics |= flags;
       UnMapAndLoad(li);
    }
    

    and then calling

    //Optional dll characteristics
    const IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE = 0x0040; //The DLL can be relocated at load time.
    const IMAGE_DLLCHARACTERISTICS_NX_COMPAT =    0x0100; //The image is compatible with data execution prevention (DEP).
    
    
    SetPEOptFlags("C:\Foo\Contoso.exe", 
       IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE | IMAGE_DLLCHARACTERISTICS_NX_COMPAT);