Shield from thread injection
Originally posted on rootkit.com
This method was discovered when I was doing some random debugging. Sudden idea came to my mind when I inject some DLL into olly-debugged process. Olly log traced that one thread was created and terminated. Then I thought since the DLL loading takes place in user-mode, why cant I prevent it from loading by hooking some function ?
So I put a bp on kernel32.LoadLibraryA() and inject DLL again. ollydbg halted. I traced the stack frame to one function in kernel32.dll. I inject some DLL again, and yet I traced to the same function.
My sense tell me that is the function I’m looking for. So I began coding and hook that function. Voila, now Winject reports DLL-injection failed. But wait, our job is not done yet.
After more debugging I found that my hook was preventing the our own thread from creating too. So I need a method to distinguish rogue thread from our own thread.
Finally, I found a method used by Piotr Bania to prevent shellcode execution. He used VirtualProtect() to determine whether a code is rouge or not. Usually shellcode is injected as a result of stack-overflow or any other memory-based leak. These memory should be writable. If any pointer is pointing to a writable memory section, we can conclude that it is altered by the shellcode.
Yet, this method has a flaw. Most packer and protector modifies PE and mark the image as writable (to decompress or decrypt the content) and doesn’t bother to restore them. It would raise false alarm when we use VirtualProtect() to check the protection. So I thought of a better solution.
I used VirtualQuery() to check for memory type. Usually when we create a thread, it should point to code within the image. (marked by loader as MEM_IMAGE) Any VirtualAllocEx() allocated memory would not have that flag set.
Coming soon – Stopping SetWindowsHookEx() injection. 😉