A simple Windows code Injection example written in C#
Some months ago I've written a brief post about code injection on Windows using python.
Some readers asked me if the code proposed in the post (which calls standard windows API) is portable on other languages.
Well, obviously yes!
Today I share a porting of that code in C#.
As in the previous article, I use the CreateRemoteThread function in order to inject a simple shellcode generated using the “windows/messagebox” payload of Metasploit payload generator.
Here the code (with a brief explanation below):
Lines 43 – 52: read process name from command line parameter and get the process handle using OpenProcess function.
We’re specifically asking for all possible process rights (using the paramether 0x1F0FFF).
Lines 55 - 81: The shellcode string.
Lines 84 - 88: some code to covert the shellcode string into byte array
Line 91: calls VirtualAllocEx, in order to allocate a memory area in target process.
It requires a handle to the process that will have memory allocated (obtained from the OpenProcess call), the size that should be allocated (shellcode length), the type of memory allocation that should be performed (0x00001000), and the memory protection that should be placed on the allocated memory range (read, write, execute, 0x40).
Line 95: calls WriteProcessMemory which writes the shellcode to the memory area within the target process.
Line 98: This line calls CreateRemoteThread, which will create a thread within the target process.
And here an injection test on notepad process: