Reverse Engineering for Beginners

(avery) #1

CHAPTER 67. LINUX CHAPTER 67. LINUX


Let’s try to write our own dynamic library with the open(), read(), close() functions working as we need.


At first, our open() will compare the name of the file to be opened with what we need and if it is so, it will write down the
descriptor of the file opened. Second, read(), if called for this file descriptor, will substitute the output, and in the rest of
the cases will call the original read() from libc.so.6. And also close(), will note if the file we are currently following is to be
closed.


We are going to use the dlopen() and dlsym() functions to determine the original function addresses in libc.so.6.


We need them because we must pass control to the “real” functions.


On the other hand, if we intercepted strcmp() and monitored each string comparisons in the program, then we would have
to implement a strcmp(), and not use the original function^3.


#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <dlfcn.h>
#include <string.h>


void libc_handle = NULL;
int (
open_ptr)(const char , int) = NULL;
int (
close_ptr)(int) = NULL;
ssize_t (read_ptr)(int, void, size_t) = NULL;


bool inited = false;


_Noreturn void die (const char * fmt, ...)
{
va_list va;
va_start (va, fmt);


vprintf (fmt, va);
exit(0);
};


static void find_original_functions ()
{
if (inited)
return;


libc_handle = dlopen ("libc.so.6", RTLD_LAZY);
if (libc_handle==NULL)
die ("can't open libc.so.6\n");

open_ptr = dlsym (libc_handle, "open");
if (open_ptr==NULL)
die ("can't find open()\n");

close_ptr = dlsym (libc_handle, "close");
if (close_ptr==NULL)
die ("can't find close()\n");

read_ptr = dlsym (libc_handle, "read");
if (read_ptr==NULL)
die ("can't find read()\n");

inited = true;
}


static int opened_fd=0;


int open(const char *pathname, int flags)
{
find_original_functions();


int fd=(*open_ptr)(pathname, flags);
if (strcmp(pathname, "/proc/uptime")==0)

(^3) For example, here is how simple strcmp() interception works in this article (^4) written by Yong Huang

Free download pdf