Tuesday, August 6, 2013

Visual C++ direct code injection using WriteProcessMemory

Visual C++ direct code injection using WriteProcessMemory

This is my first time around, and I really hope you guys can help me, as I
have ran out of ideas by now.
I have searched for an answer for a couple of hours now, and could not
find an answer that would actually work.
First things first. Yes, you have read it right. I am trying to inject
code into another application, and - believe it or not - this is only to
extend the functionality of an existing application.
I am using Visual Studio 2012 Express Edition on Windows.
I have the following code:
__declspec(naked) void Foo()
{
__asm
{
// Inline assembly code here
}
}
__declspec(naked) void FooEnd() {}
int main()
{
cout << HEX(Foo) << endl;
cout << HEX(FooEnd) << endl;
cout << (int)FooEnd - (int)Foo << endl;
// Inject code here using WriteProcessMemory
return 0;
}
Most of the code has been removed in order to maintain readability, though
I can post other portions of it on request.
Output is the following:
0x010B1000
0x010B1010
16
The resulting size is actually incorrect. The functions are compiled in
the right order (made sure using /ORDER), but the compiler adds a bunch of
0xCC (int 3) bytes after each method which extends it's size, and so I
can't get the real (useful) number of bytes that contains actual
executable code.
In another stackoverflow question, it has been said that disabling "Edit
and Continue" would make these extra bytes go away, but no matter what,
that didn't work for me.
I also tried using Release setup instead of Debug, changed a bunch of
optimization settings, but none of these had any effect. What do you think
could be the solution? I may be missing something obvious.
Second question is; is this (in your opinion) the best way to acquire a
function's length (readability, reliability, ease of use)?
I hope I explained everything I had to in order for you to be able to
help. If you have further questions, please feel free to leave a comment.
Thanks for your time and efforts, Levente Morva

No comments:

Post a Comment