Search This Blog

Friday, November 2, 2007

library level system call hooking

We can use LD_PRELOAD to load our own library before any other libraries are loaded.


// myopen.c
#include
#include
#include
#include
#include

int open(const char *pathname, int flags)
{
void *handle;
char *error;
int ret;
static int (*orig_open)(const char *pathname, int flag) = NULL;

if (!orig_open) {
handle = dlopen("/lib/libc.so.6", RTLD_LAZY);
if (!handle) {
fputs(dlerror(), stderr);
exit(1);
}
orig_open = dlsym(handle, "open");
if ((error = dlerror()) != NULL) {
fprintf(stderr, "%s\n", error);
exit(1);
}
}
printf("calling open for %s\n", pathname);
ret = (*orig_open)(pathname, flags);

return ret;
}


// test.c
#include
#include
#include
#include

int main()
{
int fd;

fd = open("test.txt", O_CREAT);
write(fd, "cool", 4);
close(fd);
return 0;
}

# gcc -Wall -fpic -shared -ldl -o myopen.so myopen.c
# gcc -Wall -o test test.c
# LD_PRELOAD=/tmp/myopen.so ./test

No comments:

Post a Comment