views:

115

answers:

2

Hi, I have a code that changes the function that would be called, to my new function, but I don't want to call only my new function, I also want to call the old one. This is an example, so you can understand what I'm saying:

If I disassemble my .exe, I will look at this part:

L00123456:
      mov   eax, [L00654321] //doesn't matter
      mov   ecx, [eax+1Ch]   //doesn't matter
      push  esi              //the only parameter
0x123 call  SUB_L00999999    //this is the function I wanna overwrite
      //...

(0x123 is the address of that line) So, I used this code:

DWORD old;
DWORD from = 0x123;
DWORD to   = MyNewFunction;
VirtualProtect(from, 5, PAGE_EXECUTE_READWRITE, &old);

DWORD disp = to - (from + 5);
*(BYTE *)(from) = 0xE8;
*(DWORD *)(from + 1) = (DWORD)disp;

Now, instead of calling SUB_L00999999, it calls MyNewFunction...

So... any ideas on how can I still call the old function?

I tried things like this (in many ways), but it crashes my application:

int MyNewFunction(int parameter)
{
    DWORD oldfunction = 0x00999999;
    _asm push parameter
    _asm call oldfunction
}

Notes: I use Visual Studio C++ 2010 and these codes are in a .dll loaded in an .exe.

Thanks.

+2  A: 

ret expects the top stack argument to be the address to return to. You can exploit this by pushing the oldfunction address onto the stack immediately before your ret instruction in your new function. As the call returns (or rather, branches to the oldfunction), the stack pointer will shift to leave the original return address (0x128 here) on top, so the stack will appear undamaged. (same as it should have been had you not taken a detour).

Mark H
Can you give me an example code using "ret"? Thank you.
Flávio Toribio
Try out `_asm { push oldfunction; ret 4 }` and check your output with a debugger. I'm unsure whether the C compiler might add/remove anything else which could upset the stack. The stack should look identical when it enters oldfunction as it did when it entered newfunction. (Oh, and some registers may need to be the same, you may need to set them before retn).
Mark H
Your answer should work too, but it's more complicated by the fact that instead of just calling the function with my parameters, we'd return to the old stack and then call the function. I saw this in some project file and tried to do in that way, but it's harder then @myeviltacos' way. Thank you for helping out.
Flávio Toribio
+2  A: 

I had a problem like this a while back. Anyway, _asm call dword ptr [oldfunction] worked for me.

myeviltacos
Thank you man, this worked fine, I wasn't remembering that I used this some time ago...
Flávio Toribio