So, mal alles zusammengesucht:
hook.c
Code:
#include <stdio.h>
#include <string.h>
#include <sys/mman.h> /* mprotect */
void hookFunction(int from, int to)
{
int relative = to - (from+5); // +5 is the position of next opcode
memset((void *)from, 0xE9, 1); // JMP-OPCODE
memcpy((void *)(from+1), &relative, 4); // set relative address with endian
}
int hook()
{
printf("hook\n");
return 666;
}
int original()
{
printf("original\n");
return 123;
}
int main()
{
// allow to write in executable memory
mprotect((void *)0x08048000, 0x135000, PROT_READ | PROT_WRITE | PROT_EXEC);
original();
hookFunction((int)original, (int)hook);
printf("%.8x %.8x\n", original, hook);
original();
/*
example-output of /proc/$pid/maps:
08048000-08049000 rwxp 00000000 92:1d 84377624 /home/gruena/hook/a.out
08049000-0804a000 rwxp 00000000 92:1d 84377624 /home/gruena/hook/a.out
*/
printf("change mprotect() if needed: /proc/%d/maps", getpid());
getchar(); // dont kill process till we got what we need from /proc/$pid/maps
}
Kompilieren 32-bit: Ausgabe:
Code:
original
0804856b 08048552
hook
change mprotect() if needed: /proc/17565/maps
Also ich patche direkt die Funktion und nicht die CALL's darauf.