#include <stdio.h>
#include <dlfcn.h>
#include <string.h>
#include <elf.h>
#include <sys/mman.h>
ssize_t (*old_read)(
int
,
void
*,
size_t
);
ssize_t my_read(
int
fd,
void
*buf,
size_t
count) {
printf
(
"[+] Hooked read()! fd: %d, count: %zu\n"
, fd, count);
return
old_read(fd, buf, count);
}
void
hook_function(
const
char
*symbol,
void
*new_func) {
void
*handle = dlopen(NULL, RTLD_NOW);
if
(!handle)
return
;
old_read = dlsym(handle, symbol);
ElfW(Dyn) *dyn = (ElfW(Dyn) *)dlsym(handle,
"_DYNAMIC"
);
while
(dyn->d_tag != DT_NULL) {
if
(dyn->d_tag == DT_PLTGOT) {
void
**got = (
void
**)dyn->d_un.d_ptr;
for
(
int
i = 0; got[i] != NULL; i++) {
if
(got[i] == old_read) {
mprotect((
void
*)((
uintptr_t
)got & ~0xFFF), 0x1000, PROT_READ | PROT_WRITE);
got[i] = new_func;
mprotect((
void
*)((
uintptr_t
)got & ~0xFFF), 0x1000, PROT_READ);
break
;
}
}
}
dyn++;
}
dlclose(handle);
}
void
__attribute__((constructor)) init() {
hook_function(
"read"
, my_read);
}