2016
04
24
22
53
[Linux] 用 LD_PRELOAD 去 hook fopen
這隻程式是用來hook fopen,
並且檢查目前開啟的檔案是不是 /etc/resolv.conf ,
如果發現是的話, 就偷偷換成用 /tmp/resolv.conf 去開啟.
#include <stdio.h>
#include <string.h>
#define __USE_GNU
#include <dlfcn.h>
typedef FILE *(*fopen_t) (const char *path, const char *mode);
#define printf // 如果要debug, 就註解掉這個 #define
FILE *fopen(const char *pathname, const char *mode)
{
static fopen_t orig_fopen = NULL;
FILE *f;
if (orig_fopen == NULL) {
orig_fopen = (fopen_t) dlsym(RTLD_NEXT, "fopen");
}
if (strcmp(pathname, "/etc/resolv.conf") != 0) {
printf("original fopen %s\n",pathname);
f = orig_fopen(pathname, mode);
} else {
printf("hook fopen %s\n",pathname);
f = orig_fopen("/tmp/resolv.conf", mode);
}
return f;
}
編譯的方法如下:
gcc -shared -fPIC hook_fopen.c -o hook_fopen.so -ldl
然後執行 LD_PRELOAD=${PWD}/hook_fopen.so ./a.out
你就可以看到後面所執行的 a.out 當開啟 /etc/resolv.conf 會被改成開啟 /tmp/resolv.conf