Untitled


SUBMITTED BY: Guest

DATE: Feb. 4, 2014, 8:58 p.m.

FORMAT: C#

SIZE: 2.7 kB

HITS: 757

  1. /* Terminology:
  2. *
  3. * fish = function to patch
  4. * hook = patch to apply
  5. * coolbox = overwritten bytes and stack fixer
  6. * scales = memory security flags
  7. */
  8. #include <stdlib.h>
  9. #include <stdio.h>
  10. #include <assert.h>
  11. #include <stdint.h>
  12. #include <string.h>
  13. #include <windows.h>
  14. #include "hooks.h"
  15. #include "ollydisasm/disasm.h"
  16. /*register int *stackp asm ("esp");
  17. register int *basep asm ("ebp");*/
  18. unsigned long CleanBiteOff(const uint8_t *ptr, size_t amount); // how many bytes should i overwrite to fit a jump and not leave garbage behind
  19. int attachRawHook(uintptr_t fish, uintptr_t hook)
  20. {
  21. #define JMP_SIZE 5
  22. unsigned long safeSize = CleanBiteOff((uint8_t*)fish, JMP_SIZE);
  23. uint8_t *overwrite = malloc(safeSize);
  24. overwrite[0] = 0xE9;//call e8 -- jmp e9
  25. for (int i = JMP_SIZE; i < safeSize; i++)
  26. overwrite[i] = 0x90;
  27. DWORD oldScales, newScales;
  28. //__asm("int $3");
  29. uint8_t* coolbox;
  30. #define XCHG_SIZE 13
  31. #define FOOTER_SIZE 2*JMP_SIZE+XCHG_SIZE
  32. if ((coolbox = VirtualAlloc(NULL, safeSize + FOOTER_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE)) == NULL)
  33. return __HOOK_VIRTUALALLOC_COOLBOX;
  34. uintptr_t relative = (uintptr_t)coolbox + safeSize - fish;
  35. memcpy(&overwrite[1], &relative, JMP_SIZE-1);
  36. memcpy(coolbox, (void*)(fish), safeSize);
  37. relative = -relative;
  38. /*
  39. push ecx
  40. mov ecx, %coolbox
  41. xchg dword [esp+4], ecx
  42. xchg dword[esp], ecx
  43. {0x51,0xB9,0,0,0,0,0x87,0x4C,0xE4,0x04,0x87,0x0C,0xE4}
  44. */
  45. #define FOUR_BYTES 0,0,0,0
  46. uint8_t coolboxfooter[FOOTER_SIZE] = {0xE9,FOUR_BYTES,0x51,0xB9,FOUR_BYTES,0x87,0x4C,0xE4,0x04,0x87,0x0C,0xE4, 0xE9/*,FOUR_BYTES*/};
  47. memcpy(&coolboxfooter[1], &relative, JMP_SIZE-1);
  48. memcpy(&coolboxfooter[JMP_SIZE+2], &coolbox, JMP_SIZE-1);
  49. relative = hook - ((uintptr_t)coolbox + safeSize + FOOTER_SIZE);
  50. memcpy(&coolboxfooter[JMP_SIZE+XCHG_SIZE+1], &relative, JMP_SIZE-1);
  51. memcpy(coolbox+safeSize, coolboxfooter, FOOTER_SIZE);
  52. if (VirtualProtect((LPVOID) fish, safeSize, PAGE_READWRITE, &oldScales) == 0)
  53. return __HOOK_PROTECTION_DISABLE;
  54. memcpy((void*)fish, overwrite, safeSize);
  55. if (VirtualProtect((LPVOID)fish, safeSize, oldScales, &newScales) == 0)
  56. return __HOOK_PROTECTION_ENABLE;
  57. return __HOOK_ALL_OK;
  58. }
  59. unsigned long CleanBiteOff(const uint8_t *ptr, size_t amount)
  60. {
  61. static t_disasm disasm;
  62. unsigned long size = 0;
  63. do {size += Disasm(ptr+size, 16, 0x00401AAC, &disasm, DISASM_SIZE);} while(size < amount);
  64. return size;
  65. }

comments powered by Disqus