Hooking outside of DLLMain

Jun 26, 2014 at 8:24 PM
Edited Jun 26, 2014 at 8:26 PM
I'm wondering if I can hook a function from outside of DLL main. For an example, let's say I've hooked PeekMessage and replaced it with myPeekMessage. From my master hooking application I send a message to the injected slave application and myPeekMessage picks it up and calls LhInstallHook on MessageBox to replace it with myMessageBox.

The issue that I run into is that the fourth parameter of LhInstallHook, the TRACED_HOOK_HANDLE, is now an invalid parameter and LhInstallHook returns C00000F2. The TRACED_HOOK_HANDLE is a global variable which I've created like so:
That part is standard and works for PeekMessage and it also works for MessageBox when it's hooked from DLLMain or any function called from DLLMain. What I tried to do after finding that it doesn't work was make THH a local variable and initialize it in the function. In this case LhInstallHook does not fail anymore but MessageBox is not hooked.

I'm trying to do it this way so I can hook on demand by passing a message and inject only one dll into my remote process. Is this it better to inject multiple times with different dlls? Is my technique flawed? Is there a way to make it work?

I welcome any input on this.
Jun 27, 2014 at 9:05 AM
I would steer clear of hooking from within the myPeekMessage. Doing anything involving threads from within your handlers can be quite dangerous if you are not careful.

Instead set a flag or some other piece of information that will be checked from within another thread that periodically checks for hooking tasks.

Other than that I don't see why it won't work.
Marked as answer by a1saws on 6/27/2014 at 5:42 AM