Inject shellcode without knowing the bytes

GH_Rake

New member
I answered an interesting StackOverflow question recently and thought it was kinda neat so I thought I'd share it.

Basically the user wants to write asm to a process without knowing the bytes. Typically you copy the bytes and put it into a BYTE buffer[], but this is a neat alternative/

You can write your assembly inside of a __declspec(naked) function and use WriteProcessMemory to write data into the external process, using the inline assembly function as the source. This is nice if you just need to inject some shell code real fast and don't want to convert it by hand or using a disassembler.

Here is an example that Writes from the assembly into a local buffer:
Code:
__declspec(naked) int assembly()
{
__asm
{
push eax; // \x50
mov eax, 1; // \xB8 \x01\x00\x00\x00
pop eax; // \x58
}
}
int main()
{
unsigned char buffer[7] = { 0 };
HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, NULL, GetCurrentProcessId());
WriteProcessMemory(hProc, &buffer, &assembly, 7, NULL);
for (auto c : buffer)
{
printf("0x%hhX ", c);
}
std::getchar();
return 0;
}

We use declspec to make sure no function prologue/epilogue gets in our way and no optimizations should change the bytes.

For this POC we're just writing to the local process.
The output is just for this proof of concept and will read:
Code:
0x50 0xB8 0x1 0x0 0x0 0x0 0x58

Should be simple enough to Write to a target process using this technique. Inline assembly is only possible for x86 if you're doing this in visual studio

Using the Capstone disassembler is the ultimate solution if you find yourself doing this often, it's very easy to use.
 
Top