Privilege Levels and Permission Model
Objective: Understand how Linux manages privileges at the process and file levels, and how to exploit privilege boundaries for escalation.
Table of Contents
- Linux Privilege Hierarchy
- Real UID vs Effective UID vs Saved Set-ID UID
- How SetUID Works at the Process Level
- Horizontal vs Vertical Privilege Escalation
- Linux File Permission Model
- Special Permission Bits
- Reading ls -la Output
- Checking Current Privileges
- Privilege Elevation Mechanisms
- Capabilities
- su vs sudo
- OSCP Exam Tips
Linux Privilege Hierarchy
Linux enforces a strict privilege hierarchy based on UIDs:
| Level | UID | Name | Privileges |
|---|---|---|---|
| Superuser | 0 |
Root | Full system access, bypasses all DAC checks |
| System | 1-999 |
System accounts | Service-specific privileges, usually no login |
| Regular | 1000+ |
User accounts | Standard user privileges |
| Nobody | 65534 |
Unprivileged | Minimal privileges, used by services |
Root Privileges (UID 0)
Root bypasses all Discretionary Access Control (DAC) checks:
# Root can do anything
cat /etc/shadow # Read any file
echo "data" > /etc/passwd # Write to any file
kill -9 <pid> # Kill any process
mount /dev/sda1 /mnt # Mount any device
useradd backdoor # Create users
iptables -F # Flush firewall rules
Why UID 0 Matters
- Any process running as UID 0 has full root access
- Finding a way to execute code as UID 0 = complete system compromise
- SUID binaries owned by root run with UID 0 effective UID
Real UID vs Effective UID vs Saved Set-ID UID
Linux processes carry three UID values. Understanding the difference is critical for privesc.
| UID Type | Description | Purpose |
|---|---|---|
| Real UID (rUID) | The actual user who started the process | Identifies who owns the process |
| Effective UID (eUID) | Used for permission checks | Determines what the process can access |
| Saved Set-ID UID (sUID) | Copy of eUID at exec time | Allows dropping and restoring privileges |
Why Three UIDs?
The three-UID model allows programs to temporarily drop privileges and then restore them:
1. User starts program → rUID = user, eUID = user
2. Program needs root access → eUID = 0 (via SUID)
3. Program does privileged work → eUID = 0
4. Program drops privileges → eUID = rUID (back to user)
5. Program needs root again → eUID = sUID (restore from saved)
Example: /bin/su
# /bin/su has SUID bit set, owned by root
ls -la /bin/su
# -rwsr-xr-x 1 root root ... /bin/su
# When you run su:
# rUID = your UID (e.g., 1001)
# eUID = 0 (because of SUID bit)
# sUID = 0 (saved from eUID at exec)
# su checks eUID (0 = root) → allows password prompt
# After auth, su sets rUID = 0, eUID = 0 → you are root
Checking UIDs in Python
import os
# Real UID - who started this process
print(f"Real UID: {os.getuid()}")
# Effective UID - used for permission checks
print(f"Effective UID: {os.geteuid()}")
# If eUID != rUID, you have elevated privileges
if os.getuid() != os.geteuid():
print("WARNING: Running with elevated privileges!")
print(f" rUID={os.getuid()}, eUID={os.geteuid()}")
# Check if root
if os.geteuid() == 0:
print("Running as ROOT!")
Checking UIDs in C
#include <stdio.h>
#include <unistd.h>
int main() {
printf("Real UID: %d\n", getuid());
printf("Effective UID: %d\n", geteuid());
printf("Saved UID: %d\n", getresuid());
return 0;
}
Privilege Dropping Example
import os
# A SUID root program that drops privileges
print(f"Before drop: rUID={os.getuid()}, eUID={os.geteuid()}")
# Drop to real user
os.seteuid(os.getuid())
print(f"After drop: rUID={os.getuid()}, eUID={os.geteuid()}")
# Can restore using saved UID (if sUID was set)
os.seteuid(0) # Only works if sUID = 0
print(f"After restore: rUID={os.getuid()}, eUID={os.geteuid()}")
How SetUID Works at the Process Level
System Calls Involved
| System Call | Purpose | Effect on UIDs |
|---|---|---|
clone() / fork() |
Create new process | Child inherits parent’s UIDs |
execve() |
Execute new program | If SUID set: eUID = file owner UID |
setreuid(ruid, euid) |
Set real and effective UID | Changes both rUID and eUID |
setuid(uid) |
Set UID | Changes rUID, eUID, and sUID |
seteuid(euid) |
Set effective UID | Changes only eUID |
setresuid(r, e, s) |
Set all three UIDs | Sets rUID, eUID, sUID |
execve() and SUID
When execve() loads a new program:
If SUID bit is set on the executable:
1. eUID = owner UID of the file
2. sUID = owner UID of the file
3. rUID = unchanged (stays the caller's rUID)
If SUID bit is NOT set:
1. eUID = rUID (unchanged)
2. sUID = unchanged
Practical Example
# Check SUID binary
ls -la /usr/bin/passwd
# -rwsr-xr-x 1 root root ... /usr/bin/passwd
# ^^^
# SUID bit set, owned by root
# When user runs /usr/bin/passwd:
# Before execve():
# rUID = 1001 (user)
# eUID = 1001 (user)
#
# After execve() loads /usr/bin/passwd:
# rUID = 1001 (user) - unchanged
# eUID = 0 (root) - from file owner
# sUID = 0 (root) - saved copy
# passwd can now modify /etc/shadow (needs root)
# because permission check uses eUID (0)
Security Implication
Any SUID root binary that:
- Executes user-controlled input
- Calls system() with user input
- Uses popen() with user input
- Has format string vulnerabilities
- Allows path traversal
…can potentially be exploited for root shell.
Horizontal vs Vertical Privilege Escalation
Definitions
| Type | Direction | Description | Example |
|---|---|---|---|
| Horizontal | Same privilege level | Switch to another user with same UID range | www-data → john (both UID 1000+) |
| Vertical | Higher privilege level | Gain elevated privileges | john (UID 1001) → root (UID 0) |
Horizontal Escalation Paths
www-data (33) ──→ john (1001) # Same privilege level, different user
│ │
│ Found john's │ john has sudo NOPASSWD
│ password in config │
▼ ▼
su - john sudo su - root
│
▼
root (0) # Vertical escalation
Vertical Escalation Paths
john (1001)
│
├──→ SUID binary exploit ──→ root (0)
├──→ Kernel exploit ────────→ root (0)
├──→ sudo misconfig ────────→ root (0)
├──→ Cron job exploit ──────→ root (0)
├──→ Docker escape ─────────→ root (0)
├──→ LXD escape ────────────→ root (0)
└──→ Writable /etc/passwd ──→ root (0)
Why Horizontal Matters
Horizontal escalation is often the first step:
- Start as
www-data(limited access) - Find credentials → switch to
john(more access) johnhas sudo → escalate toroot
# Horizontal: switch users
su - john
ssh john@localhost
# Then vertical: gain root
sudo -l
sudo su -
Linux File Permission Model
The Three-Tier Model
Every file has permissions for three entities:
| Entity | Description | Permission Letters |
|---|---|---|
| Owner (User) | The file’s owner | u |
| Group | The file’s group | g |
| Other (World) | Everyone else | o |
Permission Bits
| Bit | Letter | Numeric | Meaning for Files | Meaning for Directories |
|---|---|---|---|---|
| Read | r |
4 |
Read file contents | List directory contents |
| Write | w |
2 |
Modify file | Create/delete files in dir |
| Execute | x |
1 |
Run as program | Enter/traverse directory |
| None | - |
0 |
No access | No access |
Numeric Permission Calculation
rwx = 4 + 2 + 1 = 7
rw- = 4 + 2 + 0 = 6
r-x = 4 + 0 + 1 = 5
r-- = 4 + 0 + 0 = 4
-w- = 0 + 2 + 0 = 2
--x = 0 + 0 + 1 = 1
--- = 0 + 0 + 0 = 0
Common Permission Combinations
| Octal | Symbolic | Meaning | Common Use |
|---|---|---|---|
777 |
rwxrwxrwx |
Full access for all | Dangerous - avoid |
755 |
rwxr-xr-x |
Owner full, others read+exec | Directories, scripts |
750 |
rwxr-x--- |
Owner full, group read+exec | Restricted dirs |
644 |
rw-r--r-- |
Owner read/write, others read | Config files |
600 |
rw------- |
Owner only | SSH keys, sensitive files |
640 |
rw-r----- |
Owner rw, group read | /etc/shadow |
700 |
rwx------ |
Owner only | /root, private dirs |
Special Permission Bits
SUID (Set User ID) - 4000
When set on an executable, the process runs with the file owner’s UID:
# SUID bit shown as 's' in execute position
ls -la /bin/su
# -rwsr-xr-x 1 root root ... /bin/su
# ^
# 's' = SUID set + execute bit for owner
# Numeric: 4755 = 4000 (SUID) + 755
chmod 4755 /path/to/binary
chmod u+s /path/to/binary
Privesc Relevance: SUID root binaries can give root shells if exploitable.
SGID (Set Group ID) - 2000
When set on an executable, the process runs with the file group’s GID:
# SGID on file
ls -la /usr/bin/wall
# -rwxr-sr-x 1 root tty ... /usr/bin/wall
# ^
# 's' = SGID set
# SGID on directory - new files inherit directory's group
chmod 2770 /shared/project
# Files created here will have group = project's group
Privesc Relevance: SGID binaries can access group-restricted resources.
Sticky Bit - 1000
On directories, prevents users from deleting others’ files:
ls -ld /tmp
# drwxrwxrwt ... /tmp
# ^
# 't' = sticky bit
# Only file owner, directory owner, or root can delete files
chmod 1777 /tmp
Privesc Relevance: Low, but writable sticky directories can be used for LD_PRELOAD attacks.
Special Bits Summary
| Bit | Octal | Symbol | Effect | Privesc Value |
|---|---|---|---|---|
| SUID | 4000 |
s in user-x |
Run as file owner | High - root SUID = root shell |
| SGID | 2000 |
s in group-x |
Run as file group | Medium - group access |
| Sticky | 1000 |
t in other-x |
Delete restriction | Low - but writable dirs matter |
| SUID (no exec) | 4000 |
S (capital) |
SUID set, no exec | None - not exploitable |
| SGID (no exec) | 2000 |
S (capital) |
SGID set, no exec | None - not exploitable |
Capital vs Lowercase S/T
-s = SUID + execute bit set (exploitable)
-S = SUID set, no execute (NOT exploitable)
-t = Sticky + execute set
-T = Sticky set, no execute
Reading ls -la Output
File Permission Breakdown
-rwsr-xr-x 1 root root 40128 Jan 15 10:30 /bin/su
│ ││││││││ │ │ │
│ ││││││││ │ │ └── File size
│ ││││││││ │ └────── Group owner
│ ││││││││ └─────────── File owner
│ │││││││└────────────── Link count
│ ││││││└─────────────── Other: r-x (read + execute)
│ │││││└──────────────── Group: r-x (read + execute)
│ ││││└───────────────── Owner: rws (read + write + SUID)
│ │││└────────────────── SUID bit (s = setuid + execute)
│ ││└─────────────────── Write bit for owner
│ │└──────────────────── Read bit for owner
│ └───────────────────── File type (- = regular file)
└─────────────────────── File type
File Type Characters
| Character | Type | Example |
|---|---|---|
- |
Regular file | -rwxr-xr-x |
d |
Directory | drwxr-xr-x |
l |
Symbolic link | lrwxrwxrwx |
c |
Character device | crw-rw-rw- |
b |
Block device | brw-rw---- |
p |
Named pipe (FIFO) | prw-r--r-- |
s |
Socket | srwxr-xr-x |
Permission Examples
-rwsr-xr-x → SUID root binary (HIGH privesc value)
-rwsr-sr-x → SUID + SGID (check both owner and group)
-rwsr-x--- → SUID, only owner and group can execute
-rws------ → SUID, only owner can do anything
-rwxr-sr-x → SGID only (check group privileges)
-rwsr-xr-x → SUID, world-executable (DANGEROUS if root-owned)
-rwSr-xr-x → SUID set but NO execute (not exploitable)
Checking Current Privileges
Command-Line Methods
# Basic identity
whoami # Current username
id # Full ID info
id -u # Numeric UID
id -g # Numeric GID
id -G # All group IDs (numeric)
id -Gn # All group names
# Example output
id
# uid=33(www-data) gid=33(www-data) groups=33(www-data),34(backup)
Python Methods
import os, subprocess
# UID checks
print(f"Real UID: {os.getuid()}")
print(f"Effective UID: {os.geteuid()}")
# Check if root
if os.geteuid() == 0:
print("ROOT ACCESS!")
# Get username
import pwd
print(f"Username: {pwd.getpwuid(os.getuid()).pw_name}")
# Get groups
print(f"Groups: {os.getgroups()}")
# Check file access
print(f"Can read /etc/shadow: {os.access('/etc/shadow', os.R_OK)}")
print(f"Can write /etc/passwd: {os.access('/etc/passwd', os.W_OK)}")
One-Liner Privilege Check
# Complete privilege summary
echo "=== Current User ===" && whoami && id && echo "=== Groups ===" && groups && echo "=== Sudo ===" && sudo -l 2>/dev/null && echo "=== Shell ===" && echo $SHELL
Privilege Elevation Mechanisms
How sudo Elevates Privileges
User runs: sudo command
│
▼
sudo checks /etc/sudoers
│
├── User NOT allowed → Denied
├── User allowed, needs password → Prompt for password
└── User allowed, NOPASSWD → Execute immediately
│
▼
execve() with eUID = 0 (root)
Command runs as root
# Check what you can sudo
sudo -l
# Example output
# User john may run the following commands on target:
# (ALL) NOPASSWD: /usr/bin/find
# (root) /usr/bin/vim
How SUID Binaries Elevate Privileges
User runs: /path/to/suid_binary
│
▼
kernel checks SUID bit
│
├── SUID NOT set → eUID = user's UID
└── SUID IS set → eUID = file owner's UID
│
▼
If owner = root → eUID = 0 → ROOT ACCESS
How Capabilities Provide Partial Privileges
Traditional: all-or-nothing (root or not root)
Capabilities: granular privileges
CAP_NET_BIND_SERVICE → bind to ports < 1024
CAP_SYS_ADMIN → broad admin rights (almost root)
CAP_DAC_OVERRIDE → bypass file permission checks
CAP_SETUID → change UIDs
# Check capabilities on a binary
getcap /usr/bin/ping
# /usr/bin/ping = cap_net_raw+ep
# Find all files with capabilities
getcap -r / 2>/dev/null
Capabilities
Linux capabilities break root privileges into discrete units:
| Capability | Description | Privesc Risk |
|---|---|---|
CAP_SYS_ADMIN |
Broad admin rights | Critical - nearly root |
CAP_DAC_OVERRIDE |
Bypass file permissions | High - read any file |
CAP_SETUID / CAP_SETGID |
Change UIDs/GIDs | High - become any user |
CAP_NET_RAW |
Raw network access | Low - network scanning |
CAP_NET_BIND_SERVICE |
Bind low ports | Low |
CAP_SYS_PTRACE |
Trace processes | High - inject code |
CAP_SYS_MODULE |
Load kernel modules | Critical - kernel code |
CAP_FOWNER |
Bypass owner checks | High |
CAP_CHOWN |
Change file ownership | Medium |
Exploiting Capabilities
# Find binaries with dangerous capabilities
getcap -r / 2>/dev/null | grep -E 'CAP_SYS_ADMIN|CAP_SETUID|CAP_DAC_OVERRIDE'
# If a binary has CAP_SETUID, you can potentially become root
# Example: python3 with CAP_SETUID
python3 -c 'import os; os.setuid(0); os.system("/bin/bash")'
su vs sudo
| Feature | su |
sudo |
|---|---|---|
| Full name | Substitute User | SuperUser DO |
| Default target | Root | Root (configurable) |
| Password used | Target user’s password | Your own password |
| Authentication | PAM | /etc/sudoers |
| Logging | Minimal | Detailed (/var/log/auth.log) |
| Granularity | All-or-nothing | Per-command control |
| Timeout | None (full session) | 5 min default |
| NOPASSWD option | No | Yes |
| Command restriction | No | Yes |
When to Use Which
# su - requires root password (or target user's password)
su - root
su - john
# sudo - uses your password, respects sudoers
sudo su - # Get root shell
sudo -i # Root login shell
sudo -l # List allowed commands
sudo command # Run single command as root
sudo -u john command # Run as specific user
sudo Misconfigurations to Exploit
# Check for NOPASSWD
sudo -l | grep NOPASSWD
# GTFOBins: exploit allowed sudo commands
# sudo -l shows: (root) NOPASSWD: /usr/bin/find
sudo find . -exec /bin/bash -p \; -quit
# (root) NOPASSWD: /usr/bin/vim
sudo vim -c ':!/bin/bash'
# (root) NOPASSWD: /usr/bin/python3
sudo python3 -c 'import os; os.system("/bin/bash")'
OSCP Exam Tips
Always Run These First
# Priority 1: Identity
id
whoami
# Priority 2: Check effective vs real UID
python3 -c "import os; print(f'rUID={os.getuid()}, eUID={os.geteuid()}')"
# Priority 3: Sudo check
sudo -l
# Priority 4: SUID binaries
find / -perm -4000 -type f 2>/dev/null
# Priority 5: Capabilities
getcap -r / 2>/dev/null
Key Concepts to Remember
- eUID determines access - permission checks use effective UID, not real UID
- SUID root = potential root shell - every SUID root binary is a candidate
- Capabilities can bypass SUID - a binary with
CAP_SETUIDcan change UIDs - sudo -l is your friend - always check before trying
sudo su - SGID directories inherit group - writable SGID dirs let you control file groups
Common Exam Patterns
| Pattern | Detection | Exploitation |
|---|---|---|
| SUID root binary | find / -perm -4000 |
GTFOBins, custom exploit |
| sudo NOPASSWD | sudo -l |
GTFOBins for allowed command |
| CAP_SYS_ADMIN | getcap -r / |
Exploit capable binary |
| Writable SUID binary | find / -perm -4000 -writable |
Replace with reverse shell |
| eUID != rUID | Python check | Leverage elevated eUID |
Quick Reference
# SUID binaries
find / -perm -4000 -type f 2>/dev/null
# SGID binaries
find / -perm -2000 -type f 2>/dev/null
# Capabilities
getcap -r / 2>/dev/null
# Writable files owned by root
find / -writable -type f 2>/dev/null | head -20
# World-writable directories
find / -type d -perm -0002 2>/dev/null
Previous: User and Group Enumeration | Next: System Info Gathering