lunixbochs / patchkit

binary patching from Python
Other
631 stars 85 forks source link

How to hook the end of a function #27

Open MillionSky opened 5 years ago

MillionSky commented 5 years ago

Currently, we can hook the begin of a function。How to hook the end of a function? So that we can check the return value of the function, or execute some code after the function end.

lunixbochs commented 5 years ago

You can hook any address.

MillionSky commented 5 years ago

You can hook any address. Oh, Thanks very much!

MillionSky commented 5 years ago

So, if the function have multi ret point, we must hook every address.

MillionSky commented 5 years ago

I encountered a problem when hook the end of a function. The hook seems have side effect. The original instructions before hook: .text:08049A18 5B pop ebx .text:08049A19 5E pop esi .text:08049A1A 5F pop edi .text:08049A1B 5D pop ebp .text:08049A1C C3 retn .text:08049A1C TargetFunc endp .text:08049A1C .text:08049A1D .text:08049A1D ; =============== S U B R O U T I N E ============ .text:08049A1D .text:08049A1D ; Attributes: bp-based frame .text:08049A1D .text:08049A1D ; int __cdecl main(int argc, const char argv, const char envp) .text:08049A1D public main .text:08049A1D main proc near ; DATA XREF: _start+17 .text:08049A1D 8D 4C 24 04 lea ecx, [esp+4] .text:08049A21 83 E4 F0 and esp, 0FFFFFFF0h .text:08049A24 FF 71 FC push dword ptr [ecx-4] .text:08049A27 55 push ebp .text:08049A28 89 E5 mov ebp, esp

After hook, the begin of main function was modified: .text:08049A18 5B pop ebx .text:08049A19 5E pop esi .text:08049A1A 5F pop edi .text:08049A1B 5D pop ebp .text:08049A1B TargetFunc endp ; sp-analysis failed .text:08049A1C E9 db 0E9h .text:08049A1D .text:08049A1D ; =============== S U B R O U T I N E ============== .text:08049A1D .text:08049A1D .text:08049A1D ; int __cdecl main(int argc, const char argv, const char envp) .text:08049A1D public main .text:08049A1D main proc near ; DATA XREF: _start+17 .text:08049A1D 72 B6 jb short loc_80499D5 .text:08049A1F 02 00 add al, [eax] .text:08049A21 83 E4 F0 and esp, 0FFFFFFF0h .text:08049A24 FF 71 FC push dword ptr [ecx-4] .text:08049A27 55 push ebp .text:08049A28 89 E5 mov ebp, esp

We can discover that ret instruction(C3) and following 4 bytes in main was modified to "e9 72 B6 02 00"。As the result, the program failed to start.

lunixbochs commented 5 years ago

You shouldn’t hook the ret, you should hook a few bytes before. You can also pt.inject your asm and patch in a jump instead of using hook.

lunixbochs commented 5 years ago

Use the -v flag to see exactly what patchkit changed.

MillionSky commented 5 years ago

OK,I understand. Thanks very much!