'Wrapping'에 해당되는 글 1건

  1. LD_PRELOAD를 이용한 hooking, wrapping 2012.01.25

LD_PRELOAD를 이용한 hooking, wrappingLD_PRELOAD를 이용한 hooking, wrapping

Posted at 2012. 1. 25. 20:18 | Posted in 개발이야기
hook_gethostname.c
 
#include 
#include 

int gethostname(char *name, size_t len)
{
    char *p = getenv("FAKE_HOSTNAME");
    if (p == NULL) {
        p = "localhost";
    }
    strncpy(name, p, len-1);
    name[len-1] = '\0';
    return 0;
}

wrap_hostname.c
// define to use RTLD_NEXT
#define _GNU_SOURCE
#include 

#include 
#include 

// function pointer for origin gethostname function.
static int (*gethostname0)(char *name, size_t len);

// __attribute((constructor)):
//      main함수가 호출되기 전이나,
//      공유 오브젝트가 로드되었을 때 실행해야 하는 함수에 사용.
void __attribute__((constructor)) init_gethostname0()
{
    gethostname0 = dlsym(RTLD_NEXT, "gethostname");
    //NOTE: dlsym이 실패한 경우는?
}

// hooking gethostname
int gethostname(char *name, size_t len)
{
    char *p = name;
    if (len > 6) {
        memcpy(p, "name: ", 6);
        p += 6;
        len -= 6;
    }
    return (*gethostname0)(p, len);
}

Makefile
TARGET_HOOK=hook_gethostname.so
TARGET_WRAP=wrap_gethostname.so

all:
    gcc -shared -fPIC -o $(TARGET_HOOK) hook_gethostname.c
    gcc -shared -fPIC -o $(TARGET_WRAP) -ldl wrap_gethostname.c

clean:
    rm -f $(TARGET_HOOK) $(TARGET_WRAP)

hook: all
    @echo ""
    @echo "- hostname -------------------------------------------------------------"
    /bin/hostname
    @echo ""
    @echo "- hostname hooking gethostname(libc.so) --------------------------------"
    FAKE_HOSTNAME=fake.hostname LD_PRELOAD=./$(TARGET_HOOK) /bin/hostname

wrap: all
    @echo ""
    @echo "- hostname wrapping gethostname(libc.so) -------------------------------"
    LD_PRELOAD=./$(TARGET_WRAP) /bin/hostname

run: hook wrap

$ make run
을 실행하면,,
gcc -shared -fPIC -o hook_gethostname.so hook_gethostname.c
gcc -shared -fPIC -o wrap_gethostname.so -ldl wrap_gethostname.c

- hostname -------------------------------------------------------------
/bin/hostname
deepblue-ubuntu

- hostname hooking gethostname(libc.so) --------------------------------
FAKE_HOSTNAME=fake.hostname LD_PRELOAD=./hook_gethostname.so /bin/hostname
fake.hostname

- hostname wrapping gethostname(libc.so) -------------------------------
LD_PRELOAD=./wrap_gethostname.so /bin/hostname
name: deepblue-ubuntu

참고: BINARY HACKS 해커가 전수하는 테크닉 100선
//