LD_PRELOAD example
LD_PRELOAD rootkits Part2
Original Source: http://www.catonmat.net/blog/simple-ld-preload-tutorial-part-2/
이번에는 간단히 fopen
: 을 실행하는 프로그램 prog.c
를 예로 들어 보자.
#include <stdio.h>
int main(void) {
printf("Calling the fopen() function...\n");
FILE *fd = fopen("test.txt", "r");
if (!fd) {
printf("fopen() returned NULL\n");
return 1;
}
printf("fopen() succeeded\n");
return 0;
}
그리고 공유 라이브러리 myfopen.c
를 작성하자. 이 파일은 prog.c
의 fopen
을 override 하고, c standard 라이브러리 원본 fopen
를 호출한다.
#define _GNU_SOURCE
#include <stdio.h>
#include <dlfcn.h>
FILE *fopen(const char *path, const char *mode) {
printf("In our own fopen, opening %s\n", path);
FILE *(*original_fopen)(const char*, const char*);
original_fopen = dlsym(RTLD_NEXT, "fopen");
return (*original_fopen)(path, mode);
}
이 공유 라이브러리는 fopen
함수를 export 하고, path 를 출력한다. 그리고 RTLD_NEXT
pseudo handle을 통한 dlsym
을 사용하여 원본 fopen
를 찾는다. 우리는 반드시 _GNU_SOURCE feature 를 define 해야 하는데, 이것은 RTLD_NEXT
를 <dlfcn.h>
. 로부터 사용하기 위해서 이다. RTLD_NEXT
는 현재 라이브러리에서 검색순위에 따라 순차적으로 함수를 검색한다.
다음과 같이 이 공유 라이브러리를 컴파일 하고,
gcc -Wall -fPIC -shared -o myfopen.so myfopen.c -ldl
Now when we preload it and run prog
we get the following output that shows that test.txt
was successfully opened:
이제 preload 해서 prog를 실행시킨다. test.txt 가 성공적으로 open 된 것을 확인 할 수 있다.
$ LD_PRELOAD=./myfopen.so ./prog
Calling the fopen() function...
In our own fopen, opening test.txt
fopen() succeeded
'Linux Kernel' 카테고리의 다른 글
volatile keyword (0) | 2016.08.30 |
---|---|
glibc Malloc (0) | 2016.08.27 |
MMIO in PCIe (0) | 2016.08.24 |
JEMALLOC: A Scalable Concurrent malloc(3) Implementation for FreeBSD (0) | 2016.08.18 |
malloc 소개 (0) | 2016.08.18 |