Tuesday, March 21, 2006

Linux API Hooking

3 comments
Had some success today hooking APIs on linux.
Don't think that this is going to be a techy blog-site. Just pasting here for later references. Looks like blog site is quite handy repository.

Keywords: LD_PRELOAD, dlsym
http://sourceware.org/ml/libc-alpha/2001-05/msg00321.html

One more note:
LD_PRELOAD is supported for most of the UNIX flavors. I had tried it on HPUX in patni and it worked there.
read that it will work for SOLARIS and AIX also.

-----------------------------------------------------------

follow these 3 simple steps to hook APIs in Linux.

Step1: create a file with following code..say preload.c

//the blogger treats < as tags..removing < from include statements
#include dlfcn.h
#include stdio.h
#include sys/types.h
#include sys/socket.h

#if defined(RTLD_NEXT)
#define REAL_LIBC RTLD_NEXT
#else
#define REAL_LIBC ((void *) -1L)
#endif


int connect(int sockfd, const struct sockaddr *serv_addr, socklen_t
addrlen)
{
printf("NEOACCEL: connect hacked\n");
static int (*o_dlconnect) ( int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen )=0;

printf( "dlopen was called\n" );
o_dlconnect = (int(*)( int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen )) dlsym(REAL_LIBC,"connect");
return (*o_dlconnect)( sockfd, serv_addr, addrlen );

}

Step2: compile it using cmd line
gcc -Wall -fPIC -shared -o preload.so preload.c -ldl

Step3: Define env variable LD_PRELOAD as:
export LD_PRELOAD=absolute file-path of preload.so, inclding filename

and you are done....


some good respources:
http://neworder.box.sk/newsread.php?newsid=13857

http://www.security.nnov.ru/articles/reveng/

www.phrack.org

3 comments:

Jamie Pocas said...

You should be able to use C++, you probably just need to wrap (or prefix) your function with extern "C" { /* your function */ }

This is because the C++ compiler may mangle your function name and the exported name or signature will look different.

Vij said...

Thanks Jamie. You are right

Anonymous said...

May just be the Most excellent subject that i browsed through all holiday season?