Sunday, September 29, 2013

Inline API Hooking using DLL Injection

In this post I'm going to share one simple example of user more inline API hooking technique using DLL injection. This type of API hooking techniques are widely used for many good and evil purposes. Many user mode or Kernel mode malwares use this inline hooking technique to do bad many bad stuffs.

Please remember this information is for Educational Purpose only and should not be used for malicious purpose.I will not assume any liability or responsibility to any person or entity with respect to loss or damages incurred from information contained in this article.

Inline hooking is implemented by overwriting first bytes codes of any API in order to redirect code execution flow. This type of technique can also be implemented in Kernel land.

So when an inline hook is implemented first instruction of target API is overwritten with a JMP instruction. One example is given below where User32!MessageBoxW is hooked.


First I will write a Hooking dll, and when the dll is injected into any remote process it will hook the function MessageBoxW using inline hooking technique. 

int WINAPI MessageBox(
  _In_opt_  HWND hWnd,
  _In_opt_  LPCTSTR lpText,
  _In_opt_  LPCTSTR lpCaption,
  _In_      UINT uType
);

And it will simply modify the 3rd argument (MessageBox Title ) of the MessageBox API with an another text message (MessageBox Owned!). 

The DLL code is given below:


Run time Analysis:

So now lets attach the hooked process with Immunity Debugger and see how this code works. In this case we know that Notepad.exe uses User32!MessageBoxW API to show alert messages when you try to find any word in any text file. So we will inject the compiled DLL into Notepad process.

First we get the PID of Notepad.EXE from Process Hacker Tool.


Then we inject the hooking DLL into Notepad.EXE process. And when we trigger the MessageBoxW call, we can see the Title of the Alert box is overwritten with the text "MessageBox Owned!".


This is the normal stack structure when MessageBoxW is called.


In below screenshot we can see, when the dll is injected, first instruction of MessageBoxW is overwritten with a JMP instruction and the JMP points to somewhere inside the injected dll (inline.dll)


Below screenshot shows the evil code, inside inline.dll file.


And W00t!!


Detection of Inline Hooking:

There are many free rootkit detection available on the internet.Almost all of them can detect this type of inline hooks(Both user mode and Kernel mode).

Reference:

https://www.htbridge.com/publication/inline_hooking_in_windows.pdf