As I have read an article about DLL hijacking in Windows some days ago, I remembered some nice old tricks from my time when I was an administrator of test environments.

Who ever wrote C/C++ programs, has most likely heard also about libraries. Libraries are small bundles of executable code which can make your life easier. There is for example a library which handles strings.

To avoid that each program has all libraries inside, there is a mechanism to load the libraries as needed. The place where the libraries are located is handled by LD_LIBRARY_PATH variable. To avoid security risks it is highly recommended NOT to include the local directory (“.”) inside the variable. Beside LD_LIBRARY_PATH there is another variable to influence the loading of libraries: LD_PRELOAD

LD_PRELOAD allows to load a library in the very first beginning of the execution. After the library is loaded, function calls refer to the first occurrence of  name in the libraries. Lets have an easy example:

test.c:

#include <stdio.h>
#include <string.h>

int main( int argc, char **argv)
{

 int test;
 char *myst = "My   little  Test";
 printf("%s\n",myst);
 printf("%d\n",strlen(myst));
 return 0;

}

This program prints a small text and the length of it:

~/test $ ./test

My   little  Test
17

Next we write a small code which contains the strlen function:

#include <stddef.h>

size_t strlen(const char *s)
{
 return 42;
}

we generate a library out of it:

gcc -shared -Wl,-soname,your_soname -o mystrlen.so mystrlen.c

and load it before execution:

nidsche@cserver ~/test $ LD_PRELOAD=./mystrlen.so ./test
My   little  Test
42

We replaced successfully the strlen funtion with our own code. BTW: If the “s” Bit is set for an executable LD_PRELOAD is not evaluated.