Skip to content

Commit

Permalink
compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
aeventyr authored Mar 6, 2023
1 parent d1e762f commit a3e1081
Showing 1 changed file with 31 additions and 13 deletions.
44 changes: 31 additions & 13 deletions src/memjmp.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,29 +35,47 @@ void makeDetour(void* pAddress, void* dwDest, DWORD dwLen)

// allocate buffer for CALL() + orig insn + JMP()
void* gatewayAddr = VirtualAlloc(
0, dwLen + CALL_SIZE + JMP_SIZE,
0, dwLen + CALL_SIZE + JMP_SIZE,
MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (gatewayAddr == nullptr)
return;

// write CALL()
callRelAddr = (DWORD)((BYTE*)dwDest - (BYTE*)gatewayAddr) - CALL_SIZE;
// write CALL() @gatewayAddr
callRelAddr = (DWORD)dwDest - ((DWORD)gatewayAddr + CALL_SIZE);
*(BYTE*)gatewayAddr = CALL;
*(DWORD*)((BYTE*)gatewayAddr + 0x1) = callRelAddr;
// write original instruction
std::memcpy((BYTE*)gatewayAddr + CALL_SIZE, pAddress, dwLen);
// write JMP()
jmpbackRelAddr = (DWORD)((BYTE*)pAddress - (BYTE*)gatewayAddr) - CALL_SIZE
- JMP_SIZE;
*((BYTE*)gatewayAddr + CALL_SIZE + dwLen) = JMP;
*(DWORD*)((BYTE*)gatewayAddr + CALL_SIZE + dwLen + 0x1) = jmpbackRelAddr;

// in case of overwriting a existing JMP insn
if (*(BYTE*)pAddress == JMP)
{
// write JMP with newRelAddr @gatewayAddr+5
DWORD origDest = (DWORD)pAddress + *(DWORD*)((BYTE*)pAddress + 0x1) + CALL_SIZE;
DWORD newRelAddr = origDest - ((DWORD)gatewayAddr + CALL_SIZE + JMP_SIZE);
*((BYTE*)gatewayAddr + CALL_SIZE) = JMP;
*(DWORD*)((BYTE*)gatewayAddr + CALL_SIZE + 0x1) = newRelAddr;

// write JMP @gatewayAddr+10
jmpbackRelAddr = (DWORD)pAddress - ((DWORD)gatewayAddr + CALL_SIZE + JMP_SIZE);
*((BYTE*)gatewayAddr + CALL_SIZE + JMP_SIZE) = JMP;
*(DWORD*)((BYTE*)gatewayAddr + CALL_SIZE + JMP_SIZE + 0x1) = jmpbackRelAddr;
}
else
{
// write original instruction @gatewayAddr+5
std::memcpy((BYTE*)gatewayAddr + CALL_SIZE, pAddress, dwLen);

// write JMP @gatewayAddr+5+len
jmpbackRelAddr = (DWORD)pAddress - ((DWORD)gatewayAddr + CALL_SIZE + JMP_SIZE);
*((BYTE*)gatewayAddr + CALL_SIZE + dwLen) = JMP;
*(DWORD*)((BYTE*)gatewayAddr + CALL_SIZE + dwLen + 0x1) = jmpbackRelAddr;
}

// clear source and overwrite with JMP to gateway
std::memset(pAddress, NOP, dwLen);
// write JMP()
dwRelAddr = (DWORD)((BYTE*)gatewayAddr - (BYTE*)pAddress) - JMP_SIZE;
// write JMP @source
dwRelAddr = (DWORD)gatewayAddr - ((DWORD)pAddress + JMP_SIZE);
*((BYTE*)pAddress) = JMP;
*(DWORD*)((BYTE*)pAddress + 0x1) = dwRelAddr;

VirtualProtect(pAddress, dwLen, dwOldProtect, &dwBkup);
}
}

0 comments on commit a3e1081

Please sign in to comment.