Wednesday, July 12, 2017

Inline Patching: Get the Image Base of the Main Module Without Calling GetModuleHandle

When doing an inline, whether it be from a DLL or inside the main module itself, getting the image base of the main module can be tricky in some circumstances. It often involves obtaining the address of GetModuleHandle in order to pass it a NULL parameter to get the base of the main module. However, with a simple trick, you can actually read it directly from the Process Environment Block/PEB using the following ASM instructions:

x32:
MOV EAX,DWORD PTR FS:[30]
MOV EAX,DWORD PTR DS:[EAX+8]

x64:
MOV RAX,QWORD PTR GS:[60]
MOV RAX,QWORD PTR DS:[RAX+0x10]


Here, we can see the 32 bit version in action:












After executing the two instructions in this example, you can see that the image base is contained in ECX. This has saved me significant headache and code space when working on complicated inline patches.

While this technique works on every current version of windows, it is important to note that according to the Microsoft documentation on the PEB Structure, the layout of this structure may change in future versions of the operating system. However, due to its wide use in many debugging tools, I have significant doubt that Microsoft will change this structure anytime soon.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.