Skip to content

Instantly share code, notes, and snippets.

@RedTeams
Created July 21, 2019 18:57
Show Gist options
  • Save RedTeams/2b9de440393c7609dc6e0aab9b833b91 to your computer and use it in GitHub Desktop.
Save RedTeams/2b9de440393c7609dc6e0aab9b833b91 to your computer and use it in GitHub Desktop.
x86/x64 Simple JMP (Relative Offset) function hooking.
#include <windows.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#if _WIN32 || _WIN64
#if _WIN64
typedef uint64_t uint_t;
#else
typedef uint32_t uint_t;
#endif
#endif
#if __GNUC__
#if __x86_64__ || __ppc64__
typedef uint64_t uint_t;
#else
typedef uint32_t uint_t;
#endif
#endif
bool install_hook(char * module, char * function, void * rfcn)
{
void *p_module = NULL, *p_function = NULL;
uint_t jmp_offset;
uint32_t old;
char patch[1 + sizeof(uint_t)] = {
0xE9
};
p_module = LoadLibraryA(module);
if ( !p_module )
return FALSE;
p_function = GetProcAddress(p_module, function);
if ( !p_function )
return FALSE;
if ( !VirtualProtect(p_function, sizeof(patch), PAGE_READWRITE, (LPDWORD)&old) )
return FALSE;
jmp_offset = (uint_t)rfcn - (uint_t)p_function - sizeof(uint_t) - 1;
memcpy(((void *)&patch) + 1, &jmp_offset, sizeof(uint_t));
memcpy(p_function, &patch, sizeof(patch));
if ( !VirtualProtect(p_function, sizeof(uint_t), old, (LPDWORD)&old) )
return FALSE;
return TRUE;
}
int hook(HWND window, char *text, char *box, UINT lol)
{
printf("AHA! NOT TODAY\n");
return 0;
}
void main(void)
{
install_hook("user32.dll", "MessageBoxA", (void *)hook);
MessageBoxA(NULL, "test", "test", MB_OK);
}
@soumy
Copy link

soumy commented Jul 25, 2023

jmp_offset = (uint_t)rfcn - (uint_t)p_function - sizeof(uint_t) - 1;

This is correct only in 32 bit not on 64 bit. E9 jump is rel32.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment