Monday, July 18, 2016

injecting code in windows threads


Last week there was a need to inject profile markers into 3rd party dll threads.

Solved this task like that:





SuspendThread(threadHandle);

QueueUserAPC(threadHandle, WakeAPCFunc);

GetThreadContext(threadHandle, &context);
context.rip = &YourProc;
context.rsp -= 4096;
context.rsp = ~127;
ResumeThread(threadHandle);

void YourProc(void) {
if (!wasAlerted)
  SleepEx(INFINITE, TRUE);
executed = True;
while (true) {}
}

WakeAPCFunc() 
wasAlerted = true;
}



The reason I used APC - more safe context (there were random crashes if you put it in YourProc).
Also I didn't very much needed to interrupt thread immediately (you simply can't do it from user mode, if it is not in alertable wait). You must on your system know what your injecting code looks like in assembler. I know what SleepEx looks like (on my system it almost a stub to syscall 0x25).

No comments:

Post a Comment