Advertisement
HITOA

64b function detouring

Nov 11th, 2020
762
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.07 KB | None | 0 0
  1. #include "pch.h"
  2. #include <stdlib.h>
  3.  
  4. struct HOOK {
  5.     LPVOID base;
  6.     BYTE jmp[14];
  7.     BYTE org[14];
  8. };
  9.  
  10. typedef HOOK* PHOOK;
  11.  
  12. BYTE stub[] = {
  13.         0xFF, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  14. };
  15.  
  16. int DisableHook(PHOOK hook) {
  17.     DWORD current_protection = 0;
  18.     VirtualProtect(hook->base, 14, PAGE_EXECUTE_READWRITE, &current_protection);
  19.  
  20.     memcpy(hook->base, hook->org, 14);
  21.  
  22.     DWORD tmp_protection = 0;
  23.     VirtualProtect(hook->base, 14, current_protection, &tmp_protection);
  24.     return 0;
  25. }
  26.  
  27. int EnableHook(PHOOK hook) {
  28.     DWORD current_protection = 0;
  29.     VirtualProtect(hook->base, 14, PAGE_EXECUTE_READWRITE, &current_protection);
  30.  
  31.     memcpy(hook->base, hook->jmp, 14);
  32.  
  33.     DWORD tmp_protection = 0;
  34.     VirtualProtect(hook->base, 14, current_protection, &tmp_protection);
  35.     return 0;
  36. }
  37.  
  38. PHOOK CreateHook(LPVOID src, LPVOID dst) {
  39.     PHOOK hook = (PHOOK)malloc(sizeof(HOOK));
  40.  
  41.     hook->base = src;
  42.  
  43.     DWORD current_protection = 0;
  44.     VirtualProtect(src, 14, PAGE_EXECUTE_READWRITE, &current_protection);
  45.  
  46.     memcpy(hook->org, src, 14);
  47.  
  48.     memcpy(stub + 6, &dst, 8);
  49.     memcpy(hook->jmp, stub, 14);
  50.  
  51.     DWORD tmp_protection = 0;
  52.     VirtualProtect(src, 14, current_protection, &tmp_protection);
  53.  
  54.     EnableHook(hook);
  55.  
  56.     return (PHOOK)hook;
  57. }
  58.  
  59. LPVOID HookFunction(LPVOID src, LPVOID dst, int len) {
  60.  
  61.     if (len < 14)
  62.         return NULL;
  63.    
  64.     LPVOID trampoline = VirtualAlloc(NULL, len + sizeof(stub), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
  65.  
  66.     DWORD current_protection = 0;
  67.     VirtualProtect(src, len, PAGE_EXECUTE_READWRITE, &current_protection);
  68.  
  69.     DWORD64 ret = (DWORD64)src + len;
  70.     memcpy(stub + 6, &ret, 8);
  71.  
  72.     memcpy(trampoline, src, len);
  73.     memcpy((LPVOID)((DWORD64)trampoline + len), stub, sizeof(stub));
  74.  
  75.     memset(src, 0x90, len);
  76.  
  77.     memcpy(stub + 6, &dst, 8);
  78.     memcpy(src, stub, sizeof(stub));
  79.  
  80.     DWORD tmp_protection = 0;
  81.     VirtualProtect(src, len, current_protection, &tmp_protection);
  82.  
  83.     return trampoline;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement