CPLUSPLUSCreating a Detour

Posts 1–3 of 3 · Page 1 of 1
Creating a Detour
First thing you need to understand - to write a jump in binary it is NOT a simple case of doing: JMP <addr> in bytes!
To jump to the right address you must do:

Code:
address = (place_we_want_to_jump_to + start_of_memory_where_jump_is_at) - size_of_a_jmp_address
So lets say we want to jump to 0x12345678 and the jump is at 0x55555555:
Code:
address = (0x12345678 + 0x55555555) - 5; //5 is the size of the JMP instruction
So, to make our Detour we need a pointer to the original function, the hook, and the length:
Code:
void *DetourFunction(BYTE *orig, BYTE *hook, int len)
{
	DWORD dwProt = 0;
Next we allocate a place in memory for the bytes we are going to overwrite in the original, plus the size of a jump <address> instruction:
Code:
BYTE *jmp = (BYTE*)malloc(len+5);
Next we want to allow read & write access to the memory at the original function, and save the previous access to dwProt:
Code:
VirtualProtect(orig, len, PAGE_READWRITE, &dwProt);
Now we want to copy the bytes of original + length to the allocated memory place:
Code:
memcpy(jmp, orig, len);
Next we want to insert a jump back to the original + length at the end of those intructions we just copied over:
Code:
jmp += len; // increment to the end of the copied bytes
jmp[0] = JMP;
*(DWORD*)(jmp+1) = (DWORD)(orig+len - jmp) - 5;
For good practice we want to NOP out all the bytes at the original that we have saved to the memory allocated place:
Code:
memset(orig, 0x90, len);
Now we want to write a jump at the original to the hooked function:
Code:
orig[0] = JMP;
*(DWORD*)(orig+1) = (DWORD)(hook - orig) - 5;
Next we want to put back the old protection flags:
Code:
VirtualProtect(orig, len, dwProt, 0);
And finally we want to return a pointer to the start of the memory allocated place (we incremented the pointer by length before, so now we do jmp - length)
Code:
return (jmp-len);
}
Usage:
Code:
typedef int( __cdecl* tDraw2D ) ( int a1 );
tDraw2D oDraw2D = NULL;

void Draw2D(int a1)
{
	__asm PUSHAD;

        //Do your magic here XD	

	__asm POPAD;
	oDraw2D( a1 );
}

BOOL WINAPI DllMain( HMODULE hMod, DWORD dwReason, LPVOID lpReserved )
{
    if( dwReason == DLL_PROCESS_ATTACH )
    {
	oDraw2D = (tDraw2D) DetourFunction( (BYTE*)Draw2DOffset, (BYTE*)&Draw2D ,5);
    }
}
Credits:
Dwar
thx for the tut.
Decent-ish

Cheers,
kJNR
Posts 1–3 of 3 · Page 1 of 1

Post a Reply

Similar Threads

Tags for this Thread

None

Talk with us