1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
|
static int
exm_entry_point_patch(Exm *exm)
{
CONTEXT context;
unsigned char nep[2];
if (!VirtualProtectEx(exm->child.process2, exm->child.entry_point,
2, PAGE_EXECUTE_READWRITE, &exm->child.old_protect))
{
EXM_LOG_ERR("can not protect page 0x%p in process handle 0x%p failed",
exm->child.entry_point,
exm->child.process2);
return 0;
}
if (!ReadProcessMemory(exm->child.process2, exm->child.entry_point,
exm->child.oep, 2, NULL))
{
EXM_LOG_ERR("read memory 0x%p of process handle 0x%p failed",
exm->child.entry_point,
exm->child.process2);
return 0;
}
/* patch with an infinite loop : JMP -2 */
nep[0] = 0xEB;
nep[1] = 0xFE;
EXM_LOG_DBG("patching process 0x%p at entry point 0x%p",
exm->child.process2,
exm->child.entry_point);
if (!WriteProcessMemory(exm->child.process2, exm->child.entry_point,
nep, 2, NULL))
{
EXM_LOG_ERR("write memory 0x%p of process handle 0x%p failed",
exm->child.entry_point,
exm->child.process2);
return 0;
}
ResumeThread(exm->child.thread);
while (1)
{
Sleep(100);
context.ContextFlags = CONTEXT_CONTROL;
if (!GetThreadContext(exm->child.thread, &context))
{
EXM_LOG_ERR("can not retrieve the context of thread 0x%p, unpatch entry point",
exm->child.thread);
SuspendThread(exm->child.thread);
if (!exm_entry_point_unpatch(exm))
{
EXM_LOG_ERR("can not unpatch entry point");
}
ResumeThread(exm->child.thread);
return 0;
}
#if defined (_AMD64_)
if ((uintptr_t)context.Rip == (uintptr_t)exm->child.entry_point)
break;
#elif defined (_X86_)
if ((uintptr_t)context.Eip == (uintptr_t)exm->child.entry_point)
break;
#else
# error "system not supported"
#endif
}
/* SetThreadContext(exm->child.thread, &context); */
return 1;
}
static int
exm_entry_point_unpatch(Exm *exm)
{
DWORD new_protect;
if (!WriteProcessMemory(exm->child.process2, exm->child.entry_point,
exm->child.oep, 2, NULL))
{
EXM_LOG_ERR("write memory 0x%p of process handle 0x%p failed",
exm->child.entry_point,
exm->child.process2);
return 0;
}
if (!VirtualProtectEx(exm->child.process2, exm->child.entry_point,
2, exm->child.old_protect, &new_protect))
{
EXM_LOG_ERR("can not protect page 0x%p in process handle 0x%p failed",
exm->child.entry_point, exm->child.process2);
return 0;
}
return 1;
} |
Partager