Environment Variables Abuse

This section covers techniques to exploit environment variables for privilege escalation.

PATH Variable Manipulation

The PATH environment variable contains a list of directories that are searched when you execute a command. If a program runs with higher privileges and relies on relative paths to execute binaries, it may be vulnerable.

Checking Current PATH

echo $PATH

Exploitation Technique

  1. Identify a program running with elevated privileges that calls another program without specifying the full path:

# For example, a SUID binary that uses system("service apache2 start")
strings /path/to/suid_binary
ltrace /path/to/suid_binary
  1. Create a malicious version of the called program in a writable directory:

cd /tmp
echo '#!/bin/bash' > service
echo 'chmod +s /bin/bash' >> service
chmod +x service
  1. Modify the PATH variable to include your directory first:

  1. Run the vulnerable SUID program, which will execute your malicious version instead:

LD_PRELOAD and LD_LIBRARY_PATH

These environment variables control which shared libraries are loaded when a program runs.

LD_PRELOAD

LD_PRELOAD allows you to load a custom shared library before all others. If you can control this while running a command with sudo, you can potentially escalate privileges.

  1. Check if LD_PRELOAD is preserved with sudo:

  1. Create a malicious shared library:

  1. Use LD_PRELOAD with sudo to execute a command:

LD_LIBRARY_PATH

LD_LIBRARY_PATH specifies directories where the program should look for libraries. This can be abused if a program searches for libraries in a specific order.

  1. Check if a SUID binary uses shared libraries:

  1. Create a malicious library with the same name as one of the used libraries:

  1. Set LD_LIBRARY_PATH to your directory:

  1. Execute the SUID binary:

Sudo Environment Variables

Sudo may preserve certain environment variables, which can be abused if misconfigured.

Check Preserved Variables

Common Exploitable Variables

  • LD_PRELOAD - As explained above

  • LD_LIBRARY_PATH - As explained above

  • PATH - Can lead to executing malicious binaries

  • PYTHONPATH - Can be used to load malicious Python modules

  • PERL5LIB - Can be used to load malicious Perl modules

Example with PYTHONPATH

If you can run a Python script with sudo:

Shell Environment Variables

Some programs can inherit shell functionality from environment variables:

BASH_ENV Exploitation

If a SUID binary executes sh internally, it might source BASH_ENV:

Additional Resources

Last updated