Linux下系統調用的hook機制
[http://blog.csdn.net/sdulibh/article/details/42078681]
http://0pointer.de/blog/projects/mutrace.html
http://0pointer.de/blog/projects/mutrace.html – 對mutex進行trace的hook
https://github.com/dbpercona/mutrace/blob/master/README
- linux下系統調用hook機制的原理
- LD_PRELOAD機制:允許用戶手動指定使用的動態鏈接庫,將系統庫函數hook->lib.so.6
- dlyopen;dlsym: 通過句柄和連接符名稱獲取真實庫函數名或者變量名
- 實例
- main.c
- 編譯:gcc -o main main.c
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
if( strcmp(argv[1], "123") )
{
printf("Incorrect\n");
}
else
{
printf("Correct\n");
}
return 0;
}
- hook.c
- 編譯:gcc -fPIC -shared -o hook.so hook.c -ldl
#include<stdio.h>
#include<string.h>
#include<dlfcn.h>
typedef int (*STRCMP) (const char*, const char*);
int strcmp(const char* s1, const char* s2) {
static void *handle = NULL;
static STRCMP old_strcmp = NULL;
if(!handle) {
handle = dlopen("libc.so.6", RTLD_LAZY);
old_strcmp = (STRCMP)dlsym(handle, "strcmp");
}
if(old_strcmp) printf("addr=%p\n", old_strcmp);
printf("you are hacked. s1=<%s>,s2=<%s>\n", s1, s2);
return old_strcmp(s1, s2);
}
- 運行: LD_PRELOAD= ./hook.so ./main 123
未完待續…