Advertisement
captmicro

hooklib by capt micro

Mar 8th, 2013
451
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.91 KB | None | 0 0
  1. //hooklib by capt. micro
  2.  
  3. #ifndef BYTE
  4. typedef unsigned char BYTE;
  5. #endif
  6. #ifndef DWORD
  7. typedef unsigned int DWORD;
  8. #endif
  9. void HookCopy(BYTE *bSrc, BYTE *bDst, DWORD dwSz)
  10. {
  11.     while (--dwSz) *bDst++ = *bSrc++;
  12. }
  13. void HookInstall(DWORD dwInstallAt, DWORD dwInstallSz, DWORD dwDetourFunc)
  14. {
  15.     //Save instructions and generate stub before we overwrite function with the hook
  16.     BYTE *bHookStub = (BYTE*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwInstallSz + 2 + 5 + 2 + 5);
  17.     HookCopy(bHookStub, (BYTE*)dwInstallAt, dwInstallSz);
  18.     *(bHookStub + dwInstallSz + 0) = 0x60 //pushad \
  19.     *(bHookStub + dwInstallSz + 1) = 0x9C //pushfd  \-----------------------\
  20.     *(bHookStub + dwInstallSz + 2) = 0xE8 //call <users detour function>     |- So we dont utterly fuck the program
  21.     *((DWORD*)(bHookStub + dwInstallSz + 3)) = dwDetourFunc; //             /
  22.     *(bHookStub + dwInstallSz + 7) = 0x9D //popfd   /----------------------/
  23.     *(bHookStub + dwInstallSz + 8) = 0x61 //popad  /
  24.     *(bHookStub + dwInstallSz + 9) = 0xE8 //jmp <dwInstallAt + dwInstallSz> (instruction after hook)
  25.     *((DWORD*)(bHookStub + dwInstallSz + 10)) = dwInstallAt + dwInstallSz;
  26.    
  27.     //Generate 5 byte hook and install it
  28.     BYTE *bHookInstruction = (BYTE*)dwInstallAt;
  29.     *(bHookInstruction + 0) = 0xE9; //jmp <hook stub>
  30.     *((DWORD*)(bHookInstruction+1)) = bHookStub;
  31.    
  32.     //Fill the rest with NOPs (not needed really, just nice to have)
  33.     DWORD dwNopFill = dwInstallSz - 5;
  34.     while (dwNopFill > 0)
  35.     {
  36.         *(bHookInstruction + 4 + dwNopFill) = 0x90; //NOP
  37.         dwNopFill--;
  38.     }
  39. }
  40. void HookRemove(DWORD dwInstallAt, DWORD dwInstallSz)
  41. {
  42.     //Get the address of the stub (therefore the saved instructions)
  43.     DWORD dwStubAddr = *((DWORD*)(dwInstallAt + 1));
  44.     BYTE *bHookStub = (BYTE*)dwStubAddr;
  45.    
  46.     //Copy the saved instructions back to the function
  47.     HookCopy((BYTE*)dwInstallAt, bHookStub, dwInstallSz);
  48.    
  49.     //Free the stub
  50.     HeapFree(GetProcessHeap(), 0, bHookStub);
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement