Linux Privilege Escalation
Introduction
The root account on Linux gives full control over the system. In a penetration test, you might start with a low-privilege shell and need to escalate your privileges to root.
Information Gathering
Enumeration is the first and most important step in Linux privilege escalation. Once you have shell access, gather as much information as possible. Key areas to focus on include:
OS & Kernel Version
Check the Linux distribution and version (e.g., via
cat /etc/os-release
).Determine the kernel version with
uname -a
to spot any known vulnerabilities.
Running Services & Processes
List all running processes (e.g., using
ps aux
).Identify services running as root; these may be misconfigured or vulnerable.
Installed Packages
Look for outdated or vulnerable packages that might be exploited.
User Information & Home Directories
Review
/etc/passwd
to see the list of users.Check home directories for readable files like
.bash_history
or SSH keys that could contain credentials.
Sudo Privileges
Run
sudo -l
to see if the current user can execute commands as root, especially with NOPASSWD options.
Configuration Files & Credentials
Search for configuration files (e.g., files ending in
.conf
or.config
) that may contain usernames, passwords, or other secrets.
Cron Jobs & Writable Files/Directories
Look for cron jobs that run with high privileges.
Identify writable directories or files that could allow you to insert or modify scripts.
Basic System & Network Information
Use commands like
whoami
,id
,hostname
, andifconfig
orip a
to understand your current context and network layout.
Tools like linPEAS can be used to automate the information gathering process.
Environment-Based Privilege Escalation
PATH Abuse
The PATH variable tells the shell where to look for executables.
You can view it using
env | grep PATH
orecho $PATH
.If the current directory (
.
) is included in PATH, an attacker can place a malicious script (e.g., a fakels
) in that directory. When the command is run, the shell may execute the malicious version instead of the intended binary.
Wildcard & Cron Job Exploitation
Wildcards (like
*
) are processed by the shell before a command is run.Some tools (e.g.,
tar
with the--checkpoint-action
option) can execute commands when processing wildcards.If a cron job runs a backup using wildcards, an attacker might craft filenames so that when the cron job runs, unintended commands are executed.
Restricted Shells & Escaping Techniques
Restricted shells (e.g., rbash, rksh, rzsh) limit which commands a user can run or which directories can be accessed.
They are often used to protect critical systems by limiting user capabilities.
Escaping methods include:
Command Injection: Injecting extra commands through allowed commands (e.g.,
ls -l \
pwd``).Command Substitution: Using backticks or
$( )
to execute additional commands.Command Chaining: Using metacharacters (like
;
or|
) to run multiple commands.Manipulating Environment Variables or Shell Functions: Redefining variables or functions to bypass restrictions.
Permission-Based Privilege Escalation
Setuid & Setgid Exploitation
Setuid allows programs to run with the privileges of their owner (often root).
Setgid does the same for group privileges.
Vulnerable setuid/setgid programs can be exploited to gain elevated access.
Find them using:
find / -uid 0 -perm -6000 -type f 2>/dev/null
GTFOBins
GTFOBins is a curated list of binaries that can be misused to escape restricted environments, spawn shells, or transfer files.
Sudo Misconfigurations
The
sudo -l
command shows which commands you can run as root.Misconfigurations (like NOPASSWD entries or loosely defined paths) can let you run commands with elevated privileges.
Best practices include specifying absolute paths in the sudoers file and granting only minimal privileges.
Container & Group Privileges
LXC/LXD & Docker:
Membership in groups like LXD or docker can be dangerous.
For instance, running:
docker run -v /root:/mnt -it ubuntu
mounts the host’s/root
directory in a container, potentially giving full access.
Disk and Log Groups:
Users in the disk group can access device files, and adm group members can read system logs. Both can reveal sensitive data.
Linux Capabilities
Capabilities split root privileges into smaller units. Examples include:
cap_sys_admin
: Broad administrative powers.cap_dac_override
: Bypasses file permission checks.
Use
getcap
to list capabilities on binaries:find /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin -type f -exec getcap {} ;
Example: If
/usr/bin/vim.basic
hascap_dac_override=eip
, you might use it to modify system files. For example, running:echo -e ':%s/^root:[^:]*:/root::/\nwq!' | /usr/bin/vim.basic -es /etc/passwd
Service-Based Privilege Escalation
Exploiting Cron Jobs & Writable Files
Cron jobs schedule tasks (backups, cleanups, etc.) by defining six fields: minutes, hours, days, months, weeks, and the command to run. For example,
0 */12 * * * /home/admin/backup.sh
runs the backup script every 12 hours.Even though the root crontab is typically protected, you might find scripts that run as root and are world-writable. If you can modify one, you can append a command (like a reverse shell) to be executed when the cron job runs. Note: Always back up any script before editing it.
Some applications place cron files in
/etc/cron.d
that might be editable by non-root users, offering another route to escalate privileges.Use the following command to search for writable files (excluding
/proc
):find / -path /proc -prune -o -type f -perm -o+w 2>/dev/null
Tools like pspy let you monitor process activity (including cron jobs) without root privileges. For example:
pspy -pf -i 1000
This command prints processes and file events every second.
Containers & Virtual Machines
Containers vs. Virtual Machines:
Containers run at the operating system level. They share the host’s kernel and isolate application processes.
Virtual Machines (VMs) run at the hardware level, each with its own full operating system.
Linux Containers (LXC & LXD)
LXC (Linux Containers):
Uses OS-level virtualization to run multiple isolated Linux systems on one host.
Lightweight and resource-efficient, ideal for quickly deploying test environments.
LXD (Linux Daemon):
Similar to an LXC but is designed to contain a complete OS in a container.
Requires membership in the
lxc
orlxd
group (check withid
).
Such templates often are not secure, especially if it's a simple testing environment. If there is such a container on the system, it can be exploited. For example we can use the flag security.privileged which disables all isolation features allowing us to act on the host.
Docker
Client-Server Model: In Docker there are 2 main components, the Docker client issues commands while the Docker daemon runs and manages containers.
Privilege Escalation via Docker:
Docker Group & Sudo:
If your user is in the
docker
group or can run Docker with sudo, you have control over the Docker daemon.
Shared Directories:
Volume mounts can link host directories to a container. You can enumerate these directories to look for useful files.
Docker Socket Exposure:
The Docker socket (typically at
/var/run/docker.sock
) allows communication with the Docker daemon.If it’s writable by a non-root user, it can be used to launch containers with host-level access.
Logrotate
Every Linux system generates many log files. To prevent disk space from filling up, the logrotate tool archives or deletes old logs. It is controlled via the global configuration file
/etc/logrotate.conf
and is typically run via cron.There is a pre-made exploit named logrotten that can perform privilege escalation if these requirements are met:
Write Permissions: You must be able to modify the log files.
Privileged Execution: Logrotate must run as a privileged user (usually root).
Logrotate Version: 3.8.6 or 3.11.0 or 3.15.0 or 3.18.0
Miscellaneous Techniques
Passive Traffic Capture
Tools like
tcpdump
can capture network traffic.Capturing traffic may reveal cleartext credentials (e.g., for HTTP, FTP, IMAP) or hashes (Net-NTLMv2, SMBv2, Kerberos) that can be cracked offline. Utilities like net-creds or PCredz can analyze captured traffic for sensitive data.
Weak NFS Privileges
The Network File System (NFS) allows remote sharing of files (typically on TCP/UDP port 2049).
Listing Shares:
showmount -e
Important Options:
root_squash: Changes remote root user access to the unprivileged
nfsnobody
user.no_root_squash: Allows remote root access to create or modify files as root.
In the case of no_root_squash, an attacker can create a simple SETUID binary (e.g., one that runs
/bin/sh
), mount the NFS share locally, copy the binary to the NFS server as local root, and then set the SUID bit. This can lead to privilege escalation.
Hijacking Tmux Sessions
Tmux is a terminal multiplexer that allows multiple terminal sessions within one console.
A privileged user (like root) might leave a tmux session running with weak permissions.
Check for running tmux processes and look for sessions with weak permissions.
Linux Internals-based Privilege Escalation
Kernel Exploits
Kernel exploits take advantage of vulnerabilities in the Linux kernel to gain root privileges.
Check the kernel version with
uname -a
Research known exploits for that kernel version.
Kernel exploits can destabilize or crash a system, so use them carefully—especially on production systems.
Dynamic Libraries & LD_PRELOAD Privilege Escalation
Dynamic Libraries: Linux programs often load shared libraries (.so files) at runtime. Their locations can be set using compile-time options or environment variables (like
LD_LIBRARY_PATH
).LD_PRELOAD: This environment variable lets you load a custom shared library before the default ones, allowing you to override functions.
Exploitation Example:
Find Sudo Rights with
NOPASSWD
:sudo -l
Example:
NOPASSWD: /usr/sbin/apache2 restart
Create a Malicious Shared Library: Write the following C code (save as
root.c
):Compile the Library:
gcc -fPIC -shared -o root.so root.c -nostartfiles
Execute with LD_PRELOAD:
sudo LD_PRELOAD=/tmp/root.so /usr/sbin/apache2 restart
Custom Shared Library Hijacking
Many programs under development use custom libraries. For example, a SETUID binary may load a nonstandard library (like libshared.so) from a custom location. You can check this by:
Listing Dependencies:
ldd <File-Name>
This shows all shared objects the binary requires.Inspecting RUNPATH:
readelf -d <File-Name> | grep PATH
If the RUNPATH includes a directory like /development that is writable by our user, this creates an opportunity.
Exploitation Steps:
Place a Malicious Library: Copy an existing library to /development so that the binary loads from there.
Create a Replacement Library: Compile a shared object that includes the missing function (e.g., dbquery) with malicious behavior:
Compile the Library:
gcc -fPIC -shared -o /development/libshared.so src.c
Run the Binary: When executed, the binary will load your malicious libshared.so and open a root shell.
Python Library Hijacking
There are three common ways to hijack a Python library:
Wrong Write Permissions: If a Python module has incorrect permissions (writable by all), you can modify it to insert your code. If a SUID/SGID script imports this module, your changes run with elevated privileges.
Library Path Hijacking: Python imports modules based on a search order. If the intended module is located in a lower-priority directory, you can create a module with the same name in a higher-priority (editable) path. Python will load your version first.
Example: A script importing the psutil module may load your crafted version if you place it in a directory that appears earlier in Python’s module search path.
Using the PYTHONPATH Environment Variable: PYTHONPATH tells Python where to search for modules. If you have sudo rights to run Python (for example, via a trusted sudo entry like
sudo /usr/bin/python3
), you can set:sudo PYTHONPATH=/tmp/ /usr/bin/python3 ./<Python-File>
This forces Python to load modules from /tmp first—allowing you to substitute a module like psutil with your own version.
Other CVE-Based Techniques
In addition to library hijacking, always check for known vulnerabilities. For example:
CVE-2019-14287 (sudo bypass)
CVE-2021-4034 (pkexec vulnerability)
Linux Hardening Best Practices
Updates and Patching:
Regularly update the kernel and installed packages.
Use tools like unattended-upgrades (Ubuntu) or yum-cron (Red Hat) for automated patching.
Configuration Management:
Audit writable files and SUID binaries.
Specify absolute paths in cron jobs and sudoers files.
Avoid storing cleartext credentials in world-readable files.
Remove unnecessary packages and services.
Consider implementing SELinux for extra access control.
User Management:
Limit the number of user and administrative accounts.
Enforce strong, regularly rotated passwords.
Restrict group memberships and follow the principle of least privilege.
Automation and Auditing:
Use configuration management tools (Puppet, SaltStack, etc.) to enforce policies.
Regularly audit systems using tools like Lynis.
Follow security baselines such as DISA STIGs, ISO27001, PCI-DSS, or HIPAA for your environment.
Command Cheatsheet
Last updated