PATH
This section demonstrates how to exploit misconfigurations in the $PATH environment variable to escalate privileges by hijacking executable lookups. This method relies on writable directories in $PATH and improperly secured scripts.
$PATHis an environment variable in Linux. It tells the system where to look for programs when you run a command.For example, if you run
ls, the system looks forlsin the directories listed in$PATH.
To see your current $PATH, run:
echo $PATHExample Output:
/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbinExploiting $PATH in 5 Simple Steps
$PATH in 5 Simple StepsWe’ll create a situation where we trick the system into running a malicious program by taking advantage of a writable folder in $PATH.
Step 1: Check for Writable Directories
Find directories where your user can write:
find / -writable 2>/dev/nullExample Output:
/tmp
/home/yourusernameIf any of these writable directories are in $PATH, we can exploit them. If not, we'll add one (see Step 4).
Step 2: Check for Vulnerable Programs
Some programs or scripts might call other programs without using their full path. For example:
When this program runs, it looks for example-command in the directories listed in $PATH. If we create a malicious example-command, the program will run it instead of the intended one.
Step 3: Compile the Vulnerable Program
Compile the program:
Set the SUID bit to allow it to run with elevated privileges:
Verify the permissions:
Output:
Step 4: Add a Writable Directory to $PATH
$PATHIf a writable directory (like /tmp) is not in $PATH, add it:
Check the updated $PATH:
Output:
Step 5: Create the Malicious Program
Create a fake program called example-command in /tmp. This program will run instead of the real one.
Copy /bin/bash (a shell) and rename it:
Verify:
Output:
Step 6: Execute the Vulnerable Program
Run the vulnerable program:
If successful, you’ll get a root shell:
Why Does This Work?
The vulnerable program runs
example-commandfrom$PATH.$PATHincludes/tmp(or another writable directory you added).The program runs our malicious
/tmp/example-commandinstead of the real one, and it inherits root privileges because of the SUID bit.
How to Defend Against This?
Avoid writable directories in
$PATH.Use absolute paths in scripts and programs (e.g.,
/usr/bin/lsinstead ofls).Remove unnecessary SUID bits on programs.
Key Commands Recap:
View
$PATH:Find writable directories:
Add
/tmpto$PATH:Create malicious program:
Run the vulnerable program:
Last updated