The thread hijack exercise was a waste of time

A few weeks ago I wrote about hijacking threads. The principle was good, the code worked but the reason I needed it was flawed so the exercise was a failure. I assumed that it was likely to be a failure when I set out though, so it’s more a confirmation that I need to do things properly rather than hackily…

The idea was the try and outsmart the Windows program loader. My API hooking tools currently hook the target process when it gets to a point where it has started up but no ‘user’ code has run. Well, that’s not strictly true, any user code that’s invoked from the DllMain() of any DLLs loaded has been run, likewise, any code executed as part of a module’s static initialisation has also run. The point at which I hook is safe, reliable but fractionally too late for some potential scenarios.

The solution to my problem, I think, is to switch to kernel mode hooking so that I put some hooks in before I start the process and then have complete control over the process startup. That involves getting dirty with drivers though and I don’t fancy that quite yet - so I tried the hackier solution…

The idea was that I’d hijack the loader thread as it was loading dlls and (ok, ok, I can see you all rolling your eyes! I did say that I expected this plan to fail didn’t I!). Well, since my Win32 Debug API framework allows some fine grained control over the target process so I could at least try. I tried, it failed as expected. Injecting a DLL into a process after kernel32.dll has loaded but before the rest of the dlls load is possible but unreliable; things “go boom” sometimes (rarely, but it happens, ah the advantage of unit tests that you can run over and over again …).

So, it looks like I’ll have to delve into kernel level hooking after all, but not yet. I don’t actually need this functionality right now it was just a diversion for whilst I couldn’t focus on the real work at hand…