When we inject a piece of code into newly created suspended .Net process using CreateRemoteThread() technique, we will face a crash issue. The reason behind is, the .net framework will try to control the first running thread in the process and load the .net framework in order to run the .net process. We will see some surprise crashes when .net process took control of our injected thread. This is clearly explained in this thread.
ChristophHusse wrote Mar 6, 2009 at 8:48 AM
The problem is that NET seems to “adapt” the first running thread in a process. So if we start a suspended process, all things go as usual. But the moment when the remote thread is created, instead of executing the target invokation stub, NET seems to hijack this thread for its own purposes. Very funning thing ;-). I will now try to compensate this with another thread.
ChristophHusse wrote Mar 7, 2009 at 11:36 AM
It wasn’t that easy but after some debugging I found out that NET is hijacking
the first active thread in a process. And since CreateAndInject() is meant to
execute EasyHook in first place, NET hijacks the thread intended to run EasyHook.
So EasyHook is never executed and the host waits until the target terminates.
Then I tried to start another thread but the same problem occurred. It does not
matter how many suspended threads you create and which one you start, the first
active thread will always run the process instead of EasyHook!
The solution to solve this is, use usermode APC. You can queue an usermode APC using QueueUserAPC(). In this way, your code will execute before the control is passed to the “takeover” code.