h1

Shield from thread injection

April 17, 2007

Originally posted on rootkit.com
http://www.rootkit.com/blog.php?newsid=640

——————————————————————————————

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.

——————————————————————————————

Trypanophobia
http://code.google.com/p/opcode0×90/source/browse/trunk/snippets/Trypanophobia/

——————————————————————————————

Coming soon – Stopping SetWindowsHookEx() injection. ;)

One comment

  1. Hey op,

    this is just wonderful piece of code and article.

    however, this only works in xp .. I tried many times to look it up in vista, but obviously they got rid of that function or they changed the way it looks .. not sure.

    I tried to search for the same asm pattern and all I got is nothing.

    Hopefully, we find out a way in vista to block the calls.

    regards,
    -Andrew-



Leave a Comment